From e907fbdd553996de8ffcbd45472ac5ebf7de9996 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 01:42:51 -0800 Subject: [PATCH 01/16] test: the lifecycle page's procedures on two hosts with distinct server ids Five tagged binary tests run the procedures of the volume lifecycle page as written, on two blockvolume processes with server ids s1 and s2 that share one blockmaster and one SeaweedFS: the planned hand-over to another host, a same-host restart inside the lease, a return after a lapsed lease started 65 s after the stop, a forced move with the old host returning, and a revoke without an ACK followed by a forced move. The harness takes N hosts (cluster spec nodes s1..sN); the checks that read each step's output take the host and stay in the default-build check file with the existing ones. Co-Authored-By: Claude Opus 5.5 --- .../planned_handoff_checks_test.go | 58 ++- .../planned_handoff_integration_test.go | 85 +++-- .../procedure_gate_integration_test.go | 331 ++++++++++++++++++ 3 files changed, 443 insertions(+), 31 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go index dedf934a66..af534928eb 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go @@ -106,9 +106,12 @@ func showsAck(out string, e, g uint64) bool { return hasLine(out, fmt.Sprintf("recorded ACK: r1@%d HEAD generation %d", e, g)) } -// movedEpoch reads E2 from the clean move's answer. -func movedEpoch(out string, e, g, l uint64) (uint64, error) { - issued := regexp.MustCompile(fmt.Sprintf(`^clean move issued: volume v1 request move-v1-1: r1@%d -> r1@(\d+) on s1 \(sealed HEAD gen %d, remote LSN %d\)$`, e, g, l)) +// movedEpoch reads E2 from the clean move's answer to s1. +func movedEpoch(out string, e, g, l uint64) (uint64, error) { return movedEpochTo(out, e, g, l, "s1") } + +// movedEpochTo reads E2 from the clean move's answer to the target host. +func movedEpochTo(out string, e, g, l uint64, target string) (uint64, error) { + issued := regexp.MustCompile(fmt.Sprintf(`^clean move issued: volume v1 request move-v1-1: r1@%d -> r1@(\d+) on %s \(sealed HEAD gen %d, remote LSN %d\)$`, e, regexp.QuoteMeta(target), g, l)) first, _, _ := strings.Cut(out, "\n") e2, err := matchUint(issued, strings.TrimRight(first, "\r")) if err != nil { @@ -117,12 +120,14 @@ func movedEpoch(out string, e, g, l uint64) (uint64, error) { if e2 <= e { return 0, fmt.Errorf("clean move issued epoch %d; want above %d", e2, e) } - return e2, wantLines(out, "next: start volume v1 on s1 (this command moved authority only)") + return e2, wantLines(out, fmt.Sprintf("next: start volume v1 on %s (this command moved authority only)", target)) } -func checkClaimDone(line string, e2 uint64) error { - if !strings.Contains(line, "durable: HEAD claim for volume=v1 done in") || !strings.Contains(line, fmt.Sprintf(`epoch=%d holder="s1/r1"`, e2)) { - return fmt.Errorf("HEAD claim %q; want done at epoch %d holder s1/r1", line, e2) +func checkClaimDone(line string, e2 uint64) error { return checkClaimDoneBy(line, e2, "s1") } + +func checkClaimDoneBy(line string, e2 uint64, host string) error { + if !strings.Contains(line, "durable: HEAD claim for volume=v1 done in") || !strings.Contains(line, fmt.Sprintf(`epoch=%d holder="%s/r1"`, e2, host)) { + return fmt.Errorf("HEAD claim %q; want done at epoch %d holder %s/r1", line, e2, host) } return nil } @@ -134,16 +139,48 @@ func checkShowMoved(out string, e, e2, g, l uint64) error { } func checkHeadReopened(out string, e2, g, l uint64) error { + return checkHeadReopenedBy(out, e2, g, l, "s1") +} + +func checkHeadReopenedBy(out string, e2, g, l uint64, host string) error { h, err := parseHead(out) if err != nil { return err } - if h.State != "active" || h.Epoch != e2 || h.Holder != "s1/r1" || h.Gen <= g || h.RemoteLSN != l || h.DetachedBy != nil { - return fmt.Errorf("HEAD after the reopen %+v; want active, epoch %d, holder s1/r1, gen above %d, remote LSN %d, not detached", h, e2, g, l) + if h.State != "active" || h.Epoch != e2 || h.Holder != host+"/r1" || h.Gen <= g || h.RemoteLSN != l || h.DetachedBy != nil { + return fmt.Errorf("HEAD after the reopen %+v; want active, epoch %d, holder %s/r1, gen above %d, remote LSN %d, not detached", h, e2, host, g, l) } return nil } +// forcedEpoch reads E2 from a forced move's answer (`forced move issued: +// ... r1@E on FROM -> r1@E2 on TO (kept HEAD gen N, remote LSN L)`). +func forcedEpoch(out string, e uint64, from, to string) (uint64, error) { + re := regexp.MustCompile(fmt.Sprintf(`(?m)^forced move issued: volume v1 request \S+: r1@%d on %s -> r1@(\d+) on %s \(kept HEAD gen \d+, remote LSN \d+\)$`, e, regexp.QuoteMeta(from), regexp.QuoteMeta(to))) + e2, err := matchUint(re, out) + if err == nil && e2 <= e { + err = fmt.Errorf("forced move issued epoch %d; want above %d", e2, e) + } + return e2, err +} + +// forcedKeptLSN reads the remote LSN a forced move kept. +func forcedKeptLSN(out string) (uint64, error) { + return matchUint(regexp.MustCompile(`(?m)^forced move issued: .*\(kept HEAD gen \d+, remote LSN (\d+)\)$`), out) +} + +// previewAdmitted reports whether a force-move --dry-run says admitted. +func previewAdmitted(out string) bool { + return regexp.MustCompile(`(?m)^forced move admitted(: .*)?$`).MatchString(out) +} + +// frontendReady reports whether a /status?volume=v1 body says the frontend +// is ready to serve as primary. +func frontendReady(body []byte) bool { + var st struct{ FrontendPrimaryReady bool } + return json.Unmarshal(body, &st) == nil && st.FrontendPrimaryReady +} + // checkCleanMoveRefused checks a clean move refused for a missing ACK: exit // 1 (a failed precondition), nothing on stdout, the documented error. func checkCleanMoveRefused(stdout, stderr string, code int) error { @@ -265,6 +302,9 @@ func TestPlannedHandoffChecksReadCapturedProductOutput(t *testing.T) { if r := read("show-revoked.stdout"); showsAck(r, e, g) || !hasLine(r, "recorded ACK: none") { t.Error("the revoked show without an ACK is read as acknowledged") } + if !frontendReady([]byte(read("status-primary.json"))) || frontendReady([]byte(`{"FrontendPrimaryReady":false,"Healthy":true}`)) { + t.Error("the frontend-ready check does not read FrontendPrimaryReady") + } if !statusPrimary([]byte(read("status-primary.json")), e2) || statusPrimary([]byte(read("status-primary.json")), e) { t.Error("status check does not read the epoch of a healthy primary") } diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index c431049689..320fee1872 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -159,30 +159,60 @@ func TestStandaloneCleanMoveWithoutTheACKIsRefused(t *testing.T) { const plannedHandoffNQN = "nqn.2026-11.io.seaweedfs:handoff" -// startPlannedHandoff runs the chapter's steps 1-3: a weed cluster, the -// cluster spec, blockmaster with the lifecycle store, and the setup check. -// It returns the blockvolume arguments of step 4 and the show command. +// startPlannedHandoff runs the chapter's steps 1-3 for one host, s1, and +// returns the blockvolume arguments of step 4 and the show command. func startPlannedHandoff(t *testing.T) (h *plannedHandoffHarness, cluster *w4WeedCluster, chunkPath string, show, volArgs []string) { t.Helper() - h = newPlannedHandoffHarness(t) - cluster = startWorkspaceWeed(t) - chunkPath = fmt.Sprintf("/handoff-%d", time.Now().UnixNano()) + env := startHandoffEnv(t, 1) + return env.h, env.cluster, env.chunkPath, env.show, env.volArgs("s1") +} + +// handoffEnv is a running setup: weed, blockmaster with the cluster spec +// naming every host, and the hosts' blockvolume endpoints. The volume starts +// on s1. +type handoffEnv struct { + h *plannedHandoffHarness + cluster *w4WeedCluster + chunkPath string + show []string + hosts map[string]bvHost +} + +// bvHost is one host's blockvolume: its server id, endpoints and local root. +type bvHost struct { + id, data, ctrl, status, nvme, root string +} + +// startHandoffEnv runs the chapter's steps 1-3: a weed cluster, the cluster +// spec with hosts s1..sN, blockmaster with the lifecycle store, and the setup +// check. +func startHandoffEnv(t *testing.T, n int) *handoffEnv { + t.Helper() + h := newPlannedHandoffHarness(t) + env := &handoffEnv{h: h, cluster: startWorkspaceWeed(t), chunkPath: fmt.Sprintf("/handoff-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}} must, _ := fatalOn(t) + env.hosts["s1"] = bvHost{id: "s1", data: h.dataAddr, ctrl: h.ctrlAddr, status: h.statusAddr, nvme: h.nvmeAddr, root: filepath.Join(h.dir, "vol")} + for i := 2; i <= n; i++ { + id := fmt.Sprintf("s%d", i) + env.hosts[id] = bvHost{id: id, data: leaseBinaryAddress(t), ctrl: leaseBinaryAddress(t), status: leaseBinaryAddress(t), nvme: leaseBinaryAddress(t), root: filepath.Join(h.dir, "vol-"+id)} + } + cluster, chunkPath := env.cluster, env.chunkPath // 1. The cluster spec. + var nodes strings.Builder + for i := 1; i <= n; i++ { + b := env.hosts[fmt.Sprintf("s%d", i)] + fmt.Fprintf(&nodes, " - server_id: %s\n data_addr: %s\n ctrl_addr: %s\n", b.id, b.data, b.ctrl) + } spec := filepath.Join(h.dir, "cluster-spec.yaml") - must(os.WriteFile(spec, []byte(fmt.Sprintf(`nodes: - - server_id: s1 - data_addr: %s - ctrl_addr: %s -volumes: + must(os.WriteFile(spec, []byte("nodes:\n"+nodes.String()+`volumes: - id: v1 size_bytes: 268435456 replication_factor: 1 placements: - server_id: s1 replica_id: r1 -`, h.dataAddr, h.ctrlAddr)), 0o644)) +`), 0o644)) // 2. blockmaster with the lifecycle store and the cluster spec. mstate := filepath.Join(h.dir, "master") @@ -198,17 +228,21 @@ volumes: } // 3. The setup answers before any blockvolume runs. - show = []string{"ops", "workspace", "show", "--master", h.masterAddr, "--volume", "v1"} - out, _ := h.command(t, show...) + env.show = []string{"ops", "workspace", "show", "--master", h.masterAddr, "--volume", "v1"} + out, _ := h.command(t, env.show...) must(checkShowBeforeStart(out)) + return env +} - volArgs = []string{"--master", h.masterAddr, "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1", - "--data-addr", h.dataAddr, "--ctrl-addr", h.ctrlAddr, "--status-addr", h.statusAddr, - "--durable-root", filepath.Join(h.dir, "vol"), "--durable-impl", "walstore-chunk", +// volArgs is the chapter's blockvolume command for one host. +func (env *handoffEnv) volArgs(id string) []string { + b := env.hosts[id] + return []string{"--master", env.h.masterAddr, "--server-id", b.id, "--volume-id", "v1", "--replica-id", "r1", + "--data-addr", b.data, "--ctrl-addr", b.ctrl, "--status-addr", b.status, + "--durable-root", b.root, "--durable-impl", "walstore-chunk", "--durable-blocks", "65536", "--durable-blocksize", "4096", - "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath, "--chunk-control-endpoint", - "--workspace-lease", "--nvme-listen", h.nvmeAddr, "--nvme-subsysnqn", plannedHandoffNQN} - return h, cluster, chunkPath, show, volArgs + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--chunk-control-endpoint", + "--workspace-lease", "--nvme-listen", b.nvme, "--nvme-subsysnqn", plannedHandoffNQN} } func fatalOn(t *testing.T) (func(error), func(uint64, error) uint64) { @@ -414,10 +448,17 @@ func (h *plannedHandoffHarness) run(t *testing.T, args ...string) (string, strin // waitPrimary polls the status endpoint until the volume serves as a // healthy primary at epoch. func (h *plannedHandoffHarness) waitPrimary(t *testing.T, epoch uint64) { + t.Helper() + h.waitPrimaryAt(t, h.statusAddr, epoch) +} + +// waitPrimaryAt polls one host's status endpoint until the volume serves +// there as a healthy primary at epoch. +func (h *plannedHandoffHarness) waitPrimaryAt(t *testing.T, statusAddr string, epoch uint64) { t.Helper() c := &http.Client{Timeout: 5 * time.Second} - poll(t, 60*time.Second, fmt.Sprintf("status never showed a healthy primary at epoch %d", epoch), func() bool { - resp, err := c.Get("http://" + h.statusAddr + "/status?volume=v1") + poll(t, 60*time.Second, fmt.Sprintf("status at %s never showed a healthy primary at epoch %d", statusAddr, epoch), func() bool { + resp, err := c.Get("http://" + statusAddr + "/status?volume=v1") if err != nil { return false } diff --git a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go new file mode 100644 index 0000000000..62c3d521ab --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go @@ -0,0 +1,331 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "fmt" + "io" + "net" + "net/http" + "strings" + "testing" + "time" +) + +// The procedure gate: every operator procedure of docs/volume-lifecycle.md +// runs as written, with real binaries, on two blockvolume processes with +// distinct server ids (s1 and s2) sharing one blockmaster and one SeaweedFS. +// The planned return to the same host is TestStandalonePlannedHandoffToTheSameHost. + +// TestProcedurePlannedHandoffToAnotherHost: the planned hand-over from s1 to +// s2. The new holder starts with no local copy, claims the sealed HEAD at the +// new epoch and serves the written block. +func TestProcedurePlannedHandoffToAnotherHost(t *testing.T) { + env := startHandoffEnv(t, 2) + must, mustU := fatalOn(t) + h := env.h + + old := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, old, "s1") + block := pattern("to-another-host!") + env.writeBlock(t, "s1", 0, block) + + g := env.seal(t, "s1", e) + l := env.sealedLSN(t, e, g) + env.revoke(t, e, g) + if err := old.wait(30 * time.Second); err != nil { + t.Fatalf("s1 after the revocation: %v; want a clean exit by itself", err) + } + env.waitAck(t, e, g) + + moved, _ := h.command(t, env.moveClean(e, "s2", "move-v1-1")...) + e2 := mustU(movedEpochTo(moved, e, g, l, "s2")) + nw := env.start(t, "blockvolume-s2", "s2") + must(checkClaimDoneBy(nw.waitLog(t, 60*time.Second, "durable: HEAD claim for volume=v1 done in"), e2, "s2")) + if got := env.adopt(t, nw, "s2"); got != e2 { + t.Fatalf("s2 adopted at epoch %d; want %d", got, e2) + } + out, _ := h.command(t, env.show...) + must(wantLines(out, fmt.Sprintf("holder: r1@%d (logical replica)", e2), + fmt.Sprintf("move: request=move-v1-1 kind=clean issued=true s1/r1@%d -> s2/r1@%d HEAD generation %d remote LSN %d", e, e2, g, l))) + out, _ = h.command(t, env.chunkShow()...) + must(checkHeadReopenedBy(out, e2, g, l, "s2")) + if !bytes.Equal(env.readBlock(t, "s2", 0), block) { + t.Fatal("the block written on s1 does not read back on s2") + } +} + +// TestProcedureSameHostRestartInsideTheLease: the holder's process dies and is +// started again on its host within the 30 s lease. It keeps holder and epoch +// and serves again at once from its local WAL. +func TestProcedureSameHostRestartInsideTheLease(t *testing.T) { + env := startHandoffEnv(t, 2) + must, _ := fatalOn(t) + + first := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, first, "s1") + block := pattern("restart-in-lease") + env.writeBlock(t, "s1", 0, block) + first.kill(t) + + again := env.start(t, "blockvolume-s1-again", "s1") + if got := env.adopt(t, again, "s1"); got != e { + t.Fatalf("the restarted holder adopted epoch %d; want the same epoch %d", got, e) + } + out, _ := env.h.command(t, env.show...) + must(checkShowGranted(out, e)) + if !bytes.Equal(env.readBlock(t, "s1", 0), block) { + t.Fatal("the block written before the restart does not read back") + } +} + +// TestProcedureReturnAfterALapsedLease: the holder's process dies and stays +// down past its lease. Started again 65 s after it stopped (the page's +// bound with default flags), it is granted again at the same epoch, reclaims +// HEAD and serves its local WAL. +func TestProcedureReturnAfterALapsedLease(t *testing.T) { + env := startHandoffEnv(t, 2) + must, _ := fatalOn(t) + + first := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, first, "s1") + block := pattern("after-lapsed-ttl") + env.writeBlock(t, "s1", 0, block) + first.kill(t) + stopped := time.Now() + + time.Sleep(time.Until(stopped.Add(65 * time.Second))) + back := env.start(t, "blockvolume-s1-back", "s1") + if got := env.adopt(t, back, "s1"); got != e { + t.Fatalf("the returning holder adopted epoch %d; want the same epoch %d", got, e) + } + if back.has("assignment unavailable, not serving") { + t.Fatal("started 65 s after the stop, the holder still logged the not-serving line") + } + out, _ := env.h.command(t, env.show...) + must(checkShowGranted(out, e)) + if !bytes.Equal(env.readBlock(t, "s1", 0), block) { + t.Fatal("the block written before the lapse does not read back") + } +} + +// TestProcedureForcedMoveWithTheOldHostReturning: the holder on s1 dies and +// never comes back in time. A forced move to s2, admitted after the barrier, +// restores the last HEAD: a block cut before the crash is kept, one written +// after the cut is lost, as the lost range says. The old s1 process then +// returns with its old local root and must not serve; s2 keeps serving. +func TestProcedureForcedMoveWithTheOldHostReturning(t *testing.T) { + env := startHandoffEnv(t, 2) + must, mustU := fatalOn(t) + h := env.h + + old := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, old, "s1") + kept, lost := pattern("cut-before-crash"), pattern("after-the-cut!!!") + env.writeBlock(t, "s1", 0, kept) + h.command(t, "ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status) + env.writeBlock(t, "s1", 8, lost) + old.kill(t) + + out := env.forceMove(t, e, "s2", "force-v1-1") + e2, keptLSN := mustU(forcedEpoch(out, e, "s1", "s2")), mustU(forcedKeptLSN(out)) + must(wantLines(out, "next: start volume v1 on s2 (this command moved authority only)")) + if !strings.Contains(out, fmt.Sprintf("writes with LSN <= %d are preserved", keptLSN)) { + t.Fatalf("the forced move printed no lost range at LSN %d:\n%s", keptLSN, out) + } + ranges, _ := h.command(t, "ops", "workspace", "lost-range", "--master", h.masterAddr, "--volume", "v1") + if !strings.Contains(ranges, "range 1 of 1: request force-v1-1, r1@") { + t.Fatalf("lost-range does not show the forced move:\n%s", ranges) + } + + nw := env.start(t, "blockvolume-s2", "s2") + if got := env.adopt(t, nw, "s2"); got != e2 { + t.Fatalf("s2 adopted at epoch %d; want %d", got, e2) + } + if !bytes.Equal(env.readBlock(t, "s2", 0), kept) { + t.Fatal("the block cut before the crash is not on s2") + } + if got := env.readBlock(t, "s2", 8); !bytes.Equal(got, make([]byte, 4096)) { + t.Fatal("the block written after the last cut reads back on s2; the page says it is lost") + } + + // The old host returns with its old local root. It must not take s2's + // line as its own (a holder is server and replica), report its frontend + // ready, or listen for I/O; the page says it does not serve. + back := env.start(t, "blockvolume-s1-back", "s1") + var failures []string + end := time.Now().Add(40 * time.Second) + for time.Now().Before(end) && len(failures) == 0 { + if l := back.line(fmt.Sprintf("adopted as PRIMARY at r1@%d", e2)); l != "" { + failures = append(failures, "it adopted s2's line: "+l) + } + if env.frontendReadyAt("s1") { + failures = append(failures, "its status reports FrontendPrimaryReady") + } + if listening(env.hosts["s1"].nvme) { + failures = append(failures, "its NVMe/TCP target listens") + } + time.Sleep(time.Second) + } + if !back.has("refusing to attach volume=v1") && !back.has("workspace lease: stale authority") { + failures = append(failures, "it logged neither the stale-root refusal nor stale authority") + } + if len(failures) > 0 { + t.Errorf("the returning old host after the forced move: %s", strings.Join(failures, "; ")) + } + env.h.waitPrimaryAt(t, env.hosts["s2"].status, e2) + if !bytes.Equal(env.readBlock(t, "s2", 0), kept) { + t.Fatal("s2 no longer serves the kept block after the old host returned") + } +} + +// TestProcedureRevokeWithoutACKThenForcedMove: the volume is sealed and +// revoked, but its process dies before it sends the ACK. The clean move is +// refused; only a forced move to another node remains, and since HEAD is +// sealed, nothing acknowledged is lost. +func TestProcedureRevokeWithoutACKThenForcedMove(t *testing.T) { + env := startHandoffEnv(t, 2) + must, mustU := fatalOn(t) + h := env.h + + old := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, old, "s1") + block := pattern("sealed-no-ack!!!") + env.writeBlock(t, "s1", 0, block) + g := env.seal(t, "s1", e) + l := env.sealedLSN(t, e, g) + old.kill(t) + env.revoke(t, e, g) + o, eo, code := h.run(t, env.moveClean(e, "s2", "move-v1-1")...) + must(checkCleanMoveRefused(o, eo, code)) + + out := env.forceMove(t, e, "s2", "force-v1-1") + e2 := mustU(forcedEpoch(out, e, "s1", "s2")) + if got := mustU(forcedKeptLSN(out)); got != l { + t.Fatalf("the forced move kept LSN %d; want the sealed HEAD's %d", got, l) + } + nw := env.start(t, "blockvolume-s2", "s2") + if got := env.adopt(t, nw, "s2"); got != e2 { + t.Fatalf("s2 adopted at epoch %d; want %d", got, e2) + } + if !bytes.Equal(env.readBlock(t, "s2", 0), block) { + t.Fatal("the sealed block does not read back on s2") + } +} + +func pattern(s string) []byte { return bytes.Repeat([]byte(s), 4096/len(s)) } + +func (env *handoffEnv) start(t *testing.T, name, id string) *daemon { + t.Helper() + return env.h.start(t, name, env.h.volume, env.volArgs(id)...) +} + +// adopt waits for the process to adopt v1 as primary and its host to report +// it healthy, and returns the epoch. +func (env *handoffEnv) adopt(t *testing.T, d *daemon, id string) uint64 { + t.Helper() + _, mustU := fatalOn(t) + e := mustU(adoptedEpoch(d.waitLog(t, 60*time.Second, "blockvolume: volume v1 adopted as PRIMARY at r1@"))) + env.h.waitPrimaryAt(t, env.hosts[id].status, e) + return e +} + +// frontendReadyAt reports whether the host's status shows v1's frontend +// ready to serve. +func (env *handoffEnv) frontendReadyAt(id string) bool { + c := &http.Client{Timeout: 2 * time.Second} + resp, err := c.Get("http://" + env.hosts[id].status + "/status?volume=v1") + if err != nil { + return false + } + defer resp.Body.Close() + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + return frontendReady(b) +} + +// listening reports whether something accepts TCP connections at addr. +func listening(addr string) bool { + c, err := net.DialTimeout("tcp", addr, time.Second) + if err != nil { + return false + } + c.Close() + return true +} + +func (env *handoffEnv) writeBlock(t *testing.T, id string, lba uint64, data []byte) { + t.Helper() + c := dialNVMe(t, env.hosts[id].nvme, plannedHandoffNQN) + defer c.close() + c.write(t, lba, data) + c.flush(t) +} + +func (env *handoffEnv) readBlock(t *testing.T, id string, lba uint64) []byte { + t.Helper() + c := dialNVMe(t, env.hosts[id].nvme, plannedHandoffNQN) + defer c.close() + return c.read(t, lba, 4096) +} + +func (env *handoffEnv) seal(t *testing.T, id string, e uint64) uint64 { + t.Helper() + _, mustU := fatalOn(t) + out, errOut := env.h.command(t, "ops", "chunk", "detach", "--plain", "--volume", "v1", "--status-addr", env.hosts[id].status, "--timeout", "120s") + return mustU(sealedGen(out, errOut, e)) +} + +func (env *handoffEnv) chunkShow() []string { + return []string{"ops", "chunk", "show", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath} +} + +func (env *handoffEnv) sealedLSN(t *testing.T, e, g uint64) uint64 { + t.Helper() + _, mustU := fatalOn(t) + out, _ := env.h.command(t, env.chunkShow()...) + return mustU(sealedHeadLSN(out, e, g)) +} + +func (env *handoffEnv) revoke(t *testing.T, e, g uint64) { + t.Helper() + must, _ := fatalOn(t) + out, _ := env.h.command(t, "ops", "workspace", "revoke", "--master", env.h.masterAddr, "--volume", "v1", "--replica", "r1", + "--epoch", fmt.Sprint(e), "--sealed-gen", fmt.Sprint(g)) + must(checkRevoke(out, e, g)) +} + +func (env *handoffEnv) waitAck(t *testing.T, e, g uint64) { + t.Helper() + poll(t, 30*time.Second, fmt.Sprintf("workspace show never reported the ACK of r1@%d at generation %d", e, g), func() bool { + out, _ := env.h.command(t, env.show...) + return showsAck(out, e, g) + }) +} + +func (env *handoffEnv) moveClean(e uint64, target, request string) []string { + b := env.hosts[target] + return []string{"ops", "workspace", "move", "--clean", "--master", env.h.masterAddr, "--volume", "v1", "--replica", "r1", + "--epoch", fmt.Sprint(e), "--target-host", b.id, "--target-data", b.data, "--target-ctrl", b.ctrl, "--request-id", request} +} + +// forceMove runs the page's forced move: --dry-run until it says admitted +// (the barrier: at most 65 s after the holder stopped, with defaults, plus a +// margin), then the move itself, whose stdout it returns. +func (env *handoffEnv) forceMove(t *testing.T, e uint64, target, request string) string { + t.Helper() + b := env.hosts[target] + args := []string{"ops", "workspace", "force-move", "--master", env.h.masterAddr, "--volume", "v1", + "--target-host", b.id, "--target-data", b.data, "--target-ctrl", b.ctrl, + "--request-id", request, "--confirm-forced", fmt.Sprintf("v1@%d", e)} + first, _ := env.h.command(t, append(args, "--dry-run")...) + if !previewAdmitted(first) && !strings.Contains(first, "admissible at ") { + t.Fatalf("a refused preview does not say when the move is admissible:\n%s", first) + } + poll(t, 90*time.Second, "the forced move was never admitted", func() bool { + out, _ := env.h.command(t, append(args, "--dry-run")...) + return previewAdmitted(out) + }) + out, _ := env.h.command(t, args...) + return out +} From 53618e5d5b3254858d25075f2c5b11a578928593 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 01:55:57 -0800 Subject: [PATCH 02/16] test: a holder started inside the barrier wait, and one started too early Two procedure tests for a holder that returns after its lease ended but before the re-grant barrier. Started 35 s after the stop (default flags), the barrier passes within its 30 s authority wait: it must not serve while its renewals are still refused for the barrier, then serves at the same epoch. With --workspace-max-clock-skew 50s and a start 31 s after the stop, its wait ends first: it does not serve and exits 75, and a supervised restart that waits past the barrier serves at the same epoch. Co-Authored-By: Claude Opus 5.5 --- .../planned_handoff_integration_test.go | 10 +- .../procedure_gate_integration_test.go | 125 ++++++++++++++++++ 2 files changed, 130 insertions(+), 5 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index 320fee1872..9e03afddb4 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -184,9 +184,9 @@ type bvHost struct { } // startHandoffEnv runs the chapter's steps 1-3: a weed cluster, the cluster -// spec with hosts s1..sN, blockmaster with the lifecycle store, and the setup -// check. -func startHandoffEnv(t *testing.T, n int) *handoffEnv { +// spec with hosts s1..sN, blockmaster with the lifecycle store (and +// masterArgs), and the setup check. +func startHandoffEnv(t *testing.T, n int, masterArgs ...string) *handoffEnv { t.Helper() h := newPlannedHandoffHarness(t) env := &handoffEnv{h: h, cluster: startWorkspaceWeed(t), chunkPath: fmt.Sprintf("/handoff-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}} @@ -216,10 +216,10 @@ func startHandoffEnv(t *testing.T, n int) *handoffEnv { // 2. blockmaster with the lifecycle store and the cluster spec. mstate := filepath.Join(h.dir, "master") - master := h.start(t, "blockmaster", h.master, + master := h.start(t, "blockmaster", h.master, append([]string{ "--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"), "--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr, - "--workspace-rpc", "--workspace-head-base-url", "http://"+cluster.filerHTTP+chunkPath) + "--workspace-rpc", "--workspace-head-base-url", "http://" + cluster.filerHTTP + chunkPath}, masterArgs...)...) if l := master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded="); !strings.Contains(l, "listen="+h.masterAddr) { t.Fatalf("blockmaster start line %q does not name listen=%s", l, h.masterAddr) } diff --git a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go index 62c3d521ab..24861cdebf 100644 --- a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go @@ -4,10 +4,13 @@ package main_test import ( "bytes" + "errors" "fmt" "io" "net" "net/http" + "os" + "os/exec" "strings" "testing" "time" @@ -214,6 +217,128 @@ func TestProcedureRevokeWithoutACKThenForcedMove(t *testing.T) { } } +// TestProcedureStartInsideTheBarrierWaitIsReGranted: the holder's process +// dies and is started again 35 s later: its lease has ended, the re-grant +// barrier (at most 65 s after the stop, default flags) has not passed, and +// the barrier passes within the process's 30 s authority wait. It must not +// serve while its renewals are still refused for the barrier; once +// re-granted it serves its local WAL at the same epoch. +func TestProcedureStartInsideTheBarrierWaitIsReGranted(t *testing.T) { + env := startHandoffEnv(t, 1) + first := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, first, "s1") + block := pattern("inside-the-wait!") + env.writeBlock(t, "s1", 0, block) + first.kill(t) + time.Sleep(35 * time.Second) + + back := env.start(t, "blockvolume-s1-back", "s1") + var ready []time.Time + end := time.Now().Add(90 * time.Second) + for time.Now().Before(end) { + if env.frontendReadyAt("s1") || listening(env.hosts["s1"].nvme) { + ready = append(ready, time.Now()) + if len(ready) >= 5 { + break + } + } + time.Sleep(200 * time.Millisecond) + } + if len(ready) == 0 { + t.Fatal("the returning holder never served within 90 s") + } + if last := lastLogTime(back, "clock-skew margin has not elapsed"); !last.IsZero() && ready[0].Before(last) { + t.Errorf("the returning holder served at %s, before its renewal was still refused for the barrier at %s: it served without a lease", + ready[0].Format("15:04:05.000"), last.Format("15:04:05")) + } + if got := env.adopt(t, back, "s1"); got != e { + t.Fatalf("the returning holder adopted epoch %d; want the same epoch %d", got, e) + } + if !bytes.Equal(env.readBlock(t, "s1", 0), block) { + t.Fatal("the block written before the stop does not read back") + } +} + +// TestProcedureStartTooEarlyExitsAndARestartServes: with +// --workspace-max-clock-skew 50s the barrier is at most 95 s after the stop. +// A holder started 31 s after the stop ends its 30 s authority wait before +// the barrier: it does not serve and exits with status 75, so a supervisor +// (Restart=on-failure, RestartSec=5s) starts it again; a start that waits +// past the barrier is re-granted and serves at the same epoch. +func TestProcedureStartTooEarlyExitsAndARestartServes(t *testing.T) { + env := startHandoffEnv(t, 1, "--workspace-max-clock-skew", "50s") + first := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, first, "s1") + block := pattern("start-too-early!") + env.writeBlock(t, "s1", 0, block) + first.kill(t) + time.Sleep(31 * time.Second) + + for attempt := 1; ; attempt++ { + d := env.start(t, fmt.Sprintf("blockvolume-s1-try%d", attempt), "s1") + served := false + end := time.Now().Add(45 * time.Second) + for time.Now().Before(end) { + if env.frontendReadyAt("s1") { + served = true + break + } + select { + case <-d.done: + end = time.Now() + default: + time.Sleep(200 * time.Millisecond) + } + } + if served { + if attempt == 1 { + t.Fatal("started before the barrier with its wait ending first, the holder served") + } + if got := env.adopt(t, d, "s1"); got != e { + t.Fatalf("attempt %d adopted epoch %d; want the same epoch %d", attempt, got, e) + } + break + } + if err := d.wait(5 * time.Second); exitCode(err) != 75 { + t.Fatalf("attempt %d did not serve and did not exit 75: %v", attempt, err) + } + if attempt == 4 { + t.Fatal("four supervised starts never served") + } + time.Sleep(5 * time.Second) + } + if !bytes.Equal(env.readBlock(t, "s1", 0), block) { + t.Fatal("the block written before the stop does not read back") + } +} + +// lastLogTime is the time of the last log line containing s (second +// resolution, the log's local time), or zero. +func lastLogTime(d *daemon, s string) time.Time { + data, _ := os.ReadFile(d.log) + var last time.Time + for _, l := range strings.Split(string(data), "\n") { + if strings.Contains(l, s) && len(l) >= 19 { + if ts, err := time.ParseInLocation("2006/01/02 15:04:05", l[:19], time.Local); err == nil { + last = ts + } + } + } + return last +} + +// exitCode is a child's exit status (-1 when it did not exit with one). +func exitCode(err error) int { + var exit *exec.ExitError + if err == nil { + return 0 + } + if errors.As(err, &exit) { + return exit.ExitCode() + } + return -1 +} + func pattern(s string) []byte { return bytes.Repeat([]byte(s), 4096/len(s)) } func (env *handoffEnv) start(t *testing.T, name, id string) *daemon { From b2ddf6206aa85dd517b298b52a6cb3adfa28ecd5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 03:32:08 -0800 Subject: [PATCH 03/16] test: the barrier-wait start at 40 s; the refusal of another server's assignment counts Co-Authored-By: Claude Opus 5.5 --- .../blockvolume/procedure_gate_integration_test.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go index 24861cdebf..34e8ac3668 100644 --- a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go @@ -171,8 +171,8 @@ func TestProcedureForcedMoveWithTheOldHostReturning(t *testing.T) { } time.Sleep(time.Second) } - if !back.has("refusing to attach volume=v1") && !back.has("workspace lease: stale authority") { - failures = append(failures, "it logged neither the stale-root refusal nor stale authority") + if !back.has("refusing to attach volume=v1") && !back.has("workspace lease: stale authority") && !back.has("is not this process") { + failures = append(failures, "it logged no refusal (stale root, stale authority, or another server's assignment)") } if len(failures) > 0 { t.Errorf("the returning old host after the forced move: %s", strings.Join(failures, "; ")) @@ -218,9 +218,9 @@ func TestProcedureRevokeWithoutACKThenForcedMove(t *testing.T) { } // TestProcedureStartInsideTheBarrierWaitIsReGranted: the holder's process -// dies and is started again 35 s later: its lease has ended, the re-grant -// barrier (at most 65 s after the stop, default flags) has not passed, and -// the barrier passes within the process's 30 s authority wait. It must not +// dies and is started again 40 s later: its lease has ended, the re-grant +// barrier (at least 50 s and at most 65 s after the stop, default flags) has +// not passed, and it passes within the process's 30 s authority wait. It must not // serve while its renewals are still refused for the barrier; once // re-granted it serves its local WAL at the same epoch. func TestProcedureStartInsideTheBarrierWaitIsReGranted(t *testing.T) { @@ -230,7 +230,7 @@ func TestProcedureStartInsideTheBarrierWaitIsReGranted(t *testing.T) { block := pattern("inside-the-wait!") env.writeBlock(t, "s1", 0, block) first.kill(t) - time.Sleep(35 * time.Second) + time.Sleep(40 * time.Second) back := env.start(t, "blockvolume-s1-back", "s1") var ready []time.Time From 1ad3218fa986bcade94b2ec48f7c19926d7e669b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 03:52:16 -0800 Subject: [PATCH 04/16] test: a recorded foreign assignment counts as the old host's refusal Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/procedure_gate_integration_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go index 34e8ac3668..eec3f8d1bf 100644 --- a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go @@ -171,7 +171,7 @@ func TestProcedureForcedMoveWithTheOldHostReturning(t *testing.T) { } time.Sleep(time.Second) } - if !back.has("refusing to attach volume=v1") && !back.has("workspace lease: stale authority") && !back.has("is not this process") { + if !back.has("refusing to attach volume=v1") && !back.has("workspace lease: stale authority") && !back.has("is not this process") && !back.has("foreign assignment") { failures = append(failures, "it logged no refusal (stale root, stale authority, or another server's assignment)") } if len(failures) > 0 { From 501d68ea0642011e70742ab125a666a621234249 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 04:01:47 -0800 Subject: [PATCH 05/16] test: harness ports below the kernel's ephemeral range Co-Authored-By: Claude Opus 5.5 --- .../planned_handoff_integration_test.go | 46 ++++++++++++++++--- 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index 9e03afddb4..24efa719f2 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -9,12 +9,14 @@ import ( "errors" "fmt" "io" + "math/rand" "net" "net/http" "os" "os/exec" "path/filepath" "strings" + "sync" "testing" "time" @@ -194,7 +196,7 @@ func startHandoffEnv(t *testing.T, n int, masterArgs ...string) *handoffEnv { env.hosts["s1"] = bvHost{id: "s1", data: h.dataAddr, ctrl: h.ctrlAddr, status: h.statusAddr, nvme: h.nvmeAddr, root: filepath.Join(h.dir, "vol")} for i := 2; i <= n; i++ { id := fmt.Sprintf("s%d", i) - env.hosts[id] = bvHost{id: id, data: leaseBinaryAddress(t), ctrl: leaseBinaryAddress(t), status: leaseBinaryAddress(t), nvme: leaseBinaryAddress(t), root: filepath.Join(h.dir, "vol-"+id)} + env.hosts[id] = bvHost{id: id, data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t), root: filepath.Join(h.dir, "vol-"+id)} } cluster, chunkPath := env.cluster, env.chunkPath @@ -293,14 +295,46 @@ func newPlannedHandoffHarness(t *testing.T) *plannedHandoffHarness { t.Fatalf("build %s: %v\n%s", b.name, err, out) } } - h.masterAddr = leaseBinaryAddress(t) - h.dataAddr = leaseBinaryAddress(t) - h.ctrlAddr = leaseBinaryAddress(t) - h.statusAddr = leaseBinaryAddress(t) - h.nvmeAddr = leaseBinaryAddress(t) + h.masterAddr = handoffAddress(t) + h.dataAddr = handoffAddress(t) + h.ctrlAddr = handoffAddress(t) + h.statusAddr = handoffAddress(t) + h.nvmeAddr = handoffAddress(t) return h } +var handoffPorts struct { + sync.Mutex + used map[int]bool +} + +// handoffAddress returns a free loopback address below the kernel's +// ephemeral range (32768 and up on Linux). A daemon restarted minutes later +// binds it again, and an outgoing connection may take any ephemeral port in +// between; ports below the range are never handed out that way. +func handoffAddress(t *testing.T) string { + t.Helper() + handoffPorts.Lock() + defer handoffPorts.Unlock() + if handoffPorts.used == nil { + handoffPorts.used = map[int]bool{} + } + for i := 0; i < 500; i++ { + p := 21000 + rand.Intn(11000) + if handoffPorts.used[p] { + continue + } + addr := fmt.Sprintf("127.0.0.1:%d", p) + if ln, err := net.Listen("tcp", addr); err == nil { + ln.Close() + handoffPorts.used[p] = true + return addr + } + } + t.Fatal("no free loopback port below the ephemeral range") + return "" +} + // daemon is one started child: its log file and its exit. type daemon struct { name, log string From 339932cb6171cc798ebe8aad55b1365402d7e606 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 07:33:12 -0800 Subject: [PATCH 06/16] test: fold the procedure gate's test-tier review - The old host returning after a forced move: the absence checks run only while it is alive; it must exit 75 and log a refusal; a supervised restart and a start on a fresh local root (a control: no stale root to refuse) must do the same. The refusal text that the product never prints is dropped. - The same-host restart is the page's systemctl restart (SIGTERM, a start within RestartSec); the crash restart is its own test. Both must serve within 15 s, as s1/r1 at the same epoch. - The barrier wait requires at least one barrier refusal, compares with one second of log resolution, and requires the re-grant line. - Too early: the exit reason assignment_timeout, and the same serving predicate as the barrier wait. - The planned hand-over runs the page's step 1 and reads a never-written block as zero (a control). - The lapsed-lease return must serve within its 30 s authority wait, as s1/r1. Comments match the order of the revoke-without-ACK steps. - Harness ports come from 10000-19999, below weed's range; sw-block output can be captured to HANDOFF_CAPTURE_DIR for the fixtures. Co-Authored-By: Claude Opus 5.5 --- .../planned_handoff_integration_test.go | 51 ++++- .../procedure_gate_integration_test.go | 190 ++++++++++++++---- 2 files changed, 190 insertions(+), 51 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index 24efa719f2..651b9521d9 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -17,6 +17,7 @@ import ( "path/filepath" "strings" "sync" + "syscall" "testing" "time" @@ -237,8 +238,12 @@ func startHandoffEnv(t *testing.T, n int, masterArgs ...string) *handoffEnv { } // volArgs is the chapter's blockvolume command for one host. -func (env *handoffEnv) volArgs(id string) []string { - b := env.hosts[id] +func (env *handoffEnv) volArgs(id string) []string { return env.volArgsFor(env.hosts[id]) } + +// volArgsFor is the chapter's blockvolume command for b. The default +// scheduled snapshot (daily:7, at a per-volume offset) stays on, as the page +// says; a snapshot inside a test could only make a test fail, never pass. +func (env *handoffEnv) volArgsFor(b bvHost) []string { return []string{"--master", env.h.masterAddr, "--server-id", b.id, "--volume-id", "v1", "--replica-id", "r1", "--data-addr", b.data, "--ctrl-addr", b.ctrl, "--status-addr", b.status, "--durable-root", b.root, "--durable-impl", "walstore-chunk", @@ -303,15 +308,30 @@ func newPlannedHandoffHarness(t *testing.T) *plannedHandoffHarness { return h } +// captureOutput writes each sw-block answer to $HANDOFF_CAPTURE_DIR, when set, +// as --.stdout/.stderr: the source of testdata/planned-handoff. +func captureOutput(t *testing.T, args []string, stdout, stderr string) { + dir := os.Getenv("HANDOFF_CAPTURE_DIR") + if dir == "" || len(args) < 3 { + return + } + captureSeq++ + base := filepath.Join(dir, fmt.Sprintf("%s-%02d-%s-%s", t.Name(), captureSeq, args[1], args[2])) + _ = os.WriteFile(base+".stdout", []byte(stdout), 0o644) + _ = os.WriteFile(base+".stderr", []byte(stderr), 0o644) +} + +var captureSeq int + var handoffPorts struct { sync.Mutex used map[int]bool } -// handoffAddress returns a free loopback address below the kernel's -// ephemeral range (32768 and up on Linux). A daemon restarted minutes later -// binds it again, and an outgoing connection may take any ephemeral port in -// between; ports below the range are never handed out that way. +// handoffAddress returns a free loopback address in 10000-19999: below the +// kernel's ephemeral range (32768 and up on Linux), where an outgoing +// connection can take a port while a restarted daemon waits to bind it +// again, and below the 20000-49999 range startWorkspaceWeed draws from. func handoffAddress(t *testing.T) string { t.Helper() handoffPorts.Lock() @@ -320,7 +340,7 @@ func handoffAddress(t *testing.T) string { handoffPorts.used = map[int]bool{} } for i := 0; i < 500; i++ { - p := 21000 + rand.Intn(11000) + p := 10000 + rand.Intn(10000) if handoffPorts.used[p] { continue } @@ -341,6 +361,21 @@ type daemon struct { done chan struct{} err error cancel context.CancelFunc + proc *os.Process +} + +// term sends SIGTERM, as systemctl stop or restart does, and waits for the +// child to exit. +func (d *daemon) term(t *testing.T, timeout time.Duration) { + t.Helper() + if err := d.proc.Signal(syscall.SIGTERM); err != nil { + t.Fatalf("SIGTERM %s: %v", d.name, err) + } + select { + case <-d.done: + case <-time.After(timeout): + t.Fatalf("%s did not exit within %s of SIGTERM", d.name, timeout) + } } // kill kills the child (no ACK is sent on a signal) and waits for it. @@ -392,6 +427,7 @@ func (h *plannedHandoffHarness) start(t *testing.T, name, binary string, args .. t.Fatalf("start %s: %v", name, err) } started = true + d.proc = cmd.Process go func() { d.err = cmd.Wait(); close(d.done) }() return d } @@ -468,6 +504,7 @@ func (h *plannedHandoffHarness) run(t *testing.T, args ...string) (string, strin var stdout, stderr strings.Builder cmd.Stdout, cmd.Stderr = &stdout, &stderr err := cmd.Run() + captureOutput(t, args, stdout.String(), stderr.String()) var exit *exec.ExitError switch { case err == nil: diff --git a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go index eec3f8d1bf..1b1aacec6e 100644 --- a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go @@ -17,9 +17,11 @@ import ( ) // The procedure gate: every operator procedure of docs/volume-lifecycle.md -// runs as written, with real binaries, on two blockvolume processes with -// distinct server ids (s1 and s2) sharing one blockmaster and one SeaweedFS. -// The planned return to the same host is TestStandalonePlannedHandoffToTheSameHost. +// runs as written, with real binaries, on blockvolume processes with distinct +// server ids (s1, and s2 where a procedure moves the volume) sharing one +// blockmaster and one SeaweedFS. The two start-time tests and the same-host +// restarts use s1 only. The planned return to the same host is +// TestStandalonePlannedHandoffToTheSameHost. // TestProcedurePlannedHandoffToAnotherHost: the planned hand-over from s1 to // s2. The new holder starts with no local copy, claims the sealed HEAD at the @@ -34,6 +36,9 @@ func TestProcedurePlannedHandoffToAnotherHost(t *testing.T) { block := pattern("to-another-host!") env.writeBlock(t, "s1", 0, block) + // Step 1: read the holder; the lease must be granted. + out, _ := h.command(t, env.show...) + must(checkShowGranted(out, e)) g := env.seal(t, "s1", e) l := env.sealedLSN(t, e, g) env.revoke(t, e, g) @@ -49,7 +54,7 @@ func TestProcedurePlannedHandoffToAnotherHost(t *testing.T) { if got := env.adopt(t, nw, "s2"); got != e2 { t.Fatalf("s2 adopted at epoch %d; want %d", got, e2) } - out, _ := h.command(t, env.show...) + out, _ = h.command(t, env.show...) must(wantLines(out, fmt.Sprintf("holder: r1@%d (logical replica)", e2), fmt.Sprintf("move: request=move-v1-1 kind=clean issued=true s1/r1@%d -> s2/r1@%d HEAD generation %d remote LSN %d", e, e2, g, l))) out, _ = h.command(t, env.chunkShow()...) @@ -57,27 +62,59 @@ func TestProcedurePlannedHandoffToAnotherHost(t *testing.T) { if !bytes.Equal(env.readBlock(t, "s2", 0), block) { t.Fatal("the block written on s1 does not read back on s2") } + // Control: a block never written reads zero, so the comparison above can + // fail. + if !bytes.Equal(env.readBlock(t, "s2", 8), make([]byte, 4096)) { + t.Fatal("a block never written does not read zero on s2") + } } -// TestProcedureSameHostRestartInsideTheLease: the holder's process dies and is -// started again on its host within the 30 s lease. It keeps holder and epoch -// and serves again at once from its local WAL. +// TestProcedureSameHostRestartInsideTheLease: the page's restart without a +// hand-over, `systemctl restart`: the holder gets SIGTERM, exits, and is +// started again on its host within the unit's RestartSec (5 s), inside the +// 30 s lease. It keeps holder and epoch and serves again at once from its +// local WAL. func TestProcedureSameHostRestartInsideTheLease(t *testing.T) { - env := startHandoffEnv(t, 2) - must, _ := fatalOn(t) - + env := startHandoffEnv(t, 1) first := env.start(t, "blockvolume-s1", "s1") e := env.adopt(t, first, "s1") block := pattern("restart-in-lease") env.writeBlock(t, "s1", 0, block) - first.kill(t) + first.term(t, 30*time.Second) + env.restartServesAtOnce(t, "blockvolume-s1-again", e, block) +} - again := env.start(t, "blockvolume-s1-again", "s1") +// TestProcedureSameHostCrashRestartInsideTheLease: the page's "the holder +// comes back within the lease" after a crash: the process is killed and +// started again within the unit's RestartSec (5 s). The same outcome as a +// restart. +func TestProcedureSameHostCrashRestartInsideTheLease(t *testing.T) { + env := startHandoffEnv(t, 1) + first := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, first, "s1") + block := pattern("crash-in-lease!!") + env.writeBlock(t, "s1", 0, block) + first.kill(t) + env.restartServesAtOnce(t, "blockvolume-s1-again", e, block) +} + +// restartServesAtOnce starts s1 again within 5 s of its exit and requires it +// to serve within 15 s ("at once"), as s1/r1 at the same epoch, with the +// written block. +func (env *handoffEnv) restartServesAtOnce(t *testing.T, name string, e uint64, block []byte) { + t.Helper() + must, _ := fatalOn(t) + started := time.Now() + again := env.start(t, name, "s1") if got := env.adopt(t, again, "s1"); got != e { t.Fatalf("the restarted holder adopted epoch %d; want the same epoch %d", got, e) } + if took := time.Since(started); took > 15*time.Second { + t.Fatalf("the restarted holder served after %s; the page says at once", took.Round(time.Second)) + } out, _ := env.h.command(t, env.show...) must(checkShowGranted(out, e)) + env.requireHeadHolder(t, e, "s1") if !bytes.Equal(env.readBlock(t, "s1", 0), block) { t.Fatal("the block written before the restart does not read back") } @@ -99,15 +136,20 @@ func TestProcedureReturnAfterALapsedLease(t *testing.T) { stopped := time.Now() time.Sleep(time.Until(stopped.Add(65 * time.Second))) + started := time.Now() back := env.start(t, "blockvolume-s1-back", "s1") if got := env.adopt(t, back, "s1"); got != e { t.Fatalf("the returning holder adopted epoch %d; want the same epoch %d", got, e) } + if took := time.Since(started); took > 30*time.Second { + t.Fatalf("the returning holder served after %s, past its 30 s authority wait", took.Round(time.Second)) + } if back.has("assignment unavailable, not serving") { t.Fatal("started 65 s after the stop, the holder still logged the not-serving line") } out, _ := env.h.command(t, env.show...) must(checkShowGranted(out, e)) + env.requireHeadHolder(t, e, "s1") if !bytes.Equal(env.readBlock(t, "s1", 0), block) { t.Fatal("the block written before the lapse does not read back") } @@ -153,40 +195,30 @@ func TestProcedureForcedMoveWithTheOldHostReturning(t *testing.T) { t.Fatal("the block written after the last cut reads back on s2; the page says it is lost") } - // The old host returns with its old local root. It must not take s2's - // line as its own (a holder is server and replica), report its frontend - // ready, or listen for I/O; the page says it does not serve. - back := env.start(t, "blockvolume-s1-back", "s1") - var failures []string - end := time.Now().Add(40 * time.Second) - for time.Now().Before(end) && len(failures) == 0 { - if l := back.line(fmt.Sprintf("adopted as PRIMARY at r1@%d", e2)); l != "" { - failures = append(failures, "it adopted s2's line: "+l) - } - if env.frontendReadyAt("s1") { - failures = append(failures, "its status reports FrontendPrimaryReady") - } - if listening(env.hosts["s1"].nvme) { - failures = append(failures, "its NVMe/TCP target listens") - } - time.Sleep(time.Second) - } - if !back.has("refusing to attach volume=v1") && !back.has("workspace lease: stale authority") && !back.has("is not this process") && !back.has("foreign assignment") { - failures = append(failures, "it logged no refusal (stale root, stale authority, or another server's assignment)") - } - if len(failures) > 0 { - t.Errorf("the returning old host after the forced move: %s", strings.Join(failures, "; ")) - } + // The old host returns with its old local root, and a supervisor starts + // it again after it exits. Each time it must not take s2's line as its + // own (a holder is server and replica), report its frontend ready or + // listen for I/O, and it must log a refusal and exit with status 75. + env.oldHostRefuses(t, "blockvolume-s1-back", env.hosts["s1"], e2) + time.Sleep(5 * time.Second) // RestartSec of the example unit + env.oldHostRefuses(t, "blockvolume-s1-restarted", env.hosts["s1"], e2) + // Control: on a fresh local root there is no stale root to refuse, and + // it must still refuse s2's line. + fresh := env.hosts["s1"] + fresh.root = fresh.root + "-fresh" + env.oldHostRefuses(t, "blockvolume-s1-fresh-root", fresh, e2) env.h.waitPrimaryAt(t, env.hosts["s2"].status, e2) if !bytes.Equal(env.readBlock(t, "s2", 0), kept) { t.Fatal("s2 no longer serves the kept block after the old host returned") } } -// TestProcedureRevokeWithoutACKThenForcedMove: the volume is sealed and -// revoked, but its process dies before it sends the ACK. The clean move is -// refused; only a forced move to another node remains, and since HEAD is -// sealed, nothing acknowledged is lost. +// TestProcedureRevokeWithoutACKThenForcedMove: the volume is sealed, its +// process is gone before the revoke (so no process ever sends the ACK), and +// the lease is revoked with the sealed generation. The clean move is refused; +// only a forced move to another node remains, and since HEAD is sealed, +// nothing acknowledged is lost. Killing before the revoke makes the missing +// ACK certain; the page's row "Revoked, but no ACK" has the same outcome. func TestProcedureRevokeWithoutACKThenForcedMove(t *testing.T) { env := startHandoffEnv(t, 2) must, mustU := fatalOn(t) @@ -236,7 +268,7 @@ func TestProcedureStartInsideTheBarrierWaitIsReGranted(t *testing.T) { var ready []time.Time end := time.Now().Add(90 * time.Second) for time.Now().Before(end) { - if env.frontendReadyAt("s1") || listening(env.hosts["s1"].nvme) { + if env.servingNow("s1") { ready = append(ready, time.Now()) if len(ready) >= 5 { break @@ -247,10 +279,19 @@ func TestProcedureStartInsideTheBarrierWaitIsReGranted(t *testing.T) { if len(ready) == 0 { t.Fatal("the returning holder never served within 90 s") } - if last := lastLogTime(back, "clock-skew margin has not elapsed"); !last.IsZero() && ready[0].Before(last) { - t.Errorf("the returning holder served at %s, before its renewal was still refused for the barrier at %s: it served without a lease", + // Started before the barrier, its renewals must have been refused for it + // at least once; log times have 1 s resolution. + last := lastLogTime(back, "clock-skew margin has not elapsed") + if last.IsZero() { + t.Fatal("started 40 s after the stop, the returning holder logged no renewal refused for the barrier") + } + if ready[0].Before(last.Add(time.Second)) { + t.Errorf("the returning holder served at %s, while its renewal was still refused for the barrier at %s: it served without a lease", ready[0].Format("15:04:05.000"), last.Format("15:04:05")) } + if !back.has("workspace lease: re-granted after ") { + t.Error("the returning holder served without logging its re-grant") + } if got := env.adopt(t, back, "s1"); got != e { t.Fatalf("the returning holder adopted epoch %d; want the same epoch %d", got, e) } @@ -274,12 +315,15 @@ func TestProcedureStartTooEarlyExitsAndARestartServes(t *testing.T) { first.kill(t) time.Sleep(31 * time.Second) + // Attempt 2 starts about 66 s after the stop and its wait ends about + // 96 s after it, against a barrier of at most 95 s, so attempt 2 normally + // serves; up to 4 attempts allow for scheduling on a loaded host. for attempt := 1; ; attempt++ { d := env.start(t, fmt.Sprintf("blockvolume-s1-try%d", attempt), "s1") served := false end := time.Now().Add(45 * time.Second) for time.Now().Before(end) { - if env.frontendReadyAt("s1") { + if env.servingNow("s1") { served = true break } @@ -302,6 +346,9 @@ func TestProcedureStartTooEarlyExitsAndARestartServes(t *testing.T) { if err := d.wait(5 * time.Second); exitCode(err) != 75 { t.Fatalf("attempt %d did not serve and did not exit 75: %v", attempt, err) } + if !d.has("blockvolume: exiting status=75 reason=assignment_timeout") { + t.Fatalf("attempt %d exited 75 without the reason assignment_timeout", attempt) + } if attempt == 4 { t.Fatal("four supervised starts never served") } @@ -339,6 +386,61 @@ func exitCode(err error) int { return -1 } +// oldHostRefuses starts the old holder b after the volume moved to epoch e2 +// on another host. While it runs it must not adopt the new line, report its +// frontend ready or listen; it must log a refusal and exit with status 75 +// (a later change may give a stale local root its own status). +func (env *handoffEnv) oldHostRefuses(t *testing.T, name string, b bvHost, e2 uint64) { + t.Helper() + d := env.h.start(t, name, env.h.volume, env.volArgsFor(b)...) + var failures []string + end := time.Now().Add(60 * time.Second) + for alive := true; alive && time.Now().Before(end); { + if l := d.line(fmt.Sprintf("adopted as PRIMARY at r1@%d", e2)); l != "" { + failures = append(failures, "it adopted the new holder's line: "+l) + } + if env.frontendReadyAt("s1") { + failures = append(failures, "its status reports FrontendPrimaryReady") + } + if listening(b.nvme) { + failures = append(failures, "its NVMe/TCP target listens") + } + select { + case <-d.done: + alive = false + case <-time.After(500 * time.Millisecond): + } + } + if err := d.wait(5 * time.Second); exitCode(err) != 75 { + failures = append(failures, fmt.Sprintf("it did not exit with status 75: %v", err)) + } + if !d.has("refusing to attach volume=v1") && !d.has("workspace lease: stale authority") && !d.has("foreign assignment") { + failures = append(failures, "it logged no refusal (stale root, stale authority, or another server's assignment)") + } + if len(failures) > 0 { + t.Errorf("%s after the forced move: %s", name, strings.Join(failures, "; ")) + } +} + +// servingNow reports whether the host serves: its frontend is ready or its +// NVMe/TCP target accepts connections. +func (env *handoffEnv) servingNow(id string) bool { + return env.frontendReadyAt(id) || listening(env.hosts[id].nvme) +} + +// requireHeadHolder checks that HEAD is active, held by host/r1 at epoch e. +func (env *handoffEnv) requireHeadHolder(t *testing.T, e uint64, host string) { + t.Helper() + out, _ := env.h.command(t, env.chunkShow()...) + head, err := parseHead(out) + if err != nil { + t.Fatal(err) + } + if head.State != "active" || head.Epoch != e || head.Holder != host+"/r1" { + t.Fatalf("HEAD %+v; want active at epoch %d held by %s/r1", head, e, host) + } +} + func pattern(s string) []byte { return bytes.Repeat([]byte(s), 4096/len(s)) } func (env *handoffEnv) start(t *testing.T, name, id string) *daemon { From 4098abca8283613f85bcce08ac5b405f8984ae4f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 07:46:41 -0800 Subject: [PATCH 07/16] test: the procedure gate's captured outputs as fixtures The move to s2, HEAD reclaimed by s2, the forced move, its dry-run previews (refused with an admissible time, then admitted) and lost-range, captured from a passing gate run, are read by the default-build check test; each check also refuses a neighbouring output. Co-Authored-By: Claude Opus 5.5 --- .../planned_handoff_checks_test.go | 35 +++++++++++++++++-- .../force-move-dry-run-admitted.stdout | 4 +++ .../force-move-dry-run-refused.stdout | 3 ++ .../planned-handoff/force-move.stdout | 3 ++ .../planned-handoff/head-reopened-s2.stdout | 1 + .../planned-handoff/lost-range.stdout | 2 ++ .../planned-handoff/move-clean-s2.stdout | 2 ++ 7 files changed, 47 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move-dry-run-admitted.stdout create mode 100644 seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move-dry-run-refused.stdout create mode 100644 seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move.stdout create mode 100644 seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-reopened-s2.stdout create mode 100644 seaweed-block/cmd/blockvolume/testdata/planned-handoff/lost-range.stdout create mode 100644 seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-clean-s2.stdout diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go index af534928eb..1a64651a8d 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go @@ -229,9 +229,10 @@ func matchUint(re *regexp.Regexp, s string) (uint64, error) { // TestPlannedHandoffChecksReadCapturedProductOutput runs every check on the // output the real binaries printed in one passing hand-over (E=1, G=3, L=1, -// E2=2) and in the refused clean move without an ACK (move-refused, -// show-revoked), and each check on an output of another step, which it must -// refuse. +// E2=2), in the refused clean move without an ACK (move-refused, +// show-revoked), and in the procedure gate's move to s2 and forced move +// (move-clean-s2, head-reopened-s2, force-move*, lost-range), and each check +// on an output of another step, which it must refuse. func TestPlannedHandoffChecksReadCapturedProductOutput(t *testing.T) { read := func(name string) string { b, err := os.ReadFile(filepath.Join("testdata", "planned-handoff", name)) @@ -302,6 +303,34 @@ func TestPlannedHandoffChecksReadCapturedProductOutput(t *testing.T) { if r := read("show-revoked.stdout"); showsAck(r, e, g) || !hasLine(r, "recorded ACK: none") { t.Error("the revoked show without an ACK is read as acknowledged") } + // The procedure gate's two-host outputs (a planned move to s2, a forced + // move s1 -> s2 at E=1 -> E2=2 keeping gen 3, LSN 1). + if got, err := movedEpochTo(read("move-clean-s2.stdout"), e, g, l, "s2"); err != nil || got != e2 { + t.Errorf("moved epoch to s2 %d, %v; want %d", got, err, e2) + } + _, err = movedEpochTo(read("move-clean-s2.stdout"), e, g, l, "s1") + refused("clean move to s2 read as a move to s1", err) + ok("HEAD reopened by s2", checkHeadReopenedBy(read("head-reopened-s2.stdout"), e2, g, l, "s2")) + refused("HEAD reopened by s2 read as s1's", checkHeadReopenedBy(read("head-reopened-s2.stdout"), e2, g, l, "s1")) + if got, err := forcedEpoch(read("force-move.stdout"), e, "s1", "s2"); err != nil || got != e2 { + t.Errorf("forced epoch %d, %v; want %d", got, err, e2) + } + _, err = forcedEpoch(read("force-move.stdout"), e, "s2", "s1") + refused("forced move read the other way round", err) + _, err = forcedEpoch(read("move-clean-s2.stdout"), e, "s1", "s2") + refused("forced epoch", err) + if got, err := forcedKeptLSN(read("force-move.stdout")); err != nil || got != l { + t.Errorf("forced kept LSN %d, %v; want %d", got, err, l) + } + if !previewAdmitted(read("force-move-dry-run-admitted.stdout")) || previewAdmitted(read("force-move-dry-run-refused.stdout")) { + t.Error("the dry-run preview is not told admitted from not admitted") + } + if !strings.Contains(read("force-move-dry-run-refused.stdout"), "admissible at ") { + t.Error("the refused preview has no admissible time") + } + if !strings.Contains(read("lost-range.stdout"), "range 1 of 1: request force-v1-1, r1@") { + t.Error("lost-range does not show the forced move") + } if !frontendReady([]byte(read("status-primary.json"))) || frontendReady([]byte(`{"FrontendPrimaryReady":false,"Healthy":true}`)) { t.Error("the frontend-ready check does not read FrontendPrimaryReady") } diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move-dry-run-admitted.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move-dry-run-admitted.stdout new file mode 100644 index 0000000000..9442ec483d --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move-dry-run-admitted.stdout @@ -0,0 +1,4 @@ +preview (advisory): at master time 2026-11-22T15:36:16.705621624Z, may change; admission is re-checked at the move. Nothing was written; this is not a confirmation. +forced move admitted +HEAD now: gen 3, epoch 1, holder s1/r1, remote LSN 1, published at 2026-11-22T15:35:12Z (publishing host clock as recorded in the filer, 1 s resolution) +if moved now: writes with LSN <= 1 are kept; writes acknowledged after that and before 2026-11-22T15:36:16.617154582Z, master clock, may be lost diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move-dry-run-refused.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move-dry-run-refused.stdout new file mode 100644 index 0000000000..082cfcc755 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move-dry-run-refused.stdout @@ -0,0 +1,3 @@ +preview (advisory): at master time 2026-11-22T15:35:12.107989752Z, may change; admission is re-checked at the move. Nothing was written; this is not a confirmation. +forced move not admitted: workspace forced move lease expiry plus clock-skew margin has not elapsed +admissible at 2026-11-22T15:36:16.617154582Z, master clock diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move.stdout new file mode 100644 index 0000000000..0484f10cbc --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move.stdout @@ -0,0 +1,3 @@ +forced move issued: volume v1 request force-v1-1: r1@1 on s1 -> r1@2 on s2 (kept HEAD gen 3, remote LSN 1) +volume v1 restored to the last published image at 2026-11-22T15:35:12Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 3, LSN 1): writes with LSN <= 1 are preserved; writes acknowledged by r1@1 after that and before 2026-11-22T15:36:16.617154582Z, master clock, may be lost; the upper bound is a time, not an LSN. +next: start volume v1 on s2 (this command moved authority only) diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-reopened-s2.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-reopened-s2.stdout new file mode 100644 index 0000000000..8bcafeb22b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-reopened-s2.stdout @@ -0,0 +1 @@ +{"volumeID":"v1","volume":{"origin":"create","numBlocks":65536,"blockSize":4096,"chunkBlocks":1024,"createdNs":1795361693554515613,"parent":null},"head":{"gen":4,"epoch":2,"holder":"s2/r1","remoteLSN":1,"state":"active","detachedBy":null,"chunkCount":1}} diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/lost-range.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/lost-range.stdout new file mode 100644 index 0000000000..6da93bf717 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/lost-range.stdout @@ -0,0 +1,2 @@ +range 1 of 1: request force-v1-1, r1@1 -> epoch 2, lost after LSN 1, until 2026-11-22T15:36:16.617154582Z (master clock) + volume v1 restored to the last published image at 2026-11-22T15:35:12Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 3, LSN 1): writes with LSN <= 1 are preserved; writes acknowledged by r1@1 after that and before 2026-11-22T15:36:16.617154582Z, master clock, may be lost; the upper bound is a time, not an LSN. diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-clean-s2.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-clean-s2.stdout new file mode 100644 index 0000000000..829f37454f --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-clean-s2.stdout @@ -0,0 +1,2 @@ +clean move issued: volume v1 request move-v1-1: r1@1 -> r1@2 on s2 (sealed HEAD gen 3, remote LSN 1) +next: start volume v1 on s2 (this command moved authority only) From 376e40c91ee72de6ed4bbe95d03771113e8a340b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 08:38:18 -0800 Subject: [PATCH 08/16] test(deploy): expose unbounded blockvolume startup retries --- .../testops/blockvolume_systemd_test.go | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 seaweed-block/internal/testops/blockvolume_systemd_test.go diff --git a/seaweed-block/internal/testops/blockvolume_systemd_test.go b/seaweed-block/internal/testops/blockvolume_systemd_test.go new file mode 100644 index 0000000000..134971291d --- /dev/null +++ b/seaweed-block/internal/testops/blockvolume_systemd_test.go @@ -0,0 +1,41 @@ +package testops + +import ( + "strings" + "testing" +) + +// M2 restart: the shipped supervisor bounds retries after exit 75. +func TestBlockvolumeUnitsBoundStartupRetries(t *testing.T) { + for _, name := range []string{"sw-blockvolume.service", "sw-blockvolume-ublk.service"} { + t.Run(name, func(t *testing.T) { + body := readRepoFile(t, "deploy", "systemd", name) + section := "" + seen := map[string]bool{} + for _, line := range strings.Split(body, "\n") { + line = strings.TrimSpace(line) + if strings.HasPrefix(line, "[") { + section = line + continue + } + key, value, ok := strings.Cut(line, "=") + if !ok { + continue + } + want, checked := map[string]string{"StartLimitIntervalSec": "600", "StartLimitBurst": "10"}[key] + if !checked { + continue + } + if seen[key] || section != "[Unit]" || value != want { + t.Errorf("%s: %s=%s in %s (duplicate=%t), want %s=%s once in [Unit]", name, key, value, section, seen[key], key, want) + } + seen[key] = true + } + for _, key := range []string{"StartLimitIntervalSec", "StartLimitBurst"} { + if !seen[key] { + t.Errorf("%s: missing [Unit] %s", name, key) + } + } + }) + } +} From 3dc1bac4c9bb7d84e06299c7aef4e03ca26240cb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 08:38:34 -0800 Subject: [PATCH 09/16] fix(deploy): bound blockvolume supervisor retries --- .../deploy/systemd/sw-blockvolume-ublk.service | 2 ++ seaweed-block/deploy/systemd/sw-blockvolume.service | 2 ++ seaweed-block/docs/design/invariants.md | 1 + seaweed-block/docs/standalone-deployment.md | 10 ++++++++++ 4 files changed, 15 insertions(+) diff --git a/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service b/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service index ee1904fa86..6819f4d9d6 100644 --- a/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service +++ b/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service @@ -9,6 +9,8 @@ # # Load the module at boot: echo ublk_drv | sudo tee /etc/modules-load.d/ublk.conf [Unit] +StartLimitIntervalSec=600 +StartLimitBurst=10 Description=Seaweed Block volume over ublk (one replica, root) Documentation=https://github.com/seaweedfs/seaweed-block After=network-online.target sw-blockmaster.service diff --git a/seaweed-block/deploy/systemd/sw-blockvolume.service b/seaweed-block/deploy/systemd/sw-blockvolume.service index 7ad8a3ed5e..30a69d729c 100644 --- a/seaweed-block/deploy/systemd/sw-blockvolume.service +++ b/seaweed-block/deploy/systemd/sw-blockvolume.service @@ -7,6 +7,8 @@ # For ublk (needs root) do not edit this unit: use # sw-blockvolume-ublk.service, which has its own state directory. [Unit] +StartLimitIntervalSec=600 +StartLimitBurst=10 Description=Seaweed Block volume (one replica) Documentation=https://github.com/seaweedfs/seaweed-block After=network-online.target sw-blockmaster.service diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a40b33ba70..8ee4057e95 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1011,6 +1011,7 @@ Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed sc |---|---|---|---|---| | 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. | +| Workspace primary supervisor retries | M2 restart; `INV-WS-STARTUP-RETRY-001` | Shipped systemd units: `StartLimitIntervalSec=600`, `StartLimitBurst=10`, `RestartSec=5s` | systemd owns the restart window: after 10 starts in 600 s, another start within the window is refused and the unit fails; operator reset/start follows remediation. Exit 78 and ACKed exit 0 do not restart. | No application lock; `TestBlockvolumeUnitsBoundStartupRetries` (`internal/testops/blockvolume_systemd_test.go`) checks both shipped units. | | 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. | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 041aada217..10dd3ef822 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -79,6 +79,16 @@ The binaries take command-line flags. The `SWB_*` variables are read only by the example units, which turn them into flags. blockvolume itself reads only `SW_BLOCK_ISCSI_CHAP_USERNAME` and `SW_BLOCK_ISCSI_CHAP_SECRET`. +Both blockvolume units restart failed processes after 5 seconds, except exit 78 +(superseded). Exit 75 retries through the ordinary lease and HEAD-claim gates. +`StartLimitIntervalSec=600` and `StartLimitBurst=10` in `[Unit]` allow at most +10 starts in a 10-minute window; another start in that window is refused and +the unit enters `failed` (`start-limit-hit`). This bounds retries on a host +that no longer holds the volume. After correcting the assignment or disabling +the obsolete unit, an operator can use `systemctl reset-failed ` and +`systemctl start ` to resume attempts. An ACKed planned stop exits 0 +and is not automatically restarted. + ## Required setup: make the volume known to blockmaster blockmaster gives a blockvolume an assignment only for a volume and replica From e082155232468da23ff4406a01226064e82dae00 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 08:48:38 -0800 Subject: [PATCH 10/16] docs(deploy): explain no-restart outcomes and retry window --- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/standalone-deployment.md | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 8ee4057e95..caab17aee9 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1011,7 +1011,7 @@ Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed sc |---|---|---|---|---| | 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. | -| Workspace primary supervisor retries | M2 restart; `INV-WS-STARTUP-RETRY-001` | Shipped systemd units: `StartLimitIntervalSec=600`, `StartLimitBurst=10`, `RestartSec=5s` | systemd owns the restart window: after 10 starts in 600 s, another start within the window is refused and the unit fails; operator reset/start follows remediation. Exit 78 and ACKed exit 0 do not restart. | No application lock; `TestBlockvolumeUnitsBoundStartupRetries` (`internal/testops/blockvolume_systemd_test.go`) checks both shipped units. | +| Workspace primary supervisor retries | M2 restart; `INV-WS-STARTUP-RETRY-001` | Shipped systemd units: `StartLimitIntervalSec=600`, `StartLimitBurst=10`, `RestartSec=5s`. Each cycle is the assignment wait (default 30 s) + 5 s, reaching the limit in about 6 minutes. If the assignment wait exceeds about 55 s, raise the interval too or the window never fills | systemd owns the restart window: after 10 starts in 600 s, another start within the window is refused and the unit fails; operator reset/start follows remediation. Exit 78 and ACKed exit 0 do not restart. | No application lock; `TestBlockvolumeUnitsBoundStartupRetries` (`internal/testops/blockvolume_systemd_test.go`) checks both shipped units. | | 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. | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 10dd3ef822..6a4fd485fa 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -80,11 +80,16 @@ the example units, which turn them into flags. blockvolume itself reads only `SW_BLOCK_ISCSI_CHAP_USERNAME` and `SW_BLOCK_ISCSI_CHAP_SECRET`. Both blockvolume units restart failed processes after 5 seconds, except exit 78 -(superseded). Exit 75 retries through the ordinary lease and HEAD-claim gates. +(a no-restart outcome; the final log line names the reason). Exit 75 retries +through the ordinary lease and HEAD-claim gates. `StartLimitIntervalSec=600` and `StartLimitBurst=10` in `[Unit]` allow at most 10 starts in a 10-minute window; another start in that window is refused and the unit enters `failed` (`start-limit-hit`). This bounds retries on a host -that no longer holds the volume. After correcting the assignment or disabling +that no longer holds the volume. Each retry cycle is the assignment wait +(default 30 seconds) plus `RestartSec=5s`, so the retries reach the limit in +about 6 minutes, inside 600 seconds. Raising the assignment wait above about +55 seconds prevents this window from filling; raise `StartLimitIntervalSec` +with it to retain the bound. After correcting the assignment or disabling the obsolete unit, an operator can use `systemctl reset-failed ` and `systemctl start ` to resume attempts. An ACKed planned stop exits 0 and is not automatically restarted. From be1337aeaa1026948c36d72c41369efbb8e5bdcc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 08:40:46 -0800 Subject: [PATCH 11/16] test(workspace): expose divergent lease validity decisions --- .../core/authority/workspace_validity_test.go | 43 +++++++++++++++++++ .../core/host/master/workspace_skew_test.go | 27 ++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 seaweed-block/core/authority/workspace_validity_test.go diff --git a/seaweed-block/core/authority/workspace_validity_test.go b/seaweed-block/core/authority/workspace_validity_test.go new file mode 100644 index 0000000000..dcce84f5b4 --- /dev/null +++ b/seaweed-block/core/authority/workspace_validity_test.go @@ -0,0 +1,43 @@ +package authority + +import ( + "context" + "testing" + "time" +) + +func TestWorkspaceAckUsesGrantedHalfSkewBoundary(t *testing.T) { + for _, tc := range []struct { + name string + elapsed time.Duration + allowed bool + }{ + {"before", 28*time.Second - time.Nanosecond, true}, + {"at", 28 * time.Second, false}, + {"after", 29 * time.Second, false}, + } { + t.Run(tc.name, func(t *testing.T) { + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(4*time.Second)) + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + ctx := context.Background() + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + now = now.Add(tc.elapsed) + err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}) + if (err == nil) != tc.allowed { + t.Fatalf("ACK allowed=%t, want %t: %v", err == nil, tc.allowed, err) + } + if (p.WorkspaceState("v").Ack != nil) != tc.allowed { + t.Fatal("ACK persistence differs from admission") + } + }) + } +} diff --git a/seaweed-block/core/host/master/workspace_skew_test.go b/seaweed-block/core/host/master/workspace_skew_test.go index a2db589ec8..a26ec75701 100644 --- a/seaweed-block/core/host/master/workspace_skew_test.go +++ b/seaweed-block/core/host/master/workspace_skew_test.go @@ -145,3 +145,30 @@ func TestWorkspaceClockSkewConfigReachesLeaseReply(t *testing.T) { t.Fatal("configuration not applied to host validity", lease, reply) } } + +// The lease reply uses the publisher clock even when it differs from this +// process's wall clock; configured skew also covers legacy leases with no bound. +func TestWorkspaceLeaseFactUsesPublisherClockAndSkew(t *testing.T) { + now := time.Unix(1000, 0) + p := authority.NewPublisher(nil, authority.WithWorkspaceLeaseConfig(12*time.Second, func() time.Time { return now }), authority.WithWorkspaceMaxClockSkew(4*time.Second)) + _ = p + for _, tc := range []struct { + name string + expiry time.Duration + skew int64 + want time.Duration + }{ + {"legacy-configured-bound", 10 * time.Second, 0, 8 * time.Second}, + {"persisted-larger-bound", 10 * time.Second, int64(6 * time.Second), 7 * time.Second}, + {"configured-ttl-cap", 40 * time.Second, 0, 12 * time.Second}, + {"expired", time.Second, 0, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + l := authority.WorkspaceLease{ReplicaID: "r", Epoch: 1, ExpiresAtNS: now.Add(tc.expiry).UnixNano(), MaxClockSkewNS: tc.skew} + fact := leaseFact("v", l) + if fact.ValidForNs != int64(tc.want) { + t.Fatalf("validity=%s, want %s", time.Duration(fact.ValidForNs), tc.want) + } + }) + } +} From b528a0c9ecd3e11135c9b3daf68bc1b67e2e2156 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 08:42:32 -0800 Subject: [PATCH 12/16] fix(workspace): share detached proof and lease validity decisions --- .../cmd/blockvolume/workspace_lease.go | 6 +- .../cmd/blockvolume/workspace_proof_test.go | 58 +++++++++++++++++++ seaweed-block/core/authority/workspace.go | 5 +- .../core/authority/workspace_lease_view.go | 14 ++++- .../workspace_renewal_slowstore_test.go | 2 +- .../core/host/master/workspace_service.go | 26 ++------- .../core/host/master/workspace_skew_test.go | 5 +- seaweed-block/docs/design/invariants.md | 10 ++-- 8 files changed, 89 insertions(+), 37 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/workspace_proof_test.go diff --git a/seaweed-block/cmd/blockvolume/workspace_lease.go b/seaweed-block/cmd/blockvolume/workspace_lease.go index b0724b8288..4362b51e82 100644 --- a/seaweed-block/cmd/blockvolume/workspace_lease.go +++ b/seaweed-block/cmd/blockvolume/workspace_lease.go @@ -60,13 +60,9 @@ func workspaceDetachedGeneration(ctx context.Context, remoteFor func(string) (st if err != nil { return 0, err } - head, err := remote.GetHead(ctx) + head, err := storage.ReadDetachedChunkHead(ctx, remote, id.Epoch, holder) if err != nil { return 0, err } - proof := head.DetachedBy - if head.Gen == 0 || head.Epoch != id.Epoch || head.Holder != holder || head.State != storage.ChunkHeadDetached || proof == nil || proof.Gen != head.Gen || proof.Epoch != head.Epoch || proof.Holder != head.Holder { - return 0, fmt.Errorf("workspace shutdown has no matching stored detached HEAD") - } return head.Gen, nil } diff --git a/seaweed-block/cmd/blockvolume/workspace_proof_test.go b/seaweed-block/cmd/blockvolume/workspace_proof_test.go new file mode 100644 index 0000000000..6bbbf4e56d --- /dev/null +++ b/seaweed-block/cmd/blockvolume/workspace_proof_test.go @@ -0,0 +1,58 @@ +package main + +import ( + "context" + "errors" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" + "testing" +) + +type workspaceProofRemote struct { + storage.ChunkRemote + head storage.ChunkHead + err error + reads int +} + +func (r *workspaceProofRemote) GetHead(context.Context) (storage.ChunkHead, error) { + r.reads++ + return r.head, r.err +} + +func TestWorkspaceRevocationUsesExactStoredSeal(t *testing.T) { + for _, name := range []string{"valid", "zero-epoch", "empty-holder", "active", "proof-gen", "foreign-holder", "read-error"} { + t.Run(name, func(t *testing.T) { + h := storage.ChunkHead{Gen: 7, Epoch: 2, Holder: "s/r", State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Gen: 7, Epoch: 2, Holder: "s/r"}} + id := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 2} + holder := "s/r" + r := &workspaceProofRemote{head: h} + switch name { + case "zero-epoch": + id.Epoch = 0 + r.head.Epoch = 0 + r.head.DetachedBy.Epoch = 0 + case "empty-holder": + holder = "" + r.head.Holder = "" + r.head.DetachedBy.Holder = "" + case "active": + r.head.State = storage.ChunkHeadActive + case "proof-gen": + r.head.DetachedBy.Gen = 6 + case "foreign-holder": + r.head.Holder = "other/r" + case "read-error": + r.err = errors.New("HEAD answer lost") + } + gen, err := workspaceDetachedGeneration(context.Background(), func(string) (storage.ChunkRemote, error) { return r, nil }, id, holder) + if name == "valid" { + if err != nil || gen != 7 || r.reads != 1 { + t.Fatalf("stored seal: gen%d reads%d err%v", gen, r.reads, err) + } + } else if err == nil || gen != 0 { + t.Fatalf("unproven ACK gen%d err%v", gen, err) + } + }) + } +} diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index adae4867fa..8382c23230 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -277,8 +277,9 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a if !ok || line.info.ReplicaID != ack.ReplicaID || line.info.Epoch != ack.Epoch || ack.HeadGen == 0 || s == nil || s.Lease == nil || !s.Lease.Revoking { return fmt.Errorf("workspace revoke ACK: stale or unsolicited") } - now := p.workspaceNow() - if now.UnixNano() >= s.Lease.ExpiresAtNS || !now.Before(p.leaseDeadlineLocked(volume)) { + lease := *s.Lease + lease.ExpiresAtNS = min(lease.ExpiresAtNS, p.leaseDeadlineLocked(volume).UnixNano()) + if p.WorkspaceLeaseValidity(lease) == 0 { return fmt.Errorf("workspace revoke ACK: lease expired; forced move required") } if s.Ack != nil && *s.Ack != ack { diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index 354aff74bd..b4c08095cf 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -144,6 +144,18 @@ func (p *Publisher) WorkspaceLeaseReply(volume string) (WorkspaceLease, bool) { return l, true } +// WorkspaceLeaseValidity reports host validity on the publisher clock, with +// the configured TTL and the larger configured/persisted skew bound. +// M2 grant/revoke ACK; INV-WS-FORCED-MOVE-HALF-SKEW-001. +func (p *Publisher) WorkspaceLeaseValidity(l WorkspaceLease) time.Duration { + return p.workspaceLeaseValidityAt(l, p.workspaceNow()) +} + +func (p *Publisher) workspaceLeaseValidityAt(l WorkspaceLease, now time.Time) time.Duration { + remaining := time.Unix(0, l.ExpiresAtNS).Add(-p.workspaceSkew(&l) / 2).Sub(now) + return max(0, min(remaining, p.workspaceTTL)) +} + // PublishedLine is a volume's committed authority line as the lease view // publishes it. type PublishedLine struct { @@ -261,7 +273,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri // A grant without positive host validity (expiry minus half the skew // bound, leaseFact) would make the host fence on an invalid reply and lose // its remaining validity; refuse with an error instead. - if grant-lv.d.maxSkewNS/2 <= now.UnixNano() { + if p.workspaceLeaseValidityAt(WorkspaceLease{ExpiresAtNS: grant, MaxClockSkewNS: lv.d.maxSkewNS}, now) == 0 { horizon := lv.d.horizon // the view is leaseMu's: read it before the unlock (#242) summary := p.leaseStats.summaryDue(now) p.leaseMu.Unlock() diff --git a/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go index a9c488dbcb..c02ed5a927 100644 --- a/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go +++ b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go @@ -112,7 +112,7 @@ func (c deadlineLeaseClient) RenewWorkspaceLease(ctx context.Context, id *contro done <- result{err: err} return } - done <- result{fact: leaseFact(id.VolumeId, l)} + done <- result{fact: leaseFact(c.p, id.VolumeId, l)} }() select { case r := <-done: diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 2a84382c6a..04981c09fa 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -78,23 +78,9 @@ func workspaceError(err error) error { return status.Error(codes.FailedPrecondition, err.Error()) } -func leaseFact(volume string, l authority.WorkspaceLease) *control.WorkspaceLeaseFact { - // Client anchors this duration to its request START, not response arrival. - // The host fences half a skew bound before the stored master expiry. - // Never grant more than the server's configured 30s TTL after a restart. - skew := time.Duration(l.MaxClockSkewNS) - // Older persisted leases predate the bound; use the production default. - if skew <= 0 { - skew = 20 * time.Second - } - remaining := time.Until(time.Unix(0, l.ExpiresAtNS).Add(-skew / 2)) - if remaining > 30*time.Second { - remaining = 30 * time.Second - } - if remaining < 0 { - remaining = 0 - } - return &control.WorkspaceLeaseFact{VolumeId: volume, ReplicaId: l.ReplicaID, Epoch: l.Epoch, ExpiresAtNs: l.ExpiresAtNS, ValidForNs: int64(remaining), Revoking: l.Revoking} +func leaseFact(p *authority.Publisher, volume string, l authority.WorkspaceLease) *control.WorkspaceLeaseFact { + // The client anchors this duration to its request START, not response arrival. + return &control.WorkspaceLeaseFact{VolumeId: volume, ReplicaId: l.ReplicaID, Epoch: l.Epoch, ExpiresAtNs: l.ExpiresAtNS, ValidForNs: int64(p.WorkspaceLeaseValidity(l)), Revoking: l.Revoking} } // holderMatches implements INV-AUTH-HOLDER-IDENTITY-001 for both holder RPCs. @@ -125,7 +111,7 @@ func (s *services) RenewWorkspaceLease(ctx context.Context, q *control.Workspace if err != nil { return nil, workspaceError(err) } - return leaseFact(q.GetVolumeId(), l), nil + return leaseFact(s.host.Publisher(), q.GetVolumeId(), l), nil } func (s *services) RevokeWorkspace(ctx context.Context, q *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) { @@ -140,7 +126,7 @@ func (s *services) RevokeWorkspace(ctx context.Context, q *control.WorkspaceIden if !ok { return nil, status.Error(codes.FailedPrecondition, "workspace moved during revocation") } - return leaseFact(q.GetVolumeId(), lease), nil + return leaseFact(s.host.Publisher(), q.GetVolumeId(), lease), nil } func (s *services) AckWorkspaceRevoked(ctx context.Context, q *control.WorkspaceRevocationAck) (*control.WorkspaceEmpty, error) { @@ -416,7 +402,7 @@ func (s *services) QueryWorkspace(ctx context.Context, q *control.WorkspaceVolum return out, nil } if lease, ok := s.host.Publisher().WorkspaceLeaseReply(q.GetVolumeId()); ok { - out.Lease = leaseFact(q.GetVolumeId(), lease) // granted expiry, not the durable horizon + out.Lease = leaseFact(s.host.Publisher(), q.GetVolumeId(), lease) // granted expiry, not the durable horizon } if state.Ack != nil { out.RevocationAck = &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: q.GetVolumeId(), ReplicaId: state.Ack.ReplicaID, Epoch: state.Ack.Epoch}, HeadGen: state.Ack.HeadGen} diff --git a/seaweed-block/core/host/master/workspace_skew_test.go b/seaweed-block/core/host/master/workspace_skew_test.go index a26ec75701..e6a3317d2d 100644 --- a/seaweed-block/core/host/master/workspace_skew_test.go +++ b/seaweed-block/core/host/master/workspace_skew_test.go @@ -19,7 +19,7 @@ func (c skewLeaseClient) RenewWorkspaceLease(ctx context.Context, id *control.Wo if err != nil { return nil, err } - return leaseFact(id.VolumeId, l), nil + return leaseFact(c.p, id.VolumeId, l), nil } func (skewLeaseClient) AckWorkspaceRevoked(context.Context, *control.WorkspaceRevocationAck, ...grpc.CallOption) (*control.WorkspaceEmpty, error) { panic("expiry must not ACK clean") @@ -151,7 +151,6 @@ func TestWorkspaceClockSkewConfigReachesLeaseReply(t *testing.T) { func TestWorkspaceLeaseFactUsesPublisherClockAndSkew(t *testing.T) { now := time.Unix(1000, 0) p := authority.NewPublisher(nil, authority.WithWorkspaceLeaseConfig(12*time.Second, func() time.Time { return now }), authority.WithWorkspaceMaxClockSkew(4*time.Second)) - _ = p for _, tc := range []struct { name string expiry time.Duration @@ -165,7 +164,7 @@ func TestWorkspaceLeaseFactUsesPublisherClockAndSkew(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { l := authority.WorkspaceLease{ReplicaID: "r", Epoch: 1, ExpiresAtNS: now.Add(tc.expiry).UnixNano(), MaxClockSkewNS: tc.skew} - fact := leaseFact("v", l) + fact := leaseFact(p, "v", l) if fact.ValidForNs != int64(tc.want) { t.Fatalf("validity=%s, want %s", time.Duration(fact.ValidForNs), tc.want) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 19bb6ca18b..3d06edcae3 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -134,7 +134,7 @@ a pre-issued publication. | none | Granted | `RenewWorkspaceLease` from the current primary (server id, replica id) at the current epoch; a missing/foreign server is refused by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`); no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL (an epoch issued by a move already has its lease) | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-AUTH-HOLDER-IDENTITY-001` | | Granted | Granted | current primary server/replica/epoch required by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing server refused); renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LEASE-HORIZON-MONO-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001`, `INV-AUTH-HOLDER-IDENTITY-001` | | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-REPLY-001` | -| Revoking | Acked | `AckWorkspaceRevocation` from the primary server/replica at the current epoch, validated by the same RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing/foreign server refused), a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001`, `INV-AUTH-HOLDER-IDENTITY-001` | +| Revoking | Acked | `AckWorkspaceRevocation` from the primary server/replica at the current epoch, validated by the same RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing/foreign server refused), a nonzero HEAD generation, positive granted validity after half the configured/persisted skew on the publisher clock; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001`, `INV-AUTH-HOLDER-IDENTITY-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation; the target may be the same host, with a newly issued epoch and every binding/collision/isolation check retained | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `validateWorkspaceMoveRequest`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-SAME-HOST-CLEAN-MOVE-001` | | 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` | @@ -722,7 +722,7 @@ Notes: | `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-FORCED-MOVE-001` | A forced move is admitted only after the persisted lease horizon and the granted or restart deadline, each plus the clock-skew bound, have passed for the lease the last move issue started (never a predecessor's): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE | | `INV-WS-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry, never the persisted horizon. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE | -| `INV-WS-FORCED-MOVE-HALF-SKEW-001` | The validity the master gives a host with a lease ends half the clock-skew bound before the reported lease expiry. | M2 Granted → Granted (reply); M4 NoLease, Valid → Valid | `core/host/master/workspace_service.go` `leaseFact`; `core/host/volume/workspace_lease.go` `Refresh` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`) | — | ACTIVE | +| `INV-WS-FORCED-MOVE-HALF-SKEW-001` | The validity the master gives a host with a lease ends half the clock-skew bound before the reported lease expiry. | M2 Granted → Granted (reply); M4 NoLease, Valid → Valid | `core/authority/workspace_lease_view.go` `WorkspaceLeaseValidity`, `workspaceLeaseValidityAt`; `core/host/master/workspace_service.go` `leaseFact`; `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/volume/workspace_lease.go` `Refresh` | `TestWorkspaceLeaseFactUsesPublisherClockAndSkew` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceAckUsesGrantedHalfSkewBoundary` (`core/authority/workspace_validity_test.go`); `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`) | — | ACTIVE | | `INV-WS-LOST-RANGE-READOUT-001` | Every issued forced grant the master returns, also on a replay and after a restart, carries the lost range stored in the authority store before the issue, never a recomputed one: see M2 Moved → epoch issued. | M2 lease: Expired → Moved (forced); Moved → epoch issued | `core/authority/workspace_lost_range.go` `recordLostRangeLocked`, `WorkspaceLostRangeReadouts`, `encodeLostRangeEnvelope`; `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/host/master/workspace_head.go` `headFilerMtimeNS`; `core/host/master/workspace_service.go` `grantWithLostRange`, `issuedRecord`; `core/rpc/wsclient/wsclient.go` `Readout` | `TestWorkspaceForcedMoveRecordsTheLostRange`, `TestWorkspaceForcedMoveLostRangeOrdering`, `TestWorkspaceForcedReservationResumeNeedsItsRange` (`core/authority/workspace_lost_range_test.go`); `TestWorkspaceForcedMoveStoresHeadFilerTime` (`core/authority/workspace_lost_range_readout_test.go`); `TestWorkspaceForcedMoveLostRangeOverRPC`, `TestWorkspaceHEADReadsFilerMtime` (`core/host/master/workspace_lost_range_readout_test.go`); `TestReadoutWording` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row3and4_SentAndGranted` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`) | — | ACTIVE | | `INV-WS-LOST-RANGE-QUERY-001` | `QueryWorkspaceLostRange` returns the stored ranges unchanged: every issued forced move's range in issue order, or the single range of a given request id. | M2 lease: Moved → epoch issued (readout) | `core/authority/workspace_lost_range.go` `WorkspaceLostRangeReadouts`; `core/host/master/workspace_service.go` `QueryWorkspaceLostRange`; `core/rpc/wsclient/wsclient.go` `LostRanges`; `cmd/sw-block/workspace.go` `runWorkspaceLostRange` | `TestWorkspaceLostRangeAccumulatesInIssueOrder` (`core/authority/workspace_lost_range_readout_test.go`); `TestLostRangesBindsTheAnswer` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceLostRangeListsAllInOrder` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | | `INV-WS-LOST-RANGE-FAILCLOSED-001` | If an issued forced move's range record is missing or fails its range or HEAD-time checksum, the readout fails: the grant carries no range but the reason, the query returns `DataLoss`, the CLI exits 4; none reports the move as no loss. | M2 lease: Moved → epoch issued | `core/authority/workspace_lost_range.go` `LoadWorkspaceLostRanges`, `decodeLostRangeHeadTimes`, `WorkspaceLostRangeReadouts`; `core/host/master/workspace_service.go` `grantWithLostRange`, `QueryWorkspaceLostRange`; `core/rpc/wsclient/wsclient.go` `classify`, `checkRange`; `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `runWorkspaceLostRange` | `TestWorkspaceLostRangeReadoutFailsClosed`, `TestWorkspaceLostRangeHeadTimeTamperFailsClosed`, `TestWorkspaceLostRangeSkippedWriteIsDetected` (`core/authority/workspace_lost_range_readout_test.go`); `TestForceMoveGrantWithoutRangeIsUnproven` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row7_ReadoutUnproven` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | @@ -755,7 +755,7 @@ Notes: - `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. Extended for a new holder that dies between its grant and its HEAD claim: the move issue starts its lease, admission uses that grant's lease, HEAD is read after admission, an older-epoch HEAD is accepted (its generation and remote LSN may have moved by an earlier holder's late claim), and a returning holder is refused by two fences, its lease-gated attach and the higher HEAD epoch. `WorkspaceTakeover` models one move from A to B and does not cover a second move away from an unclaimed grant; that model check is open and not claimed here. - `INV-WS-LOST-RANGE-READOUT-001`: The HEAD time is the HEAD filer entry's mtime from the filer's `Last-Modified` header on the same read as the HEAD content (1 s resolution). chunkstore writes that mtime from the clock of the host that wrote the entry (the cut); the readout labels it "(publishing host clock as recorded in the filer, 1 s resolution)", and it is not a master time; there is no HEAD format change. The HEAD times sit beside the v1 ranges in the lost-range file with their own checksum, so a binary that predates them still verifies the file; a record without one reads as unknown. The readout reads the ranges loaded at startup: damage after startup shows at the next load. The no-HEAD form ("no remote image exists") is defensive: the master refuses a forced move without a published HEAD. The header is checked against test HTTP servers only; the `chunkstore_integration` test does not assert it. Not in the TLA+ models. - `INV-WS-FORCED-CONFIRM-001`: A client-side rule: the master's own guards (explicit force, admission, expected epoch) are `INV-WS-FORCED-MOVE-001`. The holder's logical replica id is read from `QueryWorkspace` (the lease, or the journal on a rerun). The holder check (`INV-WS-FORCED-CONFIRM-HOLDER-001`) sends that one `QueryWorkspace` RPC; only the move is withheld. -- `INV-WS-FORCED-MOVE-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001`: the persisted lease horizon is at least every grant (`INV-WS-LEASE-HORIZON-001`). blockmaster reads HEAD only after the forced admission holds; HEAD must be the expected holder's at the expected epoch, or any HEAD at an older epoch; the lost range starts at that HEAD's remote LSN: see M2 Expired → Moved (forced) (tests `TestWorkspaceUnclaimedGrantForcedReassignOverRPC`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceForcedMoveRecordsTheLostRange`). The publisher checks the admission again when it issues the move. The host counts its validity from the start of its renewal request: see M4 NoLease, Valid → Valid. The validity is a duration computed on the master's wall clock (`time.Until`); `leaseFact` also caps it at 30 s and uses a 20 s bound when an older persisted lease carries none. +- `INV-WS-FORCED-MOVE-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001`: the persisted lease horizon is at least every grant (`INV-WS-LEASE-HORIZON-001`). blockmaster reads HEAD only after the forced admission holds; HEAD must be the expected holder's at the expected epoch, or any HEAD at an older epoch; the lost range starts at that HEAD's remote LSN: see M2 Expired → Moved (forced) (tests `TestWorkspaceUnclaimedGrantForcedReassignOverRPC`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceForcedMoveRecordsTheLostRange`). The publisher checks the admission again when it issues the move. The host counts its validity from the start of its renewal request: see M4 NoLease, Valid → Valid. The authority-owned `WorkspaceLeaseValidity` computes duration on the publisher clock with its configured TTL and the larger configured/persisted skew, including legacy leases with no stored bound. Renewal admission, RPC replies and revocation ACK admission share that calculation; ACK uses the granted deadline clamped to the durable horizon. `workspaceDetachedGeneration` reads its exact stored seal through `ReadDetachedChunkHead`; `TestWorkspaceRevocationUsesExactStoredSeal` (`cmd/blockvolume/workspace_proof_test.go`) covers valid and refused proofs without publishing. - `INV-WS-LOST-RANGE-READOUT-001`: a stored range holds the kept HEAD's remote LSN; the forced-move barrier as LostUntil, in master time; the kept HEAD's generation (via the move record); and the HEAD entry's filer mtime read with that HEAD, or "unknown". A missing or damaged record is `INV-WS-LOST-RANGE-FAILCLOSED-001`. A failure after the issue (for example the binding reconciliation) is answered `Internal` naming the move ISSUED, never as a refusal: see M2 Moved → epoch issued. `PreviewWorkspaceMove` runs the forced admission, reads HEAD only once admitted, and writes nothing: see M2 Expired → Moved (forced) (tests `TestWorkspaceForcedMovePreviewWritesNothing`, `TestWorkspaceForceMove_Row2_DryRunPreview`). - `INV-WS-LOST-RANGE-UNCERTAIN-001`, `INV-WS-LOST-RANGE-PRE-ISSUE-001`: on a volume already uncertain, every failed move, an admission refusal or a HEAD-read error included, is answered as an unknown outcome and logged as unknown; only the request's own cancellation or deadline stays typed, and an issued move's replay still returns its stored grant: see `INV-AUTH-UNCERTAIN-001` and M2 Uncertain → Uncertain (move answer). - Enforced by reading (no test asserts it): the publisher's second admission check when it issues a forced move (`prepareWorkspaceMoveLocked` calls `forcedMoveAdmissionLocked`). @@ -1060,13 +1060,13 @@ A row that names a function existing only on an open pull request says so ("on # | Term | Meaning | Field(s) | Deciding function (one per side) | Known second derivations to remove | Owner role | |---|---|---|---|---|---| | `TERM-HOLDER-001` Holder identity (the primary of a single-copy workspace volume only; supporting replicas are not holders) | The process that may act as primary of a single-copy workspace volume at an epoch is the pair (server id, replica id) at that epoch. A matching replica id or endpoint alone never names it, and a missing server id is refused. A local-root nonce joins the pair later (pending). | `AssignmentFact` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/control.proto`; `server_id` on [#411](https://github.com/seaweedfs/seaweed-block/pull/411)); `WorkspaceIdentity` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/workspace.proto`; `server_id` on #411); the published line's `PublishedLine.IssuedHost` (`core/authority/workspace_lease_view.go`) and the move journal's `WorkspaceMoveRecord.NewHost` (`core/authority/workspace.go`); the volume's `Config.ServerID`, `Config.ReplicaID` (`core/host/volume/host.go`, from `--server-id`, `--replica-id`); the HEAD `Holder`, written as `/` (`cmd/blockvolume/chunk_remote.go` `chunkHolder`) | Master: `core/host/master/workspace_service.go` `services.holderMatches(volume, replica, server, epoch)`, on #411; it gates `RenewWorkspaceLease` and `AckWorkspaceRevoked`, after the host check of #416, and takes the line's owner server from `core/host/master/workspace_binding.go` `Host.workspaceLineOwner`, on #423, the one owner decision for current and historical lines (through `PublishedLine.Owner`, which the snapshot builder's `expectOwnerForLine` also calls). The line's owner server is carried in the published line; a move's line names the move's new host; placement names the owner only for the initial line; an unknown owner is sent empty and never adopted. A volume that has seen an epoch owned by one server never adopts that epoch for another (this covers replays). The safety rule is the refusal to adopt a line naming another server; fencing on a foreign line is defence in depth, and only a process that has adopted a lineage fences, on a strictly newer foreign line. Volume: `core/host/volume/assignment_holder.go` `Host.assignmentNamesSelf`, on #411; called by `applyFact` and `IsSuperseded`. | `Host.applyFact` adopts a fact on the replica id alone. `Host.IsSuperseded` ignores a same-replica line from another server. `Host.recordOtherLine` lets an older line overwrite a newer one. Lease renewals and revocation ACKs carry no server id. All four are removed by #411. The master's status frontends and CSI publish target take the freshest same-replica heartbeat from any server (`ObservationStore.SlotFact` via `statusFrontendsForAssignedVolume`), and the operator's primary node is the placement slot (`serverForReplica`). Both are removed by [#416](https://github.com/seaweedfs/seaweed-block/pull/416), stacked on #411. The master computed the line's owner server twice; #423 makes it one function. | authority (master side); volume host (volume side) | -| `TERM-LEASE-NOW-001` Lease valid now | The holder may act on its workspace lease at this instant only while the guard has not fenced and host monotonic time is before the start of its last successful renewal plus the granted validity. The granted validity is the master expiry less half the clock-skew bound, at most 30 s. | `WorkspaceLease` `ExpiresAtNS`, `MaxClockSkewNS`, and the lease view's durable horizon and granted deadline (`core/authority/workspace_lease_view.go`); `WorkspaceLeaseFact` `valid_for_ns`, `expires_at_ns`, `revoking` (`core/rpc/proto/workspace.proto`); `WorkspaceLeaseGuard` `until`, `fenced` (`core/host/volume/workspace_lease.go`) | Holder: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.permits`. Master: `core/authority/workspace_lease_view.go` `Publisher.RenewWorkspaceLease`. `firstWorkspaceGrant` and `regrantWorkspaceLease` are reached only from it, and only it starts the extender `extendWorkspaceLease`. | `Publisher.AckWorkspaceRevocation` (`core/authority/workspace.go`) checks expiry again inline, without the skew term: open. `leaseFact` (`core/host/master/workspace_service.go`) recomputes the host validity with `time.Now` instead of the publisher's clock, with a 20 s skew fallback, while `RenewWorkspaceLease` refuses a grant on the same term inline: open (one helper for both). `WorkspaceLeaseGuard.drain` checks `now < until` again inline before the ACK, and `WorkspaceLeaseGuard.Refresh` repeats the expiry check of `permits`: open (both should call one predicate). The 30 s TTL is written three times: the publisher's default TTL (`core/authority/authority.go`), the cap in `leaseFact`, and the reply bound in `Refresh`: open. Not a duplicate: `Publisher.forcedMoveBarrierLocked` decides the opposite term, "the lease is over for the master" (the horizon and the deadline each plus the full skew bound), which a forced move and a re-grant need. | authority (grant); volume host (guard) | +| `TERM-LEASE-NOW-001` Lease valid now | The holder may act on its workspace lease at this instant only while the guard has not fenced and host monotonic time is before the start of its last successful renewal plus the granted validity. The granted validity is the master expiry less half the clock-skew bound, capped by the configured TTL. | `WorkspaceLease` `ExpiresAtNS`, `MaxClockSkewNS`, and the lease view's durable horizon and granted deadline (`core/authority/workspace_lease_view.go`); `WorkspaceLeaseFact` `valid_for_ns`, `expires_at_ns`, `revoking` (`core/rpc/proto/workspace.proto`); `WorkspaceLeaseGuard` `until`, `fenced` (`core/host/volume/workspace_lease.go`) | Holder: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.permits`. Master: `core/authority/workspace_lease_view.go` `Publisher.WorkspaceLeaseValidity` / `workspaceLeaseValidityAt` is shared by renewal admission, `leaseFact` and `AckWorkspaceRevocation`. `WorkspaceLeaseValidity` reads the publisher clock; its leaf calculation uses the larger configured/persisted skew and configured TTL. `Publisher.RenewWorkspaceLease`. `firstWorkspaceGrant` and `regrantWorkspaceLease` are reached only from it, and only it starts the extender `extendWorkspaceLease`. | `WorkspaceLeaseGuard.drain` checks `now < until` again inline before the ACK, and `WorkspaceLeaseGuard.Refresh` repeats the expiry check of `permits`: open (both should call one predicate). The host reply sanity bound in `Refresh` still repeats the publisher's default 30 s TTL: open. Not a duplicate: `Publisher.forcedMoveBarrierLocked` decides the opposite term, "the lease is over for the master" (the horizon and the deadline each plus the full skew bound), which a forced move and a re-grant need. | authority (grant); volume host (guard) | | `TERM-SERVING-001` Serving / ready | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now and its durable backend is operational. Without a granted lease it holds at the gate and exits 75 after the start-time wait. | `frontend.Projection.Healthy`; the `StorageBackend` operational flag and its evidence, reported as `VolumeStatus.Operational` (`core/frontend/durable`); `StatusProjection.FrontendPrimaryReady` (and `NotReadyReason`, on [#410](https://github.com/seaweedfs/seaweed-block/pull/410)); the ALUA and ANA state; `HeartbeatSlot.frontends` | Authority side: `core/host/volume/projection_bridge.go` `AdapterProjectionView.projectionWithSupersede`, which ANDs in `WorkspaceLeaseGuard.permits` for workspace volumes. Storage side: the `StorageBackend` operational flag (`core/frontend/durable/storage_adapter.go`), written only by `SetOperational` and read by `readyCheck`. The one decision of both sides together is `StorageBackend.AdmitsIO` (the guarded AND), read by the status, the frontend start gate and every I/O: on #410 (today `StorageBackend.gate` on `main`). | `StatusServer.authorityProjection` derives `FrontendPrimaryReady` from the authority view alone, and it repeats the supersede and supporting tests that `Healthy` already contains. #410 adds the backend half in `statusProjection`; the repeated tests remain open. The frontends listen whether or not the backend admits I/O: #410 holds them in `awaitBackendAdmitsIO` until it does. #410 replaces its earlier `backendAdmitsIO` (which read only `VolumeStatus.Operational`) with `StorageBackend.AdmitsIO`. A later lease fence ends the process on [#409](https://github.com/seaweedfs/seaweed-block/pull/409). `projectionALUAProvider.ALUAState` and `projectionANAProvider.ANAState` (`cmd/blockvolume`) follow the projection only: open. The start-time wait (`chunkAuthorityWait`; `ProviderConfig.ChunkAssignmentTimeout`, 30 s by default) ends once, and the process then stays up without serving: #409 makes it exit 75. iSCSI reports a not-ready or busy backend as a medium error, while NVMe retries the same error: [#415](https://github.com/seaweedfs/seaweed-block/pull/415) (`frontend.ClassifyBackendError`). The heartbeat `Frontends` are set when the listeners start and cleared only at shutdown: open. | volume host | | `TERM-STOP-SUPERSEDED-001` Superseded | A newer published line for this volume names another holder (another replica, or the same replica on another server) at or above this process's epoch and endpoint version. From then on the process is not healthy. | `Host.lastOther` (an `AssignmentFact`); the process's own epoch and endpoint version | Volume: `core/host/volume/host.go` `Host.IsSuperseded`. Its same-replica branch, and the ordered `recordOtherLine` it reads, are on #411. | The status repeat listed under `TERM-SERVING-001`. `Host.IsCurrentReplicaSuperseded` (on #409) and `Host.promotionReady` call `IsSuperseded` with other lineages. They are wrappers, not second derivations. | volume host | | `TERM-STOP-LEASE-FENCED-001` Lease fenced / revoked | The lease guard has latched: its deadline passed, a reply was invalid or late, the lease is revoking, or the process is stopping. A fenced guard never reopens. The host drains, and only when the lease was revoked does it acknowledge with the HEAD generation. | `WorkspaceLeaseGuard` `fenced`, `cause`, `revoked` (`core/host/volume/workspace_lease.go`) | Volume: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.fenceLocked`, the one writer of `fenced`; it is read through `permits`. | `Host.FenceWorkspaceLease` and `runWorkspaceLease` (`core/host/volume/workspace_runtime.go`) set `fenced` directly, with no cause, and keep a second latch, `Host.workspaceLeaseFenced`: open. On `main` a guard fence ends the process with status 0: #409 makes it exit 75. | volume host | | `TERM-STOP-HEAD-FENCED-001` HEAD fenced | HEAD shows a higher epoch, or another holder at this epoch. The chunk layer latches fenced and publishes nothing more, and the backend refuses I/O as stale. | HEAD `Epoch`, `Holder`, `Gen`; `chunkLayerImpl` `fenced` (`core/storage`) | Volume: `core/storage/chunk_layer.go` `chunkLayerImpl.supersededBy`. | `ClaimChunkHead` (`core/storage/chunk_restore.go`) repeats the comparison inline: open. Four cut and detach paths in `chunk_layer.go` set `fenced` directly, next to the setter `fencePublication`: open (one setter). A HEAD fence after startup ends the process with 78 (`head_fenced`): on #410. A refused startup claim exits with 78: on #409. | chunk layer | | `TERM-STOP-STALE-ROOT-001` Stale local root | An existing local root whose HEAD another holder has published is refused before the claim and never served. The process stays up without serving. | HEAD `Holder`; `ProviderConfig.ChunkHolder` | Volume: the `PrepareRestore` check inside `DurableProvider.newChunkLayer` (`core/frontend/durable/provider_chunk.go`). It is not a named function: open. | It compares the holder only, so a rolled-back root of the same holder passes: pending the local-root nonce. | volume host | -| `TERM-STOP-SEALED-001` Sealed | HEAD is detached by this holder at this epoch with a matching `DetachedBy` proof (generation, epoch, holder). The sealing process never reopens it, and only that proof licenses a clean move. | HEAD `State`, `DetachedBy` `Gen`, `Epoch`, `Holder` | Volume: `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead`. Master: `core/host/master/workspace_head.go` `NewWorkspaceHEADReader`, whose reader checks the proof before `workspaceHeadAdmits` sees the HEAD. | `workspaceDetachedGeneration` (`cmd/blockvolume/workspace_lease.go`) reimplements the proof check for the revocation ACK: open. The sealed-reopen test in `ClaimChunkHead` checks state, epoch and holder without the proof: open. | chunk layer (volume side); authority (master side) | +| `TERM-STOP-SEALED-001` Sealed | HEAD is detached by this holder at this epoch with a matching `DetachedBy` proof (generation, epoch, holder). The sealing process never reopens it, and only that proof licenses a clean move. | HEAD `State`, `DetachedBy` `Gen`, `Epoch`, `Holder` | Volume: `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead`. Master: `core/host/master/workspace_head.go` `NewWorkspaceHEADReader`, whose reader checks the proof before `workspaceHeadAdmits` sees the HEAD. | `workspaceDetachedGeneration` (`cmd/blockvolume/workspace_lease.go`) delegates revocation ACK proof to `ReadDetachedChunkHead`, with `TestWorkspaceRevocationUsesExactStoredSeal` coverage. The sealed-reopen test in `ClaimChunkHead` checks state, epoch and holder without the proof: open. | chunk layer (volume side); authority (master side) | | `TERM-STOP-EXIT-001` Exit class of a stopped workspace primary | A workspace primary that stops ends its process with one latched class. 75 means retry (start-time wait exhausted, lease fence, unconfirmed ACK). 78 means superseded (the line names another holder). 0 is used only after an ACKed revocation or a signal. | `workspaceExit` `code`, `reason`; the `processExit` decision (`cmd/blockvolume/process_exit.go`, on #409) | Volume: `cmd/blockvolume/process_exit.go` `workspaceRetryOutcome`, on #409. `processExit.choose` latches the first outcome. | `chooseChunkStartupExit` (on #409) turns 75 into 78 on a refused HEAD claim (`DurableProvider.ChunkStartupSuperseded`), outside `workspaceRetryOutcome`: open. On #409 alone, "superseded" means another replica; the same replica on another server counts only with #411's `IsSuperseded`: open until both merge. | volume host | | `TERM-ONE-PROCESS-001` One live process per holder | At most one blockvolume process serves a holder at a time. Today a second process is refused only when it opens the same store file. A local-root nonce in the holder identity is to close the other cases (pending). | The store file `<--durable-root>/.bin` (`cmd/blockvolume/main.go` `durableCreateGeometry`); its exclusive OS file lock; the HEAD `Holder` | Volume: `core/storage/volume_lock.go` `LockWALStoreFile`: an exclusive, non-blocking `flock` in `volume_lock_unix.go` and an exclusive, fail-immediately `LockFileEx` in `volume_lock_windows.go`. It is taken by v3 create and open and by the read-only open. | Not a second derivation but the lock's limit: it covers one file. A second process is not refused when it uses another `--durable-root`, runs on another host with the same server id, or runs on a copied root. Two such processes with one holder string both pass `ClaimChunkHead` and both renew. A failed CAS against the other process's same-epoch, same-holder HEAD is treated as a conflict, not a fence (`publicationOwnerChanged`): open, pending the local-root nonce. #416 refuses a server id that heartbeats from another host's address (`refuseServerIDFromOtherHost`), which covers part of this. The master's grants carry no per-process identity: open. | storage engine | From 402a0d747966a0b76a11d2c95cc882114a13a127 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 08:49:11 -0800 Subject: [PATCH 13/16] refactor(workspace): defer seal proof integration until holder update --- .../cmd/blockvolume/workspace_lease.go | 6 +- .../cmd/blockvolume/workspace_proof_test.go | 58 ------------------- seaweed-block/docs/design/invariants.md | 4 +- 3 files changed, 7 insertions(+), 61 deletions(-) delete mode 100644 seaweed-block/cmd/blockvolume/workspace_proof_test.go diff --git a/seaweed-block/cmd/blockvolume/workspace_lease.go b/seaweed-block/cmd/blockvolume/workspace_lease.go index 4362b51e82..b0724b8288 100644 --- a/seaweed-block/cmd/blockvolume/workspace_lease.go +++ b/seaweed-block/cmd/blockvolume/workspace_lease.go @@ -60,9 +60,13 @@ func workspaceDetachedGeneration(ctx context.Context, remoteFor func(string) (st if err != nil { return 0, err } - head, err := storage.ReadDetachedChunkHead(ctx, remote, id.Epoch, holder) + head, err := remote.GetHead(ctx) if err != nil { return 0, err } + proof := head.DetachedBy + if head.Gen == 0 || head.Epoch != id.Epoch || head.Holder != holder || head.State != storage.ChunkHeadDetached || proof == nil || proof.Gen != head.Gen || proof.Epoch != head.Epoch || proof.Holder != head.Holder { + return 0, fmt.Errorf("workspace shutdown has no matching stored detached HEAD") + } return head.Gen, nil } diff --git a/seaweed-block/cmd/blockvolume/workspace_proof_test.go b/seaweed-block/cmd/blockvolume/workspace_proof_test.go deleted file mode 100644 index 6bbbf4e56d..0000000000 --- a/seaweed-block/cmd/blockvolume/workspace_proof_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package main - -import ( - "context" - "errors" - control "github.com/seaweedfs/seaweed-block/core/rpc/control" - "github.com/seaweedfs/seaweed-block/core/storage" - "testing" -) - -type workspaceProofRemote struct { - storage.ChunkRemote - head storage.ChunkHead - err error - reads int -} - -func (r *workspaceProofRemote) GetHead(context.Context) (storage.ChunkHead, error) { - r.reads++ - return r.head, r.err -} - -func TestWorkspaceRevocationUsesExactStoredSeal(t *testing.T) { - for _, name := range []string{"valid", "zero-epoch", "empty-holder", "active", "proof-gen", "foreign-holder", "read-error"} { - t.Run(name, func(t *testing.T) { - h := storage.ChunkHead{Gen: 7, Epoch: 2, Holder: "s/r", State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Gen: 7, Epoch: 2, Holder: "s/r"}} - id := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 2} - holder := "s/r" - r := &workspaceProofRemote{head: h} - switch name { - case "zero-epoch": - id.Epoch = 0 - r.head.Epoch = 0 - r.head.DetachedBy.Epoch = 0 - case "empty-holder": - holder = "" - r.head.Holder = "" - r.head.DetachedBy.Holder = "" - case "active": - r.head.State = storage.ChunkHeadActive - case "proof-gen": - r.head.DetachedBy.Gen = 6 - case "foreign-holder": - r.head.Holder = "other/r" - case "read-error": - r.err = errors.New("HEAD answer lost") - } - gen, err := workspaceDetachedGeneration(context.Background(), func(string) (storage.ChunkRemote, error) { return r, nil }, id, holder) - if name == "valid" { - if err != nil || gen != 7 || r.reads != 1 { - t.Fatalf("stored seal: gen%d reads%d err%v", gen, r.reads, err) - } - } else if err == nil || gen != 0 { - t.Fatalf("unproven ACK gen%d err%v", gen, err) - } - }) - } -} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 3d06edcae3..532ac12870 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -755,7 +755,7 @@ Notes: - `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. Extended for a new holder that dies between its grant and its HEAD claim: the move issue starts its lease, admission uses that grant's lease, HEAD is read after admission, an older-epoch HEAD is accepted (its generation and remote LSN may have moved by an earlier holder's late claim), and a returning holder is refused by two fences, its lease-gated attach and the higher HEAD epoch. `WorkspaceTakeover` models one move from A to B and does not cover a second move away from an unclaimed grant; that model check is open and not claimed here. - `INV-WS-LOST-RANGE-READOUT-001`: The HEAD time is the HEAD filer entry's mtime from the filer's `Last-Modified` header on the same read as the HEAD content (1 s resolution). chunkstore writes that mtime from the clock of the host that wrote the entry (the cut); the readout labels it "(publishing host clock as recorded in the filer, 1 s resolution)", and it is not a master time; there is no HEAD format change. The HEAD times sit beside the v1 ranges in the lost-range file with their own checksum, so a binary that predates them still verifies the file; a record without one reads as unknown. The readout reads the ranges loaded at startup: damage after startup shows at the next load. The no-HEAD form ("no remote image exists") is defensive: the master refuses a forced move without a published HEAD. The header is checked against test HTTP servers only; the `chunkstore_integration` test does not assert it. Not in the TLA+ models. - `INV-WS-FORCED-CONFIRM-001`: A client-side rule: the master's own guards (explicit force, admission, expected epoch) are `INV-WS-FORCED-MOVE-001`. The holder's logical replica id is read from `QueryWorkspace` (the lease, or the journal on a rerun). The holder check (`INV-WS-FORCED-CONFIRM-HOLDER-001`) sends that one `QueryWorkspace` RPC; only the move is withheld. -- `INV-WS-FORCED-MOVE-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001`: the persisted lease horizon is at least every grant (`INV-WS-LEASE-HORIZON-001`). blockmaster reads HEAD only after the forced admission holds; HEAD must be the expected holder's at the expected epoch, or any HEAD at an older epoch; the lost range starts at that HEAD's remote LSN: see M2 Expired → Moved (forced) (tests `TestWorkspaceUnclaimedGrantForcedReassignOverRPC`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceForcedMoveRecordsTheLostRange`). The publisher checks the admission again when it issues the move. The host counts its validity from the start of its renewal request: see M4 NoLease, Valid → Valid. The authority-owned `WorkspaceLeaseValidity` computes duration on the publisher clock with its configured TTL and the larger configured/persisted skew, including legacy leases with no stored bound. Renewal admission, RPC replies and revocation ACK admission share that calculation; ACK uses the granted deadline clamped to the durable horizon. `workspaceDetachedGeneration` reads its exact stored seal through `ReadDetachedChunkHead`; `TestWorkspaceRevocationUsesExactStoredSeal` (`cmd/blockvolume/workspace_proof_test.go`) covers valid and refused proofs without publishing. +- `INV-WS-FORCED-MOVE-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001`: the persisted lease horizon is at least every grant (`INV-WS-LEASE-HORIZON-001`). blockmaster reads HEAD only after the forced admission holds; HEAD must be the expected holder's at the expected epoch, or any HEAD at an older epoch; the lost range starts at that HEAD's remote LSN: see M2 Expired → Moved (forced) (tests `TestWorkspaceUnclaimedGrantForcedReassignOverRPC`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceForcedMoveRecordsTheLostRange`). The publisher checks the admission again when it issues the move. The host counts its validity from the start of its renewal request: see M4 NoLease, Valid → Valid. The authority-owned `WorkspaceLeaseValidity` computes duration on the publisher clock with its configured TTL and the larger configured/persisted skew, including legacy leases with no stored bound. Renewal admission, RPC replies and revocation ACK admission share that calculation; ACK uses the granted deadline clamped to the durable horizon. - `INV-WS-LOST-RANGE-READOUT-001`: a stored range holds the kept HEAD's remote LSN; the forced-move barrier as LostUntil, in master time; the kept HEAD's generation (via the move record); and the HEAD entry's filer mtime read with that HEAD, or "unknown". A missing or damaged record is `INV-WS-LOST-RANGE-FAILCLOSED-001`. A failure after the issue (for example the binding reconciliation) is answered `Internal` naming the move ISSUED, never as a refusal: see M2 Moved → epoch issued. `PreviewWorkspaceMove` runs the forced admission, reads HEAD only once admitted, and writes nothing: see M2 Expired → Moved (forced) (tests `TestWorkspaceForcedMovePreviewWritesNothing`, `TestWorkspaceForceMove_Row2_DryRunPreview`). - `INV-WS-LOST-RANGE-UNCERTAIN-001`, `INV-WS-LOST-RANGE-PRE-ISSUE-001`: on a volume already uncertain, every failed move, an admission refusal or a HEAD-read error included, is answered as an unknown outcome and logged as unknown; only the request's own cancellation or deadline stays typed, and an issued move's replay still returns its stored grant: see `INV-AUTH-UNCERTAIN-001` and M2 Uncertain → Uncertain (move answer). - Enforced by reading (no test asserts it): the publisher's second admission check when it issues a forced move (`prepareWorkspaceMoveLocked` calls `forcedMoveAdmissionLocked`). @@ -1066,7 +1066,7 @@ A row that names a function existing only on an open pull request says so ("on # | `TERM-STOP-LEASE-FENCED-001` Lease fenced / revoked | The lease guard has latched: its deadline passed, a reply was invalid or late, the lease is revoking, or the process is stopping. A fenced guard never reopens. The host drains, and only when the lease was revoked does it acknowledge with the HEAD generation. | `WorkspaceLeaseGuard` `fenced`, `cause`, `revoked` (`core/host/volume/workspace_lease.go`) | Volume: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.fenceLocked`, the one writer of `fenced`; it is read through `permits`. | `Host.FenceWorkspaceLease` and `runWorkspaceLease` (`core/host/volume/workspace_runtime.go`) set `fenced` directly, with no cause, and keep a second latch, `Host.workspaceLeaseFenced`: open. On `main` a guard fence ends the process with status 0: #409 makes it exit 75. | volume host | | `TERM-STOP-HEAD-FENCED-001` HEAD fenced | HEAD shows a higher epoch, or another holder at this epoch. The chunk layer latches fenced and publishes nothing more, and the backend refuses I/O as stale. | HEAD `Epoch`, `Holder`, `Gen`; `chunkLayerImpl` `fenced` (`core/storage`) | Volume: `core/storage/chunk_layer.go` `chunkLayerImpl.supersededBy`. | `ClaimChunkHead` (`core/storage/chunk_restore.go`) repeats the comparison inline: open. Four cut and detach paths in `chunk_layer.go` set `fenced` directly, next to the setter `fencePublication`: open (one setter). A HEAD fence after startup ends the process with 78 (`head_fenced`): on #410. A refused startup claim exits with 78: on #409. | chunk layer | | `TERM-STOP-STALE-ROOT-001` Stale local root | An existing local root whose HEAD another holder has published is refused before the claim and never served. The process stays up without serving. | HEAD `Holder`; `ProviderConfig.ChunkHolder` | Volume: the `PrepareRestore` check inside `DurableProvider.newChunkLayer` (`core/frontend/durable/provider_chunk.go`). It is not a named function: open. | It compares the holder only, so a rolled-back root of the same holder passes: pending the local-root nonce. | volume host | -| `TERM-STOP-SEALED-001` Sealed | HEAD is detached by this holder at this epoch with a matching `DetachedBy` proof (generation, epoch, holder). The sealing process never reopens it, and only that proof licenses a clean move. | HEAD `State`, `DetachedBy` `Gen`, `Epoch`, `Holder` | Volume: `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead`. Master: `core/host/master/workspace_head.go` `NewWorkspaceHEADReader`, whose reader checks the proof before `workspaceHeadAdmits` sees the HEAD. | `workspaceDetachedGeneration` (`cmd/blockvolume/workspace_lease.go`) delegates revocation ACK proof to `ReadDetachedChunkHead`, with `TestWorkspaceRevocationUsesExactStoredSeal` coverage. The sealed-reopen test in `ClaimChunkHead` checks state, epoch and holder without the proof: open. | chunk layer (volume side); authority (master side) | +| `TERM-STOP-SEALED-001` Sealed | HEAD is detached by this holder at this epoch with a matching `DetachedBy` proof (generation, epoch, holder). The sealing process never reopens it, and only that proof licenses a clean move. | HEAD `State`, `DetachedBy` `Gen`, `Epoch`, `Holder` | Volume: `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead`. Master: `core/host/master/workspace_head.go` `NewWorkspaceHEADReader`, whose reader checks the proof before `workspaceHeadAdmits` sees the HEAD. | `workspaceDetachedGeneration` (`cmd/blockvolume/workspace_lease.go`) reimplements the proof check for the revocation ACK: open. The sealed-reopen test in `ClaimChunkHead` checks state, epoch and holder without the proof: open. | chunk layer (volume side); authority (master side) | | `TERM-STOP-EXIT-001` Exit class of a stopped workspace primary | A workspace primary that stops ends its process with one latched class. 75 means retry (start-time wait exhausted, lease fence, unconfirmed ACK). 78 means superseded (the line names another holder). 0 is used only after an ACKed revocation or a signal. | `workspaceExit` `code`, `reason`; the `processExit` decision (`cmd/blockvolume/process_exit.go`, on #409) | Volume: `cmd/blockvolume/process_exit.go` `workspaceRetryOutcome`, on #409. `processExit.choose` latches the first outcome. | `chooseChunkStartupExit` (on #409) turns 75 into 78 on a refused HEAD claim (`DurableProvider.ChunkStartupSuperseded`), outside `workspaceRetryOutcome`: open. On #409 alone, "superseded" means another replica; the same replica on another server counts only with #411's `IsSuperseded`: open until both merge. | volume host | | `TERM-ONE-PROCESS-001` One live process per holder | At most one blockvolume process serves a holder at a time. Today a second process is refused only when it opens the same store file. A local-root nonce in the holder identity is to close the other cases (pending). | The store file `<--durable-root>/.bin` (`cmd/blockvolume/main.go` `durableCreateGeometry`); its exclusive OS file lock; the HEAD `Holder` | Volume: `core/storage/volume_lock.go` `LockWALStoreFile`: an exclusive, non-blocking `flock` in `volume_lock_unix.go` and an exclusive, fail-immediately `LockFileEx` in `volume_lock_windows.go`. It is taken by v3 create and open and by the read-only open. | Not a second derivation but the lock's limit: it covers one file. A second process is not refused when it uses another `--durable-root`, runs on another host with the same server id, or runs on a copied root. Two such processes with one holder string both pass `ClaimChunkHead` and both renew. A failed CAS against the other process's same-epoch, same-holder HEAD is treated as a conflict, not a fence (`publicationOwnerChanged`): open, pending the local-root nonce. #416 refuses a server id that heartbeats from another host's address (`refuseServerIDFromOtherHost`), which covers part of this. The master's grants carry no per-process identity: open. | storage engine | From 115ae3651a95ea4d0ca5430291c7e8e686672183 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 08:59:22 -0800 Subject: [PATCH 14/16] test(workspace): document ACK validity edge and horizon controls --- .../core/authority/workspace_validity_test.go | 28 +++++++++++++++---- .../core/host/master/workspace_skew_test.go | 1 + .../docs/design/agent-workspace-design.md | 2 +- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/authority/workspace_validity_test.go b/seaweed-block/core/authority/workspace_validity_test.go index dcce84f5b4..96e8e74a47 100644 --- a/seaweed-block/core/authority/workspace_validity_test.go +++ b/seaweed-block/core/authority/workspace_validity_test.go @@ -11,14 +11,19 @@ func TestWorkspaceAckUsesGrantedHalfSkewBoundary(t *testing.T) { name string elapsed time.Duration allowed bool + restart bool }{ - {"before", 28*time.Second - time.Nanosecond, true}, - {"at", 28 * time.Second, false}, - {"after", 29 * time.Second, false}, + {"before", 28*time.Second - time.Nanosecond, true, false}, + {"at", 28 * time.Second, false, false}, + {"after", 29 * time.Second, false, false}, + {"horizon-before", 43*time.Second - time.Nanosecond, true, true}, + {"horizon-at", 43 * time.Second, false, true}, + {"horizon-after", 44 * time.Second, false, true}, } { t.Run(tc.name, func(t *testing.T) { disk, _ := newTempStore(t) - now := time.Unix(1000, 0) + start := time.Unix(1000, 0) + now := start p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(4*time.Second)) if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { t.Fatal(err) @@ -30,7 +35,20 @@ func TestWorkspaceAckUsesGrantedHalfSkewBoundary(t *testing.T) { if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { t.Fatal(err) } - now = now.Add(tc.elapsed) + if tc.restart { + // Reopening at +20s gives a restart deadline of +50s, beyond + // the persisted +45s horizon. ACK must stop at +43s. + now = start.Add(20 * time.Second) + p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(4*time.Second)) + p.mu.Lock() + deadline := p.leaseDeadlineLocked("v") + horizon := p.workspace["v"].Lease.ExpiresAtNS + p.mu.Unlock() + if !deadline.After(time.Unix(0, horizon)) { + t.Fatal("fixture deadline does not exceed persisted horizon") + } + } + now = start.Add(tc.elapsed) err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}) if (err == nil) != tc.allowed { t.Fatalf("ACK allowed=%t, want %t: %v", err == nil, tc.allowed, err) diff --git a/seaweed-block/core/host/master/workspace_skew_test.go b/seaweed-block/core/host/master/workspace_skew_test.go index e6a3317d2d..129667348c 100644 --- a/seaweed-block/core/host/master/workspace_skew_test.go +++ b/seaweed-block/core/host/master/workspace_skew_test.go @@ -158,6 +158,7 @@ func TestWorkspaceLeaseFactUsesPublisherClockAndSkew(t *testing.T) { want time.Duration }{ {"legacy-configured-bound", 10 * time.Second, 0, 8 * time.Second}, + {"persisted-smaller-bound", 10 * time.Second, int64(2 * time.Second), 8 * time.Second}, {"persisted-larger-bound", 10 * time.Second, int64(6 * time.Second), 7 * time.Second}, {"configured-ttl-cap", 40 * time.Second, 0, 12 * time.Second}, {"expired", time.Second, 0, 0}, diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 265cde146c..ef5d1db91a 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -358,7 +358,7 @@ stateDiagram-v2 [*] --> Granted: move issue starts the new holder's lease Granted --> Granted: Renew before horizon and deadline (from memory; registered server id, from its registered host) Granted --> Revoking: BeginWorkspaceRevocation - Revoking --> Acked: host acks detached HEAD gen while the lease is valid (from its registered host) + Revoking --> Acked: registered host acks detached HEAD gen; publisher-clock validity after half max(configured, persisted) skew is positive Acked --> Moved: CLEAN move, including same host, new epoch Granted --> Expired: horizon or deadline passes Expired --> Granted: unchanged holder from its registered host, no move/revocation, MAX expiry + skew passed; durable re-grant From f0662dd31f4152fc3a54fdeebec0ac2c95d91178 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 09:08:31 -0800 Subject: [PATCH 15/16] test: an old host on its stale local root exits 78; on a fresh root, 75 Co-Authored-By: Claude Opus 5.5 --- .../procedure_gate_integration_test.go | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go index 5b41a4a7a7..2b65e12024 100644 --- a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go @@ -195,22 +195,22 @@ func TestProcedureForcedMoveWithTheOldHostReturning(t *testing.T) { t.Fatal("the block written after the last cut reads back on s2; the page says it is lost") } - // The old host returns with its old local root, and a supervisor starts - // it again after it exits. Each time it must not take s2's line as its - // own (a holder is server and replica), report its frontend ready or - // listen for I/O, and it must log a refusal and exit with status 75. - back := env.oldHostRefuses(t, "blockvolume-s1-back", env.hosts["s1"], e2) - time.Sleep(5 * time.Second) // RestartSec of the example unit - restarted := env.oldHostRefuses(t, "blockvolume-s1-restarted", env.hosts["s1"], e2) - // Control: on a fresh local root there is no stale root to refuse, and - // it must still refuse s2's line. + // The old host returns with its old local root. It must not take s2's + // line as its own (a holder is server and replica), report its frontend + // ready or listen for I/O; it logs a refusal and exits with status 78, the + // no-restart class for a local root older than HEAD (the example unit + // does not restart on 78). Started again by hand, it does the same. + back := env.oldHostRefuses(t, "blockvolume-s1-back", env.hosts["s1"], e2, 78) + again := env.oldHostRefuses(t, "blockvolume-s1-started-again", env.hosts["s1"], e2, 78) + // Control: on a fresh local root there is no stale root, so its refusal + // is the identity check alone; it exits 75, the retry class. fresh := env.hosts["s1"] fresh.root = fresh.root + "-fresh" - freshRoot := env.oldHostRefuses(t, "blockvolume-s1-fresh-root", fresh, e2) + freshRoot := env.oldHostRefuses(t, "blockvolume-s1-fresh-root", fresh, e2, 75) // A line carries its owner and that owner's endpoints: every line // delivered at the forced epoch, to the new owner and to each returning // old host alike, carries s2's own endpoints, never another host's. - if bad := wrongOwnerEndpoints(e2, env.hosts["s2"], nw, back, restarted, freshRoot); len(bad) > 0 { + if bad := wrongOwnerEndpoints(e2, env.hosts["s2"], nw, back, again, freshRoot); len(bad) > 0 { t.Errorf("epoch-%d deliveries not proven to carry s2's endpoints (want data=%s ctrl=%s in every recipient's lines):\n%s", e2, env.hosts["s2"].data, env.hosts["s2"].ctrl, strings.Join(bad, "\n")) } @@ -394,10 +394,10 @@ func exitCode(err error) int { } // oldHostRefuses starts the old holder b after the volume moved to epoch e2 -// on another host, and returns it. While it runs it must not adopt the new line, report its -// frontend ready or listen; it must log a refusal and exit with status 75 -// (a later change may give a stale local root its own status). -func (env *handoffEnv) oldHostRefuses(t *testing.T, name string, b bvHost, e2 uint64) *daemon { +// on another host, and returns it. While it runs it must not adopt the new +// line, report its frontend ready or listen; it must log a refusal and exit +// with wantExit. +func (env *handoffEnv) oldHostRefuses(t *testing.T, name string, b bvHost, e2 uint64, wantExit int) *daemon { t.Helper() d := env.h.start(t, name, env.h.volume, env.volArgsFor(b)...) var failures []string @@ -418,8 +418,8 @@ func (env *handoffEnv) oldHostRefuses(t *testing.T, name string, b bvHost, e2 ui case <-time.After(500 * time.Millisecond): } } - if err := d.wait(5 * time.Second); exitCode(err) != 75 { - failures = append(failures, fmt.Sprintf("it did not exit with status 75: %v", err)) + if err := d.wait(5 * time.Second); exitCode(err) != wantExit { + failures = append(failures, fmt.Sprintf("it did not exit with status %d: %v", wantExit, err)) } if !d.has("refusing to attach volume=v1") && !d.has("workspace lease: stale authority") && !d.has("foreign assignment") { failures = append(failures, "it logged no refusal (stale root, stale authority, or another server's assignment)") From 440f9eff3cff3d7b0fc0708c06ecfb4d13a4a45c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 09:26:58 -0800 Subject: [PATCH 16/16] test: the returning old host exits 75 on its old root and on a fresh root, and the unit restarts it Co-Authored-By: Claude Opus 5.5 --- .../procedure_gate_integration_test.go | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go index 2b65e12024..640bb67930 100644 --- a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go @@ -195,15 +195,16 @@ func TestProcedureForcedMoveWithTheOldHostReturning(t *testing.T) { t.Fatal("the block written after the last cut reads back on s2; the page says it is lost") } - // The old host returns with its old local root. It must not take s2's - // line as its own (a holder is server and replica), report its frontend - // ready or listen for I/O; it logs a refusal and exits with status 78, the - // no-restart class for a local root older than HEAD (the example unit - // does not restart on 78). Started again by hand, it does the same. - back := env.oldHostRefuses(t, "blockvolume-s1-back", env.hosts["s1"], e2, 78) - again := env.oldHostRefuses(t, "blockvolume-s1-started-again", env.hosts["s1"], e2, 78) + // The old host returns with its old local root, and the example unit + // (Restart=on-failure, RestartSec=5s) starts it again after it exits, + // until its start limit. Each time it must not take s2's line as its own + // (a holder is server and replica), report its frontend ready or listen + // for I/O; it logs a refusal and exits with status 75. + back := env.oldHostRefuses(t, "blockvolume-s1-back", env.hosts["s1"], e2, 75) + time.Sleep(5 * time.Second) // RestartSec of the example unit + again := env.oldHostRefuses(t, "blockvolume-s1-restarted", env.hosts["s1"], e2, 75) // Control: on a fresh local root there is no stale root, so its refusal - // is the identity check alone; it exits 75, the retry class. + // is the identity check alone; it also exits 75. fresh := env.hosts["s1"] fresh.root = fresh.root + "-fresh" freshRoot := env.oldHostRefuses(t, "blockvolume-s1-fresh-root", fresh, e2, 75)