fix: preserve retained startup and planned-drain ownership

This commit is contained in:
pingqiu committed 2026-11-22 01:01:28 -08:00
1 parent 85139083d6
commit 7600be4e81
6 files changed
+214 -62

No files matched your search

+30 -6
View File
@@ -28,15 +28,35 @@ type workspaceExit struct {
// INV-WS-STARTUP-RETRY-001: the first outcome is immutable. The channel is a
// single latched wakeup, not a queue of competing shutdown events.
type processExit struct {
parent context.Context
once sync.Once
done chan struct{}
decision chan workspaceExit
parent context.Context
once sync.Once
done chan struct{}
decision chan workspaceExit
startupMu sync.Mutex
startupCtx context.Context
startupCancel context.CancelFunc
}
func newProcessExit(ctx context.Context) *processExit {
return &processExit{parent: ctx, done: make(chan struct{}), decision: make(chan workspaceExit, 1)}
startupCtx, cancel := context.WithCancel(ctx)
return &processExit{parent: ctx, done: make(chan struct{}), decision: make(chan workspaceExit, 1), startupCtx: startupCtx, startupCancel: cancel}
}
// INV-WS-STARTUP-RETRY-001: once the resource owner takes shutdown, startup
// outcomes cannot arbitrate it. ACK success is still selected only after ACK.
func (e *processExit) stopChunkStartup() {
e.startupMu.Lock()
defer e.startupMu.Unlock()
e.startupCancel()
}
func (e *processExit) chooseChunkStartup(out workspaceExit) {
e.startupMu.Lock()
defer e.startupMu.Unlock()
if e.startupCtx.Err() == nil {
e.choose(out)
}
}
func (e *processExit) choose(out workspaceExit) {
e.once.Do(func() {
if e.parent.Err() != nil {
@@ -118,6 +138,8 @@ func watchChunkStartup(ctx context.Context, e *processExit, f flags, h *volume.H
}
select {
case <-e.startupCtx.Done():
return
case <-ctx.Done():
return
case <-e.done:
@@ -136,6 +158,7 @@ func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan
case <-e.done:
return nil, done
case request := <-requests:
e.stopChunkStartup()
out := workspaceExit{reason: "revoked"}
if !h.WorkspaceLeaseRevoking() {
out = workspaceRetryOutcome("lease_expired", h)
@@ -145,6 +168,7 @@ func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan
}
return &request, done
case err := <-done:
e.stopChunkStartup()
fmt.Fprintln(os.Stderr, "blockvolume: workspace lease stopped:", err)
e.choose(workspaceRetryOutcome("lease_expired", h))
return nil, nil
@@ -186,5 +210,5 @@ func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p chunkStar
return false
}
out := workspaceRetryOutcome("assignment_timeout", h)
return p.ChooseChunkStartupExit(f.volumeID, gen, func() { e.choose(out) })
return p.ChooseChunkStartupExit(f.volumeID, gen, func() { e.chooseChunkStartup(out) })
}
@@ -21,6 +21,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
hostvolume "github.com/seaweedfs/seaweed-block/core/host/volume"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
@@ -37,24 +38,30 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) {
if os.Getenv("CHUNKSTORE_WEED") == "" {
t.Fatal("real CHUNKSTORE_WEED binary required")
}
if out, err := exec.Command("systemctl", "show", "--property=Version").CombinedOutput(); err != nil {
probeCtx, probeCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer probeCancel()
if out, err := exec.CommandContext(probeCtx, "systemctl", "show", "--property=Version").CombinedOutput(); err != nil {
t.Fatalf("real systemd unavailable: %v %s", err, out)
}
root := t.TempDir()
fixture := newGAP1Fixture(t)
root := fixture.root
bin := filepath.Join(root, "bin")
if err := os.Mkdir(bin, 0755); err != nil {
t.Fatal(err)
}
for _, name := range []string{"blockvolume", "blockmaster"} {
cmd := exec.Command("go", "build", "-p", "4", "-o", filepath.Join(bin, name), "../"+name)
if out, err := cmd.CombinedOutput(); err != nil {
buildCtx, buildCancel := context.WithTimeout(context.Background(), 2*time.Minute)
cmd := exec.CommandContext(buildCtx, "go", "build", "-p", "4", "-o", filepath.Join(bin, name), "../"+name)
out, err := cmd.CombinedOutput()
buildCancel()
if err != nil {
t.Fatalf("real binary build: %v %s", err, out)
}
}
cluster := startWorkspaceWeed(t)
cluster := startWorkspaceWeedAt(t, filepath.Join(root, "weed"))
gap1PreserveFailure(t, root, cluster.dir)
stem := fmt.Sprintf("codex03-gap1-%d", time.Now().UnixNano())
gap1ProbeTerminalSuccess(t, stem+"-policy-probe")
gap1ProbeTerminalSuccess(t, fixture, stem+"-policy-probe")
volume := stem
base := "/" + stem
masterAddr := leaseBinaryAddress(t)
@@ -64,7 +71,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) {
if err := os.WriteFile(spec, []byte(cfg), 0600); err != nil {
t.Fatal(err)
}
startGAP1Unit(t, stem+"-master", false, filepath.Join(bin, "blockmaster"),
fixture.start(t, stem+"-master", false, filepath.Join(bin, "blockmaster"),
"--listen", masterAddr, "--authority-store", filepath.Join(root, "auth"), "--lifecycle-store", filepath.Join(root, "life"),
"--cluster-spec", spec, "--lifecycle-product-loop-interval", "200ms", "--expected-slots-per-volume", "1",
"--workspace-rpc", "--workspace-head-base-url", "http://"+cluster.filerHTTP+base)
@@ -82,7 +89,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) {
"--nvme-listen", nvmeAddr, "--nvme-subsysnqn", "nqn.2026-11.test:" + stem}
// Bootstrap is a different, non-restarting unit. Kill only this exact unit.
bootstrap := stem + "-bootstrap"
startGAP1Unit(t, bootstrap, false, filepath.Join(bin, "blockvolume"), args...)
fixture.start(t, bootstrap, false, filepath.Join(bin, "blockvolume"), args...)
waitGAP1(t, "bootstrap did not attach under a real lease", 60*time.Second, func() bool { return gap1Operational(t, statusAddr, volume) })
// Calibrate verdict parsing against actual binary responses BEFORE kill.
status, payload, err := gap1Status(statusAddr, volume)
@@ -102,7 +109,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) {
client.readExact(t, 8, want)
client.close()
remote := cluster.remote(t, base+"/"+volume)
before, err := remote.GetHead(context.Background())
before, err := gap1ReadHead(t, remote)
if err != nil || before.Gen == 0 {
t.Fatalf("bootstrap HEAD: %+v %v", before, err)
}
@@ -123,7 +130,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) {
return s.Lease.ValidForNs <= 0 && time.Now().UnixNano() >= s.Lease.ExpiresAtNs
})
unit := stem + "-returning"
startGAP1Unit(t, unit, true, filepath.Join(bin, "blockvolume"), args...)
fixture.start(t, unit, true, filepath.Join(bin, "blockvolume"), args...)
first := gap1Unit(t, unit)
t.Logf("captured effective restart policy: %+v", first)
firstPID := first["MainPID"]
@@ -156,7 +163,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) {
}
return n >= 1 && s["MainPID"] != "0" && s["MainPID"] != firstPID && gap1Operational(t, statusAddr, volume)
})
after, err := remote.GetHead(context.Background())
after, err := gap1ReadHead(t, remote)
if err != nil || after.Gen <= before.Gen || after.Holder != before.Holder || after.Epoch != before.Epoch {
t.Fatalf("return did not claim HEAD: before%+v after%+v err%v", before, after, err)
}
@@ -183,47 +190,140 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) {
t.Fatalf("systemd rate limit hit: %+v", s)
}
gap1PlannedStopDoesNotRestart(t, ws, unit, statusAddr, volume, after.Epoch, "r1", s["NRestarts"], s["InvocationID"])
gap1SupersededDoesNotRestart(t, stem, filepath.Join(bin, "blockvolume"), args, root, volume)
gap1SupersededDoesNotRestart(t, fixture, stem, filepath.Join(bin, "blockvolume"), args, root, volume)
}
func startGAP1Unit(t *testing.T, unit string, restart bool, exe string, args ...string) {
// Roots are deliberately independent of testing.TempDir: unknown unit cleanup
// must never remove an executable or WAL beneath a possible surviving service.
type gap1Fixture struct {
root string
units []string
}
func newGAP1Fixture(t *testing.T) *gap1Fixture {
t.Helper()
root, err := os.MkdirTemp("", "codex03-gap1-runtime-")
if err != nil {
t.Fatal(err)
}
f := &gap1Fixture{root: root}
t.Cleanup(func() {
safe := true
for _, unit := range f.units {
state, err := gap1ReadUnit(unit)
if err != nil || !gap1UnitGone(state) {
t.Errorf("final unit absence unproved: %s state%v err%v", unit, state, err)
safe = false
}
}
if !safe || t.Failed() {
t.Logf("retained run root: %s (safe=%v failed=%v)", root, safe, t.Failed())
return
}
if err := os.RemoveAll(root); err != nil {
t.Errorf("remove confirmed idle run root: %v", err)
}
})
return f
}
func (f *gap1Fixture) start(t *testing.T, unit string, restart bool, exe string, args ...string) {
t.Helper()
f.units = append(f.units, unit)
// Persist ownership before the create, including an aggregate test crash.
ownership, err := os.OpenFile(filepath.Join(f.root, "owned-units.txt"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
t.Fatal(err)
}
_, writeErr := fmt.Fprintln(ownership, unit)
closeErr := ownership.Close()
if writeErr != nil || closeErr != nil {
t.Fatalf("record unit ownership: %v %v", writeErr, closeErr)
}
// Register BEFORE submission: systemd may create the unit even when the
// command loses its answer or times out. Every uncertain create is owned.
t.Cleanup(func() { gap1CleanupUnit(t, unit) })
policy := "no"
if restart {
policy = "on-failure"
}
shipped := gap1ShippedPolicy(t)
cmdArgs := []string{"--unit=" + unit, "--property=Type=exec", "--property=Restart=" + policy,
"--property=RestartSec=" + shipped["RestartSec"],
"--property=RestartPreventExitStatus=" + shipped["RestartPreventExitStatus"],
"--property=TimeoutStopSec=" + shipped["TimeoutStopSec"],
"--property=StartLimitIntervalSec=10s", "--property=StartLimitBurst=5", "--", exe}
cmdArgs := []string{"--unit=" + unit, "--property=Type=exec", "--property=Restart=" + policy, "--property=RestartSec=" + shipped["RestartSec"], "--property=RestartPreventExitStatus=" + shipped["RestartPreventExitStatus"], "--property=TimeoutStopSec=" + shipped["TimeoutStopSec"], "--property=StartLimitIntervalSec=10s", "--property=StartLimitBurst=5", "--", exe}
cmdArgs = append(cmdArgs, args...)
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, "systemd-run", cmdArgs...).CombinedOutput()
if err != nil {
t.Fatalf("systemd-run %s: %v %s", unit, err, out)
if out, err := exec.CommandContext(ctx, "systemd-run", cmdArgs...).CombinedOutput(); err != nil {
t.Fatalf("systemd-run %s (creation outcome uncertain; registered cleanup owns it): %v %s", unit, err, out)
}
t.Cleanup(func() {
// Capture before stopping; never remove a run root owned by another run.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
log, _ := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=short-monotonic").CombinedOutput()
cancel()
t.Logf("real unit %s journal:\n%s", unit, log)
ctx, cancel = context.WithTimeout(context.Background(), 15*time.Second)
_, err := exec.CommandContext(ctx, "systemctl", "stop", unit).CombinedOutput()
cancel()
if err != nil && gap1Unit(t, unit)["LoadState"] != "not-found" {
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
_ = exec.CommandContext(ctx, "systemctl", "kill", "--signal=KILL", unit).Run()
cancel()
t.Errorf("unit stop required kill: %s", unit)
}
func gap1CleanupUnit(t *testing.T, unit string) {
t.Helper()
command := func(bound time.Duration, args ...string) error {
ctx, cancel := context.WithTimeout(context.Background(), bound)
defer cancel()
out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
if err != nil {
t.Logf("unit cleanup %s: %v %s", unit, err, out)
}
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
_ = exec.CommandContext(ctx, "systemctl", "reset-failed", unit).Run()
cancel()
})
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
journal, _ := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=short-monotonic").CombinedOutput()
cancel()
t.Logf("real unit %s journal:\n%s", unit, journal)
_ = command(15*time.Second, "stop", unit)
state, err := gap1ReadUnit(unit)
if err != nil || !gap1UnitGone(state) {
_ = command(5*time.Second, "kill", "--kill-who=all", "--signal=KILL", unit)
_ = command(5*time.Second, "stop", unit)
}
_ = command(5*time.Second, "reset-failed", unit)
state, err = gap1ReadUnit(unit)
if err != nil || !gap1UnitGone(state) {
t.Errorf("owned unit/PID cleanup not confirmed; retain run root: %s state%v err%v", unit, state, err)
return
}
t.Logf("confirmed owned unit stopped: %s state%v", unit, state)
}
func gap1UnitGone(s map[string]string) bool {
job, hasJob := s["Job"]
return hasJob && job == "" && s["MainPID"] == "0" && s["ControlPID"] == "0" &&
(s["LoadState"] == "not-found" || s["LoadState"] == "loaded") && s["ActiveState"] == "inactive" && s["SubState"] == "dead"
}
// The absent-unit shape is captured from real systemd249. Refuse incomplete,
// contradictory, queued-job and live-process observations before removing WAL.
func TestGAP1AbsenceRequiresNoJobAndBothPIDsZero(t *testing.T) {
for _, tc := range []struct {
name, key, value string
want bool
}{
{"collected", "LoadState", "not-found", true},
{"loaded stopped", "LoadState", "loaded", true},
{"main lives", "MainPID", "123", false},
{"control lives", "ControlPID", "123", false},
{"job queued", "Job", "123", false},
{"restart pending", "SubState", "auto-restart", false},
{"contradictory active", "ActiveState", "active", false},
{"unknown load", "LoadState", "", false},
} {
t.Run(tc.name, func(t *testing.T) {
s := map[string]string{"MainPID": "0", "ControlPID": "0", "LoadState": "not-found", "ActiveState": "inactive", "SubState": "dead", "Job": ""}
s[tc.key] = tc.value
if gap1UnitGone(s) != tc.want {
t.Fatalf("absence classification %+v want%v", s, tc.want)
}
delete(s, "Job")
if gap1UnitGone(s) {
t.Fatal("missing observation treated as absence")
}
})
}
}
func gap1ReadHead(t *testing.T, remote storage.ChunkRemote) (storage.ChunkHead, error) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return remote.GetHead(ctx)
}
func gap1Systemctl(t *testing.T, args ...string) {
t.Helper()
@@ -235,11 +335,19 @@ func gap1Systemctl(t *testing.T, args ...string) {
}
func gap1Unit(t *testing.T, unit string) map[string]string {
t.Helper()
m, err := gap1ReadUnit(unit)
if err != nil {
t.Fatal(err)
}
t.Logf("captured unit %s: %+v", unit, m)
return m
}
func gap1ReadUnit(unit string) (map[string]string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
b, err := exec.CommandContext(ctx, "systemctl", "show", unit, "--property=MainPID,NRestarts,ExecMainStatus,Result,ExecMainStartTimestampMonotonic,RestartUSec,RestartPreventExitStatus,StartLimitBurst,StartLimitIntervalUSec,ActiveState,SubState,LoadState,InvocationID").CombinedOutput()
b, err := exec.CommandContext(ctx, "systemctl", "show", unit, "--property=Job,MainPID,ControlPID,NRestarts,ExecMainStatus,Result,ExecMainStartTimestampMonotonic,RestartUSec,RestartPreventExitStatus,StartLimitBurst,StartLimitIntervalUSec,ActiveState,SubState,LoadState,InvocationID").CombinedOutput()
if err != nil {
t.Fatalf("unit show: %v %s", err, b)
return nil, fmt.Errorf("unit show %s: %w %s", unit, err, b)
}
m := map[string]string{}
for _, l := range strings.Split(strings.TrimSpace(string(b)), "\n") {
@@ -248,13 +356,12 @@ func gap1Unit(t *testing.T, unit string) map[string]string {
m[k] = v
}
}
for _, key := range []string{"MainPID", "NRestarts", "ExecMainStatus", "Result", "ExecMainStartTimestampMonotonic"} {
for _, key := range []string{"Job", "MainPID", "ControlPID", "NRestarts", "ExecMainStatus", "Result", "ExecMainStartTimestampMonotonic", "LoadState", "ActiveState", "SubState"} {
if _, ok := m[key]; !ok {
t.Fatalf("captured systemd response lacks %s: %s", key, b)
return nil, fmt.Errorf("captured systemd response lacks %s: %s", key, b)
}
}
t.Logf("captured unit %s: %s", unit, strings.TrimSpace(string(b)))
return m
return m, nil
}
func gap1Status(addr, volume string) (int, []byte, error) {
r, e := (&http.Client{Timeout: time.Second}).Get("http://" + addr + "/status/durable?volume=" + volume)
@@ -395,7 +502,7 @@ func gap1PlannedStopDoesNotRestart(t *testing.T, ws control.WorkspaceServiceClie
// assignment and names r-old, so only the observed different-replica fact may
// permit 78. Run after the live holder has ACKed and exited, avoiding a node
// registration change while that holder is serving.
func gap1SupersededDoesNotRestart(t *testing.T, stem, exe string, args []string, root, volume string) {
func gap1SupersededDoesNotRestart(t *testing.T, fixture *gap1Fixture, stem, exe string, args []string, root, volume string) {
t.Helper()
changed := append([]string(nil), args...)
addr := leaseBinaryAddress(t)
@@ -406,7 +513,7 @@ func gap1SupersededDoesNotRestart(t *testing.T, stem, exe string, args []string,
}
}
unit := stem + "-superseded"
startGAP1Unit(t, unit, true, exe, changed...)
fixture.start(t, unit, true, exe, changed...)
waitGAP1(t, "superseded process never observed the master's other-replica fact", 15*time.Second, func() bool {
resp, err := (&http.Client{Timeout: time.Second}).Get("http://" + addr + "/status?volume=" + volume)
if err != nil {
@@ -544,9 +651,9 @@ func gap1JournalTerminalSuccess(t *testing.T, unit, invocation string, expectedS
// Calibrate the terminal parser against the real supervisor before any holder
// is killed. Successful transient units can be collected; their journal is the
// proof, never the default zeros returned for an unknown unit.
func gap1ProbeTerminalSuccess(t *testing.T, unit string) {
func gap1ProbeTerminalSuccess(t *testing.T, fixture *gap1Fixture, unit string) {
t.Helper()
startGAP1Unit(t, unit, true, "/bin/true")
fixture.start(t, unit, true, "/bin/true")
waitGAP1(t, "systemd terminal-success parser preflight failed", 5*time.Second, func() bool {
return gap1JournalTerminalSuccess(t, unit, "", 1)
})
@@ -62,12 +62,21 @@ func w4WaitTCP(t *testing.T, addr string, d time.Duration) {
}
func startWorkspaceWeed(t *testing.T) *w4WeedCluster {
t.Helper()
return startWorkspaceWeedAt(t, t.TempDir())
}
// A caller-owned root lets process qualification retain its filer evidence
// when external-service cleanup is uncertain. Existing tests keep TempDir.
func startWorkspaceWeedAt(t *testing.T, dir string) *w4WeedCluster {
t.Helper()
weed := os.Getenv("CHUNKSTORE_WEED")
if weed == "" {
t.Skip("CHUNKSTORE_WEED not set")
}
dir := t.TempDir()
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
used := map[int]bool{}
mp, vp, fp := w4FreePortPair(t, used), w4FreePortPair(t, used), w4FreePortPair(t, used)
c := &w4WeedCluster{
@@ -164,10 +164,11 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
defer func() {
log.Printf("durable: chunk authority wait for volume=%s ended after %s: %s", volumeID, time.Since(start), ended)
}()
retained := false // this generation already chose sealed replay or diagnostics
waitCtx, endWait := context.WithTimeout(p.closeCtx, limit)
defer endWait()
defer func() {
if !errors.Is(waitCtx.Err(), context.DeadlineExceeded) {
if retained || !errors.Is(waitCtx.Err(), context.DeadlineExceeded) {
return
}
// The old wait must not overwrite a newer recovery's readiness.
@@ -235,6 +236,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
case errors.Is(err, storage.ErrChunkLayerDetached):
// INV-WS-STARTUP-RETRY-001: an assigned sealed incarnation stays
// non-serving for exact seal replay; restarting cannot unseal it.
retained = true
ended = "sealed assignment, retained for replay"
h.backend.SetOperational(false, "sealed assignment; replay only")
return
@@ -242,6 +244,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
ended = "fenced, not serving"
log.Printf("durable: chunk layer for volume=%s: %v (not serving)", volumeID, err)
if errors.Is(err, ErrChunkStaleLocalRoot) {
retained = true
h.attachMu.Lock()
if p.current(h, gen) && h.chunk == nil {
h.backend.SetOperational(false, "chunk layer attach refused: "+err.Error())
@@ -485,7 +485,7 @@ Guest I/O never acquires a slot. An unavailable pool skips background cuts; urge
A workspace chunk primary that exhausts its existing assignment wait, or whose
lease fences while serving, exits 75 after fail-closed cleanup bounded by the
existing five-second lease-drain limit. systemd restarts on failure with
RestartSec=5s. Only a master fact naming another replica permits exit 78;
RestartSec=5s. Only a newer master fact naming another replica permits exit 78;
RestartPreventExitStatus=78 suppresses automatic restarts until an operator
explicitly starts the unit. A higher epoch for the same replica retries.
An ACKed planned revocation and a signal stop retain their normal exit status.
@@ -500,14 +500,21 @@ stateDiagram-v2
AwaitingAssignment --> Serving: grant and HEAD claim
AwaitingAssignment --> Exit75: assignment wait exhausted
Serving --> Exit75: lease fence
AwaitingAssignment --> Exit78: master names another replica
Serving --> Exit78: lease fence and another-replica fact
AwaitingAssignment --> Exit78: newer master fact names another replica
Serving --> Exit78: lease fence and newer other-replica fact
Exit75 --> AwaitingAssignment: supervisor starts new process
Exit78 --> AwaitingAssignment: explicit operator start
AwaitingAssignment --> SealedReplay: assigned same-epoch sealed HEAD
SealedReplay --> Exit75: lease fence
SealedReplay --> [*]: signal
Serving --> [*]: revoke ACK or signal
AwaitingAssignment --> Draining: planned revoke owns shutdown; retire startup watcher
Serving --> Draining: planned revoke owns shutdown
SealedReplay --> Draining: planned revoke owns shutdown
Draining --> [*]: stored detached proof and revoke ACK
Draining --> Exit75: ACK unconfirmed
Serving --> [*]: signal
```
GAP-1 exit classification compares a newer other-replica fact with the newest own assignment this process observed, including a locally blocked assignment; historical other facts do not suppress restart. The shared `Host.IsSuperseded` predicate is reused without changing frontend admission. An unconfirmed revocation ACK exits75 with `revoke_ack_unconfirmed`. Restart can retry ACK only while the original revoking lease remains valid; after expiry the revoking/recorded-ACK re-grant guards still refuse, so restart alone cannot resolve that case and operator recovery is required.
Once the resource owner accepts a stop request, startup-monitor cancellation and startup exit choice serialize on the process owner's startup mutex. A delayed startup deadline cannot replace planned drain ownership; success remains unselected until the real guard confirms the stored detached proof's ACK. A wait that already chose sealed replay or stale-local-root diagnostics keeps that disposition even if its context expires at return.
+3 -1
View File
@@ -100,7 +100,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a
| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node (the source itself only for a clean, non-force move), and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` |
| Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` |
| Expired | Granted | Same current holder/epoch, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); a busy authority writer refuses this attempt, otherwise persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001` |
| Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait or lease fence exits 75 after bounded cleanup; only a newer master fact naming another replica exits 78. Revocation ACK and signal retain normal exit. Restart follows the unchanged grant and HEAD-claim gates. | `cmd/blockvolume/process_exit.go` `superviseProcess`, `watchChunkStartup`, `waitWorkspaceStop`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `INV-WS-STARTUP-RETRY-001` |
| Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait or lease fence exits 75 after bounded cleanup; only a newer master fact naming another replica exits 78. Planned drain retires startup monitoring before cleanup; ACK and signal retain normal exit. Restart follows the unchanged grant and HEAD-claim gates. | `cmd/blockvolume/process_exit.go` `superviseProcess`, `watchChunkStartup`, `waitWorkspaceStop`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `INV-WS-STARTUP-RETRY-001` |
| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced <volume>@<expected epoch>`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` |
| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` |
@@ -674,6 +674,8 @@ Notes:
| `INV-WS-STARTUP-RETRY-001` | A workspace primary whose assignment wait ends or lease expires exits 75 after bounded fail-closed cleanup; only a newer master fact naming another replica permits exit 78 without restart. Revocation ACK and signal keep normal exit. The lease and HEAD-claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome` (`core/frontend/durable/provider_startup_outcome_test.go`); `TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake` (`core/frontend/durable/provider_startup_internal_test.go`); `TestWorkspaceRetryUsesNewestOwnAssignment` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE |
- `INV-WS-STARTUP-RETRY-001`: exit 78 is an optimisation, permitted only by a NEWER observed master fact for this volume naming another replica, compared with the latest own assignment observed by this process (zero before any). Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process.
- Startup arbitration: sealed-replay/stale-local-root dispositions suppress the same wait's deadline defer (`TestChunkStartupRetainedDispositionWinsExpiredAttachContext`, `core/frontend/durable/provider_startup_outcome_test.go`). A stop request retires startup monitoring and its atomic-choice callback before resource cleanup; success is chosen only after the guard's ACK (`TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck`, `cmd/blockvolume/process_exit_authority_test.go`). Provider-validated startup selection briefly takes the process startup mutex; cancellation takes only that mutex. No reverse provider-lock acquisition or remote call occurs.
- ACK closeout: the guard sets `revoked` under its mutex before calling `drain` and invoking the stop callback. After a drain reply, its ACK call is bounded by the original lease deadline and 2 s RPC timeout. The existing 3 s closeout wait therefore expires before a newly selected retry's 5 s supervisor bound starts; a prior nonzero decision remains immutable. A restart can ACK the sealed HEAD only while the original revoking lease is still valid. Once it expires, re-grant refuses revoking/ACKed leases: repeated 75 is not recovery of an unconfirmed ACK, and operator recovery is required; no lease or ACK gate is bypassed.
Notes: