From f5eab654a5952ae797dd3e38e8faba43190727cc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 23:40:19 -0800 Subject: [PATCH 01/57] test: reproduce expired startup under real systemd restart policy --- .../startup_systemd_integration_test.go | 256 ++++++++++++++++++ 1 file changed, 256 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go new file mode 100644 index 0000000000..c5686ce13d --- /dev/null +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -0,0 +1,256 @@ +//go:build linux && subprocess && chunkstore_integration && systemd_integration + +package main_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +// Real systemd owns every restart. No test goroutine relaunches the holder. +// The first assertion is RED on GAP-1: the expired startup stays alive. +func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { + if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" { + t.Fatal("explicit booked WSL systemd qualification required; no skip counts as proof") + } + if os.Geteuid() != 0 { + t.Fatal("systemd qualification needs the booked root harness") + } + if os.Getenv("CHUNKSTORE_WEED") == "" { + t.Fatal("real CHUNKSTORE_WEED binary required") + } + if out, err := exec.Command("systemctl", "show", "--property=Version").CombinedOutput(); err != nil { + t.Fatalf("real systemd unavailable: %v %s", err, out) + } + root := t.TempDir() + 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 { + t.Fatalf("real binary build: %v %s", err, out) + } + } + cluster := startWorkspaceWeed(t) + stem := fmt.Sprintf("codex03-gap1-%d", time.Now().UnixNano()) + volume := stem + base := "/" + stem + masterAddr := leaseBinaryAddress(t) + dataAddr, ctrlAddr, statusAddr, nvmeAddr := leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t) + cfg := fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n - id: %s\n size_bytes: 262144\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: r1\n source: existing_replica\n", dataAddr, ctrlAddr, volume) + spec := filepath.Join(root, "cluster.yaml") + if err := os.WriteFile(spec, []byte(cfg), 0600); err != nil { + t.Fatal(err) + } + startGAP1Unit(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) + w4WaitTCP(t, masterAddr, 20*time.Second) + conn, err := grpc.NewClient(masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + ws := control.NewWorkspaceServiceClient(conn) + args := []string{"--master", masterAddr, "--server-id", "s1", "--volume-id", volume, "--replica-id", "r1", + "--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--heartbeat-interval", "200ms", "--t1-readiness", "--status-addr", statusAddr, + "--durable-root", filepath.Join(root, "store"), "--durable-impl", "walstore-chunk", "--durable-blocks", "64", + "--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease", + "--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...) + waitGAP1(t, "bootstrap did not attach under a real lease", 60*time.Second, func() bool { return gap1Operational(t, statusAddr, volume) }) + remote := cluster.remote(t, base+"/"+volume) + before, err := remote.GetHead(context.Background()) + if err != nil || before.Gen == 0 { + t.Fatalf("bootstrap HEAD: %+v %v", before, err) + } + gap1Systemctl(t, "kill", "--signal=KILL", "--kill-whom=main", bootstrap) + waitGAP1(t, "bootstrap still running", 10*time.Second, func() bool { return gap1Unit(t, bootstrap)["MainPID"] == "0" }) + // QueryWorkspace is read-only. Do not renew or advance a fake master clock. + waitGAP1(t, "holder's reported validity never lapsed", 60*time.Second, func() bool { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + s, e := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: volume}) + if e != nil || s.GetLease() == nil { + return false + } + t.Logf("captured master lease: %s", s.String()) + return s.Lease.ValidForNs <= 0 + }) + unit := stem + "-returning" + startGAP1Unit(t, unit, true, filepath.Join(bin, "blockvolume"), args...) + firstPID := gap1Unit(t, unit)["MainPID"] + if firstPID == "0" { + t.Fatal("returning unit did not start a real process") + } + // Existing assignment wait is30s. This is an outer failed-run guard, not + // an injected success delay or a replacement product deadline. + waitGAP1(t, "GAP-1: first startup never exited75; stayed alive non-serving", 45*time.Second, func() bool { + s := gap1Unit(t, unit) + if s["ExecMainStatus"] == "75" { + return true + } + if s["MainPID"] != "0" && s["MainPID"] != firstPID { + t.Fatalf("restart without captured75: %+v", s) + } + return false + }) + waitGAP1(t, "systemd did not restart/regrant/attach", 100*time.Second, func() bool { + s := gap1Unit(t, unit) + n, e := strconv.Atoi(s["NRestarts"]) + if e != nil { + t.Fatalf("invalid captured NRestarts: %+v", s) + } + if n > 2 { + t.Fatalf("barrier retry exceeded three total launches: %+v", s) + } + return n >= 1 && s["MainPID"] != "0" && s["MainPID"] != firstPID && gap1Operational(t, statusAddr, volume) + }) + after, err := remote.GetHead(context.Background()) + 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) + } + // A real control cut must pass the lease and layer gates after restart. + req, err := http.NewRequest(http.MethodPost, "http://"+statusAddr+"/chunk/cut", bytes.NewBufferString(fmt.Sprintf(`{"volumeID":%q,"timeoutMs":3000}`, volume))) + if err != nil { + t.Fatal(err) + } + resp, err := (&http.Client{Timeout: 5 * time.Second}).Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("post-regrant real cut status%d", resp.StatusCode) + } + s := gap1Unit(t, unit) + if s["Result"] == "start-limit-hit" { + t.Fatalf("systemd rate limit hit: %+v", s) + } +} + +func startGAP1Unit(t *testing.T, unit string, restart bool, exe string, args ...string) { + t.Helper() + policy := "no" + if restart { + policy = "on-failure" + } + cmdArgs := []string{"--unit=" + unit, "--property=Type=exec", "--property=Restart=" + policy, "--property=RestartSec=5s", "--property=RestartPreventExitStatus=78", "--property=TimeoutStopSec=10s", "--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) + } + 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 { + 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) + } + ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second) + _ = exec.CommandContext(ctx, "systemctl", "reset-failed", unit).Run() + cancel() + }) +} +func gap1Systemctl(t *testing.T, args ...string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput(); err != nil { + t.Fatalf("systemctl: %v %s", err, out) + } +} +func gap1Unit(t *testing.T, unit string) map[string]string { + t.Helper() + 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").CombinedOutput() + if err != nil { + t.Fatalf("unit show: %v %s", err, b) + } + m := map[string]string{} + for _, l := range strings.Split(strings.TrimSpace(string(b)), "\n") { + k, v, ok := strings.Cut(l, "=") + if ok { + m[k] = v + } + } + for _, key := range []string{"MainPID", "NRestarts", "ExecMainStatus", "Result", "ExecMainStartTimestampMonotonic"} { + if _, ok := m[key]; !ok { + t.Fatalf("captured systemd response lacks %s: %s", key, b) + } + } + t.Logf("captured unit %s: %s", unit, strings.TrimSpace(string(b))) + return m +} +func gap1Operational(t *testing.T, addr, volume string) bool { + t.Helper() + r, e := (&http.Client{Timeout: time.Second}).Get("http://" + addr + "/status/durable?volume=" + volume) + if e != nil { + return false + } + defer r.Body.Close() + var body struct { + Volumes []durable.VolumeStatus `json:"volumes"` + } + if r.StatusCode != http.StatusOK { + return false + } + if e = json.NewDecoder(r.Body).Decode(&body); e != nil { + return false + } + for _, v := range body.Volumes { + if v.VolumeID == volume { + return v.Operational && v.Chunk != nil && v.Chunk.Attached && !v.Chunk.Fenced + } + } + return false +} +func waitGAP1(t *testing.T, what string, bound time.Duration, ready func() bool) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), bound) + defer cancel() + tick := time.NewTicker(200 * time.Millisecond) + defer tick.Stop() + for { + if ready() { + return + } + select { + case <-ctx.Done(): + t.Fatal(what) + case <-tick.C: + } + } +} From 45e24335da93c3e4113cf869b6eb676e6b84aae3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 23:42:00 -0800 Subject: [PATCH 02/57] test: anchor lapse fixture to master expiry and captured status --- .../startup_systemd_integration_test.go | 50 ++++++++++++++----- 1 file changed, 38 insertions(+), 12 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index c5686ce13d..38d20bb177 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -7,6 +7,7 @@ import ( "context" "encoding/json" "fmt" + "io" "net/http" "os" "os/exec" @@ -79,6 +80,17 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { bootstrap := stem + "-bootstrap" startGAP1Unit(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) + t.Logf("captured real status200: status%d body%s", status, payload) + if err != nil || !gap1StatusOperational(status, payload, volume) { + t.Fatalf("real status200 parser control: %v", err) + } + missing, body404, err := gap1Status(statusAddr, volume+"-not-served") + t.Logf("captured real status404: status%d body%s", missing, body404) + if err != nil || missing != http.StatusNotFound || gap1StatusOperational(missing, body404, volume) { + t.Fatalf("real status404 parser control: %v", err) + } remote := cluster.remote(t, base+"/"+volume) before, err := remote.GetHead(context.Background()) if err != nil || before.Gen == 0 { @@ -86,7 +98,10 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { } gap1Systemctl(t, "kill", "--signal=KILL", "--kill-whom=main", bootstrap) waitGAP1(t, "bootstrap still running", 10*time.Second, func() bool { return gap1Unit(t, bootstrap)["MainPID"] == "0" }) - // QueryWorkspace is read-only. Do not renew or advance a fake master clock. + // QueryWorkspace is read-only. These real binaries and this test share + // one WSL kernel wall clock. Use the reported MASTER expiry timestamp, + // not ValidForNs (which ends half a skew earlier and could renew live). + // No product barrier formula or fake master clock is introduced. waitGAP1(t, "holder's reported validity never lapsed", 60*time.Second, func() bool { ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() @@ -95,11 +110,13 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { return false } t.Logf("captured master lease: %s", s.String()) - return s.Lease.ValidForNs <= 0 + return s.Lease.ValidForNs <= 0 && time.Now().UnixNano() >= s.Lease.ExpiresAtNs }) unit := stem + "-returning" startGAP1Unit(t, unit, true, filepath.Join(bin, "blockvolume"), args...) - firstPID := gap1Unit(t, unit)["MainPID"] + first := gap1Unit(t, unit) + t.Logf("captured effective restart policy: %+v", first) + firstPID := first["MainPID"] if firstPID == "0" { t.Fatal("returning unit did not start a real process") } @@ -107,6 +124,9 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { // an injected success delay or a replacement product deadline. waitGAP1(t, "GAP-1: first startup never exited75; stayed alive non-serving", 45*time.Second, func() bool { s := gap1Unit(t, unit) + if gap1Operational(t, statusAddr, volume) { + t.Fatal("fixture returned before the expired-grant barrier: cannot count this as a startup-timeout red") + } if s["ExecMainStatus"] == "75" { return true } @@ -195,7 +215,7 @@ func gap1Unit(t *testing.T, unit string) map[string]string { t.Helper() 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").CombinedOutput() + b, err := exec.CommandContext(ctx, "systemctl", "show", unit, "--property=MainPID,NRestarts,ExecMainStatus,Result,ExecMainStartTimestampMonotonic,RestartUSec,RestartPreventExitStatus,StartLimitBurst,StartLimitIntervalUSec").CombinedOutput() if err != nil { t.Fatalf("unit show: %v %s", err, b) } @@ -214,20 +234,21 @@ func gap1Unit(t *testing.T, unit string) map[string]string { t.Logf("captured unit %s: %s", unit, strings.TrimSpace(string(b))) return m } -func gap1Operational(t *testing.T, addr, volume string) bool { - t.Helper() +func gap1Status(addr, volume string) (int, []byte, error) { r, e := (&http.Client{Timeout: time.Second}).Get("http://" + addr + "/status/durable?volume=" + volume) if e != nil { - return false + return 0, nil, e } defer r.Body.Close() - var body struct { - Volumes []durable.VolumeStatus `json:"volumes"` - } - if r.StatusCode != http.StatusOK { + body, e := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + return r.StatusCode, body, e +} +func gap1StatusOperational(status int, payload []byte, volume string) bool { + if status != http.StatusOK { return false } - if e = json.NewDecoder(r.Body).Decode(&body); e != nil { + var body struct{ Volumes []durable.VolumeStatus } + if json.Unmarshal(payload, &body) != nil { return false } for _, v := range body.Volumes { @@ -237,6 +258,11 @@ func gap1Operational(t *testing.T, addr, volume string) bool { } return false } +func gap1Operational(t *testing.T, addr, volume string) bool { + t.Helper() + status, payload, e := gap1Status(addr, volume) + return e == nil && gap1StatusOperational(status, payload, volume) +} func waitGAP1(t *testing.T, what string, bound time.Duration, ready func() bool) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), bound) From 42e8491478d7524806415c6e9e92967109af5fb5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 23:49:16 -0800 Subject: [PATCH 03/57] test: expose the exhausted chunk assignment wait to its process owner --- .../durable/provider_startup_outcome_test.go | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/provider_startup_outcome_test.go diff --git a/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go b/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go new file mode 100644 index 0000000000..c476da0133 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go @@ -0,0 +1,58 @@ +package durable_test + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// INV-WS-STARTUP-RETRY-001: a bounded authority wait must expose a latched +// outcome to its process owner, rather than merely leaving status not-ready. +func TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome(t *testing.T) { + logs := &lockedLog{} + captureWriteLogs(t, logs) + v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, + BlockSize: 4096, ChunkBlocks: 4, ChunkAssignmentTimeout: time.Millisecond, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { + t.Error("remote reached without authority") + return storage.NewMemChunkRemote(), nil + }, + }, v) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + v.active.Store(true) + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + waitLog(t, logs, "assignment unavailable, not serving") + outcomes, ok := any(p).(interface{ ChunkStartupOutcome(string) (uint64, bool) }) + if !ok { + t.Fatal("assignment wait ended without a process-owner outcome; process stays up forever") + } + gen, failed := outcomes.ChunkStartupOutcome("v1") + if !failed || gen != 1 { + t.Fatalf("timeout outcome = generation %d, failed %v; want current generation 1", gen, failed) + } + if again, ok := outcomes.ChunkStartupOutcome("v1"); !ok || again != gen { + t.Fatal("outcome was consumed rather than latched") + } + if _, ok := outcomes.ChunkStartupOutcome("other"); ok { + t.Fatal("outcome escaped its volume") + } + if err := p.Close(); err != nil { + t.Fatal(err) + } + if _, ok := outcomes.ChunkStartupOutcome("v1"); ok { + t.Fatal("closed provider retained an actionable outcome") + } +} From 5d730c1ecc752a367d7a3ea76bb0c6861b7512b4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 23:52:54 -0800 Subject: [PATCH 04/57] fix: latch exhausted workspace startup and bound process retry exit --- seaweed-block/cmd/blockvolume/main.go | 32 ++-- seaweed-block/cmd/blockvolume/process_exit.go | 143 ++++++++++++++++++ .../cmd/blockvolume/process_exit_test.go | 73 +++++++++ .../core/frontend/durable/provider.go | 24 +-- .../core/frontend/durable/provider_chunk.go | 6 + .../core/frontend/durable/provider_startup.go | 32 ++++ .../durable/provider_startup_internal_test.go | 24 +++ .../core/host/volume/workspace_lease.go | 6 +- .../core/host/volume/workspace_runtime.go | 12 ++ seaweed-block/deploy/config/blockmaster.env | 7 +- .../systemd/sw-blockvolume-ublk.service | 1 + .../deploy/systemd/sw-blockvolume.service | 1 + .../docs/design/agent-workspace-design.md | 14 ++ seaweed-block/docs/design/invariants.md | 6 +- 14 files changed, 343 insertions(+), 38 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/process_exit.go create mode 100644 seaweed-block/cmd/blockvolume/process_exit_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_startup.go create mode 100644 seaweed-block/core/frontend/durable/provider_startup_internal_test.go diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 73f0176fd2..7dc91a37d7 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -13,12 +13,10 @@ import ( "net" "os" "os/exec" - "os/signal" "path/filepath" "runtime/debug" "strconv" "strings" - "syscall" "time" "github.com/seaweedfs/seaweed-block/core/adapter" @@ -584,7 +582,7 @@ func durableCreateGeometry(f flags) (uint32, int, error) { return uint32(f.durableBlocks), int(f.durableBlockSize), nil } -func run(f flags) int { +func runVolume(f flags, exits *processExit) int { // Diagnostics first: parseFlags validated the directory, and nothing // has been activated yet, so a failure here leaves nothing to clean up. stopProfile, err := startCPUProfileSignal(f.cpuProfileDir) @@ -719,6 +717,9 @@ func run(f flags) int { return 1 } durableProv = dp + watchCtx, stopWatch := context.WithCancel(exits.parent) + defer stopWatch() + go watchChunkStartup(watchCtx, exits, f, h, dp) provider = dp if status != nil { status.SetDurableStatusSource(dp) @@ -772,7 +773,7 @@ func run(f flags) int { return 1 case durableStartupFaulted: fmt.Fprintln(os.Stderr, "blockvolume: durable recovery failed:", evidence) - return waitFaultedDurableRecovery(h, status, durableProv, evidence) + return waitFaultedDurableRecovery(exits.done, h, status, durableProv, evidence) default: fmt.Fprintln(os.Stderr, "blockvolume: durable recovered:", evidence) } @@ -1245,25 +1246,13 @@ func run(f flags) int { }) } - shutdownCtx, stopSignals := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) - defer stopSignals() + shutdownCtx := exits.parent var leaseRequests <-chan workspaceStopRequest var leaseDone <-chan error if f.workspaceLease { leaseRequests, leaseDone = startWorkspaceLease(shutdownCtx, h) } - var leaseStop *workspaceStopRequest - select { - case <-shutdownCtx.Done(): - case request := <-leaseRequests: - // The lease guard fenced and asks for the drain; it logs its cause as - // "workspace lease: fenced ...". Say here that this is why we stop (#205). - fmt.Fprintln(os.Stderr, "blockvolume: stopping: the workspace lease guard fenced and requested the drain") - leaseStop = &request - case err := <-leaseDone: - fmt.Fprintln(os.Stderr, "blockvolume: workspace lease stopped:", err) - leaseDone = nil - } + leaseStop, leaseDone := waitWorkspaceStop(exits, f, h, leaseRequests, leaseDone) // The main goroutine owns shutdown. The lease callback waits for this // exact drain; it cannot ACK a merely requested or failed close. h.FenceWorkspaceLease() @@ -1477,12 +1466,9 @@ func rdmaBindAddressFact(listen string) volume.FrontendTransportPreflightFact { return volume.FrontendTransportPreflightFact{Name: "rdma_bind_address", Available: true, Reason: "rdma_bind_address_candidate", Detail: host} } -func waitFaultedDurableRecovery(h *volume.Host, status *volume.StatusServer, durableProv *durable.DurableProvider, evidence string) int { +func waitFaultedDurableRecovery(stop <-chan struct{}, h *volume.Host, status *volume.StatusServer, durableProv *durable.DurableProvider, evidence string) int { fmt.Fprintln(os.Stderr, "blockvolume: durable recovery faulted; status endpoint remains available and local readiness remains blocked:", evidence) - sig := make(chan os.Signal, 1) - signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) - <-sig - signal.Stop(sig) + <-stop if durableProv != nil { _ = durableProv.Close() diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go new file mode 100644 index 0000000000..29ee1e8497 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -0,0 +1,143 @@ +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "sync" + "syscall" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +const ( + exitWorkspaceRetry = 75 + exitWorkspaceSuperseded = 78 +) + +type workspaceExit struct { + code int + reason string +} + +// 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{} + outcome workspaceExit +} + +func newProcessExit(ctx context.Context) *processExit { + return &processExit{parent: ctx, done: make(chan struct{})} +} +func (e *processExit) choose(out workspaceExit) { + e.once.Do(func() { + if e.parent.Err() != nil { + out = workspaceExit{reason: "signal"} + } + e.outcome = out + close(e.done) + }) +} + +// The original resource owner still drains everything. This outer process +// owner bounds even a stuck Close or deferred cleanup; main alone calls Exit. +func run(f flags) int { + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + return superviseProcess(ctx, func(e *processExit) int { return runVolume(f, e) }) +} + +func superviseProcess(ctx context.Context, work func(*processExit) int) int { + e := newProcessExit(ctx) + finished := make(chan int, 1) + go func() { finished <- work(e) }() + select { + case code := <-finished: + select { + case <-e.done: + return reportWorkspaceExit(e.outcome) + default: + return code + } + case <-ctx.Done(): + e.choose(workspaceExit{reason: "signal"}) + case <-e.done: + } + if e.outcome.code == 0 { + return <-finished + } + timer := time.NewTimer(volume.WorkspaceDrainTimeout) + defer timer.Stop() + return finishWorkspaceExit(e.outcome, finished, timer.C) +} + +func finishWorkspaceExit(out workspaceExit, finished <-chan int, deadline <-chan time.Time) int { + select { + case <-finished: + case <-deadline: + } + return reportWorkspaceExit(out) +} + +func reportWorkspaceExit(out workspaceExit) int { + if out.code != 0 { + fmt.Fprintf(os.Stderr, "blockvolume: exiting status=%d reason=%s\n", out.code, out.reason) + } + return out.code +} + +// Only a positive, volume-specific other-replica fact permits no-retry. A +// higher epoch for the same replica must restart for the new assignment. +func workspaceRetryOutcome(volumeID, replicaID, reason string, other *control.AssignmentFact) workspaceExit { + if other != nil && other.VolumeId == volumeID && other.ReplicaId != "" && other.ReplicaId != replicaID { + return workspaceExit{exitWorkspaceSuperseded, "superseded"} + } + return workspaceExit{exitWorkspaceRetry, reason} +} + +func watchChunkStartup(ctx context.Context, e *processExit, f flags, h *volume.Host, p *durable.DurableProvider) { + if !f.workspaceLease || f.durableImpl != "walstore-chunk" { + return + } + for { + if _, failed := p.ChunkStartupOutcome(f.volumeID); failed { + e.choose(workspaceRetryOutcome(f.volumeID, f.replicaID, "assignment_timeout", h.LastOtherLine())) + return + } + select { + case <-ctx.Done(): + return + case <-e.done: + return + case <-p.ChunkStartupUpdates(): + } + } +} + +func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan workspaceStopRequest, done <-chan error) (*workspaceStopRequest, <-chan error) { + select { + case <-e.parent.Done(): + e.choose(workspaceExit{reason: "signal"}) + return nil, done + case <-e.done: + return nil, done + case request := <-requests: + out := workspaceExit{reason: "revoked"} + if !h.WorkspaceLeaseRevoking() { + out = workspaceRetryOutcome(f.volumeID, f.replicaID, "lease_expired", h.LastOtherLine()) + } + e.choose(out) + return &request, done + case err := <-done: + fmt.Fprintln(os.Stderr, "blockvolume: workspace lease stopped:", err) + e.choose(workspaceRetryOutcome(f.volumeID, f.replicaID, "lease_expired", h.LastOtherLine())) + return nil, nil + } +} diff --git a/seaweed-block/cmd/blockvolume/process_exit_test.go b/seaweed-block/cmd/blockvolume/process_exit_test.go new file mode 100644 index 0000000000..7a570a7ae0 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/process_exit_test.go @@ -0,0 +1,73 @@ +package main + +import ( + "context" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "testing" + "time" +) + +func TestWorkspaceRetryNeedsPositiveOtherReplica(t *testing.T) { + for _, tc := range []struct { + name string + fact *control.AssignmentFact + code int + }{ + {"absent", nil, 75}, + {"same replica higher epoch", &control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 99}, 75}, + {"another volume", &control.AssignmentFact{VolumeId: "other", ReplicaId: "other"}, 75}, + {"empty holder", &control.AssignmentFact{VolumeId: "v"}, 75}, + {"other replica", &control.AssignmentFact{VolumeId: "v", ReplicaId: "other"}, 78}, + } { + t.Run(tc.name, func(t *testing.T) { + out := workspaceRetryOutcome("v", "r", "assignment_timeout", tc.fact) + if out.code != tc.code { + t.Fatalf("outcome=%+v want %d", out, tc.code) + } + }) + } +} + +func TestWorkspaceExitFirstOutcomeIsLatched(t *testing.T) { + for _, first := range []workspaceExit{{75, "lease_expired"}, {78, "superseded"}, {0, "revoked"}} { + e := newProcessExit(context.Background()) + e.choose(first) + e.choose(workspaceExit{75, "assignment_timeout"}) + <-e.done + if e.outcome != first { + t.Fatalf("first=%+v changed to %+v", first, e.outcome) + } + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + e := newProcessExit(ctx) + e.choose(workspaceExit{78, "superseded"}) + if e.outcome.code != 0 || e.outcome.reason != "signal" { + t.Fatalf("observed signal lost: %+v", e.outcome) + } +} + +func TestWorkspaceExitDoesNotWaitForBlockedFrontendClose(t *testing.T) { + finished := make(chan int) // a frontend Close that never returns + deadline := make(chan time.Time, 1) + deadline <- time.Time{} + if code := finishWorkspaceExit(workspaceExit{75, "lease_expired"}, finished, deadline); code != 75 { + t.Fatalf("code=%d", code) + } + // Cleanup errors do not overwrite an already selected retry/no-retry status. + done := make(chan int, 1) + done <- 1 + if code := finishWorkspaceExit(workspaceExit{78, "superseded"}, done, make(chan time.Time)); code != 78 { + t.Fatalf("code=%d", code) + } +} + +func TestWorkspacePlannedStopKeepsSuccess(t *testing.T) { + code := superviseProcess(context.Background(), func(e *processExit) int { + e.choose(workspaceExit{reason: "revoked"}) + return 0 // the close/ACK owner completed normally + }) + if code != 0 { + t.Fatalf("planned stop would restart: %d", code) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 83aa2241ad..d5b282877c 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -233,10 +233,11 @@ type DurableProvider struct { cfg ProviderConfig view frontend.ProjectionView - mu sync.Mutex - volumes map[string]*volHandle // keyed by volumeID - opening map[string]*sync.Mutex // keyed by volumeID; serializes open/create - closed bool + mu sync.Mutex + volumes map[string]*volHandle // keyed by volumeID + opening map[string]*sync.Mutex // keyed by volumeID; serializes open/create + closed bool + startupUpdates chan struct{} // wake only; the generation-bound result stays on the handle // testAfterChunkResolve, test-only, runs in CutVolume right after the // volume's handle and layer are resolved. @@ -286,6 +287,7 @@ type volHandle struct { // latest recovery's. recoverGen uint64 waitGen uint64 + startupEnded uint64 // recovery generation with a terminal startup outcome; guarded by p.mu chunk storage.ChunkLayer // after RecoverVolume chunkLineage chunkLineage // immutable authority captured by this attachment // Private until the owner commit succeeds; retained for attach retry. @@ -392,12 +394,13 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura } closeCtx, closeCancel := context.WithCancel(context.Background()) return &DurableProvider{ - cfg: cfg, - view: view, - volumes: map[string]*volHandle{}, - opening: map[string]*sync.Mutex{}, - closeCtx: closeCtx, - closeCancel: closeCancel, + cfg: cfg, + view: view, + volumes: map[string]*volHandle{}, + opening: map[string]*sync.Mutex{}, + closeCtx: closeCtx, + closeCancel: closeCancel, + startupUpdates: make(chan struct{}, 1), }, nil } @@ -947,6 +950,7 @@ func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (R p.mu.Lock() h.recoverGen++ // any earlier recovery's authority wait is now stale gen = h.recoverGen + h.startupEnded = 0 p.mu.Unlock() } report := Recover(h.storage, volumeID) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 7018eb0363..706be6bcf1 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -124,6 +124,9 @@ func (p *DurableProvider) recoverChunk(ctx context.Context, volumeID string, h * p.startChunkAuthorityWait(volumeID, h, gen) return false, nil } + if errors.Is(err, storage.ErrChunkLayerFenced) && !errors.Is(err, ErrChunkStaleLocalRoot) { + p.endChunkStartup(h, gen) + } return err == nil, err } @@ -173,6 +176,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen if p.current(h, gen) && h.chunk == nil { ended = fmt.Sprintf("assignment unavailable, not serving (projection lacks %s)", chunkAuthorityGap(p.view.Projection(), volumeID)) h.backend.SetOperational(false, "chunk assignment unavailable: "+waitCtx.Err().Error()) + p.endChunkStartup(h, gen) } }() defer func() { @@ -237,6 +241,8 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen h.backend.SetOperational(false, "chunk layer attach refused: "+err.Error()) } h.attachMu.Unlock() + } else { + p.endChunkStartup(h, gen) } return case errors.Is(err, errChunkNoAuthority): diff --git a/seaweed-block/core/frontend/durable/provider_startup.go b/seaweed-block/core/frontend/durable/provider_startup.go new file mode 100644 index 0000000000..7efc2b75af --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_startup.go @@ -0,0 +1,32 @@ +package durable + +// ChunkStartupUpdates wakes the process owner when a startup wait ends. It is +// not an event queue: the owner must read ChunkStartupOutcome for its volume. +// INV-WS-STARTUP-RETRY-001 keeps stale recoveries from terminating a newer one. +func (p *DurableProvider) ChunkStartupUpdates() <-chan struct{} { return p.startupUpdates } + +// ChunkStartupOutcome is a latched, generation-bound startup failure. A new +// recovery or Close invalidates it; reading it does not consume it. It grants +// no assignment and makes no claim about whether this holder was superseded. +func (p *DurableProvider) ChunkStartupOutcome(volumeID string) (uint64, bool) { + p.mu.Lock() + defer p.mu.Unlock() + h := p.volumes[volumeID] + if p.closed || h == nil || h.startupEnded == 0 || h.startupEnded != h.recoverGen { + return 0, false + } + return h.startupEnded, true +} + +func (p *DurableProvider) endChunkStartup(h *volHandle, gen uint64) { + p.mu.Lock() + defer p.mu.Unlock() + if p.closed || gen != h.recoverGen || h.startupEnded != 0 { + return + } + h.startupEnded = gen + select { + case p.startupUpdates <- struct{}{}: + default: + } +} diff --git a/seaweed-block/core/frontend/durable/provider_startup_internal_test.go b/seaweed-block/core/frontend/durable/provider_startup_internal_test.go new file mode 100644 index 0000000000..6d747b639d --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_startup_internal_test.go @@ -0,0 +1,24 @@ +package durable + +import "testing" + +func TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake(t *testing.T) { + h := &volHandle{recoverGen: 1} + p := &DurableProvider{volumes: map[string]*volHandle{"v": h}, startupUpdates: make(chan struct{}, 1)} + p.endChunkStartup(h, 1) + h.recoverGen = 2 + h.startupEnded = 0 // RecoverVolume invalidates the old generation under p.mu. + p.endChunkStartup(h, 1) + if _, ok := p.ChunkStartupOutcome("v"); ok { + t.Fatal("stale wait ended the new recovery") + } + p.endChunkStartup(h, 2) // full wake channel must not discard the current latched result + <-p.ChunkStartupUpdates() + if gen, ok := p.ChunkStartupOutcome("v"); !ok || gen != 2 { + t.Fatalf("current result lost: %d %v", gen, ok) + } + p.endChunkStartup(h, 1) + if gen, ok := p.ChunkStartupOutcome("v"); !ok || gen != 2 { + t.Fatal("late old completion overwrote the current result") + } +} diff --git a/seaweed-block/core/host/volume/workspace_lease.go b/seaweed-block/core/host/volume/workspace_lease.go index 3a829129a8..339cfc1383 100644 --- a/seaweed-block/core/host/volume/workspace_lease.go +++ b/seaweed-block/core/host/volume/workspace_lease.go @@ -57,6 +57,10 @@ type WorkspaceLeaseGuard struct { // revocation to its ACK also includes that renewal, the drain and the ACK. const stopPendingPoll = 250 * time.Millisecond +// WorkspaceDrainTimeout is the existing fail-closed lease drain bound. +// INV-WS-STARTUP-RETRY-001 also bounds the process cleanup by this duration. +const WorkspaceDrainTimeout = 5 * time.Second + // StopPending records that a graceful stop of this workspace has begun (the // chunk layer is being detached) and wakes Run to renew at once; while it // stays pending Run sleeps at most stopPendingPoll between renewals. @@ -280,7 +284,7 @@ func (g *WorkspaceLeaseGuard) drainAfterFence(ctx context.Context, err error) er func (g *WorkspaceLeaseGuard) drain(parent context.Context, ack bool) error { if !g.stopped { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), WorkspaceDrainTimeout) gen, err := g.stop(ctx) cancel() if err != nil { diff --git a/seaweed-block/core/host/volume/workspace_runtime.go b/seaweed-block/core/host/volume/workspace_runtime.go index 13e8d55c15..d6fad91ccf 100644 --- a/seaweed-block/core/host/volume/workspace_runtime.go +++ b/seaweed-block/core/host/volume/workspace_runtime.go @@ -110,3 +110,15 @@ func (h *Host) FenceWorkspaceLease() { g.mu.Unlock() } } + +// WorkspaceLeaseRevoking distinguishes the ACK-owning planned drain from a +// retryable fence without interpreting an error string (M2 Revoking -> Revoked). +func (h *Host) WorkspaceLeaseRevoking() bool { + g := h.view.workspaceGuard.Load() + if g == nil { + return false + } + g.mu.Lock() + defer g.mu.Unlock() + return g.revoked +} diff --git a/seaweed-block/deploy/config/blockmaster.env b/seaweed-block/deploy/config/blockmaster.env index 4c160d497b..3169518dff 100644 --- a/seaweed-block/deploy/config/blockmaster.env +++ b/seaweed-block/deploy/config/blockmaster.env @@ -39,7 +39,8 @@ SWB_MASTER_WORKSPACE_HEAD_BASE_URL= # --workspace-max-clock-skew (default 20s; must be >0 and <60s). Host leases # shorten by half of it; forced moves wait the full bound. SWB_MASTER_WORKSPACE_MAX_CLOCK_SKEW=20s -# Extra blockmaster flags, split on spaces. The --launcher-*, --lifecycle-*, -# --cluster-spec, --failback-runtime-rpc and --frontend-publication-runtime-* -# flags belong to the Kubernetes path and are set by the Helm chart. +# Extra blockmaster flags, split on spaces. +# A standalone workspace volume (lease, planned hand-over) needs --cluster-spec, +# --lifecycle-store and the --workspace-* flags here: see docs/volume-lifecycle.md. +# Kubernetes launcher/runtime flags are configured separately by the Helm chart. SWB_MASTER_EXTRA_ARGS= diff --git a/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service b/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service index 50a3ca26f8..ee1904fa86 100644 --- a/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service +++ b/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service @@ -69,6 +69,7 @@ ExecStart=/usr/local/bin/blockvolume \ KillSignal=SIGTERM TimeoutStopSec=30s Restart=on-failure +RestartPreventExitStatus=78 RestartSec=5s NoNewPrivileges=true diff --git a/seaweed-block/deploy/systemd/sw-blockvolume.service b/seaweed-block/deploy/systemd/sw-blockvolume.service index 6cbcb6a6fa..7ad8a3ed5e 100644 --- a/seaweed-block/deploy/systemd/sw-blockvolume.service +++ b/seaweed-block/deploy/systemd/sw-blockvolume.service @@ -68,6 +68,7 @@ ExecStart=/usr/local/bin/blockvolume \ KillSignal=SIGTERM TimeoutStopSec=30s Restart=on-failure +RestartPreventExitStatus=78 RestartSec=5s NoNewPrivileges=true diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 7679f68611..cd498ef1bf 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -479,3 +479,17 @@ stateDiagram-v2 ``` Guest I/O never acquires a slot. An unavailable pool skips background cuts; urgent and named seals may use per-process fallback with an alarm. Active coordinated reservations exclude orphaned crash spill. Upload pacing debt survives leases in one process, but a new process starts fresh, so arbitrary process turnover has no fixed host-rate bound. + +### Workspace primary supervisor retry + +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; +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. +Sealed same-epoch recovery stays non-serving for seal replay after assignment. +Local-root, WAL-corruption and I/O diagnostics retain their existing wait. +No restart bypasses the master barrier, durable re-grant, or HEAD claim. +See M2 and INV-WS-STARTUP-RETRY-001 in the invariant ledger. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0c566e3b11..5921d64e39 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -100,6 +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 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` | | 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 @`; `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` | @@ -410,7 +411,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -303 rows: 217 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 288 new. +304 rows: 218 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 289 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -670,7 +671,9 @@ Notes: | `INV-WS-FORCED-CONFIRM-LOCAL-001` | A missing or malformed `--confirm-forced` is refused before any connection or RPC, with exit 2. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`; `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `request` | `TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally` (`cmd/sw-block/workspace_test.go`); `TestParseConfirmation` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | +| `INV-WS-STARTUP-RETRY-001` | A workspace primary whose assignment wait ends or lease expires exits 75 after bounded fail-closed cleanup; only a 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`); `TestWorkspaceRetryNeedsPositiveOtherReplica`, `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 an observed master fact for this volume naming another replica. 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. Notes: - `INV-WS-SINGLE-FILER-001`: the same census runs in every `sw-block ops chunk` command that writes chunk metadata (snapshot-delete, fork, retain, volume-delete, gc --apply), and in verify, which writes nothing but would report false findings against a split filer view, before it reads or writes; other read-only commands and modes do not run it. @@ -942,6 +945,7 @@ Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed sc | Wait | Machine / invariant | Bound | Release and cancellation | Locks / remote work | |---|---|---|---|---| +| Workspace primary retry cleanup | M2 restart; `INV-WS-STARTUP-RETRY-001` | Existing `WorkspaceDrainTimeout` (5 s) after retry/no-retry outcome selection | Process supervisor owns the deadline and returns 75 or 78 even if resource-owner cleanup blocks; first outcome stays latched. Signal and ACKed revocation retain normal exit. | Provider latches by recovery generation under p.mu; wake is nonblocking; the supervisor holds no provider/storage lock. | | Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; positive HTTP timeoutMs. Completed uploads resume only within one blockvolume process and matching owner/HEAD/chunk versions; after restart the seal must fit seal_timeout_ms. | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. | | Plain seal remote proof | M5 RemoteProof; `INV-WS-SEAL-REPLAY-001` | Earlier caller context or existing 2 s HEAD-operation bound for the filer read; attachment serialization retains its owner's cooperative caller bound | Provider registers with Close; closeBoundRemote cancels the read, and Close joins it. Failure keeps frontend admission closed. | Attachment mutex serializes against recover/detach; no backend/store/map lock spans the filer read. | | Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` (not reachable in this release) | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. | From 8b4fd25776e81a381d6a9ac235b8f69a826d6e65 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 23:53:57 -0800 Subject: [PATCH 05/57] fix: preserve acknowledged planned-stop status and witness stuck cleanup exit --- seaweed-block/cmd/blockvolume/main.go | 11 +------- seaweed-block/cmd/blockvolume/process_exit.go | 25 ++++++++++++++++++- .../cmd/blockvolume/process_exit_test.go | 24 ++++++++++++++++++ 3 files changed, 49 insertions(+), 11 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 7dc91a37d7..6ef619b49f 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -1305,16 +1305,7 @@ func runVolume(f flags, exits *processExit) int { } leaseStop.reply <- workspaceStopResult{gen: gen, err: drainErr} } - if leaseDone != nil { - select { - case err := <-leaseDone: - if err != nil { - fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout:", err) - } - case <-time.After(3 * time.Second): - fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout deadline") - } - } + finishWorkspaceLease(exits, f, h, leaseDone) if err := h.Close(); err != nil { fmt.Fprintln(os.Stderr, "blockvolume: close:", err) return 1 diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index 29ee1e8497..1c22244168 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -62,6 +62,9 @@ func superviseProcess(ctx context.Context, work func(*processExit) int) int { case code := <-finished: select { case <-e.done: + if e.outcome.code == 0 { + return code + } return reportWorkspaceExit(e.outcome) default: return code @@ -133,7 +136,9 @@ func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan if !h.WorkspaceLeaseRevoking() { out = workspaceRetryOutcome(f.volumeID, f.replicaID, "lease_expired", h.LastOtherLine()) } - e.choose(out) + if out.code != 0 { + e.choose(out) + } return &request, done case err := <-done: fmt.Fprintln(os.Stderr, "blockvolume: workspace lease stopped:", err) @@ -141,3 +146,21 @@ func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan return nil, nil } } + +// An ACKed revocation completes with status zero. A failure to confirm that +// ACK is retryable; a signal observed first still retains the signal status. +func finishWorkspaceLease(e *processExit, f flags, h *volume.Host, done <-chan error) { + if done == nil { + return + } + select { + case err := <-done: + if err == nil { + return + } + fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout:", err) + case <-time.After(3 * time.Second): + fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout deadline") + } + e.choose(workspaceRetryOutcome(f.volumeID, f.replicaID, "lease_expired", h.LastOtherLine())) +} diff --git a/seaweed-block/cmd/blockvolume/process_exit_test.go b/seaweed-block/cmd/blockvolume/process_exit_test.go index 7a570a7ae0..7c0d24a8fe 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_test.go @@ -2,7 +2,10 @@ package main import ( "context" + "errors" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "os" + "os/exec" "testing" "time" ) @@ -71,3 +74,24 @@ func TestWorkspacePlannedStopKeepsSuccess(t *testing.T) { t.Fatalf("planned stop would restart: %d", code) } } + +// A real child process contains the stuck resource owner. An injected event +// tests the select above; this witness also covers deferred-cleanup isolation. +func TestWorkspaceRetryProcessExitsWhenCloseBlocks(t *testing.T) { + if os.Getenv("GAP1_BLOCKED_CLOSE_CHILD") == "1" { + code := superviseProcess(context.Background(), func(e *processExit) int { + e.choose(workspaceExit{75, "lease_expired"}) + select {} // the frontend/resource owner's Close never returns + }) + os.Exit(code) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestWorkspaceRetryProcessExitsWhenCloseBlocks$") + cmd.Env = append(os.Environ(), "GAP1_BLOCKED_CLOSE_CHILD=1") + out, err := cmd.CombinedOutput() + var exit *exec.ExitError + if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 75 { + t.Fatalf("blocked close exit: %v %s", err, out) + } +} From d638377ee6117de199d51f23f47ac18c4d363187 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 23:55:52 -0800 Subject: [PATCH 06/57] test: retain an assigned sealed restart for exact seal replay --- .../durable/provider_startup_outcome_test.go | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go b/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go index c476da0133..b61b3ac534 100644 --- a/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go +++ b/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go @@ -2,6 +2,7 @@ package durable_test import ( "context" + "reflect" "testing" "time" @@ -56,3 +57,47 @@ func TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome(t *testing.T) { t.Fatal("closed provider retained an actionable outcome") } } + +func TestChunkStartupSealedAssignmentStaysForReplay(t *testing.T) { + logs := &lockedLog{} + captureWriteLogs(t, logs) + ctx := hangGuard(t) + remote := storage.NewMemChunkRemote() + root := t.TempDir() + first := chunkProvider(t, root, remote, v1View(), 0) + openRecovered(t, first) + sealed, _, err := first.DetachVolumePlain(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if err := first.Close(); err != nil { + t.Fatal(err) + } + view := v1View() + assigned := view.Projection() + waiting := assigned + waiting.Epoch = 0 + waiting.Healthy = false + view.set(waiting) + second := chunkProvider(t, root, remote, view, 0) + if _, err := second.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := second.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + view.set(assigned) + waitLog(t, logs, "sealed assignment, retained for replay") + if _, failed := second.ChunkStartupOutcome("v1"); failed { + t.Fatal("sealed assignment became a process retry") + } + replay, _, err := second.DetachVolumePlain(ctx, "v1") + if err != nil || !reflect.DeepEqual(replay.Head, sealed.Head) { + t.Fatalf("sealed replay changed: %+v %v", replay, err) + } + for _, status := range second.DurableStatuses() { + if status.Operational { + t.Fatal("sealed restart served") + } + } +} From d060e9ab3f50203f44fcc6690f0bf1a0f6bf6dbb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 23:59:38 -0800 Subject: [PATCH 07/57] fix: retain sealed startup and atomically choose the current recovery exit --- seaweed-block/cmd/blockvolume/main.go | 1 + seaweed-block/cmd/blockvolume/process_exit.go | 16 ++++++++++++++-- .../core/frontend/durable/provider_chunk.go | 6 ++++++ .../core/frontend/durable/provider_startup.go | 15 +++++++++++++++ .../durable/provider_startup_internal_test.go | 16 ++++++++++++++++ 5 files changed, 52 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 6ef619b49f..4e58bc784c 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -760,6 +760,7 @@ func runVolume(f flags, exits *processExit) int { // (wal_corrupt / io_error) faults fail-closed and is reported at // once by a primary assignment; see openAndRecoverDurable. outcome, evidence, sErr := openAndRecoverDurable(dp, h, f.volumeID, 10*time.Second) + chooseChunkStartupExit(exits, f, h, dp) switch outcome { case durableStartupFatal: fmt.Fprintln(os.Stderr, "blockvolume: durable storage open:", sErr) diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index 1c22244168..79e3d673dd 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -110,10 +110,10 @@ func watchChunkStartup(ctx context.Context, e *processExit, f flags, h *volume.H return } for { - if _, failed := p.ChunkStartupOutcome(f.volumeID); failed { - e.choose(workspaceRetryOutcome(f.volumeID, f.replicaID, "assignment_timeout", h.LastOtherLine())) + if chooseChunkStartupExit(e, f, h, p) { return } + select { case <-ctx.Done(): return @@ -164,3 +164,15 @@ func finishWorkspaceLease(e *processExit, f flags, h *volume.Host, done <-chan e } e.choose(workspaceRetryOutcome(f.volumeID, f.replicaID, "lease_expired", h.LastOtherLine())) } + +func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p *durable.DurableProvider) bool { + if !f.workspaceLease || f.durableImpl != "walstore-chunk" { + return false + } + gen, failed := p.ChunkStartupOutcome(f.volumeID) + if !failed { + return false + } + out := workspaceRetryOutcome(f.volumeID, f.replicaID, "assignment_timeout", h.LastOtherLine()) + return p.ChooseChunkStartupExit(f.volumeID, gen, func() { e.choose(out) }) +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 706be6bcf1..206d3e5616 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -232,6 +232,12 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen case errors.Is(err, errProviderClosed): ended = "provider closed" return + 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. + ended = "sealed assignment, retained for replay" + h.backend.SetOperational(false, "sealed assignment; replay only") + return case errors.Is(err, storage.ErrChunkLayerFenced): ended = "fenced, not serving" log.Printf("durable: chunk layer for volume=%s: %v (not serving)", volumeID, err) diff --git a/seaweed-block/core/frontend/durable/provider_startup.go b/seaweed-block/core/frontend/durable/provider_startup.go index 7efc2b75af..ff61f0978d 100644 --- a/seaweed-block/core/frontend/durable/provider_startup.go +++ b/seaweed-block/core/frontend/durable/provider_startup.go @@ -30,3 +30,18 @@ func (p *DurableProvider) endChunkStartup(h *volHandle, gen uint64) { default: } } + +// ChooseChunkStartupExit validates and selects an outcome in one provider-lock +// section, so recovery cannot change generation between observation and choice. +// choose must only latch the process outcome; it must not block or call back +// into the provider. No remote work or resource cleanup belongs in this call. +func (p *DurableProvider) ChooseChunkStartupExit(volumeID string, gen uint64, choose func()) bool { + p.mu.Lock() + defer p.mu.Unlock() + h := p.volumes[volumeID] + if p.closed || h == nil || h.startupEnded != gen || gen == 0 || h.recoverGen != gen { + return false + } + choose() + return true +} diff --git a/seaweed-block/core/frontend/durable/provider_startup_internal_test.go b/seaweed-block/core/frontend/durable/provider_startup_internal_test.go index 6d747b639d..61fff6fdb6 100644 --- a/seaweed-block/core/frontend/durable/provider_startup_internal_test.go +++ b/seaweed-block/core/frontend/durable/provider_startup_internal_test.go @@ -22,3 +22,19 @@ func TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake(t *testing.T) { t.Fatal("late old completion overwrote the current result") } } + +func TestChunkStartupExitRechecksGenerationBeforeChoice(t *testing.T) { + h := &volHandle{recoverGen: 2, startupEnded: 2} + p := &DurableProvider{volumes: map[string]*volHandle{"v": h}} + calls := 0 + if p.ChooseChunkStartupExit("v", 1, func() { calls++ }) || calls != 0 { + t.Fatal("stale observation selected process exit") + } + if !p.ChooseChunkStartupExit("v", 2, func() { calls++ }) || calls != 1 { + t.Fatal("current result was not selectable") + } + p.closed = true + if p.ChooseChunkStartupExit("v", 2, func() { calls++ }) || calls != 1 { + t.Fatal("closed provider selected exit") + } +} From 2170b6449a94063831d99102ab88f9689480c58f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:02:58 -0800 Subject: [PATCH 08/57] test: qualify systemd with the shipped workspace restart policy --- .../startup_systemd_integration_test.go | 39 ++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index 38d20bb177..676e91017c 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -175,7 +175,12 @@ func startGAP1Unit(t *testing.T, unit string, restart bool, exe string, args ... if restart { policy = "on-failure" } - cmdArgs := []string{"--unit=" + unit, "--property=Type=exec", "--property=Restart=" + policy, "--property=RestartSec=5s", "--property=RestartPreventExitStatus=78", "--property=TimeoutStopSec=10s", "--property=StartLimitIntervalSec=10s", "--property=StartLimitBurst=5", "--", exe} + 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 = append(cmdArgs, args...) ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() @@ -280,3 +285,35 @@ func waitGAP1(t *testing.T, what string, bound time.Duration, ready func() bool) } } } + +// The transient unit exercises the shipped restart policy, not an independently +// tuned retry loop. Both deployed frontend variants must carry the same policy. +func gap1ShippedPolicy(t *testing.T) map[string]string { + t.Helper() + var first map[string]string + for _, name := range []string{"sw-blockvolume.service", "sw-blockvolume-ublk.service"} { + raw, err := os.ReadFile(filepath.Join("..", "..", "deploy", "systemd", name)) + if err != nil { + t.Fatal(err) + } + fields := map[string]string{} + for _, line := range strings.Split(string(raw), "\n") { + key, value, ok := strings.Cut(strings.TrimSpace(line), "=") + if ok { + fields[key] = value + } + } + if fields["Restart"] != "on-failure" || fields["RestartPreventExitStatus"] != "78" || fields["RestartSec"] != "5s" { + t.Fatalf("shipped policy changed: %s %+v", name, fields) + } + if first != nil { + for _, key := range []string{"Restart", "RestartSec", "RestartPreventExitStatus", "TimeoutStopSec"} { + if fields[key] != first[key] { + t.Fatalf("unit policies differ at %s", key) + } + } + } + first = fields + } + return first +} From 0d564ec2135ebb971043abe0aacb2329065bb38b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:04:03 -0800 Subject: [PATCH 09/57] test: require recorded revoke ACK and terminal systemd success after planned stop --- .../startup_systemd_integration_test.go | 53 ++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index 676e91017c..e251aaf4cc 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -167,6 +167,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { if s["Result"] == "start-limit-hit" { t.Fatalf("systemd rate limit hit: %+v", s) } + gap1PlannedStopDoesNotRestart(t, ws, unit, statusAddr, volume, after.Epoch, after.Holder, s["NRestarts"]) } func startGAP1Unit(t *testing.T, unit string, restart bool, exe string, args ...string) { @@ -220,7 +221,7 @@ func gap1Unit(t *testing.T, unit string) map[string]string { t.Helper() 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").CombinedOutput() + b, err := exec.CommandContext(ctx, "systemctl", "show", unit, "--property=MainPID,NRestarts,ExecMainStatus,Result,ExecMainStartTimestampMonotonic,RestartUSec,RestartPreventExitStatus,StartLimitBurst,StartLimitIntervalUSec,ActiveState,SubState").CombinedOutput() if err != nil { t.Fatalf("unit show: %v %s", err, b) } @@ -317,3 +318,53 @@ func gap1ShippedPolicy(t *testing.T) map[string]string { } return first } + +// A successful planned revoke is not a retry outcome. The master's ACK and +// systemd's terminal inactive/dead state prove no automatic restart is queued. +func gap1PlannedStopDoesNotRestart(t *testing.T, ws control.WorkspaceServiceClient, unit, addr, volume string, epoch uint64, holder, restarts string) { + t.Helper() + req, err := http.NewRequest(http.MethodPost, "http://"+addr+"/chunk/detach", bytes.NewBufferString(fmt.Sprintf(`{"volumeID":%q,"plain":true,"timeoutMs":5000}`, volume))) + if err != nil { + t.Fatal(err) + } + resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req) + if err != nil { + t.Fatal(err) + } + body, readErr := io.ReadAll(resp.Body) + _ = resp.Body.Close() + t.Logf("captured plain seal response: status%d body%s", resp.StatusCode, body) + if readErr != nil || resp.StatusCode != http.StatusOK { + t.Fatalf("plain seal: %v status%d", readErr, resp.StatusCode) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + _, err = ws.RevokeWorkspace(ctx, &control.WorkspaceIdentity{VolumeId: volume, ReplicaId: holder, Epoch: epoch}) + cancel() + if err != nil { + t.Fatal(err) + } + waitGAP1(t, "planned revoke never recorded ACK and exited normally", 20*time.Second, func() bool { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + status, err := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: volume}) + if err != nil || status.GetRevocationAck() == nil { + return false + } + ack := status.GetRevocationAck() + t.Logf("captured planned-stop ACK: %s", ack.String()) + if ack.GetIdentity().GetVolumeId() != volume || ack.GetIdentity().GetReplicaId() != holder || ack.GetIdentity().GetEpoch() != epoch || ack.GetHeadGen() == 0 { + t.Fatalf("wrong planned ACK: %s", ack.String()) + } + state := gap1Unit(t, unit) + if state["NRestarts"] != restarts { + t.Fatalf("planned stop restarted: %+v", state) + } + if state["MainPID"] != "0" { + return false + } + if state["ExecMainStatus"] != "0" || state["ActiveState"] != "inactive" || state["SubState"] != "dead" { + t.Fatalf("planned stop is not terminal success: %+v", state) + } + return true + }) +} From 41dfb5ec901d913229e04e78b8e65ce1e11a8e5a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:06:21 -0800 Subject: [PATCH 10/57] docs: trace workspace process exits and show supervisor restart lifecycle --- seaweed-block/cmd/blockvolume/main.go | 2 +- seaweed-block/cmd/blockvolume/process_exit.go | 7 ++++++- .../docs/design/agent-workspace-design.md | 16 ++++++++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 4e58bc784c..65dcfc3e5c 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -1254,7 +1254,7 @@ func runVolume(f flags, exits *processExit) int { leaseRequests, leaseDone = startWorkspaceLease(shutdownCtx, h) } leaseStop, leaseDone := waitWorkspaceStop(exits, f, h, leaseRequests, leaseDone) - // The main goroutine owns shutdown. The lease callback waits for this + // The resource owner performs shutdown. The lease callback waits for this // exact drain; it cannot ACK a merely requested or failed close. h.FenceWorkspaceLease() var drainErr error diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index 79e3d673dd..48b79fb064 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -54,6 +54,7 @@ func run(f flags) int { return superviseProcess(ctx, func(e *processExit) int { return runVolume(f, e) }) } +// INV-WS-STARTUP-RETRY-001: M2 process exit owns the cleanup bound. func superviseProcess(ctx context.Context, work func(*processExit) int) int { e := newProcessExit(ctx) finished := make(chan int, 1) @@ -96,7 +97,8 @@ func reportWorkspaceExit(out workspaceExit) int { return out.code } -// Only a positive, volume-specific other-replica fact permits no-retry. A +// INV-WS-STARTUP-RETRY-001: only a positive, volume-specific other-replica +// fact permits no-retry. A // higher epoch for the same replica must restart for the new assignment. func workspaceRetryOutcome(volumeID, replicaID, reason string, other *control.AssignmentFact) workspaceExit { if other != nil && other.VolumeId == volumeID && other.ReplicaId != "" && other.ReplicaId != replicaID { @@ -105,6 +107,7 @@ func workspaceRetryOutcome(volumeID, replicaID, reason string, other *control.As return workspaceExit{exitWorkspaceRetry, reason} } +// M2 startup outcome; INV-WS-STARTUP-RETRY-001. Workspace chunk primaries only. func watchChunkStartup(ctx context.Context, e *processExit, f flags, h *volume.Host, p *durable.DurableProvider) { if !f.workspaceLease || f.durableImpl != "walstore-chunk" { return @@ -124,6 +127,7 @@ func watchChunkStartup(ctx context.Context, e *processExit, f flags, h *volume.H } } +// M2 process exit / Revoking -> Revoked; INV-WS-STARTUP-RETRY-001. func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan workspaceStopRequest, done <-chan error) (*workspaceStopRequest, <-chan error) { select { case <-e.parent.Done(): @@ -149,6 +153,7 @@ func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan // An ACKed revocation completes with status zero. A failure to confirm that // ACK is retryable; a signal observed first still retains the signal status. +// M2 Revoking -> Revoked; INV-WS-REVOKE-ACK-001, INV-WS-STARTUP-RETRY-001. func finishWorkspaceLease(e *processExit, f flags, h *volume.Host, done <-chan error) { if done == nil { return diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index cd498ef1bf..9eab6ab1b6 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -493,3 +493,19 @@ Sealed same-epoch recovery stays non-serving for seal replay after assignment. Local-root, WAL-corruption and I/O diagnostics retain their existing wait. No restart bypasses the master barrier, durable re-grant, or HEAD claim. See M2 and INV-WS-STARTUP-RETRY-001 in the invariant ledger. + +```mermaid +stateDiagram-v2 + [*] --> AwaitingAssignment + 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 + 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 +``` From b257486f3ee7c9df82f56b435fcae5359173c659 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:12:21 -0800 Subject: [PATCH 11/57] test: verify flushed NVMe records before and after supervised holder return --- .../startup_nvme_integration_test.go | 179 ++++++++++++++++++ .../startup_systemd_integration_test.go | 10 + 2 files changed, 189 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go b/seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go new file mode 100644 index 0000000000..247faffe94 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go @@ -0,0 +1,179 @@ +//go:build linux && subprocess && chunkstore_integration && systemd_integration + +package main_test + +import ( + "bytes" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" +) + +// This small initiator uses the same exported wire types and admin/IO queue +// handshake as core/frontend/nvme/client_support_test.go. It talks only to the +// real blockvolume in this harness; no kernel device or unrelated NQN is used. +type gap1NVMe struct { + admin, io net.Conn + r *nvme.Reader + w *nvme.Writer + cid uint16 +} + +func gap1ConnectNVMe(t *testing.T, addr, nqn string) *gap1NVMe { + t.Helper() + c := &gap1NVMe{} + t.Cleanup(c.close) + var controller uint16 = 0xffff + for q := uint16(0); q < 2; q++ { + conn, err := net.DialTimeout("tcp", addr, 5*time.Second) + if err != nil { + t.Fatal(err) + } + if q == 0 { + c.admin = conn + } else { + c.io = conn + } + _ = conn.SetDeadline(time.Now().Add(10 * time.Second)) + r, w := nvme.NewReader(conn), nvme.NewWriter(conn) + if err := w.SendHeaderOnly(0, &nvme.ICRequest{PDUFormatVersion: 0, PDUMaxR2T: 1}, 120); err != nil { + t.Fatal(err) + } + h, err := r.Dequeue() + if err != nil || h.Type != 1 { + t.Fatalf("NVMe IC response: %+v %v", h, err) + } + var ic nvme.ICResponse + if err := r.Receive(&ic); err != nil { + t.Fatal(err) + } + c.cid++ + cmd := nvme.CapsuleCommand{OpCode: 0x7f, FCType: 1, CID: c.cid, D10: uint32(q) << 16} + data := make([]byte, 1024) + (&nvme.ConnectData{HostID: [16]byte{1, 2, 3, 4}, CNTLID: controller, SubNQN: nqn, HostNQN: "nqn.2026-11.test:gap1-host"}).Marshal(data) + if err := w.SendWithData(4, 0, &cmd, 64, data); err != nil { + t.Fatal(err) + } + reply := gap1NVMeReply(t, r, c.cid) + if q == 0 { + controller = uint16(reply.DW0) + if controller == 0 { + t.Fatal("no controller assigned") + } + } + if q == 1 { + c.r, c.w = r, w + } + } + return c +} + +func (c *gap1NVMe) close() { + if c.io != nil { + _ = c.io.Close() + } + if c.admin != nil { + _ = c.admin.Close() + } +} + +func gap1NVMeReply(t *testing.T, r *nvme.Reader, cid uint16) nvme.CapsuleResponse { + t.Helper() + h, err := r.Dequeue() + if err != nil || h.Type != 5 { + t.Fatalf("NVMe capsule header: %+v %v", h, err) + } + var reply nvme.CapsuleResponse + if err := r.Receive(&reply); err != nil { + t.Fatal(err) + } + if reply.CID != cid || reply.Status != 0 { + t.Fatalf("NVMe CID %d: %+v", cid, reply) + } + return reply +} + +func (c *gap1NVMe) writeFlush(t *testing.T, lba uint64, payload []byte) { + t.Helper() + if len(payload) != 4096 { + t.Fatal("harness writes exactly one block") + } + c.cid++ + cmd := nvme.CapsuleCommand{OpCode: 1, CID: c.cid, NSID: 1, D10: uint32(lba), D11: uint32(lba >> 32)} + if err := c.w.SendHeaderOnly(4, &cmd, 64); err != nil { + t.Fatal(err) + } + h, err := c.r.Dequeue() + if err != nil || h.Type != 9 { + t.Fatalf("NVMe R2T: %+v %v", h, err) + } + var r2t nvme.R2THeader + if err := c.r.Receive(&r2t); err != nil { + t.Fatal(err) + } + if r2t.CCCID != c.cid || r2t.DATAO != 0 || r2t.DATAL != uint32(len(payload)) { + t.Fatalf("wrong R2T %+v", r2t) + } + data := nvme.H2CDataHeader{CCCID: c.cid, TAG: r2t.TAG, DATAO: 0, DATAL: uint32(len(payload))} + if err := c.w.SendWithData(6, 0, &data, 16, payload); err != nil { + t.Fatal(err) + } + gap1NVMeReply(t, c.r, c.cid) + c.cid++ + flush := nvme.CapsuleCommand{OpCode: 0, CID: c.cid, NSID: 1} + if err := c.w.SendHeaderOnly(4, &flush, 64); err != nil { + t.Fatal(err) + } + gap1NVMeReply(t, c.r, c.cid) // only this completed Flush makes the record durable +} + +func (c *gap1NVMe) readExact(t *testing.T, lba uint64, want []byte) { + t.Helper() + c.cid++ + cmd := nvme.CapsuleCommand{OpCode: 2, CID: c.cid, NSID: 1, D10: uint32(lba), D11: uint32(lba >> 32)} + if err := c.w.SendHeaderOnly(4, &cmd, 64); err != nil { + t.Fatal(err) + } + h, err := c.r.Dequeue() + if err != nil || h.Type != 7 { + t.Fatalf("NVMe read data: %+v %v", h, err) + } + var header nvme.C2HDataHeader + if err := c.r.Receive(&header); err != nil { + t.Fatal(err) + } + if header.CCCID != c.cid || header.DATAO != 0 || header.DATAL != uint32(len(want)) || c.r.Length() != len(want) { + t.Fatalf("wrong read frame %+v length%d", header, c.r.Length()) + } + got := make([]byte, c.r.Length()) + if err := c.r.ReceiveData(got); err != nil { + t.Fatal(err) + } + gap1NVMeReply(t, c.r, c.cid) + if !bytes.Equal(got, want) { + t.Fatal("fsync-acknowledged NVMe record changed after supervised restart") + } +} + +// Calibration of the witness client only, not a systemd/re-grant proof. +func TestGAP1NVMeWitnessRoundTripsAcknowledgedBlock(t *testing.T) { + backend := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1}) + nqn := "nqn.2026-11.test:gap1-witness-calibration" + target := nvme.NewTarget(nvme.TargetConfig{Listen: "127.0.0.1:0", SubsysNQN: nqn, VolumeID: "v", Provider: testback.NewStaticProvider(backend), Handler: nvme.HandlerConfig{NSID: 1, BlockSize: 4096, VolumeSize: 64 * 4096}}) + addr, err := target.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = target.Close() }) + c := gap1ConnectNVMe(t, addr, nqn) + want := bytes.Repeat([]byte{0x6d}, 4096) + c.writeFlush(t, 8, want) + c.readExact(t, 8, want) + if backend.WriteCount() != 1 || backend.SyncCount() != 1 || backend.ReadCount() != 1 { + t.Fatalf("witness bypassed backend write/flush/read: %d/%d/%d", backend.WriteCount(), backend.SyncCount(), backend.ReadCount()) + } +} diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index e251aaf4cc..9477c529cd 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -91,6 +91,11 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { if err != nil || missing != http.StatusNotFound || gap1StatusOperational(missing, body404, volume) { t.Fatalf("real status404 parser control: %v", err) } + want := bytes.Repeat([]byte{0x6d}, 4096) + client := gap1ConnectNVMe(t, nvmeAddr, "nqn.2026-11.test:"+stem) + client.writeFlush(t, 8, want) + client.readExact(t, 8, want) + client.close() remote := cluster.remote(t, base+"/"+volume) before, err := remote.GetHead(context.Background()) if err != nil || before.Gen == 0 { @@ -150,6 +155,11 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { 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) } + returned := gap1ConnectNVMe(t, nvmeAddr, "nqn.2026-11.test:"+stem) + returned.readExact(t, 8, want) + returned.writeFlush(t, 9, want) + returned.readExact(t, 9, want) + returned.close() // A real control cut must pass the lease and layer gates after restart. req, err := http.NewRequest(http.MethodPost, "http://"+statusAddr+"/chunk/cut", bytes.NewBufferString(fmt.Sprintf(`{"volumeID":%q,"timeoutMs":3000}`, volume))) if err != nil { From 103b944c037662946bfd59eeeef11745354a9d04 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:12:34 -0800 Subject: [PATCH 12/57] test: compare NVMe data frame lengths in wire units --- seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go b/seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go index 247faffe94..e743064263 100644 --- a/seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go @@ -146,7 +146,7 @@ func (c *gap1NVMe) readExact(t *testing.T, lba uint64, want []byte) { if err := c.r.Receive(&header); err != nil { t.Fatal(err) } - if header.CCCID != c.cid || header.DATAO != 0 || header.DATAL != uint32(len(want)) || c.r.Length() != len(want) { + if header.CCCID != c.cid || header.DATAO != 0 || header.DATAL != uint32(len(want)) || c.r.Length() != uint32(len(want)) { t.Fatalf("wrong read frame %+v length%d", header, c.r.Length()) } got := make([]byte, c.r.Length()) From 59a6767e2ee66b788022b8175e1a1baf3c795fc0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:14:10 -0800 Subject: [PATCH 13/57] test: qualify no-retry exit from a real other-replica master fact --- .../startup_systemd_integration_test.go | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index 9477c529cd..b67cda4218 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -18,6 +18,7 @@ import ( "time" "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" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" @@ -178,6 +179,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { t.Fatalf("systemd rate limit hit: %+v", s) } gap1PlannedStopDoesNotRestart(t, ws, unit, statusAddr, volume, after.Epoch, after.Holder, s["NRestarts"]) + gap1SupersededDoesNotRestart(t, stem, filepath.Join(bin, "blockvolume"), args, root, volume) } func startGAP1Unit(t *testing.T, unit string, restart bool, exe string, args ...string) { @@ -378,3 +380,57 @@ func gap1PlannedStopDoesNotRestart(t *testing.T, ws control.WorkspaceServiceClie return true }) } + +// The master keeps the real r1 authority line. This process has never had an +// 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) { + t.Helper() + changed := append([]string(nil), args...) + addr := leaseBinaryAddress(t) + replacements := map[string]string{"--replica-id": "r-old", "--data-addr": leaseBinaryAddress(t), "--ctrl-addr": leaseBinaryAddress(t), "--status-addr": addr, "--durable-root": filepath.Join(root, "superseded-store"), "--nvme-listen": leaseBinaryAddress(t), "--nvme-subsysnqn": "nqn.2026-11.test:" + stem + "-superseded"} + for i := 0; i+1 < len(changed); i++ { + if value, ok := replacements[changed[i]]; ok { + changed[i+1] = value + } + } + unit := stem + "-superseded" + startGAP1Unit(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 { + return false + } + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + if err != nil { + return false + } + t.Logf("captured real supersede status: status%d body%s", resp.StatusCode, raw) + if resp.StatusCode != http.StatusOK { + return false + } + var status hostvolume.StatusProjection + if err := json.Unmarshal(raw, &status); err != nil { + t.Fatal(err) + } + if status.Healthy || status.FrontendPrimaryReady { + t.Fatalf("unassigned old identity served: %+v", status) + } + return status.AuthorityRole == hostvolume.AuthorityRoleSuperseded + }) + waitGAP1(t, "positive supersede did not exit78 without restart", 45*time.Second, func() bool { + s := gap1Unit(t, unit) + if s["NRestarts"] != "0" { + t.Fatalf("superseded unit restarted: %+v", s) + } + if s["MainPID"] != "0" { + return false + } + if s["ExecMainStatus"] != "78" || s["ActiveState"] != "failed" || s["SubState"] != "failed" { + t.Fatalf("supersede not a terminal no-retry exit: %+v", s) + } + return true + }) +} From 741cdbfbc9a609505c8623654284d084b7d1a235 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:17:12 -0800 Subject: [PATCH 14/57] fix: deliver the first process exit through one immutable buffered slot --- seaweed-block/cmd/blockvolume/process_exit.go | 26 ++++++++++--------- .../cmd/blockvolume/process_exit_test.go | 14 +++++++--- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index 48b79fb064..43f54269b1 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -27,21 +27,21 @@ 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{} - outcome workspaceExit + parent context.Context + once sync.Once + done chan struct{} + decision chan workspaceExit } func newProcessExit(ctx context.Context) *processExit { - return &processExit{parent: ctx, done: make(chan struct{})} + return &processExit{parent: ctx, done: make(chan struct{}), decision: make(chan workspaceExit, 1)} } func (e *processExit) choose(out workspaceExit) { e.once.Do(func() { if e.parent.Err() != nil { out = workspaceExit{reason: "signal"} } - e.outcome = out + e.decision <- out // exactly one send; the sole slot cannot block under a provider lock close(e.done) }) } @@ -59,27 +59,29 @@ func superviseProcess(ctx context.Context, work func(*processExit) int) int { e := newProcessExit(ctx) finished := make(chan int, 1) go func() { finished <- work(e) }() + var out workspaceExit select { case code := <-finished: select { - case <-e.done: - if e.outcome.code == 0 { + case out = <-e.decision: + if out.code == 0 { return code } - return reportWorkspaceExit(e.outcome) + return reportWorkspaceExit(out) default: return code } case <-ctx.Done(): e.choose(workspaceExit{reason: "signal"}) - case <-e.done: + out = <-e.decision + case out = <-e.decision: } - if e.outcome.code == 0 { + if out.code == 0 { return <-finished } timer := time.NewTimer(volume.WorkspaceDrainTimeout) defer timer.Stop() - return finishWorkspaceExit(e.outcome, finished, timer.C) + return finishWorkspaceExit(out, finished, timer.C) } func finishWorkspaceExit(out workspaceExit, finished <-chan int, deadline <-chan time.Time) int { diff --git a/seaweed-block/cmd/blockvolume/process_exit_test.go b/seaweed-block/cmd/blockvolume/process_exit_test.go index 7c0d24a8fe..1c54c93b4a 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_test.go @@ -37,16 +37,22 @@ func TestWorkspaceExitFirstOutcomeIsLatched(t *testing.T) { e.choose(first) e.choose(workspaceExit{75, "assignment_timeout"}) <-e.done - if e.outcome != first { - t.Fatalf("first=%+v changed to %+v", first, e.outcome) + if got := <-e.decision; got != first { + t.Fatalf("first=%+v changed to %+v", first, got) + } + e.choose(workspaceExit{78, "superseded"}) + select { + case got := <-e.decision: + t.Fatalf("later outcome published: %+v", got) + default: } } ctx, cancel := context.WithCancel(context.Background()) cancel() e := newProcessExit(ctx) e.choose(workspaceExit{78, "superseded"}) - if e.outcome.code != 0 || e.outcome.reason != "signal" { - t.Fatalf("observed signal lost: %+v", e.outcome) + if got := <-e.decision; got.code != 0 || got.reason != "signal" { + t.Fatalf("observed signal lost: %+v", got) } } From 5646cad9283676a86f18a985949ae6e985946302 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:17:48 -0800 Subject: [PATCH 15/57] fix: keep signal and acknowledged revoke status immutable during cleanup --- seaweed-block/cmd/blockvolume/process_exit.go | 7 +++---- seaweed-block/cmd/blockvolume/process_exit_test.go | 12 ++++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index 43f54269b1..4a6bc7d259 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -64,9 +64,6 @@ func superviseProcess(ctx context.Context, work func(*processExit) int) int { case code := <-finished: select { case out = <-e.decision: - if out.code == 0 { - return code - } return reportWorkspaceExit(out) default: return code @@ -77,7 +74,8 @@ func superviseProcess(ctx context.Context, work func(*processExit) int) int { case out = <-e.decision: } if out.code == 0 { - return <-finished + <-finished + return 0 } timer := time.NewTimer(volume.WorkspaceDrainTimeout) defer timer.Stop() @@ -163,6 +161,7 @@ func finishWorkspaceLease(e *processExit, f flags, h *volume.Host, done <-chan e select { case err := <-done: if err == nil { + e.choose(workspaceExit{reason: "revoked"}) return } fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout:", err) diff --git a/seaweed-block/cmd/blockvolume/process_exit_test.go b/seaweed-block/cmd/blockvolume/process_exit_test.go index 1c54c93b4a..38b96416a9 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_test.go @@ -101,3 +101,15 @@ func TestWorkspaceRetryProcessExitsWhenCloseBlocks(t *testing.T) { t.Fatalf("blocked close exit: %v %s", err, out) } } + +func TestWorkspaceSignalFirstKeepsZeroAfterLaterFailure(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + code := superviseProcess(ctx, func(e *processExit) int { + e.choose(workspaceExit{78, "superseded"}) + return 1 // a later cleanup error cannot replace the chosen signal status + }) + if code != 0 { + t.Fatalf("first signal status changed to %d", code) + } +} From cf019bfb3f30df0a6422d597a8304f7ae18c86d3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:25:21 -0800 Subject: [PATCH 16/57] test: preserve failed systemd runtime state and acknowledged record hash --- .../startup_systemd_integration_test.go | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index b67cda4218..545d686286 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -5,6 +5,7 @@ package main_test import ( "bytes" "context" + "crypto/sha256" "encoding/json" "fmt" "io" @@ -51,6 +52,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { } } cluster := startWorkspaceWeed(t) + gap1PreserveFailure(t, root, cluster.dir) stem := fmt.Sprintf("codex03-gap1-%d", time.Now().UnixNano()) volume := stem base := "/" + stem @@ -95,6 +97,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { want := bytes.Repeat([]byte{0x6d}, 4096) client := gap1ConnectNVMe(t, nvmeAddr, "nqn.2026-11.test:"+stem) client.writeFlush(t, 8, want) + t.Logf("acknowledged NVMe record: lba=8 bytes=%d sha256=%x", len(want), sha256.Sum256(want)) client.readExact(t, 8, want) client.close() remote := cluster.remote(t, base+"/"+volume) @@ -434,3 +437,29 @@ func gap1SupersededDoesNotRestart(t *testing.T, stem, exe string, args []string, return true }) } + +// Register before the units: their exact-unit cleanup runs first, then this +// retains failed-run local state before testing.TempDir removes it. Nothing is +// deleted from the evidence directory, including a partial copy on failure. +func gap1PreserveFailure(t *testing.T, roots ...string) { + t.Helper() + destination := os.Getenv("GAP1_EVIDENCE_DIR") + if destination == "" { + return + } + t.Cleanup(func() { + if !t.Failed() { + return + } + if err := os.MkdirAll(destination, 0700); err != nil { + t.Logf("evidence mkdir: %v", err) + return + } + for i, root := range roots { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + out, err := exec.CommandContext(ctx, "cp", "-a", "--sparse=always", root, filepath.Join(destination, fmt.Sprintf("runtime-%d", i))).CombinedOutput() + cancel() + t.Logf("failed-run state retained: source=%s destination=%s err=%v output=%s", root, destination, err, out) + } + }) +} From 99781fe33743fd7b644343c1a0a967dfefbd692b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:26:25 -0800 Subject: [PATCH 17/57] test: use the supported systemd kill-who option in WSL qualification --- .../cmd/blockvolume/startup_systemd_integration_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index 545d686286..2a2140e9cf 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -105,7 +105,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { if err != nil || before.Gen == 0 { t.Fatalf("bootstrap HEAD: %+v %v", before, err) } - gap1Systemctl(t, "kill", "--signal=KILL", "--kill-whom=main", bootstrap) + gap1Systemctl(t, "kill", "--signal=KILL", "--kill-who=main", bootstrap) waitGAP1(t, "bootstrap still running", 10*time.Second, func() bool { return gap1Unit(t, bootstrap)["MainPID"] == "0" }) // QueryWorkspace is read-only. These real binaries and this test share // one WSL kernel wall clock. Use the reported MASTER expiry timestamp, From cb6ad61c81d541b571f09b7660dd315784e21f17 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:29:32 -0800 Subject: [PATCH 18/57] test: prove successful transient exits from captured systemd journal identities --- .../startup_systemd_integration_test.go | 86 +++++++++++++++++-- 1 file changed, 80 insertions(+), 6 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index 2a2140e9cf..c5edc07775 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -54,6 +54,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { cluster := startWorkspaceWeed(t) gap1PreserveFailure(t, root, cluster.dir) stem := fmt.Sprintf("codex03-gap1-%d", time.Now().UnixNano()) + gap1ProbeTerminalSuccess(t, stem+"-policy-probe") volume := stem base := "/" + stem masterAddr := leaseBinaryAddress(t) @@ -181,7 +182,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { if s["Result"] == "start-limit-hit" { t.Fatalf("systemd rate limit hit: %+v", s) } - gap1PlannedStopDoesNotRestart(t, ws, unit, statusAddr, volume, after.Epoch, after.Holder, s["NRestarts"]) + gap1PlannedStopDoesNotRestart(t, ws, unit, statusAddr, volume, after.Epoch, after.Holder, s["NRestarts"], s["InvocationID"]) gap1SupersededDoesNotRestart(t, stem, filepath.Join(bin, "blockvolume"), args, root, volume) } @@ -213,7 +214,7 @@ func startGAP1Unit(t *testing.T, unit string, restart bool, exe string, args ... ctx, cancel = context.WithTimeout(context.Background(), 15*time.Second) _, err := exec.CommandContext(ctx, "systemctl", "stop", unit).CombinedOutput() cancel() - if err != nil { + 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() @@ -236,7 +237,7 @@ func gap1Unit(t *testing.T, unit string) map[string]string { t.Helper() 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").CombinedOutput() + b, err := exec.CommandContext(ctx, "systemctl", "show", unit, "--property=MainPID,NRestarts,ExecMainStatus,Result,ExecMainStartTimestampMonotonic,RestartUSec,RestartPreventExitStatus,StartLimitBurst,StartLimitIntervalUSec,ActiveState,SubState,LoadState,InvocationID").CombinedOutput() if err != nil { t.Fatalf("unit show: %v %s", err, b) } @@ -336,7 +337,7 @@ func gap1ShippedPolicy(t *testing.T) map[string]string { // A successful planned revoke is not a retry outcome. The master's ACK and // systemd's terminal inactive/dead state prove no automatic restart is queued. -func gap1PlannedStopDoesNotRestart(t *testing.T, ws control.WorkspaceServiceClient, unit, addr, volume string, epoch uint64, holder, restarts string) { +func gap1PlannedStopDoesNotRestart(t *testing.T, ws control.WorkspaceServiceClient, unit, addr, volume string, epoch uint64, holder, restarts, invocation string) { t.Helper() req, err := http.NewRequest(http.MethodPost, "http://"+addr+"/chunk/detach", bytes.NewBufferString(fmt.Sprintf(`{"volumeID":%q,"plain":true,"timeoutMs":5000}`, volume))) if err != nil { @@ -371,7 +372,9 @@ func gap1PlannedStopDoesNotRestart(t *testing.T, ws control.WorkspaceServiceClie t.Fatalf("wrong planned ACK: %s", ack.String()) } state := gap1Unit(t, unit) - if state["NRestarts"] != restarts { + // systemd may unload a successful transient unit, resetting its + // counters. In that case use the exact invocation's journal proof. + if state["LoadState"] != "not-found" && state["NRestarts"] != restarts { t.Fatalf("planned stop restarted: %+v", state) } if state["MainPID"] != "0" { @@ -380,7 +383,11 @@ func gap1PlannedStopDoesNotRestart(t *testing.T, ws control.WorkspaceServiceClie if state["ExecMainStatus"] != "0" || state["ActiveState"] != "inactive" || state["SubState"] != "dead" { t.Fatalf("planned stop is not terminal success: %+v", state) } - return true + starts, parseErr := strconv.Atoi(restarts) + if parseErr != nil || invocation == "" { + t.Fatalf("missing pre-stop systemd identity: starts=%q invocation=%q", restarts, invocation) + } + return gap1JournalTerminalSuccess(t, unit, invocation, starts+1) }) } @@ -463,3 +470,70 @@ func gap1PreserveFailure(t *testing.T, roots ...string) { } }) } + +// Captured systemd249 journal records supply stable manager message IDs. The +// raw journal is logged when this witness succeeds; no fabricated PID status +// can turn an unknown unit into an ACKed successful invocation. +func gap1JournalTerminalSuccess(t *testing.T, unit, invocation string, expectedStarts int) bool { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + raw, err := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=json").CombinedOutput() + if err != nil { + t.Fatalf("unit journal: %v %s", err, raw) + } + starts := 0 + started := map[string]bool{} + succeeded := map[string]bool{} + for _, line := range bytes.Split(raw, []byte{'\n'}) { + if len(line) == 0 { + continue + } + var entry struct { + Unit string `json:"UNIT"` + Invocation string `json:"INVOCATION_ID"` + Message string `json:"MESSAGE_ID"` + PID string `json:"_PID"` + JobResult string `json:"JOB_RESULT"` + } + if err := json.Unmarshal(line, &entry); err != nil { + t.Fatalf("captured journal JSON: %v", err) + } + if entry.Unit != unit+".service" || entry.PID != "1" { + continue + } + switch entry.Message { + case "39f53479d3a045ac8e11786248231fbf": + if entry.JobResult == "done" { + starts++ + started[entry.Invocation] = true + } + case "7ad2d189f7e94e70a38c781354912448": + succeeded[entry.Invocation] = true + } + } + if starts > expectedStarts { + t.Fatalf("unexpected restart in captured unit journal: starts%d want%d", starts, expectedStarts) + } + if invocation == "" && expectedStarts == 1 { + for id := range started { + invocation = id + } + } + complete := invocation != "" && starts == expectedStarts && started[invocation] && succeeded[invocation] + if complete { + t.Logf("captured terminal-success journal for %s invocation%s: %s", unit, invocation, raw) + } + return complete +} + +// 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) { + t.Helper() + startGAP1Unit(t, unit, true, "/bin/true") + waitGAP1(t, "systemd terminal-success parser preflight failed", 5*time.Second, func() bool { + return gap1JournalTerminalSuccess(t, unit, "", 1) + }) +} From 60123091339d7242e270d0caeae7406ca4ab2a25 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:34:41 -0800 Subject: [PATCH 19/57] test: use replica identity for planned revoke witness --- .../cmd/blockvolume/startup_systemd_integration_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index c5edc07775..63dbb63889 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -182,7 +182,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { if s["Result"] == "start-limit-hit" { t.Fatalf("systemd rate limit hit: %+v", s) } - gap1PlannedStopDoesNotRestart(t, ws, unit, statusAddr, volume, after.Epoch, after.Holder, s["NRestarts"], s["InvocationID"]) + gap1PlannedStopDoesNotRestart(t, ws, unit, statusAddr, volume, after.Epoch, "r1", s["NRestarts"], s["InvocationID"]) gap1SupersededDoesNotRestart(t, stem, filepath.Join(bin, "blockvolume"), args, root, volume) } From 1943f93ce6fb899ba3e846de7ad85ea203100021 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:37:54 -0800 Subject: [PATCH 20/57] test: observe supersede fact for never-assigned replica --- .../startup_systemd_integration_test.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index 63dbb63889..49db69ecf8 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -428,7 +428,21 @@ func gap1SupersededDoesNotRestart(t *testing.T, stem, exe string, args []string, if status.Healthy || status.FrontendPrimaryReady { t.Fatalf("unassigned old identity served: %+v", status) } - return status.AuthorityRole == hostvolume.AuthorityRoleSuperseded + // A never-assigned replica remains ModeIdle, so /status intentionally + // reports unknown even after recording the other-replica fact. Prove + // receipt in this process before checking its terminal78 decision. + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + journal, err := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=cat").CombinedOutput() + if err != nil { + t.Fatalf("supersede journal: %v %s", err, journal) + } + observed := fmt.Sprintf("volume %s authority is now r1@1 (not this replica r-old); recording supersede", volume) + if strings.Contains(string(journal), observed) { + t.Logf("captured authoritative other-replica observation: %s", observed) + return true + } + return false }) waitGAP1(t, "positive supersede did not exit78 without restart", 45*time.Second, func() bool { s := gap1Unit(t, unit) From ef9bcb00322509706d4821b0fd955f279f9e460a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:44:27 -0800 Subject: [PATCH 21/57] test: expose stale supersede and unconfirmed ACK exit causes --- .../process_exit_authority_test.go | 136 ++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/process_exit_authority_test.go diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go new file mode 100644 index 0000000000..e231155d2e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -0,0 +1,136 @@ +package main + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "net" + "testing" + "time" +) + +type exitAssignmentStream struct { + control.UnimplementedAssignmentServiceServer + control.UnimplementedObservationServiceServer + facts chan *control.AssignmentFact +} + +func (s *exitAssignmentStream) ReportHeartbeat(context.Context, *control.HeartbeatReport) (*control.HeartbeatAck, error) { + return &control.HeartbeatAck{}, nil +} +func (s *exitAssignmentStream) SubscribeAssignments(_ *control.SubscribeRequest, stream control.AssignmentService_SubscribeAssignmentsServer) error { + for { + select { + case <-stream.Context().Done(): + return stream.Context().Err() + case f := <-s.facts: + if err := stream.Send(f); err != nil { + return err + } + } + } +} +func exitAuthorityHost(t *testing.T) (*volume.Host, func(string, uint64)) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + stream := &exitAssignmentStream{facts: make(chan *control.AssignmentFact, 4)} + control.RegisterAssignmentServiceServer(srv, stream) + control.RegisterObservationServiceServer(srv, stream) + go srv.Serve(ln) + t.Cleanup(srv.Stop) + h, err := volume.New(volume.Config{MasterAddr: ln.Addr().String(), ServerID: "s", VolumeID: "v", ReplicaID: "r", DataAddr: "127.0.0.1:1", CtrlAddr: "127.0.0.1:2"}) + if err != nil { + t.Fatal(err) + } + h.Start() + t.Cleanup(func() { + if err := h.Close(); err != nil { + t.Error(err) + } + }) + return h, func(replica string, epoch uint64) { + t.Helper() + stream.facts <- &control.AssignmentFact{VolumeId: "v", ReplicaId: replica, Epoch: epoch, EndpointVersion: 1} + deadline := time.NewTimer(3 * time.Second) + defer deadline.Stop() + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for { + ready := false + if replica == "r" { + ready = h.Adapter().Projection().Epoch == epoch + } else { + f := h.LastOtherLine() + ready = f != nil && f.ReplicaId == replica && f.Epoch == epoch + } + if ready { + return + } + select { + case <-deadline.C: + t.Fatal("assignment observation did not arrive") + case <-tick.C: + } + } + } +} + +// Exercise the real Host subscription and the process stop seam, including a +// historical other-replica record retained after the master assigns us again. +func TestWorkspaceRetryUsesNewestOwnAssignment(t *testing.T) { + for _, tc := range []struct { + name string + facts []struct { + replica string + epoch uint64 + } + want int + }{ + {"old other then own", []struct { + replica string + epoch uint64 + }{{"other", 6}, {"r", 7}}, 75}, + {"own then newer other", []struct { + replica string + epoch uint64 + }{{"r", 5}, {"other", 6}}, 78}, + {"never assigned", []struct { + replica string + epoch uint64 + }{{"other", 6}}, 78}, + {"same replica higher epoch", []struct { + replica string + epoch uint64 + }{{"r", 5}, {"r", 7}}, 75}, + } { + t.Run(tc.name, func(t *testing.T) { + h, send := exitAuthorityHost(t) + for _, f := range tc.facts { + send(f.replica, f.epoch) + } + e := newProcessExit(context.Background()) + done := make(chan error, 1) + done <- errors.New("lease ended") + waitWorkspaceStop(e, flags{volumeID: "v", replicaID: "r"}, h, nil, done) + if out := <-e.decision; out.code != tc.want { + t.Fatalf("lease end classified %+v, want%d", out, tc.want) + } + }) + } +} +func TestWorkspaceUnconfirmedRevokeHasOwnReason(t *testing.T) { + h, _ := exitAuthorityHost(t) + e := newProcessExit(context.Background()) + done := make(chan error, 1) + done <- errors.New("ACK answer lost") + finishWorkspaceLease(e, flags{volumeID: "v", replicaID: "r"}, h, done) + if out := <-e.decision; out.code != 75 || out.reason != "revoke_ack_unconfirmed" { + t.Fatalf("unconfirmed ACK classified %+v", out) + } +} From 3daa1d216273450843493dfcaa942a5de11dee1c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:46:24 -0800 Subject: [PATCH 22/57] fix: compare supersede exits with latest own authority lineage --- seaweed-block/cmd/blockvolume/process_exit.go | 22 ++++++------- .../cmd/blockvolume/process_exit_test.go | 22 ------------- seaweed-block/core/host/volume/host.go | 5 +++ .../core/host/volume/workspace_startup.go | 30 ++++++++++++++++++ .../host/volume/workspace_startup_test.go | 31 +++++++++++++++++++ .../docs/design/agent-workspace-design.md | 2 ++ seaweed-block/docs/design/invariants.md | 9 ++++-- 7 files changed, 85 insertions(+), 36 deletions(-) create mode 100644 seaweed-block/core/host/volume/workspace_startup.go create mode 100644 seaweed-block/core/host/volume/workspace_startup_test.go diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index 4a6bc7d259..8a3ae07c37 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -11,12 +11,13 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/host/volume" - control "github.com/seaweedfs/seaweed-block/core/rpc/control" ) const ( exitWorkspaceRetry = 75 exitWorkspaceSuperseded = 78 + // Existing post-drain ACK wait; M2 Revoking -> Revoked, Part D. + workspaceLeaseCloseoutTimeout = 3 * time.Second ) type workspaceExit struct { @@ -97,11 +98,10 @@ func reportWorkspaceExit(out workspaceExit) int { return out.code } -// INV-WS-STARTUP-RETRY-001: only a positive, volume-specific other-replica -// fact permits no-retry. A -// higher epoch for the same replica must restart for the new assignment. -func workspaceRetryOutcome(volumeID, replicaID, reason string, other *control.AssignmentFact) workspaceExit { - if other != nil && other.VolumeId == volumeID && other.ReplicaId != "" && other.ReplicaId != replicaID { +// INV-WS-STARTUP-RETRY-001: only a newer other-replica authority fact +// permits no-retry. Host owns the lineage observation and shared predicate. +func workspaceRetryOutcome(reason string, h *volume.Host) workspaceExit { + if h.IsCurrentReplicaSuperseded() { return workspaceExit{exitWorkspaceSuperseded, "superseded"} } return workspaceExit{exitWorkspaceRetry, reason} @@ -138,7 +138,7 @@ func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan case request := <-requests: out := workspaceExit{reason: "revoked"} if !h.WorkspaceLeaseRevoking() { - out = workspaceRetryOutcome(f.volumeID, f.replicaID, "lease_expired", h.LastOtherLine()) + out = workspaceRetryOutcome("lease_expired", h) } if out.code != 0 { e.choose(out) @@ -146,7 +146,7 @@ func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan return &request, done case err := <-done: fmt.Fprintln(os.Stderr, "blockvolume: workspace lease stopped:", err) - e.choose(workspaceRetryOutcome(f.volumeID, f.replicaID, "lease_expired", h.LastOtherLine())) + e.choose(workspaceRetryOutcome("lease_expired", h)) return nil, nil } } @@ -165,10 +165,10 @@ func finishWorkspaceLease(e *processExit, f flags, h *volume.Host, done <-chan e return } fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout:", err) - case <-time.After(3 * time.Second): + case <-time.After(workspaceLeaseCloseoutTimeout): fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout deadline") } - e.choose(workspaceRetryOutcome(f.volumeID, f.replicaID, "lease_expired", h.LastOtherLine())) + e.choose(workspaceExit{exitWorkspaceRetry, "revoke_ack_unconfirmed"}) } func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p *durable.DurableProvider) bool { @@ -179,6 +179,6 @@ func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p *durable. if !failed { return false } - out := workspaceRetryOutcome(f.volumeID, f.replicaID, "assignment_timeout", h.LastOtherLine()) + out := workspaceRetryOutcome("assignment_timeout", h) return p.ChooseChunkStartupExit(f.volumeID, gen, func() { e.choose(out) }) } diff --git a/seaweed-block/cmd/blockvolume/process_exit_test.go b/seaweed-block/cmd/blockvolume/process_exit_test.go index 38b96416a9..444d13caa0 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_test.go @@ -3,34 +3,12 @@ package main import ( "context" "errors" - control "github.com/seaweedfs/seaweed-block/core/rpc/control" "os" "os/exec" "testing" "time" ) -func TestWorkspaceRetryNeedsPositiveOtherReplica(t *testing.T) { - for _, tc := range []struct { - name string - fact *control.AssignmentFact - code int - }{ - {"absent", nil, 75}, - {"same replica higher epoch", &control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 99}, 75}, - {"another volume", &control.AssignmentFact{VolumeId: "other", ReplicaId: "other"}, 75}, - {"empty holder", &control.AssignmentFact{VolumeId: "v"}, 75}, - {"other replica", &control.AssignmentFact{VolumeId: "v", ReplicaId: "other"}, 78}, - } { - t.Run(tc.name, func(t *testing.T) { - out := workspaceRetryOutcome("v", "r", "assignment_timeout", tc.fact) - if out.code != tc.code { - t.Fatalf("outcome=%+v want %d", out, tc.code) - } - }) - } -} - func TestWorkspaceExitFirstOutcomeIsLatched(t *testing.T) { for _, first := range []workspaceExit{{75, "lease_expired"}, {78, "superseded"}, {0, "revoked"}} { e := newProcessExit(context.Background()) diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 920ac49717..3ac6f3860b 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -203,6 +203,9 @@ type Host struct { otherMu sync.Mutex lastOther *control.AssignmentFact + selfLineageMu sync.RWMutex + selfEpoch, selfEV uint64 + frontendMu sync.RWMutex frontendTargets []*control.FrontendTarget } @@ -847,6 +850,8 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { return } + h.recordSelfAssignment(fact) + // The recovery watchdog runs from the primary assignment, before any // admission step can fail (#128 rule 6). h.wd.primaryAssigned(fact.Epoch) diff --git a/seaweed-block/core/host/volume/workspace_startup.go b/seaweed-block/core/host/volume/workspace_startup.go new file mode 100644 index 0000000000..629abd5d38 --- /dev/null +++ b/seaweed-block/core/host/volume/workspace_startup.go @@ -0,0 +1,30 @@ +package volume + +import control "github.com/seaweedfs/seaweed-block/core/rpc/control" + +// INV-WS-STARTUP-RETRY-001: remember the newest assignment observed for us, +// including one whose local readiness admission subsequently refuses. +func (h *Host) recordSelfAssignment(f *control.AssignmentFact) { + if f.VolumeId != h.cfg.VolumeID { + return + } + h.selfLineageMu.Lock() + defer h.selfLineageMu.Unlock() + if f.Epoch > h.selfEpoch || f.Epoch == h.selfEpoch && f.EndpointVersion > h.selfEV { + h.selfEpoch, h.selfEV = f.Epoch, f.EndpointVersion + } +} + +// IsCurrentReplicaSuperseded reuses the authority predicate with the newest +// observed own lineage, zero before any own assignment. Keep that lineage +// stable through the comparison; a historical other line alone cannot mean78. +// This is exit classification only: frontend admission keeps its own lineage. +func (h *Host) IsCurrentReplicaSuperseded() bool { + h.selfLineageMu.RLock() + defer h.selfLineageMu.RUnlock() + other := h.LastOtherLine() + if other == nil || other.VolumeId != h.cfg.VolumeID { + return false + } + return h.IsSuperseded(h.cfg.ReplicaID, h.selfEpoch, h.selfEV) +} diff --git a/seaweed-block/core/host/volume/workspace_startup_test.go b/seaweed-block/core/host/volume/workspace_startup_test.go new file mode 100644 index 0000000000..28330e77f5 --- /dev/null +++ b/seaweed-block/core/host/volume/workspace_startup_test.go @@ -0,0 +1,31 @@ +package volume + +import ( + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "testing" +) + +func TestWorkspaceExitLineageIncludesBlockedOwnAssignment(t *testing.T) { + h, _, _ := newStubbedHost(t, "v", "r", &orderingRecorder{}) + h.applyFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "other", Epoch: 6, EndpointVersion: 1}) + if !h.IsCurrentReplicaSuperseded() { + t.Fatal("never-assigned newer other line did not supersede") + } + h.BlockLocalReadiness("local recovery pending") + h.applyFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 7, EndpointVersion: 1}) + if h.IsCurrentReplicaSuperseded() { + t.Fatal("blocked own assignment left historical other line current for exit") + } + // Exit classification must not change frontend admission at its old lineage. + if !h.IsSuperseded("r", 5, 1) { + t.Fatal("exit observation weakened serving supersede predicate") + } + h.applyFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 4, EndpointVersion: 1}) + if h.IsCurrentReplicaSuperseded() { + t.Fatal("older own delivery lowered the exit lineage") + } + h.recordOtherLine(&control.AssignmentFact{VolumeId: "other-volume", ReplicaId: "other", Epoch: 99}) + if h.IsCurrentReplicaSuperseded() { + t.Fatal("another volume produced a no-retry outcome") + } +} diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 9eab6ab1b6..c8a8882f37 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -509,3 +509,5 @@ stateDiagram-v2 SealedReplay --> [*]: signal Serving --> [*]: revoke ACK or 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. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5921d64e39..eac66bed24 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -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 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. 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` | | 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 @`; `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` | @@ -671,9 +671,11 @@ Notes: | `INV-WS-FORCED-CONFIRM-LOCAL-001` | A missing or malformed `--confirm-forced` is refused before any connection or RPC, with exit 2. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`; `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `request` | `TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally` (`cmd/sw-block/workspace_test.go`); `TestParseConfirmation` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | -| `INV-WS-STARTUP-RETRY-001` | A workspace primary whose assignment wait ends or lease expires exits 75 after bounded fail-closed cleanup; only a 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`); `TestWorkspaceRetryNeedsPositiveOtherReplica`, `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE | +| `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. +- 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. -- `INV-WS-STARTUP-RETRY-001`: exit 78 is an optimisation, permitted only by an observed master fact for this volume naming another replica. 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. Notes: - `INV-WS-SINGLE-FILER-001`: the same census runs in every `sw-block ops chunk` command that writes chunk metadata (snapshot-delete, fork, retain, volume-delete, gc --apply), and in verify, which writes nothing but would report false findings against a split filer view, before it reads or writes; other read-only commands and modes do not run it. @@ -945,6 +947,7 @@ Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed sc | Wait | Machine / invariant | Bound | Release and cancellation | Locks / remote work | |---|---|---|---|---| +| Workspace revocation ACK closeout | M2 Revoking → Revoked; `INV-WS-STARTUP-RETRY-001` | Existing `workspaceLeaseCloseoutTimeout` (3 s), after the resource owner replies to the guard | `finishWorkspaceLease` owns the wait. ACK success selects normal exit; error/expiry selects 75 with `revoke_ack_unconfirmed`. The 5 s supervisor cleanup clock starts only after a nonzero outcome is selected. | No provider/storage lock held. | | Workspace primary retry cleanup | M2 restart; `INV-WS-STARTUP-RETRY-001` | Existing `WorkspaceDrainTimeout` (5 s) after retry/no-retry outcome selection | Process supervisor owns the deadline and returns 75 or 78 even if resource-owner cleanup blocks; first outcome stays latched. Signal and ACKed revocation retain normal exit. | Provider latches by recovery generation under p.mu; wake is nonblocking; the supervisor holds no provider/storage lock. | | Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; positive HTTP timeoutMs. Completed uploads resume only within one blockvolume process and matching owner/HEAD/chunk versions; after restart the seal must fit seal_timeout_ms. | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. | | Plain seal remote proof | M5 RemoteProof; `INV-WS-SEAL-REPLAY-001` | Earlier caller context or existing 2 s HEAD-operation bound for the filer read; attachment serialization retains its owner's cooperative caller bound | Provider registers with Close; closeBoundRemote cancels the read, and Close joins it. Failure keeps frontend admission closed. | Attachment mutex serializes against recover/detach; no backend/store/map lock spans the filer read. | From ad7b9dad404513c12239b69fdb93a641e4edbf62 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:46:58 -0800 Subject: [PATCH 23/57] fix: distinguish observed assignment from replica fence epoch --- .../core/host/volume/workspace_startup.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/host/volume/workspace_startup.go b/seaweed-block/core/host/volume/workspace_startup.go index 629abd5d38..3de4ee4516 100644 --- a/seaweed-block/core/host/volume/workspace_startup.go +++ b/seaweed-block/core/host/volume/workspace_startup.go @@ -8,10 +8,10 @@ func (h *Host) recordSelfAssignment(f *control.AssignmentFact) { if f.VolumeId != h.cfg.VolumeID { return } - h.selfLineageMu.Lock() - defer h.selfLineageMu.Unlock() - if f.Epoch > h.selfEpoch || f.Epoch == h.selfEpoch && f.EndpointVersion > h.selfEV { - h.selfEpoch, h.selfEV = f.Epoch, f.EndpointVersion + h.ownAssignmentMu.Lock() + defer h.ownAssignmentMu.Unlock() + if f.Epoch > h.ownAssignmentEpoch || f.Epoch == h.ownAssignmentEpoch && f.EndpointVersion > h.ownAssignmentEV { + h.ownAssignmentEpoch, h.ownAssignmentEV = f.Epoch, f.EndpointVersion } } @@ -20,11 +20,11 @@ func (h *Host) recordSelfAssignment(f *control.AssignmentFact) { // stable through the comparison; a historical other line alone cannot mean78. // This is exit classification only: frontend admission keeps its own lineage. func (h *Host) IsCurrentReplicaSuperseded() bool { - h.selfLineageMu.RLock() - defer h.selfLineageMu.RUnlock() + h.ownAssignmentMu.RLock() + defer h.ownAssignmentMu.RUnlock() other := h.LastOtherLine() if other == nil || other.VolumeId != h.cfg.VolumeID { return false } - return h.IsSuperseded(h.cfg.ReplicaID, h.selfEpoch, h.selfEV) + return h.IsSuperseded(h.cfg.ReplicaID, h.ownAssignmentEpoch, h.ownAssignmentEV) } From 92c886c12933af956cd7bb7070fb145d91ae2a5a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:47:14 -0800 Subject: [PATCH 24/57] fix: name observed assignment fields consistently --- seaweed-block/core/host/volume/host.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 3ac6f3860b..b7591515d8 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -203,8 +203,8 @@ type Host struct { otherMu sync.Mutex lastOther *control.AssignmentFact - selfLineageMu sync.RWMutex - selfEpoch, selfEV uint64 + ownAssignmentMu sync.RWMutex + ownAssignmentEpoch, ownAssignmentEV uint64 frontendMu sync.RWMutex frontendTargets []*control.FrontendTarget From e08888aac1daa77e1ad69e98ace1b05d8b43baae Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:53:35 -0800 Subject: [PATCH 25/57] test: expose retained timeout and planned-drain startup races --- .../process_exit_authority_test.go | 115 +++++++++++++++++- .../durable/provider_startup_outcome_test.go | 48 ++++++++ 2 files changed, 160 insertions(+), 3 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go index e231155d2e..6ffe4db778 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -3,10 +3,14 @@ package main import ( "context" "errors" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" "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" "net" + "sync/atomic" "testing" "time" ) @@ -14,9 +18,23 @@ import ( type exitAssignmentStream struct { control.UnimplementedAssignmentServiceServer control.UnimplementedObservationServiceServer - facts chan *control.AssignmentFact + control.UnimplementedWorkspaceServiceServer + revoke bool + ackError error + acks atomic.Int32 + facts chan *control.AssignmentFact } +func (s *exitAssignmentStream) RenewWorkspaceLease(_ context.Context, id *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) { + return &control.WorkspaceLeaseFact{VolumeId: id.VolumeId, ReplicaId: id.ReplicaId, Epoch: id.Epoch, ValidForNs: int64(30 * time.Second), Revoking: s.revoke}, nil +} +func (s *exitAssignmentStream) AckWorkspaceRevoked(_ context.Context, a *control.WorkspaceRevocationAck) (*control.WorkspaceEmpty, error) { + if a.GetHeadGen() != 1 { + return nil, errors.New("ACK lacks the stored detached proof") + } + s.acks.Add(1) + return &control.WorkspaceEmpty{}, s.ackError +} func (s *exitAssignmentStream) ReportHeartbeat(context.Context, *control.HeartbeatReport) (*control.HeartbeatAck, error) { return &control.HeartbeatAck{}, nil } @@ -32,7 +50,7 @@ func (s *exitAssignmentStream) SubscribeAssignments(_ *control.SubscribeRequest, } } } -func exitAuthorityHost(t *testing.T) (*volume.Host, func(string, uint64)) { +func exitAuthorityHost(t *testing.T, configure ...func(*exitAssignmentStream)) (*volume.Host, func(string, uint64)) { t.Helper() ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { @@ -40,11 +58,15 @@ func exitAuthorityHost(t *testing.T) (*volume.Host, func(string, uint64)) { } srv := grpc.NewServer() stream := &exitAssignmentStream{facts: make(chan *control.AssignmentFact, 4)} + for _, f := range configure { + f(stream) + } + control.RegisterWorkspaceServiceServer(srv, stream) control.RegisterAssignmentServiceServer(srv, stream) control.RegisterObservationServiceServer(srv, stream) go srv.Serve(ln) t.Cleanup(srv.Stop) - h, err := volume.New(volume.Config{MasterAddr: ln.Addr().String(), ServerID: "s", VolumeID: "v", ReplicaID: "r", DataAddr: "127.0.0.1:1", CtrlAddr: "127.0.0.1:2"}) + h, err := volume.New(volume.Config{WorkspaceLease: true, MasterAddr: ln.Addr().String(), ServerID: "s", VolumeID: "v", ReplicaID: "r", DataAddr: "127.0.0.1:1", CtrlAddr: "127.0.0.1:2"}) if err != nil { t.Fatal(err) } @@ -134,3 +156,90 @@ func TestWorkspaceUnconfirmedRevokeHasOwnReason(t *testing.T) { t.Fatalf("unconfirmed ACK classified %+v", out) } } + +type exitWaitingProjection struct{} + +func (exitWaitingProjection) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v", ReplicaID: "r"} +} + +func TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck(t *testing.T) { + for _, failAck := range []bool{false, true} { + t.Run(map[bool]string{false: "ACK succeeds", true: "ACK lost"}[failAck], func(t *testing.T) { + var stream *exitAssignmentStream + h, send := exitAuthorityHost(t, func(s *exitAssignmentStream) { + stream = s + s.revoke = true + if failAck { + s.ackError = errors.New("ACK answer lost") + } + }) + send("r", 1) + ctx, cancel := context.WithCancel(context.Background()) + doneConsumed := false + requests, done := startWorkspaceLease(ctx, h) + t.Cleanup(func() { + cancel() + if !doneConsumed { + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("lease worker did not join") + } + } + }) + e := newProcessExit(ctx) + f := flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v", replicaID: "r"} + // The real guard sets revoked, sends its stop request, and waits for the + // resource owner's drain reply. No success is selected yet. + request, leaseDone := waitWorkspaceStop(e, f, h, requests, done) + if request == nil || !h.WorkspaceLeaseRevoking() { + t.Fatal("real planned drain not acquired") + } + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkAssignmentTimeout: time.Nanosecond, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }}, exitWaitingProjection{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err = p.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(ctx, "v"); err != nil { + t.Fatal(err) + } + select { + case <-p.ChunkStartupUpdates(): + case <-time.After(3 * time.Second): + t.Fatal("controlled startup expiry absent") + } + chooseChunkStartupExit(e, f, h, p) + select { + case out := <-e.decision: + t.Fatalf("startup overrode the pending real drain: %+v", out) + default: + } + remote := storage.NewMemChunkRemote() + _, err = remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "s/r", State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Epoch: 1, Holder: "s/r", Gen: 1}}) + if err != nil { + t.Fatal(err) + } + gen, err := workspaceDetachedGeneration(ctx, func(string) (storage.ChunkRemote, error) { return remote, nil }, request.id, "s/r") + if err != nil { + t.Fatal(err) + } + request.reply <- workspaceStopResult{gen: gen} + finishWorkspaceLease(e, f, h, leaseDone) + doneConsumed = true + out := <-e.decision + if stream.acks.Load() != 1 { + t.Fatal("real guard did not send proof ACK") + } + if !failAck && out.code != 0 { + t.Fatalf("ACKed stop restarted: %+v", out) + } + if failAck && (out.code != 75 || out.reason != "revoke_ack_unconfirmed") { + t.Fatalf("unconfirmed ACK: %+v", out) + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go b/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go index b61b3ac534..03206667a6 100644 --- a/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go +++ b/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go @@ -2,6 +2,7 @@ package durable_test import ( "context" + "errors" "reflect" "testing" "time" @@ -101,3 +102,50 @@ func TestChunkStartupSealedAssignmentStaysForReplay(t *testing.T) { } } } + +// The attach check returns a retained disposition only AFTER its context's +// deadline. This makes the timeout-defer boundary causal, not a scheduler race. +func TestChunkStartupRetainedDispositionWinsExpiredAttachContext(t *testing.T) { + for _, tc := range []struct { + name string + err error + }{ + {"sealed", storage.ErrChunkLayerDetached}, + {"stale local root", errors.Join(storage.ErrChunkLayerFenced, durable.ErrChunkStaleLocalRoot)}, + } { + t.Run(tc.name, func(t *testing.T) { + logs := &lockedLog{} + captureWriteLogs(t, logs) + view := v1View() + assigned := view.Projection() + waiting := assigned + waiting.Epoch = 0 + waiting.Healthy = false + view.set(waiting) + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, + ChunkAssignmentTimeout: 250 * time.Millisecond, + ChunkAttachCheck: func(ctx context.Context, _ string, _ durable.ChunkGeometry) error { <-ctx.Done(); return tc.err }, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { + t.Error("retained attach reached remote") + return storage.NewMemChunkRemote(), nil + }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err = p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + view.set(assigned) + waitLog(t, logs, "chunk authority wait for volume=v1 ended") + if _, failed := p.ChunkStartupOutcome("v1"); failed { + t.Fatal("deadline defer replaced retained attach disposition with process retry") + } + }) + } +} From 85139083d60fd0ba34ba7d37dc3f4681f8f1da1a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:58:15 -0800 Subject: [PATCH 26/57] test: schedule planned-drain expiry at provider outcome seam --- seaweed-block/cmd/blockvolume/process_exit.go | 8 ++++- .../process_exit_authority_test.go | 36 ++++++++----------- .../durable/provider_startup_outcome_test.go | 11 +++++- 3 files changed, 31 insertions(+), 24 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index 8a3ae07c37..7089128a81 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -171,7 +171,13 @@ func finishWorkspaceLease(e *processExit, f flags, h *volume.Host, done <-chan e e.choose(workspaceExit{exitWorkspaceRetry, "revoke_ack_unconfirmed"}) } -func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p *durable.DurableProvider) bool { +// The provider publishes only a generation-bound outcome and an atomic choice. +type chunkStartupOutcomeProvider interface { + ChunkStartupOutcome(string) (uint64, bool) + ChooseChunkStartupExit(string, uint64, func()) bool +} + +func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p chunkStartupOutcomeProvider) bool { if !f.workspaceLease || f.durableImpl != "walstore-chunk" { return false } diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go index 6ffe4db778..be80656ae4 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -3,8 +3,6 @@ package main import ( "context" "errors" - "github.com/seaweedfs/seaweed-block/core/frontend" - "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/host/volume" control "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/core/storage" @@ -157,10 +155,17 @@ func TestWorkspaceUnconfirmedRevokeHasOwnReason(t *testing.T) { } } -type exitWaitingProjection struct{} +// Controlled provider outcome at its public generation/selection seam. The +// real provider deadline/retained-state boundary is tested in durable. +type exitStartupOutcome struct{ expired bool } -func (exitWaitingProjection) Projection() frontend.Projection { - return frontend.Projection{VolumeID: "v", ReplicaID: "r"} +func (s *exitStartupOutcome) ChunkStartupOutcome(string) (uint64, bool) { return 1, s.expired } +func (s *exitStartupOutcome) ChooseChunkStartupExit(_ string, gen uint64, choose func()) bool { + if gen != 1 || !s.expired { + return false + } + choose() + return true } func TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck(t *testing.T) { @@ -196,22 +201,9 @@ func TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck(t *testing.T) { if request == nil || !h.WorkspaceLeaseRevoking() { t.Fatal("real planned drain not acquired") } - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkAssignmentTimeout: time.Nanosecond, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }}, exitWaitingProjection{}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = p.Close() }) - if _, err = p.EnsureStorage("v"); err != nil { - t.Fatal(err) - } - if _, err = p.RecoverVolume(ctx, "v"); err != nil { - t.Fatal(err) - } - select { - case <-p.ChunkStartupUpdates(): - case <-time.After(3 * time.Second): - t.Fatal("controlled startup expiry absent") - } + // Deliver expiry only after the real guard's planned drain owns + // shutdown, while its resource-owner reply is deliberately held. + p := &exitStartupOutcome{expired: true} chooseChunkStartupExit(e, f, h, p) select { case out := <-e.decision: @@ -219,7 +211,7 @@ func TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck(t *testing.T) { default: } remote := storage.NewMemChunkRemote() - _, err = remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "s/r", State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Epoch: 1, Holder: "s/r", Gen: 1}}) + _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "s/r", State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Epoch: 1, Holder: "s/r", Gen: 1}}) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go b/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go index 03206667a6..d8741bd803 100644 --- a/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go +++ b/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "reflect" + "sync/atomic" "testing" "time" @@ -122,10 +123,15 @@ func TestChunkStartupRetainedDispositionWinsExpiredAttachContext(t *testing.T) { waiting.Epoch = 0 waiting.Healthy = false view.set(waiting) + var entered atomic.Bool p, err := durable.NewDurableProvider(durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkAssignmentTimeout: 250 * time.Millisecond, - ChunkAttachCheck: func(ctx context.Context, _ string, _ durable.ChunkGeometry) error { <-ctx.Done(); return tc.err }, + ChunkAttachCheck: func(ctx context.Context, _ string, _ durable.ChunkGeometry) error { + entered.Store(true) + <-ctx.Done() + return tc.err + }, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { t.Error("retained attach reached remote") return storage.NewMemChunkRemote(), nil @@ -143,6 +149,9 @@ func TestChunkStartupRetainedDispositionWinsExpiredAttachContext(t *testing.T) { } view.set(assigned) waitLog(t, logs, "chunk authority wait for volume=v1 ended") + if !entered.Load() { + t.Fatal("fixture deadline elapsed before attach check entered; not a retained-disposition witness") + } if _, failed := p.ChunkStartupOutcome("v1"); failed { t.Fatal("deadline defer replaced retained attach disposition with process retry") } From 7600be4e818ed8a24f7acbec265a05f792a54cd6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 01:01:28 -0800 Subject: [PATCH 27/57] fix: preserve retained startup and planned-drain ownership --- seaweed-block/cmd/blockvolume/process_exit.go | 36 ++- .../startup_systemd_integration_test.go | 205 +++++++++++++----- .../workspace_weed_integration_test.go | 11 +- .../core/frontend/durable/provider_chunk.go | 5 +- .../docs/design/agent-workspace-design.md | 15 +- seaweed-block/docs/design/invariants.md | 4 +- 6 files changed, 214 insertions(+), 62 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index 7089128a81..fe4a0e392e 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -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) }) } diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index 49db69ecf8..5827b55e85 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -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) }) diff --git a/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go b/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go index afa7e1f32f..5ca1cbde54 100644 --- a/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go +++ b/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go @@ -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{ diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 206d3e5616..7fd1e45a02 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -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()) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index c8a8882f37..e1415f2e1d 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -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. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index eac66bed24..b6ff593151 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -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 @`; `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: From 6f3aa6090b158d1d1718ff6b2b7158c6eaf3e0ec Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 01:24:06 -0800 Subject: [PATCH 28/57] test: foreign HEAD claim must select no-retry exit --- .../process_exit_authority_test.go | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go index be80656ae4..ac6ca918c9 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -3,6 +3,8 @@ package main import ( "context" "errors" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/host/volume" control "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/core/storage" @@ -235,3 +237,68 @@ func TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck(t *testing.T) { }) } } + +// The real provider must carry the claim's filer proof to the process owner, +// even when the master stream has never reported another replica. +type claimExitView struct{} + +func (claimExitView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true} +} +func TestWorkspaceForeignHeadClaimChoosesNoRetry(t *testing.T) { + for _, tc := range []struct { + name, holder string + want int + }{ + {"foreign holder", "other", 78}, {"same holder higher epoch", "r", 75}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + h, _ := exitAuthorityHost(t) + remote := storage.NewMemChunkRemote() + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 2, Holder: tc.holder, State: storage.ChunkHeadActive}); err != nil { + t.Fatal(err) + } + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, claimExitView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := p.Close(); err != nil { + t.Error(err) + } + }) + if _, err = p.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(ctx, "v"); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("claim refusal=%v", err) + } + if h.LastOtherLine() != nil { + t.Fatal("fixture unexpectedly supplied master supersede evidence") + } + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) { + t.Fatal("claim refusal did not select an exit") + } + select { + case out := <-e.decision: + if out.code != tc.want { + t.Fatalf("claim exit=%+v want %d", out, tc.want) + } + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + head, err := remote.GetHead(ctx) + if err != nil || head.Gen != 1 || head.Holder != tc.holder || remote.Puts() != 0 { + t.Fatalf("refused claim mutated remote: %+v puts=%d err=%v", head, remote.Puts(), err) + } + for _, status := range p.DurableStatuses() { + if status.Operational { + t.Fatal("refused claim became operational") + } + } + }) + } +} From c2edb7305c69109182052d036547af895031a3a1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 01:26:01 -0800 Subject: [PATCH 29/57] fix: carry foreign HEAD claim proof to startup exit classification --- seaweed-block/cmd/blockvolume/process_exit.go | 6 + .../process_exit_authority_test.go | 129 ++++++++++-------- .../core/frontend/durable/provider.go | 12 +- .../core/frontend/durable/provider_chunk.go | 16 ++- .../core/frontend/durable/provider_startup.go | 14 +- .../durable/provider_startup_internal_test.go | 25 +++- seaweed-block/core/storage/chunk_restore.go | 6 +- .../docs/design/agent-workspace-design.md | 12 +- seaweed-block/docs/design/invariants.md | 4 +- 9 files changed, 148 insertions(+), 76 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index fe4a0e392e..f19b2c6b71 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -198,6 +198,7 @@ func finishWorkspaceLease(e *processExit, f flags, h *volume.Host, done <-chan e // The provider publishes only a generation-bound outcome and an atomic choice. type chunkStartupOutcomeProvider interface { ChunkStartupOutcome(string) (uint64, bool) + ChunkStartupSuperseded(string, uint64) bool ChooseChunkStartupExit(string, uint64, func()) bool } @@ -210,5 +211,10 @@ func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p chunkStar return false } out := workspaceRetryOutcome("assignment_timeout", h) + // INV-WS-STARTUP-RETRY-001: a claim's foreign-holder proof is + // independent of the master stream; generation is rechecked below. + if p.ChunkStartupSuperseded(f.volumeID, gen) { + out = workspaceExit{exitWorkspaceSuperseded, "superseded"} + } return p.ChooseChunkStartupExit(f.volumeID, gen, func() { e.chooseChunkStartup(out) }) } diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go index ac6ca918c9..ba49d3bf7f 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -161,7 +161,8 @@ func TestWorkspaceUnconfirmedRevokeHasOwnReason(t *testing.T) { // real provider deadline/retained-state boundary is tested in durable. type exitStartupOutcome struct{ expired bool } -func (s *exitStartupOutcome) ChunkStartupOutcome(string) (uint64, bool) { return 1, s.expired } +func (s *exitStartupOutcome) ChunkStartupSuperseded(string, uint64) bool { return false } +func (s *exitStartupOutcome) ChunkStartupOutcome(string) (uint64, bool) { return 1, s.expired } func (s *exitStartupOutcome) ChooseChunkStartupExit(_ string, gen uint64, choose func()) bool { if gen != 1 || !s.expired { return false @@ -240,65 +241,83 @@ func TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck(t *testing.T) { // The real provider must carry the claim's filer proof to the process owner, // even when the master stream has never reported another replica. -type claimExitView struct{} +type claimExitView struct{ assigned atomic.Bool } -func (claimExitView) Projection() frontend.Projection { +func (v *claimExitView) Projection() frontend.Projection { + if !v.assigned.Load() { + return frontend.Projection{VolumeID: "v"} + } return frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true} } func TestWorkspaceForeignHeadClaimChoosesNoRetry(t *testing.T) { - for _, tc := range []struct { - name, holder string - want int - }{ - {"foreign holder", "other", 78}, {"same holder higher epoch", "r", 75}, - } { - t.Run(tc.name, func(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - h, _ := exitAuthorityHost(t) - remote := storage.NewMemChunkRemote() - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 2, Holder: tc.holder, State: storage.ChunkHeadActive}); err != nil { - t.Fatal(err) - } - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, claimExitView{}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - if err := p.Close(); err != nil { - t.Error(err) + for _, deferred := range []bool{false, true} { + for _, tc := range []struct { + name, holder string + want int + }{ + {"foreign holder", "other", 78}, {"same holder higher epoch", "r", 75}, + } { + t.Run(tc.name+map[bool]string{false: "/immediate", true: "/waiting"}[deferred], func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + h, _ := exitAuthorityHost(t) + remote := storage.NewMemChunkRemote() + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 2, Holder: tc.holder, State: storage.ChunkHeadActive}); err != nil { + t.Fatal(err) + } + view := &claimExitView{} + view.assigned.Store(!deferred) + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := p.Close(); err != nil { + t.Error(err) + } + }) + if _, err = p.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + _, err = p.RecoverVolume(ctx, "v") + if deferred { + if err != nil { + t.Fatal(err) + } + view.assigned.Store(true) + } else if !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("claim refusal=%v", err) + } + select { + case <-p.ChunkStartupUpdates(): + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + if h.LastOtherLine() != nil { + t.Fatal("fixture unexpectedly supplied master supersede evidence") + } + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) { + t.Fatal("claim refusal did not select an exit") + } + select { + case out := <-e.decision: + if out.code != tc.want { + t.Fatalf("claim exit=%+v want %d", out, tc.want) + } + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + head, err := remote.GetHead(ctx) + if err != nil || head.Gen != 1 || head.Holder != tc.holder || remote.Puts() != 0 { + t.Fatalf("refused claim mutated remote: %+v puts=%d err=%v", head, remote.Puts(), err) + } + for _, status := range p.DurableStatuses() { + if status.Operational { + t.Fatal("refused claim became operational") + } } }) - if _, err = p.EnsureStorage("v"); err != nil { - t.Fatal(err) - } - if _, err = p.RecoverVolume(ctx, "v"); !errors.Is(err, storage.ErrChunkLayerFenced) { - t.Fatalf("claim refusal=%v", err) - } - if h.LastOtherLine() != nil { - t.Fatal("fixture unexpectedly supplied master supersede evidence") - } - e := newProcessExit(ctx) - if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) { - t.Fatal("claim refusal did not select an exit") - } - select { - case out := <-e.decision: - if out.code != tc.want { - t.Fatalf("claim exit=%+v want %d", out, tc.want) - } - case <-ctx.Done(): - t.Fatal(ctx.Err()) - } - head, err := remote.GetHead(ctx) - if err != nil || head.Gen != 1 || head.Holder != tc.holder || remote.Puts() != 0 { - t.Fatalf("refused claim mutated remote: %+v puts=%d err=%v", head, remote.Puts(), err) - } - for _, status := range p.DurableStatuses() { - if status.Operational { - t.Fatal("refused claim became operational") - } - } - }) + } } } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index d5b282877c..19ffa5acc5 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -285,11 +285,12 @@ type volHandle struct { // wait, 0 if none: a recovered volume whose layer waits for master // authority. A wait only acts while its generation is still the // latest recovery's. - recoverGen uint64 - waitGen uint64 - startupEnded uint64 // recovery generation with a terminal startup outcome; guarded by p.mu - chunk storage.ChunkLayer // after RecoverVolume - chunkLineage chunkLineage // immutable authority captured by this attachment + recoverGen uint64 + waitGen uint64 + startupSuperseded bool // exact foreign-holder claim proof for startupEnded; guarded by p.mu + startupEnded uint64 // recovery generation with a terminal startup outcome; guarded by p.mu + chunk storage.ChunkLayer // after RecoverVolume + chunkLineage chunkLineage // immutable authority captured by this attachment // Private until the owner commit succeeds; retained for attach retry. chunkPending storage.ChunkLayer // chunkDetach is set (under attachMu) when DetachVolume starts and @@ -951,6 +952,7 @@ func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (R h.recoverGen++ // any earlier recovery's authority wait is now stale gen = h.recoverGen h.startupEnded = 0 + h.startupSuperseded = false p.mu.Unlock() } report := Recover(h.storage, volumeID) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 7fd1e45a02..42742de6fd 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -56,8 +56,9 @@ var ( var ErrChunkStaleLocalRoot = errors.New("durable: local volume predates a HEAD published by another holder") var ( - errProviderClosed = errors.New("durable: provider closed") - errChunkNoAuthority = errors.New("durable: projection carries no master authority for the chunk layer") + errProviderClosed = errors.New("durable: provider closed") + errChunkForeignClaim = errors.New("durable: HEAD claim refused by another holder") + errChunkNoAuthority = errors.New("durable: projection carries no master authority for the chunk layer") ) const ( @@ -125,7 +126,7 @@ func (p *DurableProvider) recoverChunk(ctx context.Context, volumeID string, h * return false, nil } if errors.Is(err, storage.ErrChunkLayerFenced) && !errors.Is(err, ErrChunkStaleLocalRoot) { - p.endChunkStartup(h, gen) + p.endChunkStartup(h, gen, err) } return err == nil, err } @@ -177,7 +178,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen if p.current(h, gen) && h.chunk == nil { ended = fmt.Sprintf("assignment unavailable, not serving (projection lacks %s)", chunkAuthorityGap(p.view.Projection(), volumeID)) h.backend.SetOperational(false, "chunk assignment unavailable: "+waitCtx.Err().Error()) - p.endChunkStartup(h, gen) + p.endChunkStartup(h, gen, nil) } }() defer func() { @@ -251,7 +252,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen } h.attachMu.Unlock() } else { - p.endChunkStartup(h, gen) + p.endChunkStartup(h, gen, err) } return case errors.Is(err, errChunkNoAuthority): @@ -500,6 +501,11 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h log.Printf("durable: HEAD claim for volume=%s starting: target epoch=%d holder=%q", volumeID, cfg.Epoch, cfg.Holder) head, err := storage.ClaimChunkHead(ctx, remote, cfg) if err != nil { + // INV-WS-STARTUP-RETRY-001: only the claim's exact foreign-holder + // proof permits no-retry; a higher epoch of our own holder retries. + if errors.Is(err, storage.ErrChunkLayerFenced) && head.Gen != 0 && head.Holder != "" && head.Holder != cfg.Holder { + err = errors.Join(err, errChunkForeignClaim) + } log.Printf("durable: HEAD claim for volume=%s failed after %s: %v", volumeID, time.Since(claimStart), err) return nil, fmt.Errorf("durable: restore HEAD claim: %w", err) } diff --git a/seaweed-block/core/frontend/durable/provider_startup.go b/seaweed-block/core/frontend/durable/provider_startup.go index ff61f0978d..1d10da2aaf 100644 --- a/seaweed-block/core/frontend/durable/provider_startup.go +++ b/seaweed-block/core/frontend/durable/provider_startup.go @@ -1,5 +1,7 @@ package durable +import "errors" + // ChunkStartupUpdates wakes the process owner when a startup wait ends. It is // not an event queue: the owner must read ChunkStartupOutcome for its volume. // INV-WS-STARTUP-RETRY-001 keeps stale recoveries from terminating a newer one. @@ -18,13 +20,23 @@ func (p *DurableProvider) ChunkStartupOutcome(volumeID string) (uint64, bool) { return h.startupEnded, true } -func (p *DurableProvider) endChunkStartup(h *volHandle, gen uint64) { +// ChunkStartupSuperseded reports only a proven foreign-holder claim refusal +// for this exact recovery. Selection still rechecks gen under the provider lock. +func (p *DurableProvider) ChunkStartupSuperseded(volumeID string, gen uint64) bool { + p.mu.Lock() + defer p.mu.Unlock() + h := p.volumes[volumeID] + return !p.closed && h != nil && gen != 0 && h.recoverGen == gen && h.startupEnded == gen && h.startupSuperseded +} + +func (p *DurableProvider) endChunkStartup(h *volHandle, gen uint64, cause error) { p.mu.Lock() defer p.mu.Unlock() if p.closed || gen != h.recoverGen || h.startupEnded != 0 { return } h.startupEnded = gen + h.startupSuperseded = errors.Is(cause, errChunkForeignClaim) select { case p.startupUpdates <- struct{}{}: default: diff --git a/seaweed-block/core/frontend/durable/provider_startup_internal_test.go b/seaweed-block/core/frontend/durable/provider_startup_internal_test.go index 61fff6fdb6..3d5848f289 100644 --- a/seaweed-block/core/frontend/durable/provider_startup_internal_test.go +++ b/seaweed-block/core/frontend/durable/provider_startup_internal_test.go @@ -5,19 +5,19 @@ import "testing" func TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake(t *testing.T) { h := &volHandle{recoverGen: 1} p := &DurableProvider{volumes: map[string]*volHandle{"v": h}, startupUpdates: make(chan struct{}, 1)} - p.endChunkStartup(h, 1) + p.endChunkStartup(h, 1, nil) h.recoverGen = 2 h.startupEnded = 0 // RecoverVolume invalidates the old generation under p.mu. - p.endChunkStartup(h, 1) + p.endChunkStartup(h, 1, nil) if _, ok := p.ChunkStartupOutcome("v"); ok { t.Fatal("stale wait ended the new recovery") } - p.endChunkStartup(h, 2) // full wake channel must not discard the current latched result + p.endChunkStartup(h, 2, nil) // full wake channel must not discard the current latched result <-p.ChunkStartupUpdates() if gen, ok := p.ChunkStartupOutcome("v"); !ok || gen != 2 { t.Fatalf("current result lost: %d %v", gen, ok) } - p.endChunkStartup(h, 1) + p.endChunkStartup(h, 1, nil) if gen, ok := p.ChunkStartupOutcome("v"); !ok || gen != 2 { t.Fatal("late old completion overwrote the current result") } @@ -38,3 +38,20 @@ func TestChunkStartupExitRechecksGenerationBeforeChoice(t *testing.T) { t.Fatal("closed provider selected exit") } } + +func TestChunkStartupForeignProofIsGenerationBound(t *testing.T) { + h := &volHandle{recoverGen: 1} + p := &DurableProvider{volumes: map[string]*volHandle{"v": h}, startupUpdates: make(chan struct{}, 1)} + p.endChunkStartup(h, 1, errChunkForeignClaim) + if !p.ChunkStartupSuperseded("v", 1) || p.ChunkStartupSuperseded("other", 1) || p.ChunkStartupSuperseded("v", 2) { + t.Fatal("foreign proof escaped volume or generation") + } + h.recoverGen = 2 + h.startupEnded = 0 + h.startupSuperseded = false + p.endChunkStartup(h, 1, errChunkForeignClaim) + p.endChunkStartup(h, 2, nil) + if p.ChunkStartupSuperseded("v", 2) { + t.Fatal("old foreign proof poisoned current retry") + } +} diff --git a/seaweed-block/core/storage/chunk_restore.go b/seaweed-block/core/storage/chunk_restore.go index 5b39bdfef0..fb83e12467 100644 --- a/seaweed-block/core/storage/chunk_restore.go +++ b/seaweed-block/core/storage/chunk_restore.go @@ -11,6 +11,8 @@ import ( // persist lazy-read absence before exposing the local volume for I/O. // No WALStore, layer-state or provider-map lock is held across remote calls; // the provider may hold its per-volume attach serialization lock. +// On a proven owner fence, the returned HEAD is the exact observed proof; +// it is not an installed claim and must never be used to serve I/O. func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfig) (ChunkHead, error) { if remote == nil || cfg.Epoch == 0 || cfg.Holder == "" { return ChunkHead{}, errors.New("storage: HEAD claim needs master epoch and holder") @@ -35,7 +37,7 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi return ChunkHead{}, err } if head.Epoch > cfg.Epoch || (head.Gen != 0 && head.Epoch == cfg.Epoch && head.Holder != cfg.Holder) { - return ChunkHead{}, ErrChunkLayerFenced + return copyHead(head), ErrChunkLayerFenced } // INV-WS-SEALED-REOPEN-001: the sealing incarnation cannot reopen its // committed handoff proof. A higher-epoch takeover remains a separate claim. @@ -113,7 +115,7 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi } // A foreign publication is a fence, not permission to clean our roots. if current.Gen != 0 && (current.Epoch != head.Epoch || current.Holder != head.Holder) { - return ChunkHead{}, fmt.Errorf("storage: HEAD claim displaced: %w", ErrChunkLayerFenced) + return copyHead(current), fmt.Errorf("storage: HEAD claim displaced: %w", ErrChunkLayerFenced) } settled = errors.Is(casErr, ErrChunkHeadPrecondition) || current.Gen > head.Gen return ChunkHead{}, fmt.Errorf("storage: HEAD claim not installed: %w", casErr) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index e1415f2e1d..1e8bd22477 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -485,7 +485,8 @@ 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 newer master fact naming another replica permits exit 78; +RestartSec=5s. A newer master fact naming another replica or a refused claim proving another +HEAD holder 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,7 +501,7 @@ stateDiagram-v2 AwaitingAssignment --> Serving: grant and HEAD claim AwaitingAssignment --> Exit75: assignment wait exhausted Serving --> Exit75: lease fence - AwaitingAssignment --> Exit78: newer master fact names another replica + AwaitingAssignment --> Exit78: newer other-replica fact or exact foreign-holder HEAD claim proof Serving --> Exit78: lease fence and newer other-replica fact Exit75 --> AwaitingAssignment: supervisor starts new process Exit78 --> AwaitingAssignment: explicit operator start @@ -518,3 +519,10 @@ stateDiagram-v2 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. + +A refused HEAD claim returns its exact observed image as failure evidence, never +an installed claim. Only a nonempty foreign holder in that fenced image permits +no-retry independently of the assignment stream. Higher epochs of the same +holder and fences without that proof retain retry75. Provider generation checks +and planned-stop arbitration still apply; no readiness or listen gate changes +belong to this classification fix. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b6ff593151..40dcedce77 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -671,9 +671,9 @@ Notes: | `INV-WS-FORCED-CONFIRM-LOCAL-001` | A missing or malformed `--confirm-forced` is refused before any connection or RPC, with exit 2. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`; `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `request` | `TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally` (`cmd/sw-block/workspace_test.go`); `TestParseConfirmation` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | -| `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` | A workspace primary whose assignment wait ends or lease expires exits 75 after bounded fail-closed cleanup; a newer master fact naming another replica or a claim proving another HEAD holder 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`, `TestWorkspaceForeignHeadClaimChoosesNoRetry` (`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. +- `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another replica (compared with the latest own assignment, zero before any), or by the exact refused HEAD claim image proving another holder. The provider binds the latter proof to its recovery generation; stale-local-root diagnostics do not become no-retry. A same-holder higher-epoch HEAD fence retries 75. 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. From 3d2081756fdac27b1ffc213d78dd9330729bebe3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 01:26:33 -0800 Subject: [PATCH 30/57] docs: keep startup retry statement within ledger limit --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 40dcedce77..4e1f960a57 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -671,7 +671,7 @@ Notes: | `INV-WS-FORCED-CONFIRM-LOCAL-001` | A missing or malformed `--confirm-forced` is refused before any connection or RPC, with exit 2. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`; `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `request` | `TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally` (`cmd/sw-block/workspace_test.go`); `TestParseConfirmation` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | -| `INV-WS-STARTUP-RETRY-001` | A workspace primary whose assignment wait ends or lease expires exits 75 after bounded fail-closed cleanup; a newer master fact naming another replica or a claim proving another HEAD holder 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`, `TestWorkspaceForeignHeadClaimChoosesNoRetry` (`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` | A workspace primary exits 75 on assignment timeout or lease expiry, with bounded cleanup; a newer other-replica master fact or a refused claim proving another HEAD holder permits 78. ACKed revocation and signal retain normal exit. Lease and 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`, `TestWorkspaceForeignHeadClaimChoosesNoRetry` (`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 permitted by a NEWER observed master fact for this volume naming another replica (compared with the latest own assignment, zero before any), or by the exact refused HEAD claim image proving another holder. The provider binds the latter proof to its recovery generation; stale-local-root diagnostics do not become no-retry. A same-holder higher-epoch HEAD fence retries 75. 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. From 4a3a66597ac53be3293d39dd848073dca93f4da1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 01:28:44 -0800 Subject: [PATCH 31/57] test: superseded existing local holder must exit without retry --- .../process_exit_authority_test.go | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go index ba49d3bf7f..0c6c7d121c 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "context" "errors" "github.com/seaweedfs/seaweed-block/core/frontend" @@ -321,3 +322,66 @@ func TestWorkspaceForeignHeadClaimChoosesNoRetry(t *testing.T) { } } } + +// Unlike a move BACK to an older foreign publication, this local root's +// assignment is older than the foreign HEAD: another holder has superseded it. +func TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + h, _ := exitAuthorityHost(t) + root := t.TempDir() + remote := storage.NewMemChunkRemote() + view := &claimExitView{} + view.assigned.Store(true) + open := func() *durable.DurableProvider { + t.Helper() + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + return p + } + first := open() + if _, err := first.RecoverVolume(ctx, "v"); err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{0x73}, 4096) + if _, err := first.LogicalStorage("v").Write(0, want); err != nil { + t.Fatal(err) + } + if _, err := first.LogicalStorage("v").Sync(); err != nil { + t.Fatal(err) + } + if err := first.Close(); err != nil { + t.Fatal(err) + } + before, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: before.Gen, Epoch: before.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "other", State: storage.ChunkHeadActive}); err != nil { + t.Fatal(err) + } + second := open() + if _, err := second.RecoverVolume(ctx, "v"); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("old root refusal=%v", err) + } + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, second) { + t.Fatal("foreign HEAD attach refusal retained the superseded process") + } + if out := <-e.decision; out.code != 78 { + t.Fatalf("old holder exit=%+v", out) + } + if got, err := second.LogicalStorage("v").Read(0); err != nil || !bytes.Equal(got, want) { + t.Fatalf("refusal lost local acknowledged bytes: %v", err) + } + after, err := remote.GetHead(ctx) + if err != nil || after.Gen != before.Gen+1 || after.Holder != "other" || remote.Puts() != 0 { + t.Fatalf("refusal mutated HEAD/payload: %+v puts=%d err=%v", after, remote.Puts(), err) + } +} From 4814ce613c7bc8ce593dabe684843c43a330e957 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 01:29:40 -0800 Subject: [PATCH 32/57] fix: terminate superseded local roots while retaining move-back diagnostics --- .../process_exit_authority_test.go | 131 ++++++++++-------- .../core/frontend/durable/provider_chunk.go | 10 +- .../docs/design/agent-workspace-design.md | 5 + seaweed-block/docs/design/invariants.md | 4 +- 4 files changed, 89 insertions(+), 61 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go index 0c6c7d121c..829e8e5e18 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -326,62 +326,79 @@ func TestWorkspaceForeignHeadClaimChoosesNoRetry(t *testing.T) { // Unlike a move BACK to an older foreign publication, this local root's // assignment is older than the foreign HEAD: another holder has superseded it. func TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - h, _ := exitAuthorityHost(t) - root := t.TempDir() - remote := storage.NewMemChunkRemote() - view := &claimExitView{} - view.assigned.Store(true) - open := func() *durable.DurableProvider { - t.Helper() - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, view) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = p.Close() }) - if _, err := p.EnsureStorage("v"); err != nil { - t.Fatal(err) - } - return p - } - first := open() - if _, err := first.RecoverVolume(ctx, "v"); err != nil { - t.Fatal(err) - } - want := bytes.Repeat([]byte{0x73}, 4096) - if _, err := first.LogicalStorage("v").Write(0, want); err != nil { - t.Fatal(err) - } - if _, err := first.LogicalStorage("v").Sync(); err != nil { - t.Fatal(err) - } - if err := first.Close(); err != nil { - t.Fatal(err) - } - before, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: before.Gen, Epoch: before.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "other", State: storage.ChunkHeadActive}); err != nil { - t.Fatal(err) - } - second := open() - if _, err := second.RecoverVolume(ctx, "v"); !errors.Is(err, storage.ErrChunkLayerFenced) { - t.Fatalf("old root refusal=%v", err) - } - e := newProcessExit(ctx) - if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, second) { - t.Fatal("foreign HEAD attach refusal retained the superseded process") - } - if out := <-e.decision; out.code != 78 { - t.Fatalf("old holder exit=%+v", out) - } - if got, err := second.LogicalStorage("v").Read(0); err != nil || !bytes.Equal(got, want) { - t.Fatalf("refusal lost local acknowledged bytes: %v", err) - } - after, err := remote.GetHead(ctx) - if err != nil || after.Gen != before.Gen+1 || after.Holder != "other" || remote.Puts() != 0 { - t.Fatalf("refusal mutated HEAD/payload: %+v puts=%d err=%v", after, remote.Puts(), err) + for _, deferred := range []bool{false, true} { + t.Run(map[bool]string{false: "immediate", true: "waiting"}[deferred], func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + h, _ := exitAuthorityHost(t) + root := t.TempDir() + remote := storage.NewMemChunkRemote() + view := &claimExitView{} + view.assigned.Store(true) + open := func() *durable.DurableProvider { + t.Helper() + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + return p + } + first := open() + if _, err := first.RecoverVolume(ctx, "v"); err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{0x73}, 4096) + if _, err := first.LogicalStorage("v").Write(0, want); err != nil { + t.Fatal(err) + } + if _, err := first.LogicalStorage("v").Sync(); err != nil { + t.Fatal(err) + } + if err := first.Close(); err != nil { + t.Fatal(err) + } + before, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: before.Gen, Epoch: before.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "other", State: storage.ChunkHeadActive}); err != nil { + t.Fatal(err) + } + view.assigned.Store(!deferred) + second := open() + _, err = second.RecoverVolume(ctx, "v") + if deferred { + if err != nil { + t.Fatal(err) + } + view.assigned.Store(true) + select { + case <-second.ChunkStartupUpdates(): + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + } else if !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("old root refusal=%v", err) + } + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, second) { + t.Fatal("foreign HEAD attach refusal retained the superseded process") + } + if out := <-e.decision; out.code != 78 { + t.Fatalf("old holder exit=%+v", out) + } + if got, err := second.LogicalStorage("v").Read(0); err != nil || !bytes.Equal(got, want) { + t.Fatalf("refusal lost local acknowledged bytes: %v", err) + } + after, err := remote.GetHead(ctx) + if err != nil || after.Gen != before.Gen+1 || after.Holder != "other" || remote.Puts() != 0 { + t.Fatalf("refusal mutated HEAD/payload: %+v puts=%d err=%v", after, remote.Puts(), err) + } + + }) } } diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 42742de6fd..91f5e9e1fe 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -125,7 +125,7 @@ func (p *DurableProvider) recoverChunk(ctx context.Context, volumeID string, h * p.startChunkAuthorityWait(volumeID, h, gen) return false, nil } - if errors.Is(err, storage.ErrChunkLayerFenced) && !errors.Is(err, ErrChunkStaleLocalRoot) { + if errors.Is(err, storage.ErrChunkLayerFenced) && (!errors.Is(err, ErrChunkStaleLocalRoot) || errors.Is(err, errChunkForeignClaim)) { p.endChunkStartup(h, gen, err) } return err == nil, err @@ -244,7 +244,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen case errors.Is(err, storage.ErrChunkLayerFenced): ended = "fenced, not serving" log.Printf("durable: chunk layer for volume=%s: %v (not serving)", volumeID, err) - if errors.Is(err, ErrChunkStaleLocalRoot) { + if errors.Is(err, ErrChunkStaleLocalRoot) && !errors.Is(err, errChunkForeignClaim) { retained = true h.attachMu.Lock() if p.current(h, gen) && h.chunk == nil { @@ -450,6 +450,12 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h if head.Gen != 0 && head.Holder != holder { err := fmt.Errorf("%w: %w: volume %s local root %s, HEAD holder %q gen %d epoch %d, local holder %q; remove or quarantine the local root to attach fresh from HEAD", ErrChunkStaleLocalRoot, storage.ErrChunkLayerFenced, volumeID, h.path, head.Holder, head.Gen, head.Epoch, holder) + // INV-WS-STARTUP-RETRY-001: at or above this assignment, + // the foreign holder is a supersede proof. A lower epoch is + // the existing move-back/stale-root diagnostic, never 78. + if head.Epoch >= cfg.Epoch { + err = fmt.Errorf("%w: %w", err, errChunkForeignClaim) + } log.Printf("durable: refusing to attach volume=%s root=%s: HEAD holder=%q gen=%d epoch=%d is not this holder %q (remove or quarantine the local root)", volumeID, h.path, head.Holder, head.Gen, head.Epoch, holder) return err diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 1e8bd22477..833168a6a4 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -526,3 +526,8 @@ no-retry independently of the assignment stream. Higher epochs of the same holder and fences without that proof retain retry75. Provider generation checks and planned-stop arbitration still apply; no readiness or listen gate changes belong to this classification fix. + +The existing-local-root precheck uses the same distinction: another holder at +or above the assigned epoch is positive supersede evidence; an older foreign +publication remains the existing move-back diagnostic. Neither path serves or +publishes the local WAL, which remains on disk for diagnosis. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 4e1f960a57..d9807cda7e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -671,9 +671,9 @@ Notes: | `INV-WS-FORCED-CONFIRM-LOCAL-001` | A missing or malformed `--confirm-forced` is refused before any connection or RPC, with exit 2. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`; `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `request` | `TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally` (`cmd/sw-block/workspace_test.go`); `TestParseConfirmation` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | -| `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry, with bounded cleanup; a newer other-replica master fact or a refused claim proving another HEAD holder permits 78. ACKed revocation and signal retain normal exit. Lease and 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`, `TestWorkspaceForeignHeadClaimChoosesNoRetry` (`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` | A workspace primary exits 75 on assignment timeout or lease expiry, with bounded cleanup; a newer other-replica master fact or a refused claim proving another HEAD holder permits 78. ACKed revocation and signal retain normal exit. Lease and 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`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`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 permitted by a NEWER observed master fact for this volume naming another replica (compared with the latest own assignment, zero before any), or by the exact refused HEAD claim image proving another holder. The provider binds the latter proof to its recovery generation; stale-local-root diagnostics do not become no-retry. A same-holder higher-epoch HEAD fence retries 75. 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. +- `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another replica (compared with the latest own assignment, zero before any), or by the exact refused HEAD claim image proving another holder. The provider binds the latter proof to its recovery generation. On an existing root, a foreign HEAD at or above the assigned epoch proves supersede; a lower-epoch foreign HEAD retains the move-back diagnostic. A same-holder higher-epoch HEAD fence retries 75. 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. From c89e38f5c4e837e05de3d89d83f43a54b7959ab5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 02:04:11 -0800 Subject: [PATCH 33/57] test: empty replica fact cannot suppress workspace restart --- .../cmd/blockvolume/process_exit_authority_test.go | 4 ++++ seaweed-block/core/host/volume/workspace_startup_test.go | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go index 829e8e5e18..eb3dc01743 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -127,6 +127,10 @@ func TestWorkspaceRetryUsesNewestOwnAssignment(t *testing.T) { replica string epoch uint64 }{{"other", 6}}, 78}, + {"empty replica newer epoch", []struct { + replica string + epoch uint64 + }{{"r", 5}, {"", 7}}, 75}, {"same replica higher epoch", []struct { replica string epoch uint64 diff --git a/seaweed-block/core/host/volume/workspace_startup_test.go b/seaweed-block/core/host/volume/workspace_startup_test.go index 28330e77f5..ca8e39af63 100644 --- a/seaweed-block/core/host/volume/workspace_startup_test.go +++ b/seaweed-block/core/host/volume/workspace_startup_test.go @@ -29,3 +29,12 @@ func TestWorkspaceExitLineageIncludesBlockedOwnAssignment(t *testing.T) { t.Fatal("another volume produced a no-retry outcome") } } + +func TestWorkspaceEmptyOtherReplicaNeverSelectsNoRetry(t *testing.T) { + h, _, _ := newStubbedHost(t, "v", "r", &orderingRecorder{}) + h.applyFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 5, EndpointVersion: 1}) + h.applyFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "", Epoch: 7, EndpointVersion: 1}) + if h.IsCurrentReplicaSuperseded() { + t.Fatal("empty replica id is not another holder; must retry") + } +} From f36710e5b576b228e0ef8e357f7829a8424b6dc8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 02:05:54 -0800 Subject: [PATCH 34/57] fix: reject empty supersede identity and bound build pipe cleanup --- .../cmd/blockvolume/startup_systemd_integration_test.go | 1 + seaweed-block/core/host/volume/workspace_startup.go | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index 5827b55e85..fa869e29b3 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -52,6 +52,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { for _, name := range []string{"blockvolume", "blockmaster"} { buildCtx, buildCancel := context.WithTimeout(context.Background(), 2*time.Minute) cmd := exec.CommandContext(buildCtx, "go", "build", "-p", "4", "-o", filepath.Join(bin, name), "../"+name) + cmd.WaitDelay = time.Second // bound inherited child pipes after cancellation out, err := cmd.CombinedOutput() buildCancel() if err != nil { diff --git a/seaweed-block/core/host/volume/workspace_startup.go b/seaweed-block/core/host/volume/workspace_startup.go index 3de4ee4516..e3942fa611 100644 --- a/seaweed-block/core/host/volume/workspace_startup.go +++ b/seaweed-block/core/host/volume/workspace_startup.go @@ -23,7 +23,7 @@ func (h *Host) IsCurrentReplicaSuperseded() bool { h.ownAssignmentMu.RLock() defer h.ownAssignmentMu.RUnlock() other := h.LastOtherLine() - if other == nil || other.VolumeId != h.cfg.VolumeID { + if other == nil || other.ReplicaId == "" || other.VolumeId != h.cfg.VolumeID { return false } return h.IsSuperseded(h.cfg.ReplicaID, h.ownAssignmentEpoch, h.ownAssignmentEV) From 3fcbde02a83291efa391812ac2cc85c92857ed41 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 02:24:47 -0800 Subject: [PATCH 35/57] test: displaced lower-epoch claim must retry startup --- .../process_exit_authority_test.go | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go index eb3dc01743..80d8296aaa 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -406,3 +406,87 @@ func TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry(t *testing.T) { }) } } + +// The real claim reads E1/A; a late E2/C wins before E3/B's CAS. +// The displaced HEAD is a fence for this attempt, not proof E3 was superseded. +type displacedClaimExitRemote struct { + storage.ChunkRemote + epoch uint64 + raced bool +} + +func (r *displacedClaimExitRemote) CASHead(ctx context.Context, prev storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + if !r.raced { + r.raced = true + late := storage.ChunkHead{Epoch: r.epoch, Holder: "C", State: storage.ChunkHeadActive} + if _, err := r.ChunkRemote.CASHead(ctx, prev, late); err != nil { + return 0, err + } + } + return r.ChunkRemote.CASHead(ctx, prev, next) +} + +type displacedClaimExitView struct{} + +func (displacedClaimExitView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v", ReplicaID: "B", Epoch: 3, Healthy: true} +} +func TestWorkspaceDisplacedClaimUsesAssignedEpoch(t *testing.T) { + for _, tc := range []struct { + name string + epoch uint64 + want int + }{ + {"late lower epoch", 2, 75}, {"equal epoch foreign holder", 3, 78}, {"higher epoch foreign holder", 4, 78}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + h, _ := exitAuthorityHost(t) + base := storage.NewMemChunkRemote() + if _, err := base.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "A", State: storage.ChunkHeadActive}); err != nil { + t.Fatal(err) + } + remote := &displacedClaimExitRemote{ChunkRemote: base, epoch: tc.epoch} + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, displacedClaimExitView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := p.Close(); err != nil { + t.Error(err) + } + }) + if _, err = p.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(ctx, "v"); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("claim error=%v", err) + } + if !remote.raced { + t.Fatal("controlled CAS did not run") + } + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) { + t.Fatal("fenced claim did not choose an exit") + } + select { + case out := <-e.decision: + if out.code != tc.want { + t.Fatalf("displaced E%d/C at assigned E3/B chose %+v, want %d", tc.epoch, out, tc.want) + } + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + head, err := base.GetHead(ctx) + if err != nil || head.Gen != 2 || head.Epoch != tc.epoch || head.Holder != "C" || base.Puts() != 0 { + t.Fatalf("refused claim mutated HEAD/payload: %+v puts=%d err=%v", head, base.Puts(), err) + } + for _, status := range p.DurableStatuses() { + if status.Operational { + t.Fatal("displaced claim served I/O") + } + } + }) + } +} From 7dfa3127c1b7330b5e243c284f5e9fc03238e0e9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 02:25:28 -0800 Subject: [PATCH 36/57] fix: require assigned epoch for foreign claim no-retry proof --- seaweed-block/core/frontend/durable/provider_chunk.go | 10 ++++++++-- seaweed-block/docs/design/invariants.md | 6 +++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 91f5e9e1fe..17e438f558 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -453,7 +453,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h // INV-WS-STARTUP-RETRY-001: at or above this assignment, // the foreign holder is a supersede proof. A lower epoch is // the existing move-back/stale-root diagnostic, never 78. - if head.Epoch >= cfg.Epoch { + if claimHeadSupersedes(head, cfg) { err = fmt.Errorf("%w: %w", err, errChunkForeignClaim) } log.Printf("durable: refusing to attach volume=%s root=%s: HEAD holder=%q gen=%d epoch=%d is not this holder %q (remove or quarantine the local root)", @@ -509,7 +509,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h if err != nil { // INV-WS-STARTUP-RETRY-001: only the claim's exact foreign-holder // proof permits no-retry; a higher epoch of our own holder retries. - if errors.Is(err, storage.ErrChunkLayerFenced) && head.Gen != 0 && head.Holder != "" && head.Holder != cfg.Holder { + if errors.Is(err, storage.ErrChunkLayerFenced) && claimHeadSupersedes(head, cfg) { err = errors.Join(err, errChunkForeignClaim) } log.Printf("durable: HEAD claim for volume=%s failed after %s: %v", volumeID, time.Since(claimStart), err) @@ -1500,3 +1500,9 @@ func (w *cutWaitSlot) status(cutSeq uint64) CutScheduleStatus { } return st } + +// INV-WS-STARTUP-RETRY-001: a displaced lower-epoch claim fences this +// attempt, but cannot prove the assigned holder was superseded. +func claimHeadSupersedes(head storage.ChunkHead, cfg storage.ChunkLayerConfig) bool { + return head.Gen != 0 && head.Holder != "" && head.Holder != cfg.Holder && head.Epoch >= cfg.Epoch +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d9807cda7e..52f9338efc 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -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. 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` | +| Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait or lease fence exits 75 after bounded cleanup; a newer other-replica master fact or exact foreign HEAD at or above the assigned epoch permits 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 @`; `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` | @@ -671,9 +671,9 @@ Notes: | `INV-WS-FORCED-CONFIRM-LOCAL-001` | A missing or malformed `--confirm-forced` is refused before any connection or RPC, with exit 2. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`; `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `request` | `TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally` (`cmd/sw-block/workspace_test.go`); `TestParseConfirmation` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | -| `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry, with bounded cleanup; a newer other-replica master fact or a refused claim proving another HEAD holder permits 78. ACKed revocation and signal retain normal exit. Lease and 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`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`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` | A workspace primary exits 75 on assignment timeout or lease expiry, with bounded cleanup; a newer other-replica master fact or an exact foreign HEAD at or above the assigned epoch permits 78. ACKed revocation and signal retain normal exit. Lease and 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`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`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 permitted by a NEWER observed master fact for this volume naming another replica (compared with the latest own assignment, zero before any), or by the exact refused HEAD claim image proving another holder. The provider binds the latter proof to its recovery generation. On an existing root, a foreign HEAD at or above the assigned epoch proves supersede; a lower-epoch foreign HEAD retains the move-back diagnostic. A same-holder higher-epoch HEAD fence retries 75. 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. +- `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another replica (compared with the latest own assignment, zero before any), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. 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. From 2e2d7adf763cd4b9eb04514de91867b1f59639ed Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 02:35:56 -0800 Subject: [PATCH 37/57] docs: map displaced claim regression to startup retry invariant --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 52f9338efc..908d0c79de 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -671,7 +671,7 @@ Notes: | `INV-WS-FORCED-CONFIRM-LOCAL-001` | A missing or malformed `--confirm-forced` is refused before any connection or RPC, with exit 2. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`; `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `request` | `TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally` (`cmd/sw-block/workspace_test.go`); `TestParseConfirmation` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | -| `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry, with bounded cleanup; a newer other-replica master fact or an exact foreign HEAD at or above the assigned epoch permits 78. ACKed revocation and signal retain normal exit. Lease and 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`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`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` | A workspace primary exits 75 on assignment timeout or lease expiry, with bounded cleanup; a newer other-replica master fact or an exact foreign HEAD at or above the assigned epoch permits 78. ACKed revocation and signal retain normal exit. Lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `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`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`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 permitted by a NEWER observed master fact for this volume naming another replica (compared with the latest own assignment, zero before any), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. 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. From e5e316bf9fd90d96fd80062955c401dbced992f8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 02:40:11 -0800 Subject: [PATCH 38/57] docs: explain startup and runtime supersede evidence scope --- seaweed-block/docs/design/invariants.md | 1 + 1 file changed, 1 insertion(+) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 908d0c79de..8cdc67b999 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -674,6 +674,7 @@ Notes: | `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry, with bounded cleanup; a newer other-replica master fact or an exact foreign HEAD at or above the assigned epoch permits 78. ACKed revocation and signal retain normal exit. Lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `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`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`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 permitted by a NEWER observed master fact for this volume naming another replica (compared with the latest own assignment, zero before any), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. 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. +- Part T evidence scope: startup `chooseChunkStartupExit` ORs the newer other-replica master line with the recovery-generation-bound refused-claim HEAD proof. Runtime lease-end `workspaceRetryOutcome` has no new claim attempt supplying such a proof, so it uses only the master line and otherwise retries 75; absence of a HEAD proof never implies 78. - 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. From 329c42bc9cd5fe02fd2c7802c211a297a0d058f6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 03:20:59 -0800 Subject: [PATCH 39/57] test: host shutdown fence must record the guard terminal cause --- .../host/volume/workspace_terminal_test.go | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/seaweed-block/core/host/volume/workspace_terminal_test.go b/seaweed-block/core/host/volume/workspace_terminal_test.go index 8c12c94994..dcfc11e467 100644 --- a/seaweed-block/core/host/volume/workspace_terminal_test.go +++ b/seaweed-block/core/host/volume/workspace_terminal_test.go @@ -76,3 +76,41 @@ func TestWorkspaceCanceledReplyCannotPublishGrant(t *testing.T) { t.Error("canceled reply published a serving grant") } } + +// A synchronous host fence must use the guard's first-cause latch even +// before runtime publication; installation must carry that terminal cause. +func TestWorkspaceHostFencePublishesOneTerminalCause(t *testing.T) { + h := workspaceRuntimeHost(t, runtimeWire(t, &runtimeLeaseServer{ttl: time.Second}), true) + h.FenceWorkspaceLease() + g := h.view.workspaceGuard.Load() + if g == nil { + t.Fatal("host fence has no guard-owned terminal cause") + } + first := g.FenceCause() + if first == "" { + t.Fatal("host fence bypassed the guard first-cause latch") + } + h.FenceWorkspaceLease() + if g.FenceCause() != first || h.ProjectionView().Projection().Healthy { + t.Fatal("repeated fence changed cause or reopened admission") + } +} +func TestWorkspaceInstalledHostFenceRecordsCause(t *testing.T) { + wire := &runtimeLeaseServer{ttl: time.Second} + h := workspaceRuntimeHost(t, runtimeWire(t, wire), true) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + t.Cleanup(func() { cancel(); _ = runtimeDone(t, done) }) + go func() { + done <- h.RunWorkspaceLease(ctx, func(context.Context, *control.WorkspaceIdentity) (uint64, error) { return 7, nil }) + }() + runtimeAwait(t, "installed serving lease", func() bool { return h.ProjectionView().Projection().Healthy }) + g := h.view.workspaceGuard.Load() + h.FenceWorkspaceLease() + if g.FenceCause() == "" { + t.Error("installed host fence bypassed fenceLocked") + } + if h.ProjectionView().Projection().Healthy { + t.Error("host fence still admits I/O") + } +} From 1da0c2905dbbb1e1033cbf64ed26b296c82ddfc6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 03:22:28 -0800 Subject: [PATCH 40/57] fix: use guard fence ownership and one workspace exit decision --- seaweed-block/cmd/blockvolume/process_exit.go | 21 ++++++++--------- seaweed-block/core/host/volume/host.go | 3 +-- .../core/host/volume/workspace_runtime.go | 23 ++++++++++++++----- .../host/volume/workspace_terminal_test.go | 3 +++ .../docs/design/agent-workspace-design.md | 2 ++ seaweed-block/docs/design/invariants.md | 5 ++-- 6 files changed, 35 insertions(+), 22 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index f19b2c6b71..f1f5925e3b 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -118,10 +118,10 @@ func reportWorkspaceExit(out workspaceExit) int { return out.code } -// INV-WS-STARTUP-RETRY-001: only a newer other-replica authority fact -// permits no-retry. Host owns the lineage observation and shared predicate. -func workspaceRetryOutcome(reason string, h *volume.Host) workspaceExit { - if h.IsCurrentReplicaSuperseded() { +// INV-WS-STARTUP-RETRY-001: one decision combines a newer other-replica +// authority fact and the provider's generation-bound foreign-HEAD proof. +func workspaceRetryOutcome(reason string, h *volume.Host, claimSuperseded bool) workspaceExit { + if claimSuperseded || h.IsCurrentReplicaSuperseded() { return workspaceExit{exitWorkspaceSuperseded, "superseded"} } return workspaceExit{exitWorkspaceRetry, reason} @@ -161,7 +161,7 @@ func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan e.stopChunkStartup() out := workspaceExit{reason: "revoked"} if !h.WorkspaceLeaseRevoking() { - out = workspaceRetryOutcome("lease_expired", h) + out = workspaceRetryOutcome("lease_expired", h, false) } if out.code != 0 { e.choose(out) @@ -170,7 +170,7 @@ func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan case err := <-done: e.stopChunkStartup() fmt.Fprintln(os.Stderr, "blockvolume: workspace lease stopped:", err) - e.choose(workspaceRetryOutcome("lease_expired", h)) + e.choose(workspaceRetryOutcome("lease_expired", h, false)) return nil, nil } } @@ -210,11 +210,8 @@ func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p chunkStar if !failed { return false } - out := workspaceRetryOutcome("assignment_timeout", h) - // INV-WS-STARTUP-RETRY-001: a claim's foreign-holder proof is - // independent of the master stream; generation is rechecked below. - if p.ChunkStartupSuperseded(f.volumeID, gen) { - out = workspaceExit{exitWorkspaceSuperseded, "superseded"} - } + // INV-WS-STARTUP-RETRY-001: one exit decision consumes both proof + // sources; the provider rechecks the claim generation below. + out := workspaceRetryOutcome("assignment_timeout", h, p.ChunkStartupSuperseded(f.volumeID, gen)) return p.ChooseChunkStartupExit(f.volumeID, gen, func() { e.chooseChunkStartup(out) }) } diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index b7591515d8..9466b02ded 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -176,8 +176,7 @@ type Host struct { workspaceLeaseStarted atomic.Bool // Guard installation and terminal host fencing share this lock. Order: // workspaceLeaseMu -> guard.mu; never hold either across RPC or drain. - workspaceLeaseMu sync.Mutex - workspaceLeaseFenced bool + workspaceLeaseMu sync.Mutex // workspaceStopPending is the guard's stop-pending mode, kept here for a // guard installed later; workspaceStopAttempt numbers detach attempts so // only the latest one's resume clears it. diff --git a/seaweed-block/core/host/volume/workspace_runtime.go b/seaweed-block/core/host/volume/workspace_runtime.go index d6fad91ccf..775810b746 100644 --- a/seaweed-block/core/host/volume/workspace_runtime.go +++ b/seaweed-block/core/host/volume/workspace_runtime.go @@ -43,7 +43,14 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context, h.workspaceLeaseMu.Lock() // The guard is not yet shared: publish it already fenced if a // synchronous shutdown won the race with this installer. - guard.fenced = h.workspaceLeaseFenced || ctx.Err() != nil + if prior := h.view.workspaceGuard.Load(); prior != nil { + // Before this one-shot install, only FenceWorkspaceLease can + // publish a guard: its terminal cause must survive installation. + guard.fenceLocked(prior.FenceCause()) + } + if ctx.Err() != nil { + guard.fenceLocked("shutdown requested (context cancelled)") + } guard.stopPending = h.workspaceStopPending h.view.workspaceGuard.Store(guard) h.workspaceLeaseMu.Unlock() @@ -103,12 +110,16 @@ func (h *Host) WorkspaceStopResumed(volumeID string, attempt uint64) { func (h *Host) FenceWorkspaceLease() { h.workspaceLeaseMu.Lock() defer h.workspaceLeaseMu.Unlock() - h.workspaceLeaseFenced = true - if g := h.view.workspaceGuard.Load(); g != nil { - g.mu.Lock() - g.fenced = true - g.mu.Unlock() + // INV-WS-STARTUP-RETRY-001: the guard owns the only terminal latch, + // including shutdown before its runtime installation. + g := h.view.workspaceGuard.Load() + if g == nil { + g = &WorkspaceLeaseGuard{} } + g.mu.Lock() + g.fenceLocked("host shutdown requested") + g.mu.Unlock() + h.view.workspaceGuard.Store(g) } // WorkspaceLeaseRevoking distinguishes the ACK-owning planned drain from a diff --git a/seaweed-block/core/host/volume/workspace_terminal_test.go b/seaweed-block/core/host/volume/workspace_terminal_test.go index dcfc11e467..6bc031f272 100644 --- a/seaweed-block/core/host/volume/workspace_terminal_test.go +++ b/seaweed-block/core/host/volume/workspace_terminal_test.go @@ -42,6 +42,9 @@ func TestWorkspaceFenceBeforeHeldInstallIsTerminal(t *testing.T) { _ = runtimeDone(t, done) t.Fatal("fenced installer did not settle") } + if g := h.view.workspaceGuard.Load(); g == nil || g.FenceCause() != "host shutdown requested" { + t.Fatal("installation lost the synchronous fence cause") + } if stops.Load() != 1 || h.ProjectionView().Projection().Healthy { t.Fatal("fence failed to stop installed guard", stops.Load()) } diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 833168a6a4..9601926f6b 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -531,3 +531,5 @@ The existing-local-root precheck uses the same distinction: another holder at or above the assigned epoch is positive supersede evidence; an older foreign publication remains the existing move-back diagnostic. Neither path serves or publishes the local WAL, which remains on disk for diagnosis. + +Part T ownership: the lease guard alone holds the terminal fence and its first cause. A host shutdown before runtime installation publishes only a fenced, zero-validity guard; installation carries that cause into the valid-identity guard and never renews it. Startup and runtime exit callers both use workspaceRetryOutcome; only startup can supply a generation-bound refused-claim HEAD proof. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 8cdc67b999..927a61773d 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -189,7 +189,7 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | NoLease, Valid | Valid | the reply names this `{volume, replica, epoch}`, its validity is positive and at most 30 s, and it arrives before the old deadline; the new deadline is anchored to the request start | `core/host/volume/workspace_lease.go` `Refresh` | `INV-WS-LEASE-001`, `INV-WS-FORCED-MOVE-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001` | -| Valid, StopPending | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` | +| NoLease, Valid, StopPending | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, the lease is revoking, or synchronous host shutdown fences through the guard; first cause is kept and a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh`, `fenceLocked`; `core/host/volume/workspace_runtime.go` `FenceWorkspaceLease` | `INV-WS-LEASE-001` | | Valid | StopPending | a chunk detach of this volume starts (before its drain); the guard renews at once. Scheduling only: StopPending admits, fences and ACKs exactly as Valid | `core/frontend/durable/provider_chunk.go` `DetachVolume`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`; `core/host/volume/workspace_lease.go` `StopPending` | `INV-WS-STOP-PENDING-001` | | StopPending | StopPending | each sleep after a completed renewal is at most `stopPendingPoll` (250 ms); a renewal already in flight is not interrupted | `core/host/volume/workspace_lease.go` `renewDelay`, `Run` | `INV-WS-STOP-PENDING-001` | | StopPending | Valid | only the latest detach attempt, provably not applied, with serving resumed; an applied, fenced or unknown outcome, or an older attempt's resume, leaves StopPending | `core/frontend/durable/provider_chunk.go` `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `ClearStopPending` | `INV-WS-STOP-PENDING-001` | @@ -674,7 +674,8 @@ Notes: | `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry, with bounded cleanup; a newer other-replica master fact or an exact foreign HEAD at or above the assigned epoch permits 78. ACKed revocation and signal retain normal exit. Lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `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`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`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 permitted by a NEWER observed master fact for this volume naming another replica (compared with the latest own assignment, zero before any), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. 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. -- Part T evidence scope: startup `chooseChunkStartupExit` ORs the newer other-replica master line with the recovery-generation-bound refused-claim HEAD proof. Runtime lease-end `workspaceRetryOutcome` has no new claim attempt supplying such a proof, so it uses only the master line and otherwise retries 75; absence of a HEAD proof never implies 78. +- Part T evidence scope: `workspaceRetryOutcome` is the one retry/no-retry decision. Startup `chooseChunkStartupExit` supplies the recovery-generation-bound refused-claim HEAD proof; runtime lease-end supplies none. Both combine that input with the newer other-replica master line; absent proof means retry 75. +- Part T fence ownership: `Host.FenceWorkspaceLease` uses `WorkspaceLeaseGuard.fenceLocked`, including before runtime publication; the zero-validity terminal guard preserves the first cause through installation and can grant no I/O. No second host fence latch exists. `TestWorkspaceHostFencePublishesOneTerminalCause`, `TestWorkspaceInstalledHostFenceRecordsCause`, `TestWorkspaceFenceBeforeHeldInstallIsTerminal` (`core/host/volume/workspace_terminal_test.go`). - 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. From 764a208f4e0b9103e64420ceac5de2285615d10b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 06:05:41 -0800 Subject: [PATCH 41/57] fix: share supersession comparison across named lineage evidence --- .../process_exit_authority_test.go | 2 +- seaweed-block/core/host/volume/host.go | 32 +++++++------- .../core/host/volume/workspace_startup.go | 6 +-- .../host/volume/workspace_startup_test.go | 42 ++++++++++++++++--- seaweed-block/docs/design/invariants.md | 1 + 5 files changed, 55 insertions(+), 28 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go index 80d8296aaa..e86edd7c0c 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -79,7 +79,7 @@ func exitAuthorityHost(t *testing.T, configure ...func(*exitAssignmentStream)) ( }) return h, func(replica string, epoch uint64) { t.Helper() - stream.facts <- &control.AssignmentFact{VolumeId: "v", ReplicaId: replica, Epoch: epoch, EndpointVersion: 1} + stream.facts <- &control.AssignmentFact{VolumeId: "v", ReplicaId: replica, ServerId: "s", Epoch: epoch, EndpointVersion: 1} deadline := time.NewTimer(3 * time.Second) defer deadline.Stop() tick := time.NewTicker(time.Millisecond) diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index ddfc9c8e61..43e68fba2e 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -523,29 +523,27 @@ func (h *Host) getReplication() replicaSetUpdater { return h.replication } -// IsSuperseded gates a newer foreign replica line, or a same-replica foreign -// server identity strictly newer than an adopted local lineage. An explicitly -// matching self identity remains an ordinary adapter update. +// IsSuperseded compares an adopted lineage. Before adoption there is no +// serving incarnation to fence (INV-AUTH-HOLDER-IDENTITY-001). func (h *Host) IsSuperseded(selfReplicaID string, selfEpoch, selfEV uint64) bool { + return selfEpoch != 0 && h.isSupersededLineage(selfReplicaID, selfEpoch, selfEV) +} + +// isSupersededLineage is the one foreign-holder comparison. Callers name +// their evidence: adopted engine lineage for fencing, observed own assignment +// for process exit (INV-WS-STARTUP-RETRY-001). Zero observed lineage means this +// process never received its own assignment, not that a foreign line is ours. +func (h *Host) isSupersededLineage(selfReplicaID string, selfEpoch, selfEV uint64) bool { h.otherMu.Lock() defer h.otherMu.Unlock() - if h.lastOther == nil || selfEpoch == 0 { + other := h.lastOther + if other == nil || other.ReplicaId == "" || other.VolumeId != h.cfg.VolumeID { return false } - other := h.lastOther - if other.ReplicaId == selfReplicaID { - if h.assignmentNamesSelf(other) { - return false - } - return other.Epoch > selfEpoch || other.Epoch == selfEpoch && other.EndpointVersion > selfEV + if other.ReplicaId == selfReplicaID && h.assignmentNamesSelf(other) { + return false } - if other.Epoch > selfEpoch { - return true - } - if other.Epoch == selfEpoch && other.EndpointVersion > selfEV { - return true - } - return false + return other.Epoch > selfEpoch || other.Epoch == selfEpoch && other.EndpointVersion > selfEV } // ProjectionView returns the AdapterProjectionView that bridges diff --git a/seaweed-block/core/host/volume/workspace_startup.go b/seaweed-block/core/host/volume/workspace_startup.go index e3942fa611..1a270eb801 100644 --- a/seaweed-block/core/host/volume/workspace_startup.go +++ b/seaweed-block/core/host/volume/workspace_startup.go @@ -22,9 +22,5 @@ func (h *Host) recordSelfAssignment(f *control.AssignmentFact) { func (h *Host) IsCurrentReplicaSuperseded() bool { h.ownAssignmentMu.RLock() defer h.ownAssignmentMu.RUnlock() - other := h.LastOtherLine() - if other == nil || other.ReplicaId == "" || other.VolumeId != h.cfg.VolumeID { - return false - } - return h.IsSuperseded(h.cfg.ReplicaID, h.ownAssignmentEpoch, h.ownAssignmentEV) + return h.isSupersededLineage(h.cfg.ReplicaID, h.ownAssignmentEpoch, h.ownAssignmentEV) } diff --git a/seaweed-block/core/host/volume/workspace_startup_test.go b/seaweed-block/core/host/volume/workspace_startup_test.go index ca8e39af63..47643da2a0 100644 --- a/seaweed-block/core/host/volume/workspace_startup_test.go +++ b/seaweed-block/core/host/volume/workspace_startup_test.go @@ -7,12 +7,12 @@ import ( func TestWorkspaceExitLineageIncludesBlockedOwnAssignment(t *testing.T) { h, _, _ := newStubbedHost(t, "v", "r", &orderingRecorder{}) - h.applyFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "other", Epoch: 6, EndpointVersion: 1}) + h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "other", Epoch: 6, EndpointVersion: 1}) if !h.IsCurrentReplicaSuperseded() { t.Fatal("never-assigned newer other line did not supersede") } h.BlockLocalReadiness("local recovery pending") - h.applyFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 7, EndpointVersion: 1}) + h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 7, EndpointVersion: 1}) if h.IsCurrentReplicaSuperseded() { t.Fatal("blocked own assignment left historical other line current for exit") } @@ -20,7 +20,7 @@ func TestWorkspaceExitLineageIncludesBlockedOwnAssignment(t *testing.T) { if !h.IsSuperseded("r", 5, 1) { t.Fatal("exit observation weakened serving supersede predicate") } - h.applyFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 4, EndpointVersion: 1}) + h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 4, EndpointVersion: 1}) if h.IsCurrentReplicaSuperseded() { t.Fatal("older own delivery lowered the exit lineage") } @@ -32,9 +32,41 @@ func TestWorkspaceExitLineageIncludesBlockedOwnAssignment(t *testing.T) { func TestWorkspaceEmptyOtherReplicaNeverSelectsNoRetry(t *testing.T) { h, _, _ := newStubbedHost(t, "v", "r", &orderingRecorder{}) - h.applyFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 5, EndpointVersion: 1}) - h.applyFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "", Epoch: 7, EndpointVersion: 1}) + h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 5, EndpointVersion: 1}) + h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "", Epoch: 7, EndpointVersion: 1}) if h.IsCurrentReplicaSuperseded() { t.Fatal("empty replica id is not another holder; must retry") } } + +// The two Part T facts are intentionally different: a validated assignment can +// be observed while local recovery prevents the engine from adopting it. +func TestWorkspaceExitAndFenceUseNamedLineages(t *testing.T) { + h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "self", VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304"}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = h.Close() }) + fencer := &holderFenceCounter{} + if err := h.SetSelfFence(fencer); err != nil { + t.Fatal(err) + } + h.BlockLocalReadiness("local recovery pending") + foreign := holderAssignment(t, "other") + foreign.Epoch = 6 + h.applyFact(foreign) + if !h.IsCurrentReplicaSuperseded() || h.IsSuperseded("r1", 0, 0) || fencer.calls.Load() != 0 { + t.Fatal("foreign same-replica server must select exit78 without fencing an unadopted incarnation") + } + own := holderAssignment(t, "self") + own.Epoch = 7 + h.applyFact(own) + if h.view.EngineProjection().Epoch != 0 || h.IsCurrentReplicaSuperseded() || fencer.calls.Load() != 0 { + t.Fatal("observed own7 must suppress historical foreign6 for exit while adopted lineage stays zero") + } + foreign.Epoch = 8 + h.applyFact(foreign) + if !h.IsCurrentReplicaSuperseded() || h.IsSuperseded("r1", 0, 0) || fencer.calls.Load() != 0 { + t.Fatal("foreign8 must supersede observed own7 without changing the unadopted fencing rule") + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 759082daf5..7611fc2df8 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -717,6 +717,7 @@ Notes: | `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry, with bounded cleanup; a newer other-replica master fact or an exact foreign HEAD at or above the assigned epoch permits 78. ACKed revocation and signal retain normal exit. Lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `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`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`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 permitted by a NEWER observed master fact for this volume naming another replica (compared with the latest own assignment, zero before any), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. 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. +- Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former (zero means never assigned); fencing requires a nonzero latter. Both use `isSupersededLineage` through their named entry points; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages` and `TestWorkspaceExitLineageIncludesBlockedOwnAssignment` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal. - Part T evidence scope: `workspaceRetryOutcome` is the one retry/no-retry decision. Startup `chooseChunkStartupExit` supplies the recovery-generation-bound refused-claim HEAD proof; runtime lease-end supplies none. Both combine that input with the newer other-replica master line; absent proof means retry 75. - Part T fence ownership: `Host.FenceWorkspaceLease` uses `WorkspaceLeaseGuard.fenceLocked`, including before runtime publication; the zero-validity terminal guard preserves the first cause through installation and can grant no I/O. No second host fence latch exists. `TestWorkspaceHostFencePublishesOneTerminalCause`, `TestWorkspaceInstalledHostFenceRecordsCause`, `TestWorkspaceFenceBeforeHeldInstallIsTerminal` (`core/host/volume/workspace_terminal_test.go`). - 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. From 2332cba69650635e91f369f91eaa4ad5c804ba1b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 06:09:57 -0800 Subject: [PATCH 42/57] test: assert observed lineage precedes every adoption handoff --- .../host/volume/workspace_startup_test.go | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/seaweed-block/core/host/volume/workspace_startup_test.go b/seaweed-block/core/host/volume/workspace_startup_test.go index 47643da2a0..319e1a7b28 100644 --- a/seaweed-block/core/host/volume/workspace_startup_test.go +++ b/seaweed-block/core/host/volume/workspace_startup_test.go @@ -1,6 +1,7 @@ package volume import ( + "github.com/seaweedfs/seaweed-block/core/adapter" control "github.com/seaweedfs/seaweed-block/core/rpc/control" "testing" ) @@ -70,3 +71,71 @@ func TestWorkspaceExitAndFenceUseNamedLineages(t *testing.T) { t.Fatal("foreign8 must supersede observed own7 without changing the unadopted fencing rule") } } + +// Check at the adoption handoff, not just after applyFact: moving observation +// after adapter adoption must fail even when the eventual snapshots match. +type observationCheckedAdoption struct { + assignmentConsumer + before func(adapter.AssignmentInfo) +} + +func (a observationCheckedAdoption) OnAssignment(info adapter.AssignmentInfo) adapter.ApplyLog { + a.before(info) + return a.assignmentConsumer.OnAssignment(info) +} + +func TestWorkspaceObservedLineageNeverTrailsAdoption(t *testing.T) { + h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "self", VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304"}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = h.Close() }) + check := func(epoch, ev uint64) { + t.Helper() + h.ownAssignmentMu.RLock() + defer h.ownAssignmentMu.RUnlock() + if h.ownAssignmentEpoch < epoch || h.ownAssignmentEpoch == epoch && h.ownAssignmentEV < ev { + t.Fatalf("observation trails adoption handoff: observed=%d/%d adopted=%d/%d", h.ownAssignmentEpoch, h.ownAssignmentEV, epoch, ev) + } + } + adoptions := 0 + h.adpt = observationCheckedAdoption{h.adpt, func(info adapter.AssignmentInfo) { + check(info.Epoch, info.EndpointVersion) + adoptions++ + }} + assertAdopted := func(epoch, ev uint64) { + t.Helper() + p := h.view.EngineProjection() + if p.Epoch != epoch || p.EndpointVersion != ev { + t.Fatalf("adopted=%d/%d want=%d/%d", p.Epoch, p.EndpointVersion, epoch, ev) + } + check(p.Epoch, p.EndpointVersion) + } + own := holderAssignment(t, "self") + own.Epoch = 3 + h.applyFact(own) + assertAdopted(3, 1) + h.BlockLocalReadiness("local recovery pending") + own.Epoch = 7 + h.applyFact(own) + own.EndpointVersion = 2 + h.applyFact(own) + check(7, 2) + assertAdopted(3, 1) + h.ClearLocalReadinessBlock() + h.replayLocalReadinessFactIfReady() + assertAdopted(7, 2) + foreign := holderAssignment(t, "other") + foreign.Epoch = 8 + h.applyFact(foreign) + assertAdopted(7, 2) + own.Epoch = 9 + h.applyFact(own) + assertAdopted(9, 2) + own.Epoch = 7 + h.applyFact(own) + assertAdopted(9, 2) + if adoptions != 3 { + t.Fatalf("adoption handoffs=%d want3 (initial, readiness replay, move back)", adoptions) + } +} From e1edfe04da6671e2d324fc8ac616466560184a8d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 06:19:34 -0800 Subject: [PATCH 43/57] fix: apply zero-lineage retry rule to observed and adopted facts --- .../process_exit_authority_test.go | 2 +- .../startup_systemd_integration_test.go | 30 +++++++++---------- seaweed-block/core/host/volume/host.go | 16 ++++------ .../core/host/volume/workspace_startup.go | 2 +- .../host/volume/workspace_startup_test.go | 10 ++++--- seaweed-block/docs/design/invariants.md | 2 +- 6 files changed, 28 insertions(+), 34 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go index e86edd7c0c..44cbe8bece 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -126,7 +126,7 @@ func TestWorkspaceRetryUsesNewestOwnAssignment(t *testing.T) { {"never assigned", []struct { replica string epoch uint64 - }{{"other", 6}}, 78}, + }{{"other", 6}}, 75}, {"empty replica newer epoch", []struct { replica string epoch uint64 diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index fa869e29b3..ce34dde5d6 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -191,7 +191,7 @@ 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, fixture, stem, filepath.Join(bin, "blockvolume"), args, root, volume) + gap1NeverAssignedRetries(t, fixture, stem, filepath.Join(bin, "blockvolume"), args, root, volume) } // Roots are deliberately independent of testing.TempDir: unknown unit cleanup @@ -499,11 +499,11 @@ func gap1PlannedStopDoesNotRestart(t *testing.T, ws control.WorkspaceServiceClie }) } -// The master keeps the real r1 authority line. This process has never had an -// 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, fixture *gap1Fixture, stem, exe string, args []string, root, volume string) { +// The master keeps the real r1 authority line. A fresh r-old process has +// zero observed-own lineage, so a foreign fact selects retry75, never78. +// Run after the live holder has ACKed and exited, avoiding a node registration +// change while that holder is serving. This is not a superseded-holder witness. +func gap1NeverAssignedRetries(t *testing.T, fixture *gap1Fixture, stem, exe string, args []string, root, volume string) { t.Helper() changed := append([]string(nil), args...) addr := leaseBinaryAddress(t) @@ -538,7 +538,7 @@ func gap1SupersededDoesNotRestart(t *testing.T, fixture *gap1Fixture, stem, exe } // A never-assigned replica remains ModeIdle, so /status intentionally // reports unknown even after recording the other-replica fact. Prove - // receipt in this process before checking its terminal78 decision. + // receipt in this process before checking its retry75 decision. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() journal, err := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=cat").CombinedOutput() @@ -552,18 +552,16 @@ func gap1SupersededDoesNotRestart(t *testing.T, fixture *gap1Fixture, stem, exe } return false }) - waitGAP1(t, "positive supersede did not exit78 without restart", 45*time.Second, func() bool { + waitGAP1(t, "never-assigned foreign identity did not exit75 and restart", 45*time.Second, func() bool { s := gap1Unit(t, unit) - if s["NRestarts"] != "0" { - t.Fatalf("superseded unit restarted: %+v", s) + n, err := strconv.Atoi(s["NRestarts"]) + if err != nil { + t.Fatalf("invalid restart count: %+v", s) } - if s["MainPID"] != "0" { - return false + if s["ExecMainStatus"] == "78" { + t.Fatalf("zero-lineage process chose no-retry: %+v", s) } - if s["ExecMainStatus"] != "78" || s["ActiveState"] != "failed" || s["SubState"] != "failed" { - t.Fatalf("supersede not a terminal no-retry exit: %+v", s) - } - return true + return n >= 1 && s["MainPID"] != "0" && s["ExecMainStatus"] == "75" }) } diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 43e68fba2e..78b5613748 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -523,21 +523,15 @@ func (h *Host) getReplication() replicaSetUpdater { return h.replication } -// IsSuperseded compares an adopted lineage. Before adoption there is no -// serving incarnation to fence (INV-AUTH-HOLDER-IDENTITY-001). +// IsSuperseded is the one foreign-holder comparison. Callers supply the +// named lineage: adopted engine state for fencing, observed own assignment +// for exit classification. Zero lineage selects neither fencing nor exit78 +// (INV-AUTH-HOLDER-IDENTITY-001; INV-WS-STARTUP-RETRY-001). func (h *Host) IsSuperseded(selfReplicaID string, selfEpoch, selfEV uint64) bool { - return selfEpoch != 0 && h.isSupersededLineage(selfReplicaID, selfEpoch, selfEV) -} - -// isSupersededLineage is the one foreign-holder comparison. Callers name -// their evidence: adopted engine lineage for fencing, observed own assignment -// for process exit (INV-WS-STARTUP-RETRY-001). Zero observed lineage means this -// process never received its own assignment, not that a foreign line is ours. -func (h *Host) isSupersededLineage(selfReplicaID string, selfEpoch, selfEV uint64) bool { h.otherMu.Lock() defer h.otherMu.Unlock() other := h.lastOther - if other == nil || other.ReplicaId == "" || other.VolumeId != h.cfg.VolumeID { + if selfEpoch == 0 || other == nil || other.ReplicaId == "" || other.VolumeId != h.cfg.VolumeID { return false } if other.ReplicaId == selfReplicaID && h.assignmentNamesSelf(other) { diff --git a/seaweed-block/core/host/volume/workspace_startup.go b/seaweed-block/core/host/volume/workspace_startup.go index 1a270eb801..22a743f114 100644 --- a/seaweed-block/core/host/volume/workspace_startup.go +++ b/seaweed-block/core/host/volume/workspace_startup.go @@ -22,5 +22,5 @@ func (h *Host) recordSelfAssignment(f *control.AssignmentFact) { func (h *Host) IsCurrentReplicaSuperseded() bool { h.ownAssignmentMu.RLock() defer h.ownAssignmentMu.RUnlock() - return h.isSupersededLineage(h.cfg.ReplicaID, h.ownAssignmentEpoch, h.ownAssignmentEV) + return h.IsSuperseded(h.cfg.ReplicaID, h.ownAssignmentEpoch, h.ownAssignmentEV) } diff --git a/seaweed-block/core/host/volume/workspace_startup_test.go b/seaweed-block/core/host/volume/workspace_startup_test.go index 319e1a7b28..cec944cd7f 100644 --- a/seaweed-block/core/host/volume/workspace_startup_test.go +++ b/seaweed-block/core/host/volume/workspace_startup_test.go @@ -9,8 +9,10 @@ import ( func TestWorkspaceExitLineageIncludesBlockedOwnAssignment(t *testing.T) { h, _, _ := newStubbedHost(t, "v", "r", &orderingRecorder{}) h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "other", Epoch: 6, EndpointVersion: 1}) - if !h.IsCurrentReplicaSuperseded() { - t.Fatal("never-assigned newer other line did not supersede") + // Zero observed-own lineage inherits the fencing predicate's zero rule: + // a never-assigned process retries75; it has no own incarnation to supersede. + if h.IsCurrentReplicaSuperseded() { + t.Fatal("never-assigned process must retry75 despite a foreign line") } h.BlockLocalReadiness("local recovery pending") h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 7, EndpointVersion: 1}) @@ -56,8 +58,8 @@ func TestWorkspaceExitAndFenceUseNamedLineages(t *testing.T) { foreign := holderAssignment(t, "other") foreign.Epoch = 6 h.applyFact(foreign) - if !h.IsCurrentReplicaSuperseded() || h.IsSuperseded("r1", 0, 0) || fencer.calls.Load() != 0 { - t.Fatal("foreign same-replica server must select exit78 without fencing an unadopted incarnation") + if h.IsCurrentReplicaSuperseded() || h.IsSuperseded("r1", 0, 0) || fencer.calls.Load() != 0 { + t.Fatal("foreign same-replica server must select retry75 and no fence before any own assignment") } own := holderAssignment(t, "self") own.Epoch = 7 diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7611fc2df8..54a0d8c31a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -717,7 +717,7 @@ Notes: | `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry, with bounded cleanup; a newer other-replica master fact or an exact foreign HEAD at or above the assigned epoch permits 78. ACKed revocation and signal retain normal exit. Lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `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`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`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 permitted by a NEWER observed master fact for this volume naming another replica (compared with the latest own assignment, zero before any), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. 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. -- Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former (zero means never assigned); fencing requires a nonzero latter. Both use `isSupersededLineage` through their named entry points; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages` and `TestWorkspaceExitLineageIncludesBlockedOwnAssignment` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal. +- Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former; fencing compares the latter. Both use `IsSuperseded` with explicit lineage; zero lineage selects retry75 and no fence; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages` and `TestWorkspaceExitLineageIncludesBlockedOwnAssignment` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal. - Part T evidence scope: `workspaceRetryOutcome` is the one retry/no-retry decision. Startup `chooseChunkStartupExit` supplies the recovery-generation-bound refused-claim HEAD proof; runtime lease-end supplies none. Both combine that input with the newer other-replica master line; absent proof means retry 75. - Part T fence ownership: `Host.FenceWorkspaceLease` uses `WorkspaceLeaseGuard.fenceLocked`, including before runtime publication; the zero-validity terminal guard preserves the first cause through installation and can grant no I/O. No second host fence latch exists. `TestWorkspaceHostFencePublishesOneTerminalCause`, `TestWorkspaceInstalledHostFenceRecordsCause`, `TestWorkspaceFenceBeforeHeldInstallIsTerminal` (`core/host/volume/workspace_terminal_test.go`). - 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. From d7b7f2a432e8370675e750bd0c6cd3d6d95e8f2d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 06:19:50 -0800 Subject: [PATCH 44/57] test: observe retry exit before checking its restarted process --- .../startup_systemd_integration_test.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index ce34dde5d6..8c5cb64012 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -552,16 +552,20 @@ func gap1NeverAssignedRetries(t *testing.T, fixture *gap1Fixture, stem, exe stri } return false }) - waitGAP1(t, "never-assigned foreign identity did not exit75 and restart", 45*time.Second, func() bool { + waitGAP1(t, "never-assigned foreign identity did not exit75", 45*time.Second, func() bool { s := gap1Unit(t, unit) - n, err := strconv.Atoi(s["NRestarts"]) - if err != nil { - t.Fatalf("invalid restart count: %+v", s) - } if s["ExecMainStatus"] == "78" { t.Fatalf("zero-lineage process chose no-retry: %+v", s) } - return n >= 1 && s["MainPID"] != "0" && s["ExecMainStatus"] == "75" + return s["ExecMainStatus"] == "75" + }) + waitGAP1(t, "never-assigned retry75 did not restart", 15*time.Second, func() bool { + s := gap1Unit(t, unit) + n, err := strconv.Atoi(s["NRestarts"]) + if err != nil || n > 2 { + t.Fatalf("invalid or unbounded restart count: %+v", s) + } + return n >= 1 && s["MainPID"] != "0" }) } From 027c16171974131b547dfebedf77ddee174d6c5f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 06:21:22 -0800 Subject: [PATCH 45/57] docs: state nonzero observed-lineage requirement for superseded exit --- seaweed-block/docs/design/invariants.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 54a0d8c31a..db47d15a00 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -135,7 +135,7 @@ a pre-issued publication. | 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 primary server/replica/epoch, validated by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) with missing server refused, 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`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-AUTH-HOLDER-IDENTITY-001` | -| Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait or lease fence exits 75 after bounded cleanup; a newer other-replica master fact or exact foreign HEAD at or above the assigned epoch permits 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` | +| Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait or lease fence exits 75 after bounded cleanup; a foreign master fact newer than nonzero observed-own lineage or exact foreign HEAD at or above the assigned epoch permits 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 @`; `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 moved owner is captured with the assignment under pub.mu and persisted with the issuing move journal before publication; the stream uses that captured owner, empty when unknown, with placement fallback only for a move-less epoch; 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/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/workspace_binding.go` `workspaceLineOwner`; `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` | @@ -714,11 +714,11 @@ Notes: | `INV-WS-FORCED-CONFIRM-LOCAL-001` | A missing or malformed `--confirm-forced` is refused before any connection or RPC, with exit 2. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`; `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `request` | `TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally` (`cmd/sw-block/workspace_test.go`); `TestParseConfirmation` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | -| `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry, with bounded cleanup; a newer other-replica master fact or an exact foreign HEAD at or above the assigned epoch permits 78. ACKed revocation and signal retain normal exit. Lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `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`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`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` | A workspace primary exits 75 on assignment timeout or lease expiry after bounded cleanup. A master fact newer than nonzero observed-own, or an exact foreign HEAD at/above the assigned epoch, permits 78. ACK and signal keep normal exit; lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `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`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`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 permitted by a NEWER observed master fact for this volume naming another replica (compared with the latest own assignment, zero before any), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. 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. -- Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former; fencing compares the latter. Both use `IsSuperseded` with explicit lineage; zero lineage selects retry75 and no fence; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages` and `TestWorkspaceExitLineageIncludesBlockedOwnAssignment` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal. -- Part T evidence scope: `workspaceRetryOutcome` is the one retry/no-retry decision. Startup `chooseChunkStartupExit` supplies the recovery-generation-bound refused-claim HEAD proof; runtime lease-end supplies none. Both combine that input with the newer other-replica master line; absent proof means retry 75. +- `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another holder (compared with nonzero observed-own assignment; never-assigned zero retries75), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. 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. +- Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former; fencing compares the latter. Both use `IsSuperseded` with explicit lineage; zero lineage selects retry75 and no fence; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages`, `TestWorkspaceExitLineageIncludesBlockedOwnAssignment`, and `TestWorkspaceObservedLineageNeverTrailsAdoption` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal. +- Part T evidence scope: `workspaceRetryOutcome` is the one retry/no-retry decision. Startup `chooseChunkStartupExit` supplies the recovery-generation-bound refused-claim HEAD proof; runtime lease-end supplies none. Both combine that input with a foreign master line newer than nonzero observed-own; absent proof means retry 75. - Part T fence ownership: `Host.FenceWorkspaceLease` uses `WorkspaceLeaseGuard.fenceLocked`, including before runtime publication; the zero-validity terminal guard preserves the first cause through installation and can grant no I/O. No second host fence latch exists. `TestWorkspaceHostFencePublishesOneTerminalCause`, `TestWorkspaceInstalledHostFenceRecordsCause`, `TestWorkspaceFenceBeforeHeldInstallIsTerminal` (`core/host/volume/workspace_terminal_test.go`). - 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. From 4a517ed9aef2ad9faeb150fb497070d1faa62402 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 06:29:14 -0800 Subject: [PATCH 46/57] test: qualify supervised target started before its clean move --- .../startup_systemd_integration_test.go | 153 +++++++++++++----- 1 file changed, 111 insertions(+), 42 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index 8c5cb64012..f2c954c029 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -9,6 +9,7 @@ import ( "encoding/json" "fmt" "io" + "net" "net/http" "os" "os/exec" @@ -66,14 +67,15 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { volume := stem base := "/" + stem masterAddr := leaseBinaryAddress(t) + target, masterListen := gap1TargetAddresses(t, masterAddr) dataAddr, ctrlAddr, statusAddr, nvmeAddr := leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t) - cfg := fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n - id: %s\n size_bytes: 262144\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: r1\n source: existing_replica\n", dataAddr, ctrlAddr, volume) + cfg := fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\n - server_id: s2\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n - id: %s\n size_bytes: 262144\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: r1\n source: existing_replica\n", dataAddr, ctrlAddr, target.dataAddr, target.ctrlAddr, volume) spec := filepath.Join(root, "cluster.yaml") if err := os.WriteFile(spec, []byte(cfg), 0600); err != nil { t.Fatal(err) } fixture.start(t, stem+"-master", false, filepath.Join(bin, "blockmaster"), - "--listen", masterAddr, "--authority-store", filepath.Join(root, "auth"), "--lifecycle-store", filepath.Join(root, "life"), + "--listen", masterListen, "--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) w4WaitTCP(t, masterAddr, 20*time.Second) @@ -191,7 +193,7 @@ 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"]) - gap1NeverAssignedRetries(t, fixture, stem, filepath.Join(bin, "blockvolume"), args, root, volume) + gap1PrestartedTargetServesAfterMove(t, fixture, ws, remote, target, stem, filepath.Join(bin, "blockvolume"), args, root, volume, want) } // Roots are deliberately independent of testing.TempDir: unknown unit cleanup @@ -499,74 +501,141 @@ func gap1PlannedStopDoesNotRestart(t *testing.T, ws control.WorkspaceServiceClie }) } -// The master keeps the real r1 authority line. A fresh r-old process has -// zero observed-own lineage, so a foreign fact selects retry75, never78. -// Run after the live holder has ACKed and exited, avoiding a node registration -// change while that holder is serving. This is not a superseded-holder witness. -func gap1NeverAssignedRetries(t *testing.T, fixture *gap1Fixture, stem, exe string, args []string, root, volume string) { +// The host-consistency check uses the actual gRPC peer address. Model two +// registered hosts with loopback and a real non-loopback local IPv4 address; +// the target dials the master over that second address. Both processes and +// every restart still run under the same real WSL systemd (not two machines). +type gap1Target struct { + masterAddr, dataAddr, ctrlAddr string +} + +func gap1TargetAddresses(t *testing.T, masterAddr string) (gap1Target, string) { + t.Helper() + _, port, err := net.SplitHostPort(masterAddr) + if err != nil { + t.Fatal(err) + } + interfaces, err := net.Interfaces() + if err != nil { + t.Fatal(err) + } + for _, iface := range interfaces { + if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 { + continue + } + addresses, err := iface.Addrs() + if err != nil { + t.Fatal(err) + } + for _, address := range addresses { + ip, _, err := net.ParseCIDR(address.String()) + if err != nil || ip.To4() == nil || ip.IsLoopback() || ip.IsLinkLocalUnicast() { + continue + } + allocate := func() string { + ln, err := net.Listen("tcp", net.JoinHostPort(ip.String(), "0")) + if err != nil { + t.Fatal(err) + } + addr := ln.Addr().String() + if err := ln.Close(); err != nil { + t.Fatal(err) + } + return addr + } + return gap1Target{net.JoinHostPort(ip.String(), port), allocate(), allocate()}, net.JoinHostPort("0.0.0.0", port) + } + } + t.Fatal("qualification requires a real non-loopback IPv4 address; no skip is proof") + return gap1Target{}, "" +} + +// Start the future target before a clean move is issued. It has the same +// logical r1 slot but a different server id, and no own lineage: the source +// line cannot mean it lost anything. Prove75 and automatic restart, then issue +// a real MoveWorkspace and prove lease/HEAD/data admission without touching +// the target unit again. This is not a positive78/no-restart witness. +func gap1PrestartedTargetServesAfterMove(t *testing.T, fixture *gap1Fixture, ws control.WorkspaceServiceClient, remote storage.ChunkRemote, target gap1Target, stem, exe string, args []string, root, volume string, want []byte) { t.Helper() changed := append([]string(nil), args...) - addr := leaseBinaryAddress(t) - replacements := map[string]string{"--replica-id": "r-old", "--data-addr": leaseBinaryAddress(t), "--ctrl-addr": leaseBinaryAddress(t), "--status-addr": addr, "--durable-root": filepath.Join(root, "superseded-store"), "--nvme-listen": leaseBinaryAddress(t), "--nvme-subsysnqn": "nqn.2026-11.test:" + stem + "-superseded"} + addr, nvmeAddr := leaseBinaryAddress(t), leaseBinaryAddress(t) + nqn := "nqn.2026-11.test:" + stem + "-prestarted-target" + replacements := map[string]string{"--master": target.masterAddr, "--server-id": "s2", "--data-addr": target.dataAddr, "--ctrl-addr": target.ctrlAddr, "--status-addr": addr, "--durable-root": filepath.Join(root, "target-store"), "--nvme-listen": nvmeAddr, "--nvme-subsysnqn": nqn} for i := 0; i+1 < len(changed); i++ { if value, ok := replacements[changed[i]]; ok { changed[i+1] = value } } - unit := stem + "-superseded" + unit := stem + "-prestarted-target" 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 { + waitGAP1(t, "target never observed the source holder before the move", 15*time.Second, func() bool { + status, body, err := gap1Status(addr, volume) + if err != nil || status != http.StatusOK { return false } - defer resp.Body.Close() - raw, err := io.ReadAll(resp.Body) - if err != nil { - return false - } - t.Logf("captured real supersede status: status%d body%s", resp.StatusCode, raw) - if resp.StatusCode != http.StatusOK { - return false - } - var status hostvolume.StatusProjection - if err := json.Unmarshal(raw, &status); err != nil { + var projection hostvolume.StatusProjection + if err := json.Unmarshal(body, &projection); err != nil { t.Fatal(err) } - if status.Healthy || status.FrontendPrimaryReady { - t.Fatalf("unassigned old identity served: %+v", status) + if projection.Healthy || projection.FrontendPrimaryReady { + t.Fatalf("future target served before the move: %s", body) } - // A never-assigned replica remains ModeIdle, so /status intentionally - // reports unknown even after recording the other-replica fact. Prove - // receipt in this process before checking its retry75 decision. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - journal, err := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=cat").CombinedOutput() + cmd := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=cat") + cmd.WaitDelay = time.Second + journal, err := cmd.CombinedOutput() if err != nil { - t.Fatalf("supersede journal: %v %s", err, journal) + t.Fatalf("target journal: %v %s", err, journal) } - observed := fmt.Sprintf("volume %s authority is now r1@1 (not this replica r-old); recording supersede", volume) - if strings.Contains(string(journal), observed) { - t.Logf("captured authoritative other-replica observation: %s", observed) - return true - } - return false + observed := fmt.Sprintf("assignment identity refusal volume=%q replica=%q server=%q", volume, "r1", "s1") + return strings.Contains(string(journal), observed) }) - waitGAP1(t, "never-assigned foreign identity did not exit75", 45*time.Second, func() bool { + waitGAP1(t, "prestarted target did not exit75 before the move", 45*time.Second, func() bool { s := gap1Unit(t, unit) if s["ExecMainStatus"] == "78" { - t.Fatalf("zero-lineage process chose no-retry: %+v", s) + t.Fatalf("zero-lineage target chose no-retry before its move: %+v", s) } return s["ExecMainStatus"] == "75" }) - waitGAP1(t, "never-assigned retry75 did not restart", 15*time.Second, func() bool { + waitGAP1(t, "prestarted target retry75 did not restart", 15*time.Second, func() bool { s := gap1Unit(t, unit) n, err := strconv.Atoi(s["NRestarts"]) if err != nil || n > 2 { - t.Fatalf("invalid or unbounded restart count: %+v", s) + t.Fatalf("invalid or unbounded target restart count: %+v", s) } return n >= 1 && s["MainPID"] != "0" }) + sealed, err := gap1ReadHead(t, remote) + if err != nil || sealed.State != storage.ChunkHeadDetached || sealed.Holder != "s1/r1" || sealed.Gen == 0 { + t.Fatalf("move source not sealed by its exact holder: %+v %v", sealed, err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + grant, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: stem + "-target-move", VolumeId: volume, ExpectedReplicaId: "r1", ExpectedEpoch: sealed.Epoch, TargetReplicaId: "r1", TargetServerId: "s2", TargetDataAddr: target.dataAddr, TargetCtrlAddr: target.ctrlAddr, Kind: "clean"}) + cancel() + if err != nil || !grant.GetIssued() || grant.GetNewEpoch() <= sealed.Epoch || grant.GetOldHost() != "s1" || grant.GetNewHost() != "s2" || grant.GetHeadGen() != sealed.Gen { + t.Fatalf("real clean move failed: grant=%v err=%v", grant, err) + } + t.Logf("prestarted target move issued after its automatic restart: %s", grant) + waitGAP1(t, "automatically restarted target did not serve after the move", 60*time.Second, func() bool { + s := gap1Unit(t, unit) + n, err := strconv.Atoi(s["NRestarts"]) + if err != nil || n < 1 || n > 2 || s["Result"] == "start-limit-hit" { + t.Fatalf("target restart bound violated after move: %+v", s) + } + return gap1Operational(t, addr, volume) + }) + head, err := gap1ReadHead(t, remote) + if err != nil || head.Gen <= sealed.Gen || head.Epoch != grant.NewEpoch || head.Holder != "s2/r1" || head.State != storage.ChunkHeadActive { + t.Fatalf("target did not claim its issued HEAD: %+v %v", head, err) + } + client := gap1ConnectNVMe(t, nvmeAddr, nqn) + client.readExact(t, 8, want) + client.readExact(t, 9, want) + client.writeFlush(t, 10, want) + client.readExact(t, 10, want) + client.close() + t.Logf("prestarted target served after a real clean move without operator restart: unit=%s HEAD=%+v", unit, head) } // Register before the units: their exact-unit cleanup runs first, then this From 0a01e8156ca9487ece3bda6b146bb77f7ffe073b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 06:34:01 -0800 Subject: [PATCH 47/57] test: use neutral startup qualification names --- seaweed-block/cmd/blockvolume/process_exit.go | 2 +- .../blockvolume/startup_systemd_integration_test.go | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index f1f5925e3b..88c03b0c0c 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -62,7 +62,7 @@ func (e *processExit) choose(out workspaceExit) { if e.parent.Err() != nil { out = workspaceExit{reason: "signal"} } - e.decision <- out // exactly one send; the sole slot cannot block under a provider lock + e.decision <- out // exactly one send fits the buffer without blocking under a provider lock close(e.done) }) } diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index f2c954c029..41e2cc901c 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -31,10 +31,10 @@ import ( // The first assertion is RED on GAP-1: the expired startup stays alive. func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" { - t.Fatal("explicit booked WSL systemd qualification required; no skip counts as proof") + t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof") } if os.Geteuid() != 0 { - t.Fatal("systemd qualification needs the booked root harness") + t.Fatal("systemd qualification needs root") } if os.Getenv("CHUNKSTORE_WEED") == "" { t.Fatal("real CHUNKSTORE_WEED binary required") @@ -62,7 +62,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { } cluster := startWorkspaceWeedAt(t, filepath.Join(root, "weed")) gap1PreserveFailure(t, root, cluster.dir) - stem := fmt.Sprintf("codex03-gap1-%d", time.Now().UnixNano()) + stem := fmt.Sprintf("gap1-%d", time.Now().UnixNano()) gap1ProbeTerminalSuccess(t, fixture, stem+"-policy-probe") volume := stem base := "/" + stem @@ -205,7 +205,7 @@ type gap1Fixture struct { func newGAP1Fixture(t *testing.T) *gap1Fixture { t.Helper() - root, err := os.MkdirTemp("", "codex03-gap1-runtime-") + root, err := os.MkdirTemp("", "gap1-runtime-") if err != nil { t.Fatal(err) } @@ -551,7 +551,7 @@ func gap1TargetAddresses(t *testing.T, masterAddr string) (gap1Target, string) { } // Start the future target before a clean move is issued. It has the same -// logical r1 slot but a different server id, and no own lineage: the source +// logical r1 identity but a different server id, and no own lineage: the source // line cannot mean it lost anything. Prove75 and automatic restart, then issue // a real MoveWorkspace and prove lease/HEAD/data admission without touching // the target unit again. This is not a positive78/no-restart witness. From a9ff14e232453ea33f3a00b4d789e104319c8603 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 06:38:53 -0800 Subject: [PATCH 48/57] test: use explicit external bind and validate readiness response schema --- .../startup_systemd_integration_test.go | 86 +++++++++++++++++-- 1 file changed, 80 insertions(+), 6 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index 41e2cc901c..baeb17f0ea 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -75,7 +75,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { t.Fatal(err) } fixture.start(t, stem+"-master", false, filepath.Join(bin, "blockmaster"), - "--listen", masterListen, "--authority-store", filepath.Join(root, "auth"), "--lifecycle-store", filepath.Join(root, "life"), + "--listen", masterListen, "--insecure-external-bind", "--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) w4WaitTCP(t, masterAddr, 20*time.Second) @@ -94,6 +94,22 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { bootstrap := stem + "-bootstrap" 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 the readiness parser on the serving source's actual /status + // response before using it for the target's negative readiness assertion. + waitGAP1(t, "source readiness control never became true", 20*time.Second, func() bool { + status, body, err := gap1StatusAt(statusAddr, volume, "/status") + if err != nil || status != http.StatusOK { + return false + } + serving, err := gap1Readiness(status, body, volume) + if err != nil { + t.Fatal(err) + } + if serving { + t.Logf("captured real readiness control: status%d body%s", status, body) + } + return serving + }) // Calibrate verdict parsing against actual binary responses BEFORE kill. status, payload, err := gap1Status(statusAddr, volume) t.Logf("captured real status200: status%d body%s", status, payload) @@ -367,7 +383,10 @@ func gap1ReadUnit(unit string) (map[string]string, error) { 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) + return gap1StatusAt(addr, volume, "/status/durable") +} +func gap1StatusAt(addr, volume, route string) (int, []byte, error) { + r, e := (&http.Client{Timeout: time.Second}).Get("http://" + addr + route + "?volume=" + volume) if e != nil { return 0, nil, e } @@ -375,6 +394,61 @@ func gap1Status(addr, volume string) (int, []byte, error) { body, e := io.ReadAll(io.LimitReader(r.Body, 1<<20)) return r.StatusCode, body, e } + +// /status is a different schema from /status/durable. Presence checks make +// a wrong route or a missing field a failed oracle, not false readiness. +func gap1Readiness(status int, payload []byte, volume string) (bool, error) { + if status != http.StatusOK { + return false, fmt.Errorf("readiness HTTP status%d", status) + } + var body struct { + VolumeID string + Healthy, FrontendPrimaryReady *bool + } + if err := json.Unmarshal(payload, &body); err != nil { + return false, err + } + if body.VolumeID != volume || body.Healthy == nil || body.FrontendPrimaryReady == nil { + return false, fmt.Errorf("readiness response lacks exact volume and readiness fields: %s", payload) + } + return *body.Healthy || *body.FrontendPrimaryReady, nil +} + +func TestGAP1ReadinessRejectsWrongSchema(t *testing.T) { + projection := hostvolume.StatusProjection{} + projection.VolumeID = "v" + projectionPayload := func(healthy, ready bool) []byte { + t.Helper() + projection.Healthy, projection.FrontendPrimaryReady = healthy, ready + b, err := json.Marshal(projection) + if err != nil { + t.Fatal(err) + } + return b + } + for _, tc := range []struct { + name string + status int + body []byte + serving, refused bool + }{ + {"not-ready", 200, projectionPayload(false, false), false, false}, + {"healthy", 200, projectionPayload(true, false), true, false}, + {"frontend-ready", 200, projectionPayload(false, true), true, false}, + {"durable-route", 200, []byte(`{"VolumeID":"v","Volumes":[{"VolumeID":"v","Operational":false}]}`), false, true}, + {"missing-readiness", 200, []byte(`{"VolumeID":"v","Healthy":false}`), false, true}, + {"wrong-volume", 200, []byte(`{"VolumeID":"other","Healthy":false,"FrontendPrimaryReady":false}`), false, true}, + {"http-refusal", 404, projectionPayload(false, false), false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + got, err := gap1Readiness(tc.status, tc.body, "v") + if got != tc.serving || (err != nil) != tc.refused { + t.Fatalf("serving=%v err=%v want=%v refused=%v", got, err, tc.serving, tc.refused) + } + }) + } +} + func gap1StatusOperational(status int, payload []byte, volume string) bool { if status != http.StatusOK { return false @@ -569,15 +643,15 @@ func gap1PrestartedTargetServesAfterMove(t *testing.T, fixture *gap1Fixture, ws unit := stem + "-prestarted-target" fixture.start(t, unit, true, exe, changed...) waitGAP1(t, "target never observed the source holder before the move", 15*time.Second, func() bool { - status, body, err := gap1Status(addr, volume) + status, body, err := gap1StatusAt(addr, volume, "/status") if err != nil || status != http.StatusOK { return false } - var projection hostvolume.StatusProjection - if err := json.Unmarshal(body, &projection); err != nil { + serving, err := gap1Readiness(status, body, volume) + if err != nil { t.Fatal(err) } - if projection.Healthy || projection.FrontendPrimaryReady { + if serving { t.Fatalf("future target served before the move: %s", body) } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) From 564c0df27f500f55f9057e50e2128ad43f474649 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 07:12:31 -0800 Subject: [PATCH 49/57] fix(blockvolume): restore workspace drain diagnostic --- seaweed-block/cmd/blockvolume/process_exit.go | 1 + 1 file changed, 1 insertion(+) diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index 88c03b0c0c..d86fb0aa29 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -158,6 +158,7 @@ func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan case <-e.done: return nil, done case request := <-requests: + fmt.Fprintln(os.Stderr, "blockvolume: stopping: the workspace lease guard fenced and requested the drain") e.stopChunkStartup() out := workspaceExit{reason: "revoked"} if !h.WorkspaceLeaseRevoking() { From 34675c093065c30a6cb3e14eb21c00d74d0e1ca3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 00:28:20 -0800 Subject: [PATCH 50/57] blockvolume: no frontend listens and status is not primary-ready until the backend admits I/O A restarted old holder (G-O2 r8) started its NVMe target unconditionally at startup and reported FrontendPrimaryReady=true from the authority view alone, before and after its chunk-layer claim was refused ("fenced, not serving"). The admit gate refused every command with Namespace Not Ready, but that status is retried on the same path and then fails to the guest, and the path advertised ANA optimized, so a listening, ready-looking but fenced target is not safe. - status: FrontendPrimaryReady is false while the volume's local durable backend admits no I/O (attach pending, fenced, detached), with the backend's evidence in the new NotReadyReason; Healthy stays the authority view. - blockvolume: the iSCSI, NVMe and ublk targets start only once the backend first admits I/O (awaitBackendAdmitsIO, 10 ms); signals and the workspace lease guard now start before that wait, and a stop requested during it skips the frontends and goes straight to shutdown. INV-FE-PRIMARY-READY-OPERATIONAL-001 (304 rows, 218 ACTIVE); M1 Recovering -> Serving names the guard. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/frontend_gate.go | 42 ++ .../cmd/blockvolume/frontend_gate_test.go | 85 ++++ seaweed-block/cmd/blockvolume/main.go | 418 ++++++++++-------- .../frontend/durable/first_serving_test.go | 49 ++ .../core/frontend/durable/storage_adapter.go | 26 +- .../core/host/volume/status_server.go | 43 +- .../core/host/volume/status_server_test.go | 86 ++++ .../core/host/volume/status_warnings_test.go | 2 +- seaweed-block/docs/design/invariants.md | 7 +- seaweed-block/docs/status-schema.md | 3 +- 10 files changed, 554 insertions(+), 207 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/frontend_gate.go create mode 100644 seaweed-block/cmd/blockvolume/frontend_gate_test.go create mode 100644 seaweed-block/core/frontend/durable/first_serving_test.go diff --git a/seaweed-block/cmd/blockvolume/frontend_gate.go b/seaweed-block/cmd/blockvolume/frontend_gate.go new file mode 100644 index 0000000000..69a5b84bdc --- /dev/null +++ b/seaweed-block/cmd/blockvolume/frontend_gate.go @@ -0,0 +1,42 @@ +package main + +import ( + "fmt" + "os" +) + +// workspaceStopWait is what the process's one stop waiter (waitWorkspaceStop) +// returned: the lease drain request to honour, and the lease guard's done +// channel (nil once consumed). +type workspaceStopWait struct { + leaseStop *workspaceStopRequest + leaseDone <-chan error +} + +// awaitFrontendStart races the backend's first admitted I/O against the stop +// waiter (INV-FE-PRIMARY-READY-OPERATIONAL-001). serving is closed the first +// time the backend admits I/O (for a chunk volume: after its storage claim); +// nil means there is no durable backend to wait for. It returns start = true +// when the frontends may start; otherwise the stop that won, which the caller +// shuts down with exactly as after the frontends. A stop decided meanwhile by +// INV-WS-STARTUP-RETRY-001 (exit 75 or 78) ends the stop waiter too, so a +// refused claim never starts a frontend. +func awaitFrontendStart(serving <-chan struct{}, stopWait <-chan workspaceStopWait) (stopped *workspaceStopWait, start bool) { + if serving == nil { + return nil, true + } + select { + case <-serving: + return nil, true + default: + } + fmt.Fprintln(os.Stderr, "blockvolume: frontends wait for the storage claim: the backend admits no I/O yet") + select { + case <-serving: + fmt.Fprintln(os.Stderr, "blockvolume: backend admits I/O: starting the frontends") + return nil, true + case w := <-stopWait: + fmt.Fprintln(os.Stderr, "blockvolume: stopping before any frontend started") + return &w, false + } +} diff --git a/seaweed-block/cmd/blockvolume/frontend_gate_test.go b/seaweed-block/cmd/blockvolume/frontend_gate_test.go new file mode 100644 index 0000000000..d250af7539 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/frontend_gate_test.go @@ -0,0 +1,85 @@ +package main + +import ( + "context" + "testing" + "time" +) + +type gateResult struct { + stopped *workspaceStopWait + start bool +} + +func runGate(serving <-chan struct{}, stopWait <-chan workspaceStopWait) <-chan gateResult { + out := make(chan gateResult, 1) + go func() { + s, ok := awaitFrontendStart(serving, stopWait) + out <- gateResult{s, ok} + }() + return out +} + +// INV-FE-PRIMARY-READY-OPERATIONAL-001: the frontends start only once the +// backend first admits I/O. With no durable backend, and with a backend that +// already serves, they start at once. Sampled every 10 ms while the backend +// admits no I/O (a chunk volume before its storage claim), the gate never +// releases; it releases as soon as the backend's first-serving channel closes. +func TestFrontendGateWaitsForTheStorageClaim(t *testing.T) { + for name, serving := range map[string]chan struct{}{"no durable backend": nil, "already serving": make(chan struct{})} { + if serving != nil { + close(serving) + } + var ch <-chan struct{} + if serving != nil { + ch = serving + } + select { + case r := <-runGate(ch, make(chan workspaceStopWait)): + if !r.start || r.stopped != nil { + t.Fatalf("%s: %+v, want the frontends started at once", name, r) + } + case <-time.After(time.Second): + t.Fatalf("%s: the gate did not release at once", name) + } + } + + serving := make(chan struct{}) + res := runGate(serving, make(chan workspaceStopWait)) + for i := 0; i < 30; i++ { // 300 ms of samples while the claim is pending + select { + case r := <-res: + t.Fatalf("sample %d: the gate released (%+v) before the backend admitted I/O", i, r) + case <-time.After(10 * time.Millisecond): + } + } + close(serving) // the storage claim succeeded + select { + case r := <-res: + if !r.start { + t.Fatalf("after the claim: %+v, want the frontends started", r) + } + case <-time.After(time.Second): + t.Fatal("the gate did not release after the backend admitted I/O") + } +} + +// A refused claim never closes the first-serving channel; the process's stop +// waiter then wins (a signal, the lease guard, or INV-WS-STARTUP-RETRY-001's +// latched exit 75/78) and no frontend starts: the stop is handed back for +// the ordinary shutdown, its lease drain request included. +func TestFrontendGateStopsWithoutStartingTheFrontends(t *testing.T) { + stopWait := make(chan workspaceStopWait, 1) + res := runGate(make(chan struct{}), stopWait) // fenced: never serves + select { + case r := <-res: + t.Fatalf("a backend that never serves released the gate: %+v", r) + case <-time.After(100 * time.Millisecond): + } + req := &workspaceStopRequest{ctx: context.Background()} + stopWait <- workspaceStopWait{leaseStop: req} + r := <-res + if r.start || r.stopped == nil || r.stopped.leaseStop != req { + t.Fatalf("stop before serving: %+v, want no frontends and the lease drain request handed back", r) + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index a49a250db3..5ffa393c22 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -1019,70 +1019,163 @@ func runVolume(f flags, exits *processExit) int { var iscsiTarget *iscsi.Target var frontendTargets []*control.FrontendTarget - if f.iscsiListen != "" { - prov := provider - var probeProvider iscsi.ProbeBackendProvider - if durableProv != nil { - probeProvider = &durableProbeProvider{provider: durableProv} - } - negotiation := iscsi.NegotiableConfig{} - if f.iscsiCHAPSecret != "" { - negotiation = iscsi.DefaultNegotiableConfig() - negotiation.CHAP = iscsi.CHAPConfig{ - Username: f.iscsiCHAPUser, - Secret: f.iscsiCHAPSecret, - } - } - iscsiTarget = iscsi.NewTarget(iscsi.TargetConfig{ - Listen: f.iscsiListen, - IQN: f.iscsiIQN, - PortalAddr: f.iscsiPortalAddr, - VolumeID: f.volumeID, - Provider: prov, - ProbeProvider: probeProvider, - Negotiation: negotiation, - DataOutTimeout: f.iscsiDataOutTTL, - Handler: iscsi.HandlerConfig{ - BlockSize: frontendBlockSize, - VolumeSize: frontendVolumeSize, - ALUA: newProjectionALUAProvider(h.ProjectionView(), f.volumeID, f.replicaID, f.iscsiIQN), - }, - }) - iscsiAddr, err := iscsiTarget.Start() - if err != nil { - fmt.Fprintln(os.Stderr, "blockvolume: iscsi target:", err) - if status != nil { - shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) - _ = status.Close(shutCtx) - shutCancel() - } - _ = h.Close() - return 1 - } - _ = json.NewEncoder(os.Stdout).Encode(iscsiReadyLine{ - Component: "blockvolume", - Phase: "iscsi-listening", - IscsiAddr: iscsiAddr, - IQN: f.iscsiIQN, - }) - frontendTargets = append(frontendTargets, &control.FrontendTarget{ - Protocol: "iscsi", - Addr: iscsiAddr, - Iqn: f.iscsiIQN, - Lun: uint32(f.iscsiLUN), - }) - h.SetFrontendTargets(frontendTargets) - } - var nvmeTarget interface { Start() (string, error) Close() error } - if f.nvmeListen != "" { - if f.nvmeTransport == "rdma" { - start := nvmeRDMAListenerStartDecision(true, nvmeRDMAPreflightFacts(f.nvmeListen)) - if !start.allowed { - fmt.Fprintf(os.Stderr, "blockvolume: nvme rdma start refused: reason=%s\n", start.reason) + var ublkTarget *ublk.Target + + // One startup order (INV-FE-PRIMARY-READY-OPERATIONAL-001 with + // INV-WS-STARTUP-RETRY-001): the workspace lease guard and the process's + // one stop waiter (waitWorkspaceStop: signal, lease drain request, lease + // end, or the latched startup outcome) run from here, before any frontend; + // the frontends start only when the backend first admits I/O, and never + // if a stop wins that race. + shutdownCtx := exits.parent + var leaseRequests <-chan workspaceStopRequest + var leaseDone <-chan error + if f.workspaceLease { + leaseRequests, leaseDone = startWorkspaceLease(shutdownCtx, h) + } + stopWait := make(chan workspaceStopWait, 1) + go func(requests <-chan workspaceStopRequest, done <-chan error) { + ls, ld := waitWorkspaceStop(exits, f, h, requests, done) + stopWait <- workspaceStopWait{leaseStop: ls, leaseDone: ld} + }(leaseRequests, leaseDone) + var serving <-chan struct{} // nil: no durable backend, start at once + if durableProv != nil { + if b := durableProv.Backend(f.volumeID); b != nil { + serving = b.FirstServing() + } + } + stopped, startFrontends := awaitFrontendStart(serving, stopWait) + if startFrontends { + if f.iscsiListen != "" { + prov := provider + var probeProvider iscsi.ProbeBackendProvider + if durableProv != nil { + probeProvider = &durableProbeProvider{provider: durableProv} + } + negotiation := iscsi.NegotiableConfig{} + if f.iscsiCHAPSecret != "" { + negotiation = iscsi.DefaultNegotiableConfig() + negotiation.CHAP = iscsi.CHAPConfig{ + Username: f.iscsiCHAPUser, + Secret: f.iscsiCHAPSecret, + } + } + iscsiTarget = iscsi.NewTarget(iscsi.TargetConfig{ + Listen: f.iscsiListen, + IQN: f.iscsiIQN, + PortalAddr: f.iscsiPortalAddr, + VolumeID: f.volumeID, + Provider: prov, + ProbeProvider: probeProvider, + Negotiation: negotiation, + DataOutTimeout: f.iscsiDataOutTTL, + Handler: iscsi.HandlerConfig{ + BlockSize: frontendBlockSize, + VolumeSize: frontendVolumeSize, + ALUA: newProjectionALUAProvider(h.ProjectionView(), f.volumeID, f.replicaID, f.iscsiIQN), + }, + }) + iscsiAddr, err := iscsiTarget.Start() + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: iscsi target:", err) + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + _ = json.NewEncoder(os.Stdout).Encode(iscsiReadyLine{ + Component: "blockvolume", + Phase: "iscsi-listening", + IscsiAddr: iscsiAddr, + IQN: f.iscsiIQN, + }) + frontendTargets = append(frontendTargets, &control.FrontendTarget{ + Protocol: "iscsi", + Addr: iscsiAddr, + Iqn: f.iscsiIQN, + Lun: uint32(f.iscsiLUN), + }) + h.SetFrontendTargets(frontendTargets) + } + + if f.nvmeListen != "" { + if f.nvmeTransport == "rdma" { + start := nvmeRDMAListenerStartDecision(true, nvmeRDMAPreflightFacts(f.nvmeListen)) + if !start.allowed { + fmt.Fprintf(os.Stderr, "blockvolume: nvme rdma start refused: reason=%s\n", start.reason) + if iscsiTarget != nil { + _ = iscsiTarget.Close() + } + if replListen != nil { + replListen.Stop() + } + if replVolume != nil { + _ = replVolume.Close() + } + if durableProv != nil { + _ = durableProv.Close() + } + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + blockSize := frontendBlockSize + volumeSize := frontendVolumeSize + if blockSize == 0 { + blockSize = nvme.DefaultBlockSize + } + if volumeSize == 0 { + volumeSize = nvme.DefaultVolumeBlocks * uint64(blockSize) + } + nvmeTarget = nvmerdma.NewTarget(nvmerdma.TargetConfig{ + Listen: f.nvmeListen, + SubsysNQN: f.nvmeSubsysNQN, + VolumeID: f.volumeID, + NSID: uint32(f.nvmeNS), + BlockSize: blockSize, + VolumeSize: volumeSize, + Provider: provider, + }) + } else { + var probeProvider nvme.ProbeBackendProvider + if durableProv != nil { + probeProvider = &durableProbeProvider{provider: durableProv} + } + nvmeTarget = nvme.NewTarget(nvme.TargetConfig{ + Transport: nvme.TransportTCP, + Listen: f.nvmeListen, + SubsysNQN: f.nvmeSubsysNQN, + VolumeID: f.volumeID, + Provider: provider, + ProbeProvider: probeProvider, + ControllerID: nvmeControllerIDFromReplicaID(f.replicaID), + MaxH2CDataLength: uint32(f.nvmeMaxH2C), + Handler: nvme.HandlerConfig{ + NSID: uint32(f.nvmeNS), + BlockSize: frontendBlockSize, + VolumeSize: frontendVolumeSize, + ANA: newProjectionANAProvider(h.ProjectionView(), f.volumeID, f.replicaID, f.nvmeSubsysNQN), + }, + }) + } + nvmeAddr, err := nvmeTarget.Start() + if err != nil { + if f.nvmeTransport == "rdma" { + fmt.Fprintf(os.Stderr, "blockvolume: nvme rdma start refused: reason=%s error=%v\n", nvmeRDMATargetStartFailureReason(err), err) + } else { + fmt.Fprintln(os.Stderr, "blockvolume: nvme target:", err) + } if iscsiTarget != nil { _ = iscsiTarget.Close() } @@ -1103,6 +1196,34 @@ func runVolume(f flags, exits *processExit) int { _ = h.Close() return 1 } + if status != nil { + status.SetNVMeListenerReady(true) + } + _ = json.NewEncoder(os.Stdout).Encode(nvmeReadyLine{ + Component: "blockvolume", + Phase: "nvme-listening", + NvmeAddr: nvmeAddr, + SubsysNQN: f.nvmeSubsysNQN, + }) + if shouldPublishNVMeFrontendTarget(f.nvmeTransport) { + frontendTargets = append(frontendTargets, &control.FrontendTarget{ + Protocol: "nvme", + Transport: f.nvmeTransport, + Addr: nvmeAddr, + Nqn: f.nvmeSubsysNQN, + Nsid: uint32(f.nvmeNS), + }) + h.SetFrontendTargets(frontendTargets) + } + if status != nil { + status.SetFrontendCapabilities(nvmeFrontendCapabilities(f.nvmeListen, f.nvmeTransport, true)) + if source, ok := nvmeTarget.(interface{ Stats() nvme.Stats }); ok { + status.SetNVMeStatusSource(source) + } + } + } + + if f.ublkDevice >= 0 { blockSize := frontendBlockSize volumeSize := frontendVolumeSize if blockSize == 0 { @@ -1111,153 +1232,58 @@ func runVolume(f flags, exits *processExit) int { if volumeSize == 0 { volumeSize = nvme.DefaultVolumeBlocks * uint64(blockSize) } - nvmeTarget = nvmerdma.NewTarget(nvmerdma.TargetConfig{ - Listen: f.nvmeListen, - SubsysNQN: f.nvmeSubsysNQN, + ublkTarget = ublk.NewTarget(ublk.TargetConfig{ VolumeID: f.volumeID, - NSID: uint32(f.nvmeNS), + Provider: provider, + DevID: f.ublkDevice, BlockSize: blockSize, VolumeSize: volumeSize, - Provider: provider, + Queues: f.ublkQueues, + QueueDepth: f.ublkQueueDepth, }) - } else { - var probeProvider nvme.ProbeBackendProvider - if durableProv != nil { - probeProvider = &durableProbeProvider{provider: durableProv} - } - nvmeTarget = nvme.NewTarget(nvme.TargetConfig{ - Transport: nvme.TransportTCP, - Listen: f.nvmeListen, - SubsysNQN: f.nvmeSubsysNQN, - VolumeID: f.volumeID, - Provider: provider, - ProbeProvider: probeProvider, - ControllerID: nvmeControllerIDFromReplicaID(f.replicaID), - MaxH2CDataLength: uint32(f.nvmeMaxH2C), - Handler: nvme.HandlerConfig{ - NSID: uint32(f.nvmeNS), - BlockSize: frontendBlockSize, - VolumeSize: frontendVolumeSize, - ANA: newProjectionANAProvider(h.ProjectionView(), f.volumeID, f.replicaID, f.nvmeSubsysNQN), - }, - }) - } - nvmeAddr, err := nvmeTarget.Start() - if err != nil { - if f.nvmeTransport == "rdma" { - fmt.Fprintf(os.Stderr, "blockvolume: nvme rdma start refused: reason=%s error=%v\n", nvmeRDMATargetStartFailureReason(err), err) - } else { - fmt.Fprintln(os.Stderr, "blockvolume: nvme target:", err) - } - if iscsiTarget != nil { - _ = iscsiTarget.Close() - } - if replListen != nil { - replListen.Stop() - } - if replVolume != nil { - _ = replVolume.Close() - } - if durableProv != nil { - _ = durableProv.Close() + ublkPath, err := ublkTarget.Start() + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: ublk device:", err) + if nvmeTarget != nil { + _ = nvmeTarget.Close() + } + if iscsiTarget != nil { + _ = iscsiTarget.Close() + } + if replListen != nil { + replListen.Stop() + } + if replVolume != nil { + _ = replVolume.Close() + } + if durableProv != nil { + _ = durableProv.Close() + } + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 } if status != nil { - shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) - _ = status.Close(shutCtx) - shutCancel() + status.SetUblkStatusSource(ublkTarget) } - _ = h.Close() - return 1 - } - if status != nil { - status.SetNVMeListenerReady(true) - } - _ = json.NewEncoder(os.Stdout).Encode(nvmeReadyLine{ - Component: "blockvolume", - Phase: "nvme-listening", - NvmeAddr: nvmeAddr, - SubsysNQN: f.nvmeSubsysNQN, - }) - if shouldPublishNVMeFrontendTarget(f.nvmeTransport) { - frontendTargets = append(frontendTargets, &control.FrontendTarget{ - Protocol: "nvme", - Transport: f.nvmeTransport, - Addr: nvmeAddr, - Nqn: f.nvmeSubsysNQN, - Nsid: uint32(f.nvmeNS), + _ = json.NewEncoder(os.Stdout).Encode(ublkReadyLine{ + Component: "blockvolume", + Phase: "ublk-ready", + Device: ublkPath, }) - h.SetFrontendTargets(frontendTargets) } - if status != nil { - status.SetFrontendCapabilities(nvmeFrontendCapabilities(f.nvmeListen, f.nvmeTransport, true)) - if source, ok := nvmeTarget.(interface{ Stats() nvme.Stats }); ok { - status.SetNVMeStatusSource(source) - } - } - } + } // startFrontends - var ublkTarget *ublk.Target - if f.ublkDevice >= 0 { - blockSize := frontendBlockSize - volumeSize := frontendVolumeSize - if blockSize == 0 { - blockSize = nvme.DefaultBlockSize - } - if volumeSize == 0 { - volumeSize = nvme.DefaultVolumeBlocks * uint64(blockSize) - } - ublkTarget = ublk.NewTarget(ublk.TargetConfig{ - VolumeID: f.volumeID, - Provider: provider, - DevID: f.ublkDevice, - BlockSize: blockSize, - VolumeSize: volumeSize, - Queues: f.ublkQueues, - QueueDepth: f.ublkQueueDepth, - }) - ublkPath, err := ublkTarget.Start() - if err != nil { - fmt.Fprintln(os.Stderr, "blockvolume: ublk device:", err) - if nvmeTarget != nil { - _ = nvmeTarget.Close() - } - if iscsiTarget != nil { - _ = iscsiTarget.Close() - } - if replListen != nil { - replListen.Stop() - } - if replVolume != nil { - _ = replVolume.Close() - } - if durableProv != nil { - _ = durableProv.Close() - } - if status != nil { - shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) - _ = status.Close(shutCtx) - shutCancel() - } - _ = h.Close() - return 1 - } - if status != nil { - status.SetUblkStatusSource(ublkTarget) - } - _ = json.NewEncoder(os.Stdout).Encode(ublkReadyLine{ - Component: "blockvolume", - Phase: "ublk-ready", - Device: ublkPath, - }) + // The one stop waiter has already returned if a stop won the race above. + if stopped == nil { + w := <-stopWait + stopped = &w } - - shutdownCtx := exits.parent - var leaseRequests <-chan workspaceStopRequest - var leaseDone <-chan error - if f.workspaceLease { - leaseRequests, leaseDone = startWorkspaceLease(shutdownCtx, h) - } - leaseStop, leaseDone := waitWorkspaceStop(exits, f, h, leaseRequests, leaseDone) + leaseStop, leaseDone := stopped.leaseStop, stopped.leaseDone // The resource owner performs shutdown. The lease callback waits for this // exact drain; it cannot ACK a merely requested or failed close. h.FenceWorkspaceLease() diff --git a/seaweed-block/core/frontend/durable/first_serving_test.go b/seaweed-block/core/frontend/durable/first_serving_test.go new file mode 100644 index 0000000000..4cd3e6c097 --- /dev/null +++ b/seaweed-block/core/frontend/durable/first_serving_test.go @@ -0,0 +1,49 @@ +package durable_test + +import ( + "context" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" +) + +// INV-FE-PRIMARY-READY-OPERATIONAL-001: a non-chunk durable volume admits I/O +// right after open and recovery (the role, primary or supporting, does not +// enter), so its first-serving channel is already closed and its frontends +// start at once, as before the gate. A later loss of readiness does not +// reopen the channel (the process exit owns that window). +func TestDurableProvider_NonChunkVolumeServesRightAfterOpen(t *testing.T) { + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 64, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + b := p.Backend("v1") + if b == nil { + t.Fatal("no backend after EnsureStorage") + } + select { + case <-b.FirstServing(): + t.Fatal("first-serving closed before recovery") + default: + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + select { + case <-b.FirstServing(): + default: + t.Fatal("a recovered non-chunk volume has not admitted I/O: its frontends would wait") + } + b.SetOperational(false, "test: readiness lost") + select { + case <-b.FirstServing(): + default: + t.Fatal("a later loss of readiness reopened the first-serving channel") + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 98c7023841..703b005ad7 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -181,6 +181,11 @@ type StorageBackend struct { readyChanged chan struct{} operational atomic.Bool opEvidence atomic.Value // string + // firstServing is closed the first time the backend admits I/O (under + // mu); it never reopens. INV-FE-PRIMARY-READY-OPERATIONAL-001: the + // frontends start on it. + firstServing chan struct{} + served bool // under mu: firstServing is closed // ioMu is the I/O admission boundary: every Read, Write and Sync holds // its read side for the whole operation, gate included, so StopIO can @@ -221,10 +226,11 @@ type StorageBackend struct { // impl changes it mid-session). func NewStorageBackend(s storage.LogicalStorage, view frontend.ProjectionView, id frontend.Identity) *StorageBackend { b := &StorageBackend{ - storage: s, - view: view, - id: id, - blockSize: s.BlockSize(), + storage: s, + view: view, + id: id, + blockSize: s.BlockSize(), + firstServing: make(chan struct{}), } b.opEvidence.Store("awaiting first SetOperational") // operational.Store(false) is zero-value default; be explicit. @@ -488,11 +494,23 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) { b.mu.Unlock() } +// FirstServing is closed the first time the backend admits I/O (for a chunk +// volume: after its storage claim succeeded) and never reopens. A later loss +// of readiness does not reopen it: the process exit of +// INV-WS-STARTUP-RETRY-001 owns that window. +func (b *StorageBackend) FirstServing() <-chan struct{} { return b.firstServing } + // The caller owns mu; publication never calls the store or waits for I/O. func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) { flipped := !ok && b.operational.Load() b.opEvidence.Store(evidence) b.operational.Store(ok) + if ok && !b.served { + b.served = true + if b.firstServing != nil { // nil only for a backend built without NewStorageBackend + close(b.firstServing) + } + } if flipped { b.stopFlipAt = time.Now() // after the store: no gate after this instant admits } diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index cea8a7c79d..ccd1bd53d0 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -187,8 +187,15 @@ type StatusProjection struct { // Memory is the process's memory use at the time of the request. Memory ProcessMemoryStatus // FrontendPrimaryReady: this replica is the healthy, non-superseded - // primary and may serve guest I/O. + // primary, its local durable backend admits I/O, and it may serve guest + // I/O (INV-FE-PRIMARY-READY-OPERATIONAL-001). FrontendPrimaryReady bool + // NotReadyReason says why FrontendPrimaryReady is false, first match: the + // local durable backend admits no I/O (its evidence: attach pending, + // fenced, detached) or has no status for the volume; the frontend target + // is not listening yet; this replica is not the healthy primary. Empty + // when ready. + NotReadyReason string `json:",omitempty"` // AuthorityRole is primary, superseded or unknown. AuthorityRole string // ReplicationRole is none (a primary), recovering, not_ready, @@ -485,17 +492,47 @@ func (s *StatusServer) handleStatusNVMe(w http.ResponseWriter, r *http.Request) func (s *StatusServer) statusProjection() StatusProjection { p := s.authorityProjection() + authorityReady := p.FrontendPrimaryReady s.mu.Lock() - p.Healthy = p.Healthy && !s.nvmePending - p.FrontendPrimaryReady = p.FrontendPrimaryReady && !s.nvmePending + nvmePending := s.nvmePending + p.Healthy = p.Healthy && !nvmePending + p.FrontendPrimaryReady = p.FrontendPrimaryReady && !nvmePending src := s.durableSource s.mu.Unlock() + // INV-FE-PRIMARY-READY-OPERATIONAL-001: not FrontendPrimaryReady while the + // local backend admits no I/O (before the storage claim of a chunk volume, + // after a refused claim: fenced, after a detach), and not when there is no + // durable status for the volume at all (fail closed). The authority view + // alone (the adapter's PublishHealthy) is not readiness; Healthy stays that + // view. Whenever FrontendPrimaryReady is false, NotReadyReason says why. + backendReason := "" if src != nil { // outside s.mu: the provider takes its own lock + found := false for _, st := range src.DurableStatuses() { if st.VolumeID == p.VolumeID { + found = true p.Warnings = append(p.Warnings, st.Warnings...) + if !st.Operational { + backendReason = "durable backend not operational: " + st.Evidence + } } } + if !found { + backendReason = "no durable status for volume " + p.VolumeID + } + } + if backendReason != "" { + p.FrontendPrimaryReady = false + } + if !p.FrontendPrimaryReady { + switch { + case backendReason != "": + p.NotReadyReason = backendReason + case nvmePending: + p.NotReadyReason = "frontend target not listening yet" + case !authorityReady: + p.NotReadyReason = "not the healthy primary: authority role " + p.AuthorityRole + ", replication role " + p.ReplicationRole + } } return p } diff --git a/seaweed-block/core/host/volume/status_server_test.go b/seaweed-block/core/host/volume/status_server_test.go index cbdf18d3eb..1e341c9a3d 100644 --- a/seaweed-block/core/host/volume/status_server_test.go +++ b/seaweed-block/core/host/volume/status_server_test.go @@ -1183,3 +1183,89 @@ func TestStatusServer_UblkStatusEndpoint(t *testing.T) { resp.Body.Close() } } + +// INV-FE-PRIMARY-READY-OPERATIONAL-001: a healthy primary authority view is +// not readiness. While the volume's local durable backend admits no I/O +// (a chunk volume awaiting its attach, a refused claim: fenced, a detach), +// /status does not report FrontendPrimaryReady and says why (NotReadyReason), +// while Healthy stays the authority view; once the backend admits I/O, +// readiness follows the authority view again. A status for another +// volume does not count. +func TestStatusServer_ReadyOnlyWhileBackendOperational(t *testing.T) { + p := stubProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 2, EndpointVersion: 2}} + s := NewStatusServer(NewAdapterProjectionView(p, "v1", "r1", nil)) + addr, err := s.Start("127.0.0.1:0") + if err != nil { + t.Fatalf("start: %v", err) + } + defer func() { _ = s.Close(context.Background()) }() + read := func() StatusProjection { + t.Helper() + resp, err := http.Get("http://" + addr + "/status?volume=v1") + if err != nil { + t.Fatalf("get: %v", err) + } + defer resp.Body.Close() + var body StatusProjection + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { + t.Fatalf("decode: %v", err) + } + return body + } + for _, tc := range []struct { + name string + vols []durable.VolumeStatus + want bool + }{ + {"attach pending", []durable.VolumeStatus{{VolumeID: "v1", Operational: false, Evidence: "recovered; chunk layer awaiting master authority"}}, false}, + {"fenced", []durable.VolumeStatus{{VolumeID: "v1", Operational: false, Evidence: "chunk layer attach refused: HEAD holder h1/r1 is not this holder"}}, false}, + {"other volume not operational", []durable.VolumeStatus{{VolumeID: "v2", Operational: false}, {VolumeID: "v1", Operational: true}}, true}, + {"no status for the volume (fail closed)", []durable.VolumeStatus{{VolumeID: "v2", Operational: true}}, false}, + {"operational", []durable.VolumeStatus{{VolumeID: "v1", Operational: true}}, true}, + } { + s.SetDurableStatusSource(stubDurableStatusSource{vols: tc.vols}) + body := read() + if !body.Healthy || body.FrontendPrimaryReady != tc.want || (body.NotReadyReason == "") != tc.want { + t.Errorf("%s: Healthy=%v FrontendPrimaryReady=%v NotReadyReason=%q, want Healthy (the authority view), ready=%v, a reason exactly when not ready", tc.name, body.Healthy, body.FrontendPrimaryReady, body.NotReadyReason, tc.want) + } + } + + // The NVMe listener mask does not hide the backend's reason: with the + // target not yet listening AND the backend fenced, the reason is the + // backend's; with only the listener pending, it says so. + s.SetNVMeListenerReady(false) + s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: false, Evidence: "chunk layer attach refused"}}}) + if body := read(); body.FrontendPrimaryReady || body.NotReadyReason != "durable backend not operational: chunk layer attach refused" { + t.Errorf("listener pending + fenced: ready=%v reason=%q, want the backend's reason", body.FrontendPrimaryReady, body.NotReadyReason) + } + s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: true}}}) + if body := read(); body.FrontendPrimaryReady || body.NotReadyReason != "frontend target not listening yet" { + t.Errorf("listener pending only: ready=%v reason=%q", body.FrontendPrimaryReady, body.NotReadyReason) + } + s.SetNVMeListenerReady(true) +} + +// INV-FE-PRIMARY-READY-OPERATIONAL-001: whenever FrontendPrimaryReady is +// false, NotReadyReason is set, also when the authority view itself is not a +// healthy primary (an observed process before its assignment). +func TestStatusServer_NotReadyAlwaysHasAReason(t *testing.T) { + s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil)) + addr, err := s.Start("127.0.0.1:0") + if err != nil { + t.Fatalf("start: %v", err) + } + defer func() { _ = s.Close(context.Background()) }() + s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: true}}}) + resp, err := http.Get("http://" + addr + "/status?volume=v1") + if err != nil { + t.Fatalf("get: %v", err) + } + defer resp.Body.Close() + var body StatusProjection + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { + t.Fatalf("decode: %v", err) + } + if body.FrontendPrimaryReady || body.NotReadyReason == "" { + t.Fatalf("not-ready authority view: ready=%v reason=%q, want not ready with a reason", body.FrontendPrimaryReady, body.NotReadyReason) + } +} diff --git a/seaweed-block/core/host/volume/status_warnings_test.go b/seaweed-block/core/host/volume/status_warnings_test.go index 73bb785e40..ed9c4370fa 100644 --- a/seaweed-block/core/host/volume/status_warnings_test.go +++ b/seaweed-block/core/host/volume/status_warnings_test.go @@ -48,7 +48,7 @@ func statusWarningsCase(t *testing.T, view *AdapterProjectionView, wantHealthy b t.Fatalf("before the warning: healthy=%t ready=%t; want %t", before.Healthy, before.FrontendPrimaryReady, wantHealthy) } s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{ - VolumeID: "v1", Impl: "walstore", Warnings: []string{"wal_hole_suspected: WAL entry at offset=4134 fails its check"}, HolesSuspected: 1, + VolumeID: "v1", Impl: "walstore", Operational: true, Warnings: []string{"wal_hole_suspected: WAL entry at offset=4134 fails its check"}, HolesSuspected: 1, }}}) after := get() if len(after.Warnings) != 1 || after.Warnings[0][:18] != "wal_hole_suspected" { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index db47d15a00..0fecbcfd52 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -60,7 +60,7 @@ stateDiagram-v2 |---|---|---|---|---| | — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001`, `INV-WAL-V3-ACTIVATION-001`, `INV-WAL-V3-DESCRIPTOR-001`, `INV-WAL-V3-MAP-PUBLISH-001` | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | -| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-MAP-PUBLISH-001` | +| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-FE-PRIMARY-READY-OPERATIONAL-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001`, `INV-WAL-V3-W-RECOVERY-001` | | Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-W-001` | | Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001`, `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`, `INV-WAL-V3-RECLAIM-001`, `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001`, `INV-WAL-V3-MAP-PRIOR-LIVE-001` | @@ -447,7 +447,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -309 rows: 238 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 294 new. +310 rows: 239 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 295 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -461,6 +461,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-FE-NVME-READY-001` | A read or write on a successfully recovered chunk volume awaiting attachment waits for attachment readiness, before storage admission, for at most 3 s or until an earlier caller deadline, on the local monotonic clock. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `admitAfterAttachUnqueued`, `awaitAttachAdmission`, `readyCheck` | `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE | | `INV-FE-NVME-READY-STATUS-001` | An NVMe read or write whose attachment-readiness wait times out or is refused completes with Namespace Not Ready (SC 0x82), DNR=0, without reading or mutating storage. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` (`core/frontend/durable/takeover_read_ready_test.go`) | — | ACTIVE | | `INV-FE-NVME-READY-ANA-001` | An I/O that ends during the attachment-readiness wait because the backend closed or its lineage went stale keeps its ANA error, and a physical I/O fault keeps Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE | +| `INV-FE-PRIMARY-READY-OPERATIONAL-001` | FrontendPrimaryReady is reported only while the local durable backend admits I/O, and the frontend target starts listening only after it first does; attach-pending, fenced or no durable status reports not ready with the reason; a fence after the target listens ends the process within 5 s (`INV-WS-STARTUP-RETRY-001`). | M1 Opened / Recovering → Serving; M2 process exit | `core/host/volume/status_server.go` `statusProjection`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (the iSCSI, NVMe and ublk targets in `cmd/blockvolume/main.go` `runVolume` start after it); `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` | `TestStatusServer_ReadyOnlyWhileBackendOperational`, `TestStatusServer_NotReadyAlwaysHasAReason` (`core/host/volume/status_server_test.go`); `TestFrontendGateWaitsForTheStorageClaim`, `TestFrontendGateStopsWithoutStartingTheFrontends` (`cmd/blockvolume/frontend_gate_test.go`); `TestDurableProvider_NonChunkVolumeServesRightAfterOpen` (`core/frontend/durable/first_serving_test.go`) | — | ACTIVE | | `INV-WAL-REPLAY-LWW-001` | Replay of the validated native prefix retains the highest admitted LSN per LBA; invalid cursor, nonce or LSN order is refused. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALLSNOrderV3_RefusesDuplicateAndLower` (`core/storage/wal_lsn_order_v3_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | | `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the both durable descriptor slots has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_io_v3.go` `append`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`); `TestNativeReplacementCheckpointSIGKILL` (`core/storage/legacy_checkpoint_replacement_v3_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | @@ -979,6 +980,8 @@ One row per wait in the data and control paths. Guest-visible rows on one path m | Site | Waits for | Bound | Owner that ends it | On expiry | Lock held while waiting | Guest-visible | |---|---|---|---|---|---|---| | `core/storage/chunk_publish_settled.go` `runPublishSettled` (from `unlockCap`, on the cut or detach caller's goroutine) | the `OnPublishSettled` hook to return | the hook's duration: the hook must return without blocking and without remote calls, enqueueing its work to its own worker | the hook implementer | none: a stalled hook stalls its caller, and later reports queue without a bound (a nil hook queues nothing) | none (`capMu` and `stMu` released) | yes on detach (the detach caller delivers before returning) | +| `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (from `runVolume`, before any frontend starts) | the backend's first admitted I/O (`StorageBackend.FirstServing`), or the process's stop waiter returning | none of its own: it ends on the stop waiter, which INV-WS-STARTUP-RETRY-001 bounds (a refused or timed-out claim latches exit 75/78) | `runVolume` (`INV-FE-PRIMARY-READY-OPERATIONAL-001`) | no frontend starts; shutdown as after the frontends | none | no (no target listens yet) | +| `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` (one goroutine from `runVolume`, started with the workspace lease guard before the frontends) | a signal, the lease guard's drain request or end, or the latched startup outcome | the process lifetime | the process exit owner (`superviseProcess`, `INV-WS-STARTUP-RETRY-001`) | the chosen exit status (0 revoked/signal, 75 retry, 78 superseded) | none | no | Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The W/BASE/fence owner (`WALStore.recoverV3`) must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index f6243d2c8d..9556f4fa09 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -27,7 +27,8 @@ The volume's authority and health projection. Go type `volume.StatusProjection`. | `Memory.SoftLimitBytes` | int64 | the Go soft memory limit in force (--memory-limit-mib or GOMEMLIMIT) | | `Memory.RSSBytes` | uint64 | resident set size from /proc/self/status (VmRSS); 0 off Linux | | `Memory.AnonymousRSSBytes` | uint64 | anonymous resident memory (RssAnon); 0 off Linux | -| `FrontendPrimaryReady` | bool | FrontendPrimaryReady: this replica is the healthy, non-superseded primary and may serve guest I/O. | +| `FrontendPrimaryReady` | bool | FrontendPrimaryReady: this replica is the healthy, non-superseded primary, its local durable backend admits I/O, and it may serve guest I/O (INV-FE-PRIMARY-READY-OPERATIONAL-001). | +| `NotReadyReason` | string | NotReadyReason says why FrontendPrimaryReady is false, first match: the local durable backend admits no I/O (its evidence: attach pending, fenced, detached) or has no status for the volume; the frontend target is not listening yet; this replica is not the healthy primary. Empty when ready. (omitted when empty) | | `AuthorityRole` | string | AuthorityRole is primary, superseded or unknown. | | `ReplicationRole` | string | ReplicationRole is none (a primary), recovering, not_ready, replica_ready or unknown. | | `RoleAdmissionFailure` | string | RoleAdmissionFailure (G1) explains a not-Healthy projection caused by a failed role call on the replica listener; empty otherwise. (omitted when empty) | From 1b675b39d037aec54db0e3f1c5bf1860f756be3e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 01:49:36 -0800 Subject: [PATCH 51/57] blockvolume: lease_not_held reason and a one-time grant log for a workspace primary A workspace primary whose lease guard is missing or holds no granted lease now reports NotReadyReason=lease_not_held first (the guard decides, through the new WorkspaceLeaseGuard.Held, the lease term permits already used). The guard logs its first grant once, as "re-granted after N refused renewal(s)" when renewals were refused first (a restart before the forced-move barrier), with the request-start time in unix_ms. Co-Authored-By: Claude Opus 5.5 --- .../core/host/volume/projection_bridge.go | 10 ++ .../core/host/volume/status_server.go | 12 ++- .../core/host/volume/workspace_lease.go | 34 ++++++- .../host/volume/workspace_lease_held_test.go | 95 +++++++++++++++++++ seaweed-block/docs/status-schema.md | 2 +- 5 files changed, 149 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/core/host/volume/workspace_lease_held_test.go diff --git a/seaweed-block/core/host/volume/projection_bridge.go b/seaweed-block/core/host/volume/projection_bridge.go index 36e89ad268..88d7e23240 100644 --- a/seaweed-block/core/host/volume/projection_bridge.go +++ b/seaweed-block/core/host/volume/projection_bridge.go @@ -124,6 +124,16 @@ func (v *AdapterProjectionView) projectionWithSupersede() (frontend.Projection, return result, superseded } +// workspaceLeaseNotHeld: a workspace primary whose lease guard is not +// installed yet, or does not hold a granted lease now (the guard decides). +func (v *AdapterProjectionView) workspaceLeaseNotHeld() bool { + if !v.workspaceRequired { + return false + } + g := v.workspaceGuard.Load() + return g == nil || !g.Held() +} + func (v *AdapterProjectionView) supportingReplicaReady(selfEpoch, selfEV uint64) bool { if v == nil || v.probe == nil { return false diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index ccd1bd53d0..cbf1286ff5 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -190,7 +190,8 @@ type StatusProjection struct { // primary, its local durable backend admits I/O, and it may serve guest // I/O (INV-FE-PRIMARY-READY-OPERATIONAL-001). FrontendPrimaryReady bool - // NotReadyReason says why FrontendPrimaryReady is false, first match: the + // NotReadyReason says why FrontendPrimaryReady is false, first match: a + // workspace primary holds no granted lease now (NotReadyLeaseNotHeld); the // local durable backend admits no I/O (its evidence: attach pending, // fenced, detached) or has no status for the volume; the frontend target // is not listening yet; this replica is not the healthy primary. Empty @@ -490,6 +491,10 @@ func (s *StatusServer) handleStatusNVMe(w http.ResponseWriter, r *http.Request) _ = json.NewEncoder(w).Encode(NVMeStatus{VolumeID: p.VolumeID, Stats: src.Stats()}) } +// NotReadyLeaseNotHeld: a workspace primary without a granted lease holds at +// the gate (no claim, no listen, not ready); V1-SPEC r2.37. +const NotReadyLeaseNotHeld = "lease_not_held" + func (s *StatusServer) statusProjection() StatusProjection { p := s.authorityProjection() authorityReady := p.FrontendPrimaryReady @@ -521,11 +526,14 @@ func (s *StatusServer) statusProjection() StatusProjection { backendReason = "no durable status for volume " + p.VolumeID } } - if backendReason != "" { + leaseNotHeld := s.view.workspaceLeaseNotHeld() + if backendReason != "" || leaseNotHeld { p.FrontendPrimaryReady = false } if !p.FrontendPrimaryReady { switch { + case leaseNotHeld: + p.NotReadyReason = NotReadyLeaseNotHeld case backendReason != "": p.NotReadyReason = backendReason case nvmePending: diff --git a/seaweed-block/core/host/volume/workspace_lease.go b/seaweed-block/core/host/volume/workspace_lease.go index 944510ce1e..581140618a 100644 --- a/seaweed-block/core/host/volume/workspace_lease.go +++ b/seaweed-block/core/host/volume/workspace_lease.go @@ -46,6 +46,9 @@ type WorkspaceLeaseGuard struct { // Run from its sleep. stopPending bool kick chan struct{} + // refusedBeforeGrant counts failed renewals before the first grant + // (under mu), for the one grant log line. + refusedBeforeGrant int // after schedules Run's sleep between renewals (time.After; tests // replace it before Run starts to observe the delays chosen). after func(time.Duration) <-chan time.Time @@ -160,10 +163,23 @@ func (g *WorkspaceLeaseGuard) Projection() frontend.Projection { func (g *WorkspaceLeaseGuard) permits(p frontend.Projection) bool { g.mu.Lock() defer g.mu.Unlock() + return g.heldLocked() && p.VolumeID == g.id.VolumeId && p.ReplicaID == g.id.ReplicaId && p.Epoch == g.id.Epoch +} + +// Held reports whether the lease is granted and valid now (the lease term of +// permits, without the projection identity). Never call with mu held. +func (g *WorkspaceLeaseGuard) Held() bool { + g.mu.Lock() + defer g.mu.Unlock() + return g.heldLocked() +} + +// heldLocked latches the expiry fence; the caller owns mu. +func (g *WorkspaceLeaseGuard) heldLocked() bool { if !g.until.IsZero() && !g.now().Before(g.until) { g.fenceLocked(fmt.Sprintf("lease expired at %s without a successful renewal", g.until.UTC().Format(time.RFC3339Nano))) } - return !g.fenced && !g.until.IsZero() && p.VolumeID == g.id.VolumeId && p.ReplicaID == g.id.ReplicaId && p.Epoch == g.id.Epoch + return !g.fenced && !g.until.IsZero() } // Refresh anchors validity to the request START. Reply latency can only shorten @@ -197,6 +213,9 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { elapsed := end.Sub(start).Round(time.Millisecond) hit := renewalLimitHit(start, end, until) g.mu.Lock() + if g.until.IsZero() { + g.refusedBeforeGrant++ + } expired := !g.until.IsZero() && !end.Before(g.until) if expired { g.fenceLocked(fmt.Sprintf("lease expired after a failed renewal (renewal failed after %s, %s: %v)", elapsed, hit, err)) @@ -235,6 +254,8 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { case rpcCtx.Err() != nil: g.fenceLocked(fmt.Sprintf("renewal reply arrived after the renewal call's context ended (renewal took %s; lease still valid until %s)", g.now().Sub(start).Round(time.Millisecond), g.until.UTC().Format(time.RFC3339Nano))) } + firstGrant := !g.fenced && g.until.IsZero() + refused := g.refusedBeforeGrant if !g.fenced { g.until = start.Add(time.Duration(reply.ValidForNs)) } @@ -244,6 +265,17 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { } closed := g.fenced g.mu.Unlock() + if firstGrant { + // Once per guard: the first grant, or the re-grant after refused + // renewals (a restart before the forced-move barrier); unix_ms is the + // request start, which the lease validity is anchored to. + what := "granted" + if refused > 0 { + what = fmt.Sprintf("re-granted after %d refused renewal(s)", refused) + } + log.Printf("workspace lease: %s volume=%s replica=%s epoch=%d valid for %s at unix_ms=%d", + what, g.id.VolumeId, g.id.ReplicaId, g.id.Epoch, time.Duration(reply.ValidForNs), start.UnixMilli()) + } if closed { g.logFence() return g.drain(ctx, reply.Revoking) diff --git a/seaweed-block/core/host/volume/workspace_lease_held_test.go b/seaweed-block/core/host/volume/workspace_lease_held_test.go new file mode 100644 index 0000000000..4c149faa3e --- /dev/null +++ b/seaweed-block/core/host/volume/workspace_lease_held_test.go @@ -0,0 +1,95 @@ +package volume + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/engine" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// V1-SPEC r2.37: renewals refused before the first grant (a restart before the +// forced-move barrier) leave the lease not held; the first successful renewal +// is logged as a re-grant after the refused ones, with its time. +func TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals(t *testing.T) { + logs := captureLog(t) + now := time.Unix(1000, 0) + calls := 0 + client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) { + calls++ + if calls <= 2 { + return nil, errors.New("workspace forced move lease expiry plus clock-skew margin has not elapsed") + } + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(10 * time.Second)}, nil + }} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if err := g.Refresh(context.Background()); err == nil { + t.Fatal("a refused renewal was not reported") + } + if g.Held() || g.Projection().Healthy { + t.Fatal("the lease is held before any grant") + } + } + if strings.Contains(logs.String(), "granted") { + t.Fatalf("a grant was logged before any grant; log=%q", logs.String()) + } + // One successful renewal: with the fake clock a second one would run + // against a real-time context deadline in 1970. + if err := g.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + if !g.Held() || !g.Projection().Healthy { + t.Fatal("the granted lease is not held") + } + out := logs.String() + if n := strings.Count(out, "granted"); n != 1 || !strings.Contains(out, "workspace lease: re-granted after 2 refused renewal(s) volume=v replica=r epoch=1 valid for 10s at unix_ms=1000000") { + t.Fatalf("want exactly one re-grant line with its time, got %d; log=%q", n, out) + } + now = now.Add(11 * time.Second) + if g.Held() { + t.Fatal("an expired lease is still held") + } +} + +// V1-SPEC r2.37: a workspace primary reports NotReadyReason=lease_not_held, +// first, while its guard is missing or holds no granted lease, even with the +// backend admitting I/O; ready once the lease is held; lease_not_held again +// after the guard fences. +func TestStatusServer_WorkspacePrimaryNotReadyWithoutHeldLease(t *testing.T) { + now := time.Unix(1000, 0) + p := stubProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 1, EndpointVersion: 1}} + view := NewAdapterProjectionView(p, "v1", "r1", nil) + view.workspaceRequired = true + s := NewStatusServer(view) + s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: true}}}) + check := func(name string, wantReady bool) { + t.Helper() + got := s.statusProjection() + if got.FrontendPrimaryReady != wantReady || (!wantReady && got.NotReadyReason != NotReadyLeaseNotHeld) || (wantReady && got.NotReadyReason != "") { + t.Errorf("%s: ready=%v reason=%q, want ready=%v (reason %q when not ready)", name, got.FrontendPrimaryReady, got.NotReadyReason, wantReady, NotReadyLeaseNotHeld) + } + } + check("no guard installed", false) + g, err := NewWorkspaceLeaseGuard(view, workspaceTestClient{}, &control.WorkspaceIdentity{VolumeId: "v1", ReplicaId: "r1", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + view.workspaceGuard.Store(g) + check("guard without a grant", false) + g.mu.Lock() + g.until = now.Add(10 * time.Second) + g.mu.Unlock() + check("lease held", true) + g.mu.Lock() + g.fenceLocked("test: revoked") + g.mu.Unlock() + check("guard fenced", false) +} diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 9556f4fa09..93db9c50d6 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -28,7 +28,7 @@ The volume's authority and health projection. Go type `volume.StatusProjection`. | `Memory.RSSBytes` | uint64 | resident set size from /proc/self/status (VmRSS); 0 off Linux | | `Memory.AnonymousRSSBytes` | uint64 | anonymous resident memory (RssAnon); 0 off Linux | | `FrontendPrimaryReady` | bool | FrontendPrimaryReady: this replica is the healthy, non-superseded primary, its local durable backend admits I/O, and it may serve guest I/O (INV-FE-PRIMARY-READY-OPERATIONAL-001). | -| `NotReadyReason` | string | NotReadyReason says why FrontendPrimaryReady is false, first match: the local durable backend admits no I/O (its evidence: attach pending, fenced, detached) or has no status for the volume; the frontend target is not listening yet; this replica is not the healthy primary. Empty when ready. (omitted when empty) | +| `NotReadyReason` | string | NotReadyReason says why FrontendPrimaryReady is false, first match: a workspace primary holds no granted lease now (NotReadyLeaseNotHeld); the local durable backend admits no I/O (its evidence: attach pending, fenced, detached) or has no status for the volume; the frontend target is not listening yet; this replica is not the healthy primary. Empty when ready. (omitted when empty) | | `AuthorityRole` | string | AuthorityRole is primary, superseded or unknown. | | `ReplicationRole` | string | ReplicationRole is none (a primary), recovering, not_ready, replica_ready or unknown. | | `RoleAdmissionFailure` | string | RoleAdmissionFailure (G1) explains a not-Healthy projection caused by a failed role call on the replica listener; empty otherwise. (omitted when empty) | From 22a540d34d84ef92163fbc22bbdfa259644d72c2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 02:15:51 -0800 Subject: [PATCH 52/57] blockvolume: a runtime HEAD fence exits 78 head_fenced; serve only while the lease is held A chunk layer that fences after startup (HEAD has another publication owner) while the lease is still valid now latches the backend not operational with that evidence, and the process owner chooses the no-restart exit 78 head_fenced through processExit.choose. I/O is refused from the fence itself. The first-grant log line is written only for a reply that grants: a first reply that revokes fences the guard and logs no grant. The frontend-gate tests own their workers: cleanup is registered before each worker starts and every receive is bounded. docs/design/invariants.md: INV-WS-SERVE-LEASE-HELD-001 (V1-SPEC r2.37); INV-FE-PRIMARY-READY-OPERATIONAL-001 statement within 300 characters, with the runtime fence enforcement and tests; M1 diagram and table carry the lease-held order and the runtime fence exit; C.W names the runVolume receive of the stop waiter's result. 306 rows, 220 ACTIVE. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/frontend_gate_test.go | 76 ++++++++++------ seaweed-block/cmd/blockvolume/main.go | 1 + seaweed-block/cmd/blockvolume/process_exit.go | 29 ++++++ .../blockvolume/runtime_fence_exit_test.go | 54 +++++++++++ .../core/frontend/durable/provider.go | 3 + .../core/frontend/durable/provider_chunk.go | 1 + .../core/frontend/durable/provider_startup.go | 63 ++++++++++++- .../frontend/durable/runtime_fence_test.go | 89 +++++++++++++++++++ .../core/host/volume/workspace_lease.go | 5 +- .../host/volume/workspace_lease_held_test.go | 31 +++++++ seaweed-block/docs/design/invariants.md | 14 +-- 11 files changed, 329 insertions(+), 37 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/runtime_fence_exit_test.go create mode 100644 seaweed-block/core/frontend/durable/runtime_fence_test.go diff --git a/seaweed-block/cmd/blockvolume/frontend_gate_test.go b/seaweed-block/cmd/blockvolume/frontend_gate_test.go index d250af7539..7f6abc571b 100644 --- a/seaweed-block/cmd/blockvolume/frontend_gate_test.go +++ b/seaweed-block/cmd/blockvolume/frontend_gate_test.go @@ -11,13 +11,47 @@ type gateResult struct { start bool } -func runGate(serving <-chan struct{}, stopWait <-chan workspaceStopWait) <-chan gateResult { +// gateWait bounds every receive of a gate result in these tests. +const gateWait = 5 * time.Second + +// runGate runs awaitFrontendStart on serving and a stop channel it owns +// (buffered, returned for the test to send on). Its cleanup, registered +// before the worker starts, releases a gate that is still waiting with a +// stop and joins the worker within gateWait, so a failing check never +// strands it. +func runGate(t *testing.T, serving <-chan struct{}) (<-chan gateResult, chan<- workspaceStopWait) { + t.Helper() out := make(chan gateResult, 1) + stopWait := make(chan workspaceStopWait, 1) + exited := make(chan struct{}) + t.Cleanup(func() { + select { + case stopWait <- workspaceStopWait{}: + default: + } + select { + case <-exited: + case <-time.After(gateWait): + t.Errorf("the gate worker did not exit within %s of a stop", gateWait) + } + }) go func() { + defer close(exited) s, ok := awaitFrontendStart(serving, stopWait) out <- gateResult{s, ok} }() - return out + return out, stopWait +} + +func receiveGate(t *testing.T, res <-chan gateResult, what string) gateResult { + t.Helper() + select { + case r := <-res: + return r + case <-time.After(gateWait): + t.Fatalf("%s: the gate did not return within %s", what, gateWait) + return gateResult{} + } } // INV-FE-PRIMARY-READY-OPERATIONAL-001: the frontends start only once the @@ -26,26 +60,17 @@ func runGate(serving <-chan struct{}, stopWait <-chan workspaceStopWait) <-chan // admits no I/O (a chunk volume before its storage claim), the gate never // releases; it releases as soon as the backend's first-serving channel closes. func TestFrontendGateWaitsForTheStorageClaim(t *testing.T) { - for name, serving := range map[string]chan struct{}{"no durable backend": nil, "already serving": make(chan struct{})} { - if serving != nil { - close(serving) - } - var ch <-chan struct{} - if serving != nil { - ch = serving - } - select { - case r := <-runGate(ch, make(chan workspaceStopWait)): - if !r.start || r.stopped != nil { - t.Fatalf("%s: %+v, want the frontends started at once", name, r) - } - case <-time.After(time.Second): - t.Fatalf("%s: the gate did not release at once", name) + served := make(chan struct{}) + close(served) + for name, ch := range map[string]<-chan struct{}{"no durable backend": nil, "already serving": served} { + res, _ := runGate(t, ch) + if r := receiveGate(t, res, name); !r.start || r.stopped != nil { + t.Fatalf("%s: %+v, want the frontends started at once", name, r) } } serving := make(chan struct{}) - res := runGate(serving, make(chan workspaceStopWait)) + res, _ := runGate(t, serving) for i := 0; i < 30; i++ { // 300 ms of samples while the claim is pending select { case r := <-res: @@ -54,13 +79,8 @@ func TestFrontendGateWaitsForTheStorageClaim(t *testing.T) { } } close(serving) // the storage claim succeeded - select { - case r := <-res: - if !r.start { - t.Fatalf("after the claim: %+v, want the frontends started", r) - } - case <-time.After(time.Second): - t.Fatal("the gate did not release after the backend admitted I/O") + if r := receiveGate(t, res, "after the claim"); !r.start { + t.Fatalf("after the claim: %+v, want the frontends started", r) } } @@ -69,8 +89,7 @@ func TestFrontendGateWaitsForTheStorageClaim(t *testing.T) { // latched exit 75/78) and no frontend starts: the stop is handed back for // the ordinary shutdown, its lease drain request included. func TestFrontendGateStopsWithoutStartingTheFrontends(t *testing.T) { - stopWait := make(chan workspaceStopWait, 1) - res := runGate(make(chan struct{}), stopWait) // fenced: never serves + res, stopWait := runGate(t, make(chan struct{})) // fenced: never serves select { case r := <-res: t.Fatalf("a backend that never serves released the gate: %+v", r) @@ -78,8 +97,7 @@ func TestFrontendGateStopsWithoutStartingTheFrontends(t *testing.T) { } req := &workspaceStopRequest{ctx: context.Background()} stopWait <- workspaceStopWait{leaseStop: req} - r := <-res - if r.start || r.stopped == nil || r.stopped.leaseStop != req { + if r := receiveGate(t, res, "stop before serving"); r.start || r.stopped == nil || r.stopped.leaseStop != req { t.Fatalf("stop before serving: %+v, want no frontends and the lease drain request handed back", r) } } diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 5ffa393c22..893b2af0c5 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -724,6 +724,7 @@ func runVolume(f flags, exits *processExit) int { watchCtx, stopWatch := context.WithCancel(exits.parent) defer stopWatch() go watchChunkStartup(watchCtx, exits, f, h, dp) + go watchChunkRuntimeFence(watchCtx, exits, f, dp) provider = dp if status != nil { status.SetDurableStatusSource(dp) diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index d86fb0aa29..c264aea4bd 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -149,6 +149,35 @@ func watchChunkStartup(ctx context.Context, e *processExit, f flags, h *volume.H } } +// chunkRuntimeFenceProvider reports a runtime HEAD fence of the attached layer. +type chunkRuntimeFenceProvider interface { + ChunkRuntimeFenced(string) bool + ChunkRuntimeFenceUpdates() <-chan struct{} +} + +// watchChunkRuntimeFence: a HEAD fence after startup, while the lease may +// still be valid, ends the process with no restart (78 head_fenced): another +// holder owns HEAD (INV-FE-PRIMARY-READY-OPERATIONAL-001). Workspace chunk +// primaries only. +func watchChunkRuntimeFence(ctx context.Context, e *processExit, f flags, p chunkRuntimeFenceProvider) { + if !f.workspaceLease || f.durableImpl != "walstore-chunk" { + return + } + for { + if p.ChunkRuntimeFenced(f.volumeID) { + e.choose(workspaceExit{exitWorkspaceSuperseded, "head_fenced"}) + return + } + select { + case <-ctx.Done(): + return + case <-e.done: + return + case <-p.ChunkRuntimeFenceUpdates(): + } + } +} + // M2 process exit / Revoking -> Revoked; INV-WS-STARTUP-RETRY-001. func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan workspaceStopRequest, done <-chan error) (*workspaceStopRequest, <-chan error) { select { diff --git a/seaweed-block/cmd/blockvolume/runtime_fence_exit_test.go b/seaweed-block/cmd/blockvolume/runtime_fence_exit_test.go new file mode 100644 index 0000000000..dad78fbec4 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/runtime_fence_exit_test.go @@ -0,0 +1,54 @@ +package main + +import ( + "context" + "sync/atomic" + "testing" + "time" +) + +type runtimeFenceStub struct { + fenced atomic.Bool + updates chan struct{} +} + +func (s *runtimeFenceStub) ChunkRuntimeFenced(string) bool { return s.fenced.Load() } +func (s *runtimeFenceStub) ChunkRuntimeFenceUpdates() <-chan struct{} { return s.updates } + +// INV-FE-PRIMARY-READY-OPERATIONAL-001 (condition A): a runtime HEAD fence of +// a workspace chunk primary chooses the no-restart exit 78 head_fenced through +// the process owner's one chooser; nothing is chosen while not fenced, and a +// non-workspace volume never watches. +func TestRuntimeHeadFenceChoosesHeadFencedExit(t *testing.T) { + f := flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v1"} + e := newProcessExit(context.Background()) + stub := &runtimeFenceStub{updates: make(chan struct{}, 1)} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan struct{}) + go func() { watchChunkRuntimeFence(ctx, e, f, stub); close(done) }() + select { + case out := <-e.decision: + t.Fatalf("an exit was chosen while not fenced: %+v", out) + case <-time.After(100 * time.Millisecond): + } + stub.fenced.Store(true) + stub.updates <- struct{}{} + select { + case out := <-e.decision: + if out != (workspaceExit{exitWorkspaceSuperseded, "head_fenced"}) { + t.Fatalf("exit %+v, want 78 head_fenced", out) + } + case <-time.After(5 * time.Second): + t.Fatal("no exit chosen after the runtime fence") + } + <-done + + plain := newProcessExit(context.Background()) + watchChunkRuntimeFence(ctx, plain, flags{volumeID: "v1"}, stub) // returns at once: not a workspace chunk primary + select { + case out := <-plain.decision: + t.Fatalf("a non-workspace volume chose %+v", out) + default: + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 19ffa5acc5..220a254251 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -238,6 +238,7 @@ type DurableProvider struct { opening map[string]*sync.Mutex // keyed by volumeID; serializes open/create closed bool startupUpdates chan struct{} // wake only; the generation-bound result stays on the handle + fenceUpdates chan struct{} // wake only; runtimeFenced stays on the handle // testAfterChunkResolve, test-only, runs in CutVolume right after the // volume's handle and layer are resolved. @@ -289,6 +290,7 @@ type volHandle struct { waitGen uint64 startupSuperseded bool // exact foreign-holder claim proof for startupEnded; guarded by p.mu startupEnded uint64 // recovery generation with a terminal startup outcome; guarded by p.mu + runtimeFenced bool // the attached layer fenced after startup (HEAD has another owner); guarded by p.mu chunk storage.ChunkLayer // after RecoverVolume chunkLineage chunkLineage // immutable authority captured by this attachment // Private until the owner commit succeeds; retained for attach retry. @@ -402,6 +404,7 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura closeCtx: closeCtx, closeCancel: closeCancel, startupUpdates: make(chan struct{}, 1), + fenceUpdates: make(chan struct{}, 1), }, nil } diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 17e438f558..6818949132 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -336,6 +336,7 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v h.backend.chunkFenced = layer.Fenced h.backend.mu.Unlock() p.startChunkLoop(volumeID, h, layer) + go p.watchChunkFence(volumeID, h, layer) } return nil } diff --git a/seaweed-block/core/frontend/durable/provider_startup.go b/seaweed-block/core/frontend/durable/provider_startup.go index 1d10da2aaf..fb22ace560 100644 --- a/seaweed-block/core/frontend/durable/provider_startup.go +++ b/seaweed-block/core/frontend/durable/provider_startup.go @@ -1,6 +1,11 @@ package durable -import "errors" +import ( + "errors" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) // ChunkStartupUpdates wakes the process owner when a startup wait ends. It is // not an event queue: the owner must read ChunkStartupOutcome for its volume. @@ -57,3 +62,59 @@ func (p *DurableProvider) ChooseChunkStartupExit(volumeID string, gen uint64, ch choose() return true } + +// chunkFenceWatchInterval bounds how long after a runtime fence the backend +// reports not operational and the process owner is woken. I/O is refused +// from the fence itself (readyCheck reads the layer's latched flag). +const chunkFenceWatchInterval = 50 * time.Millisecond + +// watchChunkFence waits for the attached layer to fence after startup (its +// publication found HEAD owned by another holder or epoch: the layer latches +// fenced only on supersede or owner change, never on a clean detach), then +// latches the backend not operational with that evidence and marks the +// volume runtime-fenced (INV-FE-PRIMARY-READY-OPERATIONAL-001). It ends when +// the provider closes or the layer is no longer this volume's. +func (p *DurableProvider) watchChunkFence(volumeID string, h *volHandle, layer storage.ChunkLayer) { + t := time.NewTicker(chunkFenceWatchInterval) + defer t.Stop() + for { + select { + case <-p.closeCtx.Done(): + return + case <-t.C: + } + p.mu.Lock() + current := !p.closed && p.volumes[volumeID] == h && h.chunk == layer + p.mu.Unlock() + if !current { + return + } + if !layer.Fenced() { + continue + } + h.backend.SetOperational(false, "chunk layer fenced after startup: HEAD has another publication owner") + p.mu.Lock() + if !p.closed && p.volumes[volumeID] == h && h.chunk == layer { + h.runtimeFenced = true + select { + case p.fenceUpdates <- struct{}{}: + default: + } + } + p.mu.Unlock() + return + } +} + +// ChunkRuntimeFenceUpdates wakes the process owner when a volume's attached +// layer fenced after startup; read ChunkRuntimeFenced for the volume. +func (p *DurableProvider) ChunkRuntimeFenceUpdates() <-chan struct{} { return p.fenceUpdates } + +// ChunkRuntimeFenced reports a latched runtime fence of the volume's +// attached layer (HEAD has another publication owner). +func (p *DurableProvider) ChunkRuntimeFenced(volumeID string) bool { + p.mu.Lock() + defer p.mu.Unlock() + h := p.volumes[volumeID] + return !p.closed && h != nil && h.runtimeFenced +} diff --git a/seaweed-block/core/frontend/durable/runtime_fence_test.go b/seaweed-block/core/frontend/durable/runtime_fence_test.go new file mode 100644 index 0000000000..d359d463a6 --- /dev/null +++ b/seaweed-block/core/frontend/durable/runtime_fence_test.go @@ -0,0 +1,89 @@ +package durable_test + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// INV-FE-PRIMARY-READY-OPERATIONAL-001 (condition A): a HEAD fence after +// startup, while the lease would still be valid, refuses I/O from the fence, +// latches the backend not operational with its evidence and marks the volume +// runtime-fenced with a wakeup, so the process owner chooses the no-restart +// exit. Another holder claims HEAD at a newer epoch, or at the same epoch +// under another holder string; this holder's next publication fences. +func TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational(t *testing.T) { + for _, tc := range []struct { + name string + epoch func(uint64) uint64 + holder string + }{ + {"newer epoch", func(e uint64) uint64 { return e + 1 }, "s2/r1"}, + {"same epoch, other holder", func(e uint64) uint64 { return e }, "s2/r1"}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + remote := storage.NewMemChunkRemote() + p := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + s := openRecovered(t, p) + if _, err := s.Write(1, block(1)); err != nil { + t.Fatal(err) + } + if _, err := p.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if p.ChunkRuntimeFenced("v1") { + t.Fatal("runtime-fenced while serving") + } + backend, err := p.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + + head, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + next := head + next.Epoch, next.Holder = tc.epoch(head.Epoch), tc.holder + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, next); err != nil { + t.Fatal(err) + } + if _, err := s.Write(2, block(2)); err != nil { + t.Fatal(err) + } + if _, err := p.CaptureVolume(ctx, "v1"); err == nil { + t.Fatal("a capture over another holder's HEAD succeeded") + } + // From the fence on, no I/O is admitted (before the watcher runs). + if n, err := backend.Write(ctx, 3*4096, block(3)); err == nil || n != 0 { + t.Fatalf("a write after the fence: n=%d err=%v, want refused", n, err) + } + + select { + case <-p.ChunkRuntimeFenceUpdates(): + case <-time.After(5 * time.Second): + t.Fatal("no runtime-fence wakeup within the cleanup bound") + } + if !p.ChunkRuntimeFenced("v1") { + t.Fatal("woken but not runtime-fenced") + } + var st *durable.VolumeStatus + for _, v := range p.DurableStatuses() { + if v.VolumeID == "v1" { + v := v + st = &v + } + } + if st == nil || st.Operational || st.Evidence != "chunk layer fenced after startup: HEAD has another publication owner" { + t.Fatalf("durable status after a runtime fence: %+v, want not operational with the fence evidence", st) + } + if _, err := backend.Write(ctx, 3*4096, block(3)); err == nil { + t.Fatal("a write after the runtime fence was admitted") + } + }) + } +} diff --git a/seaweed-block/core/host/volume/workspace_lease.go b/seaweed-block/core/host/volume/workspace_lease.go index 581140618a..f3ae20dbbc 100644 --- a/seaweed-block/core/host/volume/workspace_lease.go +++ b/seaweed-block/core/host/volume/workspace_lease.go @@ -265,10 +265,11 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { } closed := g.fenced g.mu.Unlock() - if firstGrant { + if firstGrant && !closed { // Once per guard: the first grant, or the re-grant after refused // renewals (a restart before the forced-move barrier); unix_ms is the - // request start, which the lease validity is anchored to. + // request start, which the lease validity is anchored to. A first + // reply that revokes (or arrives fenced) grants nothing: no line. what := "granted" if refused > 0 { what = fmt.Sprintf("re-granted after %d refused renewal(s)", refused) diff --git a/seaweed-block/core/host/volume/workspace_lease_held_test.go b/seaweed-block/core/host/volume/workspace_lease_held_test.go index 4c149faa3e..6bb07c16e8 100644 --- a/seaweed-block/core/host/volume/workspace_lease_held_test.go +++ b/seaweed-block/core/host/volume/workspace_lease_held_test.go @@ -59,6 +59,37 @@ func TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals(t *testing.T) { } } +// A first reply that revokes grants nothing: after refused renewals, a valid +// first reply with Revoking set fences the guard, is never held and logs no +// grant line (the line is a readiness timing witness). +func TestWorkspaceLeaseFirstRevokingReplyIsNotLoggedAsAGrant(t *testing.T) { + logs := captureLog(t) + now := time.Unix(1000, 0) + calls := 0 + client := workspaceTestClient{ + renew: func() (*control.WorkspaceLeaseFact, error) { + calls++ + if calls == 1 { + return nil, errors.New("workspace forced move lease expiry plus clock-skew margin has not elapsed") + } + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(10 * time.Second), Revoking: true}, nil + }, + ack: func() error { return nil }, + } + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + _ = g.Refresh(context.Background()) + _ = g.Refresh(context.Background()) + if g.Held() || g.Projection().Healthy { + t.Fatal("a revoking first reply left the lease held") + } + if out := logs.String(); strings.Contains(out, "granted") || !strings.Contains(out, "revoked by the master") { + t.Fatalf("want no grant line and the revocation fence; log=%q", out) + } +} + // V1-SPEC r2.37: a workspace primary reports NotReadyReason=lease_not_held, // first, while its guard is missing or holds no granted lease, even with the // backend admitting I/O; ready once the lease is held; lease_not_held again diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0fecbcfd52..40671fdea4 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -46,7 +46,8 @@ The local storage engine and the durable backend in front of it. Diagrams in the stateDiagram-v2 [*] --> Opened: OpenWALStore / CreateWALStore Opened --> Recovering: RecoverVolume - Recovering --> Serving: Recover ok, backend operational + Recovering --> Serving: Recover ok, backend operational; workspace primary: lease held, then HEAD claim, then frontends listen, then ready + Serving --> Closed: runtime HEAD fence, exit 78 head_fenced Recovering --> RecoveryFailed: Recover error (typed reason) Serving --> Serving: map prepare refused (prior root released, no latch, retry) Serving --> FaultLatched: fsync or WAL append fails @@ -60,13 +61,14 @@ stateDiagram-v2 |---|---|---|---|---| | — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001`, `INV-WAL-V3-ACTIVATION-001`, `INV-WAL-V3-DESCRIPTOR-001`, `INV-WAL-V3-MAP-PUBLISH-001` | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | -| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-FE-PRIMARY-READY-OPERATIONAL-001` | +| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason); a workspace primary claims HEAD, listens and reports ready only while its lease guard permits now (`WorkspaceLeaseGuard.Held`; without a grant: `NotReadyReason=lease_not_held`, exit 75 after the start-time wait) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection`; `core/host/volume/workspace_lease.go` `Held` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-FE-PRIMARY-READY-OPERATIONAL-001`, `INV-WS-SERVE-LEASE-HELD-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001`, `INV-WAL-V3-W-RECOVERY-001` | | Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-W-001` | | Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001`, `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`, `INV-WAL-V3-RECLAIM-001`, `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001`, `INV-WAL-V3-MAP-PRIOR-LIVE-001` | | Serving | Serving (map prepare refused) | a map preparer (the flusher's checkpoint, the chunk layer's captured-map publication, BASE complete) captured prior and a publication released it before the prepare's live-set snapshot: the prepare reuses no page, writes nothing, refuses with `prior_released` without latching, counts it, and the caller's next cycle prepares from the current root | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3`; `core/storage/chunk_map_extents_v3.go` `liveSnapshotWithPriorV3` | `INV-WAL-V3-MAP-PRIOR-LIVE-001` | | Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`; `core/storage/walstore_v3.go` `appendWriteV3` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | | FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | +| Serving | Closed (process exit 78 `head_fenced`) | workspace chunk primary: the attached layer fenced after startup (HEAD has another publication owner); I/O is refused from the fence, the backend latches not operational with the evidence, and the process owner chooses the no-restart exit | `core/frontend/durable/provider_startup.go` `watchChunkFence`; `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` | `INV-FE-PRIMARY-READY-OPERATIONAL-001` | | any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | The v2 writer, scanner, checkpoint path, C11 codec/reconciler and in-place converter are retired. Native map and descriptor rules remain enforced; v2 inputs refuse open without mutation. `TestNativeReplacementLegacyBytesRefusedWithoutMutation` and `TestChunkAttachRefusesAnUnmappedNativeStore` cover these admission boundaries. The receiver session bitmap is separate and unchanged. @@ -447,7 +449,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -310 rows: 239 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 295 new. +311 rows: 240 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 296 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -461,7 +463,8 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-FE-NVME-READY-001` | A read or write on a successfully recovered chunk volume awaiting attachment waits for attachment readiness, before storage admission, for at most 3 s or until an earlier caller deadline, on the local monotonic clock. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `admitAfterAttachUnqueued`, `awaitAttachAdmission`, `readyCheck` | `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE | | `INV-FE-NVME-READY-STATUS-001` | An NVMe read or write whose attachment-readiness wait times out or is refused completes with Namespace Not Ready (SC 0x82), DNR=0, without reading or mutating storage. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` (`core/frontend/durable/takeover_read_ready_test.go`) | — | ACTIVE | | `INV-FE-NVME-READY-ANA-001` | An I/O that ends during the attachment-readiness wait because the backend closed or its lineage went stale keeps its ANA error, and a physical I/O fault keeps Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE | -| `INV-FE-PRIMARY-READY-OPERATIONAL-001` | FrontendPrimaryReady is reported only while the local durable backend admits I/O, and the frontend target starts listening only after it first does; attach-pending, fenced or no durable status reports not ready with the reason; a fence after the target listens ends the process within 5 s (`INV-WS-STARTUP-RETRY-001`). | M1 Opened / Recovering → Serving; M2 process exit | `core/host/volume/status_server.go` `statusProjection`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (the iSCSI, NVMe and ublk targets in `cmd/blockvolume/main.go` `runVolume` start after it); `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` | `TestStatusServer_ReadyOnlyWhileBackendOperational`, `TestStatusServer_NotReadyAlwaysHasAReason` (`core/host/volume/status_server_test.go`); `TestFrontendGateWaitsForTheStorageClaim`, `TestFrontendGateStopsWithoutStartingTheFrontends` (`cmd/blockvolume/frontend_gate_test.go`); `TestDurableProvider_NonChunkVolumeServesRightAfterOpen` (`core/frontend/durable/first_serving_test.go`) | — | ACTIVE | +| `INV-FE-PRIMARY-READY-OPERATIONAL-001` | FrontendPrimaryReady is reported only while the local durable backend admits I/O, and the frontend target listens only after it first does; attach-pending, fenced or no durable status reports not ready with the reason; a fence after the target listens ends the process within 5 s. | M1 Opened / Recovering → Serving; M2 process exit | `core/host/volume/status_server.go` `statusProjection`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (the iSCSI, NVMe and ublk targets in `cmd/blockvolume/main.go` `runVolume` start after it); `cmd/blockvolume/process_exit.go` `waitWorkspaceStop`; a runtime HEAD fence: `core/frontend/durable/provider_startup.go` `watchChunkFence` (not operational with the evidence) and `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (exit 78 `head_fenced`) | `TestStatusServer_ReadyOnlyWhileBackendOperational`, `TestStatusServer_NotReadyAlwaysHasAReason` (`core/host/volume/status_server_test.go`); `TestFrontendGateWaitsForTheStorageClaim`, `TestFrontendGateStopsWithoutStartingTheFrontends` (`cmd/blockvolume/frontend_gate_test.go`); `TestDurableProvider_NonChunkVolumeServesRightAfterOpen` (`core/frontend/durable/first_serving_test.go`); `TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational` (`core/frontend/durable/runtime_fence_test.go`); `TestRuntimeHeadFenceChoosesHeadFencedExit` (`cmd/blockvolume/runtime_fence_exit_test.go`) | — | ACTIVE | +| `INV-WS-SERVE-LEASE-HELD-001` | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now; without a granted lease it holds at the gate and exits 75 after the start-time wait. | M1 Recovering → Serving; M2 process exit | `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.Held` / `permits` (the one deciding function: the guarded projection gates the chunk claim, the per-I/O admit and `FrontendPrimaryReady`); `core/host/volume/status_server.go` `statusProjection` (`NotReadyReason=lease_not_held`); `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (frontends start after the claim); `cmd/blockvolume/process_exit.go` (exit 75 `assignment_timeout`) | `TestStatusServer_WorkspacePrimaryNotReadyWithoutHeldLease`, `TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals`, `TestWorkspaceLeaseFirstRevokingReplyIsNotLoggedAsAGrant` (`core/host/volume/workspace_lease_held_test.go`); real-binary cases B-late (restart before the forced-move barrier, re-granted inside the wait: no claim, listen or ready before the re-grant), B75 (no grant inside the wait: no claim, listen or ready, exit 75; a restart after the barrier serves) and B0 (restart inside the lease serves at once) | — | ACTIVE | | `INV-WAL-REPLAY-LWW-001` | Replay of the validated native prefix retains the highest admitted LSN per LBA; invalid cursor, nonce or LSN order is refused. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALLSNOrderV3_RefusesDuplicateAndLower` (`core/storage/wal_lsn_order_v3_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | | `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the both durable descriptor slots has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_io_v3.go` `append`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`); `TestNativeReplacementCheckpointSIGKILL` (`core/storage/legacy_checkpoint_replacement_v3_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | @@ -981,7 +984,8 @@ One row per wait in the data and control paths. Guest-visible rows on one path m |---|---|---|---|---|---|---| | `core/storage/chunk_publish_settled.go` `runPublishSettled` (from `unlockCap`, on the cut or detach caller's goroutine) | the `OnPublishSettled` hook to return | the hook's duration: the hook must return without blocking and without remote calls, enqueueing its work to its own worker | the hook implementer | none: a stalled hook stalls its caller, and later reports queue without a bound (a nil hook queues nothing) | none (`capMu` and `stMu` released) | yes on detach (the detach caller delivers before returning) | | `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (from `runVolume`, before any frontend starts) | the backend's first admitted I/O (`StorageBackend.FirstServing`), or the process's stop waiter returning | none of its own: it ends on the stop waiter, which INV-WS-STARTUP-RETRY-001 bounds (a refused or timed-out claim latches exit 75/78) | `runVolume` (`INV-FE-PRIMARY-READY-OPERATIONAL-001`) | no frontend starts; shutdown as after the frontends | none | no (no target listens yet) | -| `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` (one goroutine from `runVolume`, started with the workspace lease guard before the frontends) | a signal, the lease guard's drain request or end, or the latched startup outcome | the process lifetime | the process exit owner (`superviseProcess`, `INV-WS-STARTUP-RETRY-001`) | the chosen exit status (0 revoked/signal, 75 retry, 78 superseded) | none | no | +| `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` (one goroutine from `runVolume`, started with the workspace lease guard before the frontends) | a signal, the lease guard's drain request or end, or the latched process outcome (startup, or a runtime HEAD fence) | the process lifetime | the process exit owner (`superviseProcess`, `INV-WS-STARTUP-RETRY-001`) | the chosen exit status (0 revoked/signal, 75 retry, 78 superseded or `head_fenced`) | none | no | +| `cmd/blockvolume/main.go` `runVolume`, the receive of `stopWait` after the frontends started (when `awaitFrontendStart` released on first serving) | the one result of the `waitWorkspaceStop` goroutine (its only producer, a 1-slot channel it sends to exactly once) | the process lifetime, as `waitWorkspaceStop` | the process exit owner (`superviseProcess`) | shutdown with the handed-back lease drain request | none | no (the targets serve until the stop) | Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The W/BASE/fence owner (`WALStore.recoverV3`) must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. From 33e72fd0834af8e3660c68e86f85e4a02941dbd6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 02:34:10 -0800 Subject: [PATCH 53/57] blockvolume: state the fence-to-exit bound as detection plus cleanup; join the fence watcher INV-FE-PRIMARY-READY-OPERATIONAL-001 keeps the readiness and listen property; the fence-to-exit bound is its own row, INV-FE-FENCE-EXIT-001, stated as what is guaranteed: the fence's detection time (a HEAD fence: 50 ms) plus the existing 5 s cleanup bound from the decision. 307 rows, 221 ACTIVE. Provider Close joins each layer's fence watcher through p.inflight (counted under p.mu while not closed). C.W lists the two new waits. The runtime-fence watcher test owns its worker: cleanup registered before the start, the return joined with a bound on both paths. Co-Authored-By: Claude Opus 5.5 --- .../blockvolume/runtime_fence_exit_test.go | 52 +++++++++++++++---- .../core/frontend/durable/provider.go | 3 +- .../core/frontend/durable/provider_chunk.go | 1 + .../core/frontend/durable/provider_startup.go | 4 +- seaweed-block/docs/design/invariants.md | 9 ++-- 5 files changed, 54 insertions(+), 15 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/runtime_fence_exit_test.go b/seaweed-block/cmd/blockvolume/runtime_fence_exit_test.go index dad78fbec4..48e9d3bbe3 100644 --- a/seaweed-block/cmd/blockvolume/runtime_fence_exit_test.go +++ b/seaweed-block/cmd/blockvolume/runtime_fence_exit_test.go @@ -15,18 +15,41 @@ type runtimeFenceStub struct { func (s *runtimeFenceStub) ChunkRuntimeFenced(string) bool { return s.fenced.Load() } func (s *runtimeFenceStub) ChunkRuntimeFenceUpdates() <-chan struct{} { return s.updates } -// INV-FE-PRIMARY-READY-OPERATIONAL-001 (condition A): a runtime HEAD fence of -// a workspace chunk primary chooses the no-restart exit 78 head_fenced through -// the process owner's one chooser; nothing is chosen while not fenced, and a +// runtimeFenceWait bounds every receive and join in this test. +const runtimeFenceWait = 5 * time.Second + +// startRuntimeFenceWatch runs watchChunkRuntimeFence with a context it owns. +// Its cleanup, registered before the worker starts, cancels that context and +// joins the worker within runtimeFenceWait, so an earlier failed check never +// strands it. The returned channel closes when the worker returned. +func startRuntimeFenceWatch(t *testing.T, e *processExit, f flags, p chunkRuntimeFenceProvider) <-chan struct{} { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + t.Cleanup(func() { + cancel() + select { + case <-done: + case <-time.After(runtimeFenceWait): + t.Errorf("the runtime-fence watcher did not return within %s of its cancel", runtimeFenceWait) + } + }) + go func() { + defer close(done) + watchChunkRuntimeFence(ctx, e, f, p) + }() + return done +} + +// INV-FE-FENCE-EXIT-001: a runtime HEAD fence of a workspace chunk primary +// chooses the no-restart exit 78 head_fenced through the process owner's one +// chooser, and the watcher returns; nothing is chosen while not fenced, and a // non-workspace volume never watches. func TestRuntimeHeadFenceChoosesHeadFencedExit(t *testing.T) { f := flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v1"} e := newProcessExit(context.Background()) stub := &runtimeFenceStub{updates: make(chan struct{}, 1)} - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - done := make(chan struct{}) - go func() { watchChunkRuntimeFence(ctx, e, f, stub); close(done) }() + done := startRuntimeFenceWatch(t, e, f, stub) select { case out := <-e.decision: t.Fatalf("an exit was chosen while not fenced: %+v", out) @@ -39,13 +62,22 @@ func TestRuntimeHeadFenceChoosesHeadFencedExit(t *testing.T) { if out != (workspaceExit{exitWorkspaceSuperseded, "head_fenced"}) { t.Fatalf("exit %+v, want 78 head_fenced", out) } - case <-time.After(5 * time.Second): + case <-time.After(runtimeFenceWait): t.Fatal("no exit chosen after the runtime fence") } - <-done + select { + case <-done: + case <-time.After(runtimeFenceWait): + t.Fatal("the watcher chose the exit but did not return") + } plain := newProcessExit(context.Background()) - watchChunkRuntimeFence(ctx, plain, flags{volumeID: "v1"}, stub) // returns at once: not a workspace chunk primary + plainDone := startRuntimeFenceWatch(t, plain, flags{volumeID: "v1"}, stub) + select { + case <-plainDone: // not a workspace chunk primary: returns at once + case <-time.After(runtimeFenceWait): + t.Fatal("a non-workspace volume kept watching") + } select { case out := <-plain.decision: t.Fatalf("a non-workspace volume chose %+v", out) diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 220a254251..906620614c 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -262,7 +262,8 @@ type DurableProvider struct { // walstore-chunk: closeCtx ends with Close and cancels in-flight // remote attachment; inflight counts RecoverVolume calls admitted - // before Close, which Close waits for before closing any store. + // before Close, and each attached layer's fence watcher, which Close + // waits for before closing any store. closeCtx context.Context closeCancel context.CancelFunc inflight sync.WaitGroup diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 6818949132..35a45115a8 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -336,6 +336,7 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v h.backend.chunkFenced = layer.Fenced h.backend.mu.Unlock() p.startChunkLoop(volumeID, h, layer) + p.inflight.Add(1) // under p.mu with closed false: Close joins the watcher go p.watchChunkFence(volumeID, h, layer) } return nil diff --git a/seaweed-block/core/frontend/durable/provider_startup.go b/seaweed-block/core/frontend/durable/provider_startup.go index fb22ace560..ce9fc929db 100644 --- a/seaweed-block/core/frontend/durable/provider_startup.go +++ b/seaweed-block/core/frontend/durable/provider_startup.go @@ -73,8 +73,10 @@ const chunkFenceWatchInterval = 50 * time.Millisecond // fenced only on supersede or owner change, never on a clean detach), then // latches the backend not operational with that evidence and marks the // volume runtime-fenced (INV-FE-PRIMARY-READY-OPERATIONAL-001). It ends when -// the provider closes or the layer is no longer this volume's. +// the provider closes or the layer is no longer this volume's; Close joins it +// through p.inflight (counted when it starts) after cancelling closeCtx. func (p *DurableProvider) watchChunkFence(volumeID string, h *volHandle, layer storage.ChunkLayer) { + defer p.inflight.Done() t := time.NewTicker(chunkFenceWatchInterval) defer t.Stop() for { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 40671fdea4..b3f902243a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -68,7 +68,7 @@ stateDiagram-v2 | Serving | Serving (map prepare refused) | a map preparer (the flusher's checkpoint, the chunk layer's captured-map publication, BASE complete) captured prior and a publication released it before the prepare's live-set snapshot: the prepare reuses no page, writes nothing, refuses with `prior_released` without latching, counts it, and the caller's next cycle prepares from the current root | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3`; `core/storage/chunk_map_extents_v3.go` `liveSnapshotWithPriorV3` | `INV-WAL-V3-MAP-PRIOR-LIVE-001` | | Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`; `core/storage/walstore_v3.go` `appendWriteV3` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | | FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | -| Serving | Closed (process exit 78 `head_fenced`) | workspace chunk primary: the attached layer fenced after startup (HEAD has another publication owner); I/O is refused from the fence, the backend latches not operational with the evidence, and the process owner chooses the no-restart exit | `core/frontend/durable/provider_startup.go` `watchChunkFence`; `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` | `INV-FE-PRIMARY-READY-OPERATIONAL-001` | +| Serving | Closed (process exit 78 `head_fenced`) | workspace chunk primary: the attached layer fenced after startup (HEAD has another publication owner); I/O is refused from the fence, the backend latches not operational with the evidence, and the process owner chooses the no-restart exit | `core/frontend/durable/provider_startup.go` `watchChunkFence`; `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` | `INV-FE-FENCE-EXIT-001` | | any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | The v2 writer, scanner, checkpoint path, C11 codec/reconciler and in-place converter are retired. Native map and descriptor rules remain enforced; v2 inputs refuse open without mutation. `TestNativeReplacementLegacyBytesRefusedWithoutMutation` and `TestChunkAttachRefusesAnUnmappedNativeStore` cover these admission boundaries. The receiver session bitmap is separate and unchanged. @@ -449,7 +449,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -311 rows: 240 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 296 new. +312 rows: 241 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 297 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -463,7 +463,8 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-FE-NVME-READY-001` | A read or write on a successfully recovered chunk volume awaiting attachment waits for attachment readiness, before storage admission, for at most 3 s or until an earlier caller deadline, on the local monotonic clock. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `admitAfterAttachUnqueued`, `awaitAttachAdmission`, `readyCheck` | `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE | | `INV-FE-NVME-READY-STATUS-001` | An NVMe read or write whose attachment-readiness wait times out or is refused completes with Namespace Not Ready (SC 0x82), DNR=0, without reading or mutating storage. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` (`core/frontend/durable/takeover_read_ready_test.go`) | — | ACTIVE | | `INV-FE-NVME-READY-ANA-001` | An I/O that ends during the attachment-readiness wait because the backend closed or its lineage went stale keeps its ANA error, and a physical I/O fault keeps Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE | -| `INV-FE-PRIMARY-READY-OPERATIONAL-001` | FrontendPrimaryReady is reported only while the local durable backend admits I/O, and the frontend target listens only after it first does; attach-pending, fenced or no durable status reports not ready with the reason; a fence after the target listens ends the process within 5 s. | M1 Opened / Recovering → Serving; M2 process exit | `core/host/volume/status_server.go` `statusProjection`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (the iSCSI, NVMe and ublk targets in `cmd/blockvolume/main.go` `runVolume` start after it); `cmd/blockvolume/process_exit.go` `waitWorkspaceStop`; a runtime HEAD fence: `core/frontend/durable/provider_startup.go` `watchChunkFence` (not operational with the evidence) and `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (exit 78 `head_fenced`) | `TestStatusServer_ReadyOnlyWhileBackendOperational`, `TestStatusServer_NotReadyAlwaysHasAReason` (`core/host/volume/status_server_test.go`); `TestFrontendGateWaitsForTheStorageClaim`, `TestFrontendGateStopsWithoutStartingTheFrontends` (`cmd/blockvolume/frontend_gate_test.go`); `TestDurableProvider_NonChunkVolumeServesRightAfterOpen` (`core/frontend/durable/first_serving_test.go`); `TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational` (`core/frontend/durable/runtime_fence_test.go`); `TestRuntimeHeadFenceChoosesHeadFencedExit` (`cmd/blockvolume/runtime_fence_exit_test.go`) | — | ACTIVE | +| `INV-FE-PRIMARY-READY-OPERATIONAL-001` | FrontendPrimaryReady is reported only while the local durable backend admits I/O, and the frontend target listens only after it first does; attach-pending, fenced or no durable status reports not ready with the reason. | M1 Opened / Recovering → Serving; M2 process exit | `core/host/volume/status_server.go` `statusProjection`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (the iSCSI, NVMe and ublk targets in `cmd/blockvolume/main.go` `runVolume` start after it); `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` | `TestStatusServer_ReadyOnlyWhileBackendOperational`, `TestStatusServer_NotReadyAlwaysHasAReason` (`core/host/volume/status_server_test.go`); `TestFrontendGateWaitsForTheStorageClaim`, `TestFrontendGateStopsWithoutStartingTheFrontends` (`cmd/blockvolume/frontend_gate_test.go`); `TestDurableProvider_NonChunkVolumeServesRightAfterOpen` (`core/frontend/durable/first_serving_test.go`) | — | ACTIVE | +| `INV-FE-FENCE-EXIT-001` | A workspace chunk primary whose backend fences after its target listens (lease expiry or a HEAD fence) ends the process within the fence's detection time (HEAD fence: 50 ms) plus the 5 s cleanup bound. | M1 Serving → Closed; M2 process exit | `core/frontend/durable/provider_startup.go` `watchChunkFence` (HEAD fence: not operational with the evidence within 50 ms; I/O refused from the fence); `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (78 `head_fenced`) and `waitWorkspaceStop` (lease fence: 75 `lease_expired`); `superviseProcess` (the 5 s cleanup bound from the decision) | `TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational` (`core/frontend/durable/runtime_fence_test.go`); `TestRuntimeHeadFenceChoosesHeadFencedExit` (`cmd/blockvolume/runtime_fence_exit_test.go`); real-binary case C (lease expiry after listening: exit 75) | — | ACTIVE | | `INV-WS-SERVE-LEASE-HELD-001` | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now; without a granted lease it holds at the gate and exits 75 after the start-time wait. | M1 Recovering → Serving; M2 process exit | `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.Held` / `permits` (the one deciding function: the guarded projection gates the chunk claim, the per-I/O admit and `FrontendPrimaryReady`); `core/host/volume/status_server.go` `statusProjection` (`NotReadyReason=lease_not_held`); `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (frontends start after the claim); `cmd/blockvolume/process_exit.go` (exit 75 `assignment_timeout`) | `TestStatusServer_WorkspacePrimaryNotReadyWithoutHeldLease`, `TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals`, `TestWorkspaceLeaseFirstRevokingReplyIsNotLoggedAsAGrant` (`core/host/volume/workspace_lease_held_test.go`); real-binary cases B-late (restart before the forced-move barrier, re-granted inside the wait: no claim, listen or ready before the re-grant), B75 (no grant inside the wait: no claim, listen or ready, exit 75; a restart after the barrier serves) and B0 (restart inside the lease serves at once) | — | ACTIVE | | `INV-WAL-REPLAY-LWW-001` | Replay of the validated native prefix retains the highest admitted LSN per LBA; invalid cursor, nonce or LSN order is refused. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALLSNOrderV3_RefusesDuplicateAndLower` (`core/storage/wal_lsn_order_v3_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | | `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the both durable descriptor slots has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_io_v3.go` `append`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | @@ -986,6 +987,8 @@ One row per wait in the data and control paths. Guest-visible rows on one path m | `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (from `runVolume`, before any frontend starts) | the backend's first admitted I/O (`StorageBackend.FirstServing`), or the process's stop waiter returning | none of its own: it ends on the stop waiter, which INV-WS-STARTUP-RETRY-001 bounds (a refused or timed-out claim latches exit 75/78) | `runVolume` (`INV-FE-PRIMARY-READY-OPERATIONAL-001`) | no frontend starts; shutdown as after the frontends | none | no (no target listens yet) | | `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` (one goroutine from `runVolume`, started with the workspace lease guard before the frontends) | a signal, the lease guard's drain request or end, or the latched process outcome (startup, or a runtime HEAD fence) | the process lifetime | the process exit owner (`superviseProcess`, `INV-WS-STARTUP-RETRY-001`) | the chosen exit status (0 revoked/signal, 75 retry, 78 superseded or `head_fenced`) | none | no | | `cmd/blockvolume/main.go` `runVolume`, the receive of `stopWait` after the frontends started (when `awaitFrontendStart` released on first serving) | the one result of the `waitWorkspaceStop` goroutine (its only producer, a 1-slot channel it sends to exactly once) | the process lifetime, as `waitWorkspaceStop` | the process exit owner (`superviseProcess`) | shutdown with the handed-back lease drain request | none | no (the targets serve until the stop) | +| `core/frontend/durable/provider_startup.go` `watchChunkFence` (one goroutine per attached chunk layer, started when the layer attaches) | the 50 ms ticker (then reads the layer's latched fence flag) or provider close (`closeCtx`) | the attached layer's lifetime: it returns at provider close, when the layer is no longer the volume's, or after publishing a fence; Close joins it (`p.inflight`) | `DurableProvider.Close` (cancels `closeCtx`, then waits `p.inflight`) | none: the ticker is its poll, not a deadline; a HEAD fence is published at most 50 ms after the layer latches it (I/O is refused from the latch) | none while waiting (`p.mu` only briefly to check the handle and publish) | no | +| `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (one goroutine from `runVolume`, workspace chunk primaries) | the provider's runtime-fence wakeup (1-slot, `ChunkRuntimeFenceUpdates`), the process outcome (`e.done`) or the watch context | the process lifetime: it returns after choosing 78 `head_fenced`, when another outcome is chosen, or when `runVolume` cancels its watch context | the process exit owner (`superviseProcess`) | none | none | no | Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The W/BASE/fence owner (`WALStore.recoverV3`) must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. From c0e243a8882046633f5126a27038477f94292e86 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 02:42:37 -0800 Subject: [PATCH 54/57] docs: INV-FE-FENCE-EXIT-001 statement as ruled (both detection terms named) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b3f902243a..ce3bc8c165 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -464,7 +464,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-FE-NVME-READY-STATUS-001` | An NVMe read or write whose attachment-readiness wait times out or is refused completes with Namespace Not Ready (SC 0x82), DNR=0, without reading or mutating storage. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` (`core/frontend/durable/takeover_read_ready_test.go`) | — | ACTIVE | | `INV-FE-NVME-READY-ANA-001` | An I/O that ends during the attachment-readiness wait because the backend closed or its lineage went stale keeps its ANA error, and a physical I/O fault keeps Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE | | `INV-FE-PRIMARY-READY-OPERATIONAL-001` | FrontendPrimaryReady is reported only while the local durable backend admits I/O, and the frontend target listens only after it first does; attach-pending, fenced or no durable status reports not ready with the reason. | M1 Opened / Recovering → Serving; M2 process exit | `core/host/volume/status_server.go` `statusProjection`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (the iSCSI, NVMe and ublk targets in `cmd/blockvolume/main.go` `runVolume` start after it); `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` | `TestStatusServer_ReadyOnlyWhileBackendOperational`, `TestStatusServer_NotReadyAlwaysHasAReason` (`core/host/volume/status_server_test.go`); `TestFrontendGateWaitsForTheStorageClaim`, `TestFrontendGateStopsWithoutStartingTheFrontends` (`cmd/blockvolume/frontend_gate_test.go`); `TestDurableProvider_NonChunkVolumeServesRightAfterOpen` (`core/frontend/durable/first_serving_test.go`) | — | ACTIVE | -| `INV-FE-FENCE-EXIT-001` | A workspace chunk primary whose backend fences after its target listens (lease expiry or a HEAD fence) ends the process within the fence's detection time (HEAD fence: 50 ms) plus the 5 s cleanup bound. | M1 Serving → Closed; M2 process exit | `core/frontend/durable/provider_startup.go` `watchChunkFence` (HEAD fence: not operational with the evidence within 50 ms; I/O refused from the fence); `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (78 `head_fenced`) and `waitWorkspaceStop` (lease fence: 75 `lease_expired`); `superviseProcess` (the 5 s cleanup bound from the decision) | `TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational` (`core/frontend/durable/runtime_fence_test.go`); `TestRuntimeHeadFenceChoosesHeadFencedExit` (`cmd/blockvolume/runtime_fence_exit_test.go`); real-binary case C (lease expiry after listening: exit 75) | — | ACTIVE | +| `INV-FE-FENCE-EXIT-001` | A workspace chunk primary whose backend fences after its target listens ends the process within detection plus the 5 s cleanup bound: a lease expiry at the guard's own deadline, a HEAD fence within 50 ms. | M1 Serving → Closed; M2 process exit | `core/frontend/durable/provider_startup.go` `watchChunkFence` (HEAD fence: not operational with the evidence within 50 ms; I/O refused from the fence); `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (78 `head_fenced`) and `waitWorkspaceStop` (lease fence: 75 `lease_expired`); `superviseProcess` (the 5 s cleanup bound from the decision) | `TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational` (`core/frontend/durable/runtime_fence_test.go`); `TestRuntimeHeadFenceChoosesHeadFencedExit` (`cmd/blockvolume/runtime_fence_exit_test.go`); real-binary case C (lease expiry after listening: exit 75) | — | ACTIVE | | `INV-WS-SERVE-LEASE-HELD-001` | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now; without a granted lease it holds at the gate and exits 75 after the start-time wait. | M1 Recovering → Serving; M2 process exit | `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.Held` / `permits` (the one deciding function: the guarded projection gates the chunk claim, the per-I/O admit and `FrontendPrimaryReady`); `core/host/volume/status_server.go` `statusProjection` (`NotReadyReason=lease_not_held`); `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (frontends start after the claim); `cmd/blockvolume/process_exit.go` (exit 75 `assignment_timeout`) | `TestStatusServer_WorkspacePrimaryNotReadyWithoutHeldLease`, `TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals`, `TestWorkspaceLeaseFirstRevokingReplyIsNotLoggedAsAGrant` (`core/host/volume/workspace_lease_held_test.go`); real-binary cases B-late (restart before the forced-move barrier, re-granted inside the wait: no claim, listen or ready before the re-grant), B75 (no grant inside the wait: no claim, listen or ready, exit 75; a restart after the barrier serves) and B0 (restart inside the lease serves at once) | — | ACTIVE | | `INV-WAL-REPLAY-LWW-001` | Replay of the validated native prefix retains the highest admitted LSN per LBA; invalid cursor, nonce or LSN order is refused. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALLSNOrderV3_RefusesDuplicateAndLower` (`core/storage/wal_lsn_order_v3_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | | `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the both durable descriptor slots has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_io_v3.go` `append`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | From 50d6d92845c9a0e124754c2a920a36747e839535 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 03:19:27 -0800 Subject: [PATCH 55/57] blockvolume: one "may serve" function: AdmitsIO for status and the workspace start gate V1-SPEC r2.39: StorageBackend.AdmitsIO is the I/O gate itself (the backend admits I/O AND the guarded projection names this lineage as the healthy primary). /status FrontendPrimaryReady and NotReadyReason read it through the provider (lease_not_held stays first; an unopened volume fails closed). A workspace chunk primary's frontends start once AdmitsIO passes after the backend first admitted I/O (firstAdmitted: a bounded 50 ms re-check until first served, workspace primaries only; the backend has no projection-change signal). Non-chunk volumes and supporting replicas start after open as before (the #410 design condition, V1-SPEC r2.39), now pinned by a test. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/frontend_gate.go | 49 ++++++++++++ .../blockvolume/frontend_start_signal_test.go | 79 +++++++++++++++++++ seaweed-block/cmd/blockvolume/main.go | 2 +- .../core/frontend/durable/admits_io_test.go | 36 +++++++++ .../core/frontend/durable/provider.go | 10 +++ .../core/frontend/durable/storage_adapter.go | 7 ++ .../core/host/volume/status_server.go | 14 ++-- .../core/host/volume/status_server_test.go | 19 ++++- seaweed-block/docs/design/invariants.md | 3 +- 9 files changed, 209 insertions(+), 10 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/frontend_start_signal_test.go create mode 100644 seaweed-block/core/frontend/durable/admits_io_test.go diff --git a/seaweed-block/cmd/blockvolume/frontend_gate.go b/seaweed-block/cmd/blockvolume/frontend_gate.go index 69a5b84bdc..effdac1f93 100644 --- a/seaweed-block/cmd/blockvolume/frontend_gate.go +++ b/seaweed-block/cmd/blockvolume/frontend_gate.go @@ -3,6 +3,7 @@ package main import ( "fmt" "os" + "time" ) // workspaceStopWait is what the process's one stop waiter (waitWorkspaceStop) @@ -21,6 +22,54 @@ type workspaceStopWait struct { // shuts down with exactly as after the frontends. A stop decided meanwhile by // INV-WS-STARTUP-RETRY-001 (exit 75 or 78) ends the stop waiter too, so a // refused claim never starts a frontend. +// servingBackend is the part of the durable backend the start gate reads. +type servingBackend interface { + FirstServing() <-chan struct{} + AdmitsIO() error +} + +// frontendStartSignal is what the frontends wait for. A workspace chunk +// primary (V1-SPEC r2.37/r2.39) starts its targets only once the one "may +// serve" function (AdmitsIO) passes after the backend first admitted I/O; +// any other volume (non-chunk, or a supporting replica) starts right after +// open, as before: it never makes the claim a workspace primary waits for. +func frontendStartSignal(f flags, b servingBackend, stop <-chan struct{}) <-chan struct{} { + if f.workspaceLease && f.durableImpl == "walstore-chunk" { + return firstAdmitted(stop, b.FirstServing(), b.AdmitsIO) + } + return b.FirstServing() +} + +// admitRecheck bounds firstAdmitted's re-check of AdmitsIO after the backend +// first admits I/O (workspace primaries only, until first served): the +// backend has no projection-change signal. +const admitRecheck = 50 * time.Millisecond + +// firstAdmitted is closed once first has closed (the backend first admitted +// I/O) and admits() then passes; it re-checks every admitRecheck until then, +// and ends without closing when stop closes. +func firstAdmitted(stop <-chan struct{}, first <-chan struct{}, admits func() error) <-chan struct{} { + out := make(chan struct{}) + go func() { + select { + case <-first: + case <-stop: + return + } + t := time.NewTicker(admitRecheck) + defer t.Stop() + for admits() != nil { + select { + case <-t.C: + case <-stop: + return + } + } + close(out) + }() + return out +} + func awaitFrontendStart(serving <-chan struct{}, stopWait <-chan workspaceStopWait) (stopped *workspaceStopWait, start bool) { if serving == nil { return nil, true diff --git a/seaweed-block/cmd/blockvolume/frontend_start_signal_test.go b/seaweed-block/cmd/blockvolume/frontend_start_signal_test.go new file mode 100644 index 0000000000..21956ae9b1 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/frontend_start_signal_test.go @@ -0,0 +1,79 @@ +package main + +import ( + "errors" + "sync/atomic" + "testing" + "time" +) + +type servingStub struct { + first chan struct{} + admits atomic.Bool +} + +func (s *servingStub) FirstServing() <-chan struct{} { return s.first } +func (s *servingStub) AdmitsIO() error { + if s.admits.Load() { + return nil + } + return errors.New("stale primary lineage") +} + +func closedWithin(ch <-chan struct{}, d time.Duration) bool { + select { + case <-ch: + return true + case <-time.After(d): + return false + } +} + +// V1-SPEC r2.37/r2.39: a workspace chunk primary's targets start only once +// AdmitsIO passes after the backend first admitted I/O; the stop ends the +// wait without starting them. +func TestFrontendStartSignal_WorkspacePrimaryWaitsForAdmitsIO(t *testing.T) { + f := flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v1"} + stop := make(chan struct{}) + t.Cleanup(func() { close(stop) }) // ends the re-check goroutine on any path + b := &servingStub{first: make(chan struct{})} + sig := frontendStartSignal(f, b, stop) + if closedWithin(sig, 100*time.Millisecond) { + t.Fatal("started before the backend first admitted I/O") + } + close(b.first) // operational, but the guarded projection does not admit yet + if closedWithin(sig, 4*admitRecheck) { + t.Fatal("started while AdmitsIO refuses") + } + b.admits.Store(true) + if !closedWithin(sig, 5*time.Second) { + t.Fatal("did not start after AdmitsIO passed") + } + + stop2 := make(chan struct{}) + b2 := &servingStub{first: make(chan struct{})} + close(b2.first) + sig2 := frontendStartSignal(f, b2, stop2) + close(stop2) + if closedWithin(sig2, 4*admitRecheck) { + t.Fatal("a stopped wait started the targets") + } +} + +// claude06's #410 design condition: a non-chunk volume or a supporting +// replica starts its frontends right after open, as before: its start +// signal is the backend's first-serving channel itself, not AdmitsIO. +func TestFrontendStartSignal_OtherVolumesStartAfterOpenAsBefore(t *testing.T) { + stop := make(chan struct{}) + defer close(stop) + for _, f := range []flags{ + {durableImpl: "walstore", volumeID: "v1"}, + {durableImpl: "walstore-chunk", volumeID: "v1"}, // chunk without the workspace lease + } { + b := &servingStub{first: make(chan struct{})} + close(b.first) // open and recovered; AdmitsIO refuses (not the primary) + if !closedWithin(frontendStartSignal(f, b, stop), time.Second) { + t.Fatalf("impl=%s workspace-lease=%v: did not start right after open while AdmitsIO refuses", f.durableImpl, f.workspaceLease) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 893b2af0c5..36b649d6cf 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -1046,7 +1046,7 @@ func runVolume(f flags, exits *processExit) int { var serving <-chan struct{} // nil: no durable backend, start at once if durableProv != nil { if b := durableProv.Backend(f.volumeID); b != nil { - serving = b.FirstServing() + serving = frontendStartSignal(f, b, exits.done) } } stopped, startFrontends := awaitFrontendStart(serving, stopWait) diff --git a/seaweed-block/core/frontend/durable/admits_io_test.go b/seaweed-block/core/frontend/durable/admits_io_test.go new file mode 100644 index 0000000000..d44227f6a9 --- /dev/null +++ b/seaweed-block/core/frontend/durable/admits_io_test.go @@ -0,0 +1,36 @@ +package durable_test + +import ( + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +// V1-SPEC r2.39: AdmitsIO is the one "may serve" function, the I/O gate +// itself: an operational backend whose guarded projection is not this +// lineage's healthy primary does not admit, nor does a backend that is not +// operational; both together admit. +func TestStorageBackend_AdmitsIOIsTheIOGate(t *testing.T) { + for _, f := range logicalStorageFactories() { + f := f + t.Run(f.name, func(t *testing.T) { + b, view, _ := newTestBackend(t, f, 4, 4096) + if err := b.AdmitsIO(); err != nil { + t.Fatalf("healthy and operational: %v, want nil", err) + } + p := view.Projection() + p.Healthy = false + view.set(p) + if err := b.AdmitsIO(); !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("operational, projection not healthy: %v, want ErrStalePrimary", err) + } + p.Healthy = true + view.set(p) + b.SetOperational(false, "test: attach pending") + if err := b.AdmitsIO(); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("healthy, not operational: %v, want ErrNotReady", err) + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 906620614c..bf35f99d7d 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -558,6 +558,16 @@ func (p *DurableProvider) LogicalStorage(volumeID string) storage.LogicalStorage // G5-4 binary wiring to install SetWriteObserver eagerly (before // any frontend bind) — the same backend instance is returned by // the future dp.Open() call when a frontend asks. +// AdmitsIO is StorageBackend.AdmitsIO for an open volume; ErrVolumeNotOpen +// for any other (fail closed). +func (p *DurableProvider) AdmitsIO(volumeID string) error { + b := p.Backend(volumeID) + if b == nil { + return fmt.Errorf("%w: %s", ErrVolumeNotOpen, volumeID) + } + return b.AdmitsIO() +} + func (p *DurableProvider) Backend(volumeID string) *StorageBackend { p.mu.Lock() defer p.mu.Unlock() diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 703b005ad7..47249f558a 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -900,6 +900,13 @@ func (b *StorageBackend) gate() error { return b.lineageCheck() } +// AdmitsIO is the one deciding function for "may serve" (V1-SPEC r2.39): +// nil exactly when a Read, Write or Sync arriving now passes the I/O gate, +// i.e. the backend admits I/O (open, operational, not chunk-fenced, no +// pre-copy pause) AND the guarded projection names this backend's lineage as +// the healthy primary. /status FrontendPrimaryReady reads it. +func (b *StorageBackend) AdmitsIO() error { return b.gate() } + // readyCheck is the gate without the lineage check: closed, then // operational. func (b *StorageBackend) readyCheck() error { diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index cbf1286ff5..456b46f1e3 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -89,6 +89,9 @@ type peerStatusSource interface { type durableStatusSource interface { DurableStatuses() []durable.VolumeStatus + // AdmitsIO is the one deciding function for "may serve" of an open + // volume (StorageBackend.AdmitsIO); an error for any other. + AdmitsIO(volumeID string) error } type nvmeStatusSource interface { @@ -512,18 +515,15 @@ func (s *StatusServer) statusProjection() StatusProjection { // view. Whenever FrontendPrimaryReady is false, NotReadyReason says why. backendReason := "" if src != nil { // outside s.mu: the provider takes its own lock - found := false for _, st := range src.DurableStatuses() { if st.VolumeID == p.VolumeID { - found = true p.Warnings = append(p.Warnings, st.Warnings...) - if !st.Operational { - backendReason = "durable backend not operational: " + st.Evidence - } } } - if !found { - backendReason = "no durable status for volume " + p.VolumeID + // V1-SPEC r2.39: the backend's one "may serve" function decides; an + // unopened volume fails closed. + if err := src.AdmitsIO(p.VolumeID); err != nil { + backendReason = "durable backend admits no I/O: " + err.Error() } } leaseNotHeld := s.view.workspaceLeaseNotHeld() diff --git a/seaweed-block/core/host/volume/status_server_test.go b/seaweed-block/core/host/volume/status_server_test.go index 1e341c9a3d..8310f769fb 100644 --- a/seaweed-block/core/host/volume/status_server_test.go +++ b/seaweed-block/core/host/volume/status_server_test.go @@ -7,6 +7,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "github.com/seaweedfs/seaweed-block/core/storage" "net/http" "net/http/httptest" @@ -16,6 +17,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/adapter" "github.com/seaweedfs/seaweed-block/core/engine" + "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" "github.com/seaweedfs/seaweed-block/core/frontend/ublk" @@ -957,6 +959,21 @@ func (s stubDurableStatusSource) DurableStatuses() []durable.VolumeStatus { return append([]durable.VolumeStatus(nil), s.vols...) } +// AdmitsIO models StorageBackend.AdmitsIO from the stub's statuses: an open +// operational volume admits; a non-operational one refuses with its evidence; +// an unknown one fails closed. +func (s stubDurableStatusSource) AdmitsIO(volumeID string) error { + for _, v := range s.vols { + if v.VolumeID == volumeID { + if !v.Operational { + return fmt.Errorf("%w: %s", frontend.ErrNotReady, v.Evidence) + } + return nil + } + } + return fmt.Errorf("%w: %s", durable.ErrVolumeNotOpen, volumeID) +} + func TestStatusServer_DurableStatusEndpoint_Disabled_Returns404(t *testing.T) { s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil)) addr, err := s.Start("127.0.0.1:0") @@ -1235,7 +1252,7 @@ func TestStatusServer_ReadyOnlyWhileBackendOperational(t *testing.T) { // backend's; with only the listener pending, it says so. s.SetNVMeListenerReady(false) s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: false, Evidence: "chunk layer attach refused"}}}) - if body := read(); body.FrontendPrimaryReady || body.NotReadyReason != "durable backend not operational: chunk layer attach refused" { + if body := read(); body.FrontendPrimaryReady || body.NotReadyReason != "durable backend admits no I/O: frontend: volume not ready: chunk layer attach refused" { t.Errorf("listener pending + fenced: ready=%v reason=%q, want the backend's reason", body.FrontendPrimaryReady, body.NotReadyReason) } s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: true}}}) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ce3bc8c165..792f6be117 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -465,7 +465,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-FE-NVME-READY-ANA-001` | An I/O that ends during the attachment-readiness wait because the backend closed or its lineage went stale keeps its ANA error, and a physical I/O fault keeps Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE | | `INV-FE-PRIMARY-READY-OPERATIONAL-001` | FrontendPrimaryReady is reported only while the local durable backend admits I/O, and the frontend target listens only after it first does; attach-pending, fenced or no durable status reports not ready with the reason. | M1 Opened / Recovering → Serving; M2 process exit | `core/host/volume/status_server.go` `statusProjection`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (the iSCSI, NVMe and ublk targets in `cmd/blockvolume/main.go` `runVolume` start after it); `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` | `TestStatusServer_ReadyOnlyWhileBackendOperational`, `TestStatusServer_NotReadyAlwaysHasAReason` (`core/host/volume/status_server_test.go`); `TestFrontendGateWaitsForTheStorageClaim`, `TestFrontendGateStopsWithoutStartingTheFrontends` (`cmd/blockvolume/frontend_gate_test.go`); `TestDurableProvider_NonChunkVolumeServesRightAfterOpen` (`core/frontend/durable/first_serving_test.go`) | — | ACTIVE | | `INV-FE-FENCE-EXIT-001` | A workspace chunk primary whose backend fences after its target listens ends the process within detection plus the 5 s cleanup bound: a lease expiry at the guard's own deadline, a HEAD fence within 50 ms. | M1 Serving → Closed; M2 process exit | `core/frontend/durable/provider_startup.go` `watchChunkFence` (HEAD fence: not operational with the evidence within 50 ms; I/O refused from the fence); `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (78 `head_fenced`) and `waitWorkspaceStop` (lease fence: 75 `lease_expired`); `superviseProcess` (the 5 s cleanup bound from the decision) | `TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational` (`core/frontend/durable/runtime_fence_test.go`); `TestRuntimeHeadFenceChoosesHeadFencedExit` (`cmd/blockvolume/runtime_fence_exit_test.go`); real-binary case C (lease expiry after listening: exit 75) | — | ACTIVE | -| `INV-WS-SERVE-LEASE-HELD-001` | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now; without a granted lease it holds at the gate and exits 75 after the start-time wait. | M1 Recovering → Serving; M2 process exit | `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.Held` / `permits` (the one deciding function: the guarded projection gates the chunk claim, the per-I/O admit and `FrontendPrimaryReady`); `core/host/volume/status_server.go` `statusProjection` (`NotReadyReason=lease_not_held`); `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (frontends start after the claim); `cmd/blockvolume/process_exit.go` (exit 75 `assignment_timeout`) | `TestStatusServer_WorkspacePrimaryNotReadyWithoutHeldLease`, `TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals`, `TestWorkspaceLeaseFirstRevokingReplyIsNotLoggedAsAGrant` (`core/host/volume/workspace_lease_held_test.go`); real-binary cases B-late (restart before the forced-move barrier, re-granted inside the wait: no claim, listen or ready before the re-grant), B75 (no grant inside the wait: no claim, listen or ready, exit 75; a restart after the barrier serves) and B0 (restart inside the lease serves at once) | — | ACTIVE | +| `INV-WS-SERVE-LEASE-HELD-001` | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now; without a granted lease it holds at the gate and exits 75 after the start-time wait. | M1 Recovering → Serving; M2 process exit | `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.Held` / `permits` (the one deciding function: the guarded projection gates the chunk claim, the per-I/O admit and `FrontendPrimaryReady`); `core/frontend/durable/storage_adapter.go` `AdmitsIO` (the one "may serve" function, the I/O gate: backend admits AND guarded projection names this lineage; V1-SPEC r2.39); `core/host/volume/status_server.go` `statusProjection` (`FrontendPrimaryReady` from `AdmitsIO`; `NotReadyReason=lease_not_held` first); `cmd/blockvolume/frontend_gate.go` `frontendStartSignal` / `awaitFrontendStart` (a workspace primary's frontends start once `AdmitsIO` passes; non-chunk and supporting replicas start after open as before); `cmd/blockvolume/process_exit.go` (exit 75 `assignment_timeout`) | `TestStatusServer_WorkspacePrimaryNotReadyWithoutHeldLease`, `TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals`, `TestWorkspaceLeaseFirstRevokingReplyIsNotLoggedAsAGrant` (`core/host/volume/workspace_lease_held_test.go`); `TestStorageBackend_AdmitsIOIsTheIOGate` (`core/frontend/durable/admits_io_test.go`); `TestFrontendStartSignal_WorkspacePrimaryWaitsForAdmitsIO`, `TestFrontendStartSignal_OtherVolumesStartAfterOpenAsBefore` (`cmd/blockvolume/frontend_start_signal_test.go`); real-binary cases B-late (restart before the forced-move barrier, re-granted inside the wait: no claim, listen or ready before the re-grant), B75 (no grant inside the wait: no claim, listen or ready, exit 75; a restart after the barrier serves) and B0 (restart inside the lease serves at once) | — | ACTIVE | | `INV-WAL-REPLAY-LWW-001` | Replay of the validated native prefix retains the highest admitted LSN per LBA; invalid cursor, nonce or LSN order is refused. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALLSNOrderV3_RefusesDuplicateAndLower` (`core/storage/wal_lsn_order_v3_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | | `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the both durable descriptor slots has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_io_v3.go` `append`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`); `TestNativeReplacementCheckpointSIGKILL` (`core/storage/legacy_checkpoint_replacement_v3_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | @@ -985,6 +985,7 @@ One row per wait in the data and control paths. Guest-visible rows on one path m |---|---|---|---|---|---|---| | `core/storage/chunk_publish_settled.go` `runPublishSettled` (from `unlockCap`, on the cut or detach caller's goroutine) | the `OnPublishSettled` hook to return | the hook's duration: the hook must return without blocking and without remote calls, enqueueing its work to its own worker | the hook implementer | none: a stalled hook stalls its caller, and later reports queue without a bound (a nil hook queues nothing) | none (`capMu` and `stMu` released) | yes on detach (the detach caller delivers before returning) | | `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (from `runVolume`, before any frontend starts) | the backend's first admitted I/O (`StorageBackend.FirstServing`), or the process's stop waiter returning | none of its own: it ends on the stop waiter, which INV-WS-STARTUP-RETRY-001 bounds (a refused or timed-out claim latches exit 75/78) | `runVolume` (`INV-FE-PRIMARY-READY-OPERATIONAL-001`) | no frontend starts; shutdown as after the frontends | none | no (no target listens yet) | +| `cmd/blockvolume/frontend_gate.go` `firstAdmitted` (one goroutine from `runVolume`, workspace chunk primaries only) | the backend's first admitted I/O (`FirstServing`), then `AdmitsIO` passing, re-checked every 50 ms (the backend has no projection-change signal) | until first served or the process outcome (`e.done`), whichever comes first | the process exit owner (`superviseProcess`) through `e.done` | none: it ends without starting the frontends | none | no (no target listens yet) | | `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` (one goroutine from `runVolume`, started with the workspace lease guard before the frontends) | a signal, the lease guard's drain request or end, or the latched process outcome (startup, or a runtime HEAD fence) | the process lifetime | the process exit owner (`superviseProcess`, `INV-WS-STARTUP-RETRY-001`) | the chosen exit status (0 revoked/signal, 75 retry, 78 superseded or `head_fenced`) | none | no | | `cmd/blockvolume/main.go` `runVolume`, the receive of `stopWait` after the frontends started (when `awaitFrontendStart` released on first serving) | the one result of the `waitWorkspaceStop` goroutine (its only producer, a 1-slot channel it sends to exactly once) | the process lifetime, as `waitWorkspaceStop` | the process exit owner (`superviseProcess`) | shutdown with the handed-back lease drain request | none | no (the targets serve until the stop) | | `core/frontend/durable/provider_startup.go` `watchChunkFence` (one goroutine per attached chunk layer, started when the layer attaches) | the 50 ms ticker (then reads the layer's latched fence flag) or provider close (`closeCtx`) | the attached layer's lifetime: it returns at provider close, when the layer is no longer the volume's, or after publishing a fence; Close joins it (`p.inflight`) | `DurableProvider.Close` (cancels `closeCtx`, then waits `p.inflight`) | none: the ticker is its poll, not a deadline; a HEAD fence is published at most 50 ms after the layer latches it (I/O is refused from the latch) | none while waiting (`p.mu` only briefly to check the handle and publish) | no | From 10ce25ee9cbdfe7baaf956d79f31f87d901cdaf3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 03:47:41 -0800 Subject: [PATCH 56/57] blockvolume: firstAdmitted reports its own completion; the exit diagram carries the runtime HEAD fence The stop test now observes the worker's return on its own channel with bounded joins on both paths (a re-check that ignores the stop fails in 12 s); agent-workspace-design.md's supervisor diagram adds Serving -> Exit78 on a runtime HEAD fence (head_fenced), independent of the lease. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/frontend_gate.go | 19 +++++---- .../blockvolume/frontend_start_signal_test.go | 42 +++++++++++++++---- .../docs/design/agent-workspace-design.md | 4 ++ seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 51 insertions(+), 16 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/frontend_gate.go b/seaweed-block/cmd/blockvolume/frontend_gate.go index effdac1f93..c1d59ac2d2 100644 --- a/seaweed-block/cmd/blockvolume/frontend_gate.go +++ b/seaweed-block/cmd/blockvolume/frontend_gate.go @@ -35,7 +35,8 @@ type servingBackend interface { // open, as before: it never makes the claim a workspace primary waits for. func frontendStartSignal(f flags, b servingBackend, stop <-chan struct{}) <-chan struct{} { if f.workspaceLease && f.durableImpl == "walstore-chunk" { - return firstAdmitted(stop, b.FirstServing(), b.AdmitsIO) + out, _ := firstAdmitted(stop, b.FirstServing(), b.AdmitsIO) + return out } return b.FirstServing() } @@ -45,12 +46,14 @@ func frontendStartSignal(f flags, b servingBackend, stop <-chan struct{}) <-chan // backend has no projection-change signal. const admitRecheck = 50 * time.Millisecond -// firstAdmitted is closed once first has closed (the backend first admitted -// I/O) and admits() then passes; it re-checks every admitRecheck until then, -// and ends without closing when stop closes. -func firstAdmitted(stop <-chan struct{}, first <-chan struct{}, admits func() error) <-chan struct{} { - out := make(chan struct{}) +// firstAdmitted's out is closed once first has closed (the backend first +// admitted I/O) and admits() then passes; it re-checks every admitRecheck +// until then, and ends without closing out when stop closes. done is closed +// when its goroutine has returned, on either path. +func firstAdmitted(stop <-chan struct{}, first <-chan struct{}, admits func() error) (out, done <-chan struct{}) { + o, d := make(chan struct{}), make(chan struct{}) go func() { + defer close(d) select { case <-first: case <-stop: @@ -65,9 +68,9 @@ func firstAdmitted(stop <-chan struct{}, first <-chan struct{}, admits func() er return } } - close(out) + close(o) }() - return out + return o, d } func awaitFrontendStart(serving <-chan struct{}, stopWait <-chan workspaceStopWait) (stopped *workspaceStopWait, start bool) { diff --git a/seaweed-block/cmd/blockvolume/frontend_start_signal_test.go b/seaweed-block/cmd/blockvolume/frontend_start_signal_test.go index 21956ae9b1..919015b454 100644 --- a/seaweed-block/cmd/blockvolume/frontend_start_signal_test.go +++ b/seaweed-block/cmd/blockvolume/frontend_start_signal_test.go @@ -50,13 +50,41 @@ func TestFrontendStartSignal_WorkspacePrimaryWaitsForAdmitsIO(t *testing.T) { t.Fatal("did not start after AdmitsIO passed") } - stop2 := make(chan struct{}) - b2 := &servingStub{first: make(chan struct{})} - close(b2.first) - sig2 := frontendStartSignal(f, b2, stop2) - close(stop2) - if closedWithin(sig2, 4*admitRecheck) { - t.Fatal("a stopped wait started the targets") +} + +// A stop ends firstAdmitted's worker without starting the targets, both +// while it waits for the first admitted I/O and while it re-checks AdmitsIO: +// its completion is observed on its own channel, and every join is bounded. +func TestFirstAdmittedStopEndsTheWorker(t *testing.T) { + for _, served := range []bool{false, true} { + stop := make(chan struct{}) + b := &servingStub{first: make(chan struct{})} + if served { + close(b.first) // re-checking AdmitsIO, which keeps refusing + } + out, done := firstAdmitted(stop, b.FirstServing(), b.AdmitsIO) + stopped := false + t.Cleanup(func() { + if !stopped { + close(stop) + } + if !closedWithin(done, 5*time.Second) { + t.Errorf("served=%v: the worker did not return within 5s of its stop (cleanup)", served) + } + }) + if closedWithin(done, 2*admitRecheck) { + t.Fatalf("served=%v: the worker returned before any stop", served) + } + close(stop) + stopped = true + if !closedWithin(done, 5*time.Second) { + t.Fatalf("served=%v: the worker did not return within 5s of its stop", served) + } + select { + case <-out: + t.Fatalf("served=%v: a stopped wait started the targets", served) + default: + } } } diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 13ac780750..265cde146c 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -489,6 +489,9 @@ RestartSec=5s. A newer master fact naming another replica or a refused claim pro HEAD holder permits exit 78; RestartPreventExitStatus=78 suppresses automatic restarts until an operator explicitly starts the unit. A higher epoch for the same replica retries. +A HEAD fence after the target listens (the attached chunk layer finds HEAD owned +by another publisher while the lease may still be valid) is independent of the +lease and exits 78 `head_fenced` (INV-FE-FENCE-EXIT-001). An ACKed planned revocation and a signal stop retain their normal exit status. Sealed same-epoch recovery stays non-serving for seal replay after assignment. Local-root, WAL-corruption and I/O diagnostics retain their existing wait. @@ -503,6 +506,7 @@ stateDiagram-v2 Serving --> Exit75: lease fence AwaitingAssignment --> Exit78: newer other-replica fact or exact foreign-holder HEAD claim proof Serving --> Exit78: lease fence and newer other-replica fact + Serving --> Exit78: runtime HEAD fence (another publication owner), head_fenced Exit75 --> AwaitingAssignment: supervisor starts new process Exit78 --> AwaitingAssignment: explicit operator start AwaitingAssignment --> SealedReplay: assigned same-epoch sealed HEAD diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 792f6be117..7fa2d0df4f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -465,7 +465,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-FE-NVME-READY-ANA-001` | An I/O that ends during the attachment-readiness wait because the backend closed or its lineage went stale keeps its ANA error, and a physical I/O fault keeps Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE | | `INV-FE-PRIMARY-READY-OPERATIONAL-001` | FrontendPrimaryReady is reported only while the local durable backend admits I/O, and the frontend target listens only after it first does; attach-pending, fenced or no durable status reports not ready with the reason. | M1 Opened / Recovering → Serving; M2 process exit | `core/host/volume/status_server.go` `statusProjection`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (the iSCSI, NVMe and ublk targets in `cmd/blockvolume/main.go` `runVolume` start after it); `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` | `TestStatusServer_ReadyOnlyWhileBackendOperational`, `TestStatusServer_NotReadyAlwaysHasAReason` (`core/host/volume/status_server_test.go`); `TestFrontendGateWaitsForTheStorageClaim`, `TestFrontendGateStopsWithoutStartingTheFrontends` (`cmd/blockvolume/frontend_gate_test.go`); `TestDurableProvider_NonChunkVolumeServesRightAfterOpen` (`core/frontend/durable/first_serving_test.go`) | — | ACTIVE | | `INV-FE-FENCE-EXIT-001` | A workspace chunk primary whose backend fences after its target listens ends the process within detection plus the 5 s cleanup bound: a lease expiry at the guard's own deadline, a HEAD fence within 50 ms. | M1 Serving → Closed; M2 process exit | `core/frontend/durable/provider_startup.go` `watchChunkFence` (HEAD fence: not operational with the evidence within 50 ms; I/O refused from the fence); `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (78 `head_fenced`) and `waitWorkspaceStop` (lease fence: 75 `lease_expired`); `superviseProcess` (the 5 s cleanup bound from the decision) | `TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational` (`core/frontend/durable/runtime_fence_test.go`); `TestRuntimeHeadFenceChoosesHeadFencedExit` (`cmd/blockvolume/runtime_fence_exit_test.go`); real-binary case C (lease expiry after listening: exit 75) | — | ACTIVE | -| `INV-WS-SERVE-LEASE-HELD-001` | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now; without a granted lease it holds at the gate and exits 75 after the start-time wait. | M1 Recovering → Serving; M2 process exit | `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.Held` / `permits` (the one deciding function: the guarded projection gates the chunk claim, the per-I/O admit and `FrontendPrimaryReady`); `core/frontend/durable/storage_adapter.go` `AdmitsIO` (the one "may serve" function, the I/O gate: backend admits AND guarded projection names this lineage; V1-SPEC r2.39); `core/host/volume/status_server.go` `statusProjection` (`FrontendPrimaryReady` from `AdmitsIO`; `NotReadyReason=lease_not_held` first); `cmd/blockvolume/frontend_gate.go` `frontendStartSignal` / `awaitFrontendStart` (a workspace primary's frontends start once `AdmitsIO` passes; non-chunk and supporting replicas start after open as before); `cmd/blockvolume/process_exit.go` (exit 75 `assignment_timeout`) | `TestStatusServer_WorkspacePrimaryNotReadyWithoutHeldLease`, `TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals`, `TestWorkspaceLeaseFirstRevokingReplyIsNotLoggedAsAGrant` (`core/host/volume/workspace_lease_held_test.go`); `TestStorageBackend_AdmitsIOIsTheIOGate` (`core/frontend/durable/admits_io_test.go`); `TestFrontendStartSignal_WorkspacePrimaryWaitsForAdmitsIO`, `TestFrontendStartSignal_OtherVolumesStartAfterOpenAsBefore` (`cmd/blockvolume/frontend_start_signal_test.go`); real-binary cases B-late (restart before the forced-move barrier, re-granted inside the wait: no claim, listen or ready before the re-grant), B75 (no grant inside the wait: no claim, listen or ready, exit 75; a restart after the barrier serves) and B0 (restart inside the lease serves at once) | — | ACTIVE | +| `INV-WS-SERVE-LEASE-HELD-001` | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now; without a granted lease it holds at the gate and exits 75 after the start-time wait. | M1 Recovering → Serving; M2 process exit | `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.Held` / `permits` (the one deciding function: the guarded projection gates the chunk claim, the per-I/O admit and `FrontendPrimaryReady`); `core/frontend/durable/storage_adapter.go` `AdmitsIO` (the one "may serve" function, the I/O gate: backend admits AND guarded projection names this lineage; V1-SPEC r2.39); `core/host/volume/status_server.go` `statusProjection` (`FrontendPrimaryReady` from `AdmitsIO`; `NotReadyReason=lease_not_held` first); `cmd/blockvolume/frontend_gate.go` `frontendStartSignal` / `awaitFrontendStart` (a workspace primary's frontends start once `AdmitsIO` passes; non-chunk and supporting replicas start after open as before); `cmd/blockvolume/process_exit.go` (exit 75 `assignment_timeout`) | `TestStatusServer_WorkspacePrimaryNotReadyWithoutHeldLease`, `TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals`, `TestWorkspaceLeaseFirstRevokingReplyIsNotLoggedAsAGrant` (`core/host/volume/workspace_lease_held_test.go`); `TestStorageBackend_AdmitsIOIsTheIOGate` (`core/frontend/durable/admits_io_test.go`); `TestFrontendStartSignal_WorkspacePrimaryWaitsForAdmitsIO`, `TestFrontendStartSignal_OtherVolumesStartAfterOpenAsBefore`, `TestFirstAdmittedStopEndsTheWorker` (`cmd/blockvolume/frontend_start_signal_test.go`); real-binary cases B-late (restart before the forced-move barrier, re-granted inside the wait: no claim, listen or ready before the re-grant), B75 (no grant inside the wait: no claim, listen or ready, exit 75; a restart after the barrier serves) and B0 (restart inside the lease serves at once) | — | ACTIVE | | `INV-WAL-REPLAY-LWW-001` | Replay of the validated native prefix retains the highest admitted LSN per LBA; invalid cursor, nonce or LSN order is refused. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALLSNOrderV3_RefusesDuplicateAndLower` (`core/storage/wal_lsn_order_v3_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | | `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the both durable descriptor slots has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_io_v3.go` `append`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`); `TestNativeReplacementCheckpointSIGKILL` (`core/storage/legacy_checkpoint_replacement_v3_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | From 870a3d9be010a57d2cd560233ffe564b2a9bcf86 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 06:27:26 -0800 Subject: [PATCH 57/57] docs, test: name the spec row, not a seat; say channel capacity, not slots Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/frontend_start_signal_test.go | 2 +- seaweed-block/docs/design/invariants.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/frontend_start_signal_test.go b/seaweed-block/cmd/blockvolume/frontend_start_signal_test.go index 919015b454..2c4f3f646a 100644 --- a/seaweed-block/cmd/blockvolume/frontend_start_signal_test.go +++ b/seaweed-block/cmd/blockvolume/frontend_start_signal_test.go @@ -88,7 +88,7 @@ func TestFirstAdmittedStopEndsTheWorker(t *testing.T) { } } -// claude06's #410 design condition: a non-chunk volume or a supporting +// INV-WS-SERVE-LEASE-HELD-001 scope (V1-SPEC r2.39): a non-chunk volume or a supporting // replica starts its frontends right after open, as before: its start // signal is the backend's first-serving channel itself, not AdmitsIO. func TestFrontendStartSignal_OtherVolumesStartAfterOpenAsBefore(t *testing.T) { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7fa2d0df4f..a40b33ba70 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -987,9 +987,9 @@ One row per wait in the data and control paths. Guest-visible rows on one path m | `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (from `runVolume`, before any frontend starts) | the backend's first admitted I/O (`StorageBackend.FirstServing`), or the process's stop waiter returning | none of its own: it ends on the stop waiter, which INV-WS-STARTUP-RETRY-001 bounds (a refused or timed-out claim latches exit 75/78) | `runVolume` (`INV-FE-PRIMARY-READY-OPERATIONAL-001`) | no frontend starts; shutdown as after the frontends | none | no (no target listens yet) | | `cmd/blockvolume/frontend_gate.go` `firstAdmitted` (one goroutine from `runVolume`, workspace chunk primaries only) | the backend's first admitted I/O (`FirstServing`), then `AdmitsIO` passing, re-checked every 50 ms (the backend has no projection-change signal) | until first served or the process outcome (`e.done`), whichever comes first | the process exit owner (`superviseProcess`) through `e.done` | none: it ends without starting the frontends | none | no (no target listens yet) | | `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` (one goroutine from `runVolume`, started with the workspace lease guard before the frontends) | a signal, the lease guard's drain request or end, or the latched process outcome (startup, or a runtime HEAD fence) | the process lifetime | the process exit owner (`superviseProcess`, `INV-WS-STARTUP-RETRY-001`) | the chosen exit status (0 revoked/signal, 75 retry, 78 superseded or `head_fenced`) | none | no | -| `cmd/blockvolume/main.go` `runVolume`, the receive of `stopWait` after the frontends started (when `awaitFrontendStart` released on first serving) | the one result of the `waitWorkspaceStop` goroutine (its only producer, a 1-slot channel it sends to exactly once) | the process lifetime, as `waitWorkspaceStop` | the process exit owner (`superviseProcess`) | shutdown with the handed-back lease drain request | none | no (the targets serve until the stop) | +| `cmd/blockvolume/main.go` `runVolume`, the receive of `stopWait` after the frontends started (when `awaitFrontendStart` released on first serving) | the one result of the `waitWorkspaceStop` goroutine (its only producer, a channel of capacity one it sends to exactly once) | the process lifetime, as `waitWorkspaceStop` | the process exit owner (`superviseProcess`) | shutdown with the handed-back lease drain request | none | no (the targets serve until the stop) | | `core/frontend/durable/provider_startup.go` `watchChunkFence` (one goroutine per attached chunk layer, started when the layer attaches) | the 50 ms ticker (then reads the layer's latched fence flag) or provider close (`closeCtx`) | the attached layer's lifetime: it returns at provider close, when the layer is no longer the volume's, or after publishing a fence; Close joins it (`p.inflight`) | `DurableProvider.Close` (cancels `closeCtx`, then waits `p.inflight`) | none: the ticker is its poll, not a deadline; a HEAD fence is published at most 50 ms after the layer latches it (I/O is refused from the latch) | none while waiting (`p.mu` only briefly to check the handle and publish) | no | -| `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (one goroutine from `runVolume`, workspace chunk primaries) | the provider's runtime-fence wakeup (1-slot, `ChunkRuntimeFenceUpdates`), the process outcome (`e.done`) or the watch context | the process lifetime: it returns after choosing 78 `head_fenced`, when another outcome is chosen, or when `runVolume` cancels its watch context | the process exit owner (`superviseProcess`) | none | none | no | +| `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (one goroutine from `runVolume`, workspace chunk primaries) | the provider's runtime-fence wakeup (capacity one, `ChunkRuntimeFenceUpdates`), the process outcome (`e.done`) or the watch context | the process lifetime: it returns after choosing 78 `head_fenced`, when another outcome is chosen, or when `runVolume` cancels its watch context | the process exit owner (`superviseProcess`) | none | none | no | Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The W/BASE/fence owner (`WALStore.recoverV3`) must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step.