From f55f9f8b02a35b415a906b379a120effc5901cae Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 16:28:53 -0800 Subject: [PATCH 01/23] test(blockvolume): 1.0.1 red tests: a line whose epoch HEAD never reached is deletable without a revoke INV-WS-DELETE-NO-LIVE-HOLDER-001; red on main by design (the fix is the live-holder change). Three routes, none needs root, each asserted by the master's authority record (the line) and HEAD before any delete: - S1: a first start with the store down (line at 1, no lease, HEAD 0); - S2: a first start stopped at the lease grant (line and lease at 1, HEAD 0; the next candidate when the claim wins); - a clean move whose target never starts (line and lease at e+1, HEAD at e, detached). volume-delete without a revoke must complete (at once, after the lease lapsed, after a master restart), a later start must not claim, and a racing start and delete have one winner. Guards, green on main: a never-attached target is deletable and fenced, and a claimed target stays refused after a master restart. Co-Authored-By: Claude Opus 5.5 --- .../neverstarted_delete_integration_test.go | 424 ++++++++++++++++++ 1 file changed, 424 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go b/seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go new file mode 100644 index 0000000000..24b1000930 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go @@ -0,0 +1,424 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" +) + +// INV-WS-DELETE-NO-LIVE-HOLDER-001, the guard half: a restore target created but never +// attached (no blockvolume ever started for it) is deletable already on 1.0. +// volume-delete completes without a revoke, its HEAD becomes a deleted +// tombstone, and the source volume and its snapshot are untouched. The 1.0.1 +// red half is a target whose blockvolume started, was assigned and exited +// before it claimed HEAD (the TestNeverStartedLine... tests below). +func TestNeverAttachedRestoreTargetIsDeletable(t *testing.T) { + env := startHandoffEnvWith(t, 1, []string{"v2"}) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + holder := env.start(t, "blockvolume-v1", "s1") + env.adopt(t, holder, "s1") + env.writeBlock(t, "s1", 0, cutCrashBlock('N', 0)) + env.snapshot(t, "s1", "v1", "s1") + + // The target exists in the catalog; its blockvolume never starts. + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + + out, errOut, code := env.h.run(t, "ops", "chunk", "volume-delete", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC, + "--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-v2-never-started") + var del struct{ Completed bool } + if code != 0 || json.Unmarshal([]byte(out), &del) != nil || !del.Completed { + t.Fatalf("volume-delete of a never-attached target must complete; exit %d:\n%s\n%s", code, out, errOut) + } + shown, _, _ := env.h.run(t, "ops", "chunk", "show", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + if !strings.Contains(shown, `"state":"deleted"`) { + t.Fatalf("the deleted target's HEAD is not a deleted tombstone:\n%s", shown) + } + // The source and its snapshot are untouched. + if got := env.readBlock(t, "s1", 0); string(got) != string(cutCrashBlock('N', 0)) { + t.Fatalf("the source's block changed") + } + if snaps := env.snapshots(t, "v1", ""); len(snaps) != 1 { + t.Fatalf("the source has %d snapshots after the target's delete; want 1", len(snaps)) + } +} + +// 1.0.1 (INV-WS-DELETE-NO-LIVE-HOLDER-001; the fence of NeverStarted -> Deleting): once a +// never-attached target's delete is admitted, a late start of its blockvolume +// must not claim it: the process exits without serving and the catalog still +// says deleted. Recorded on 1.0 to see where it stands. +func TestNeverStartedDeleteFencesALateStart(t *testing.T) { + env := startHandoffEnvWith(t, 1, []string{"v2"}) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + holder := env.start(t, "blockvolume-v1", "s1") + env.adopt(t, holder, "s1") + env.writeBlock(t, "s1", 0, cutCrashBlock('L', 0)) + env.snapshot(t, "s1", "v1", "s1") + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + out, errOut, code := env.h.run(t, "ops", "chunk", "volume-delete", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC, + "--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-v2-late") + if code != 0 { + t.Fatalf("volume-delete of a never-attached target: exit %d:\n%s\n%s", code, out, errOut) + } + b := env.hosts["n-v2"] + late := env.h.start(t, "blockvolume-v2-late", env.h.volume, env.volArgsFor(b)...) + err := late.wait(60 * time.Second) + served := late.has("adopted as PRIMARY") || volumeFrontendReady(b.status, "v2") + shown, _, _ := env.h.run(t, "ops", "chunk", "show", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + t.Logf("late start after the delete: exit %v, served %v, HEAD %s", err, served, firstLine(shown)) + if served || err == nil || strings.Contains(fmt.Sprint(err), "still running") || !strings.Contains(shown, `"state":"deleted"`) { + t.Fatalf("1.0.1: a start after the delete must exit without claiming or serving and leave the volume deleted; exit %v, served %v, HEAD:\n%s", err, served, shown) + } +} + +// 1.0.1 (INV-WS-DELETE-NO-LIVE-HOLDER-001; the race): a start of a never-attached target and its +// volume-delete run at the same time, five times. Exactly one wins each time: +// either the volume is deleted and the process never served, or the process +// claimed and served and the delete is refused as for a live holder. +func TestNeverStartedDeleteRacesAStart(t *testing.T) { + targets := []string{"v2", "v3", "v4", "v5", "v6"} + env := startHandoffEnvWith(t, 1, targets) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + holder := env.start(t, "blockvolume-v1", "s1") + env.adopt(t, holder, "s1") + env.writeBlock(t, "s1", 0, cutCrashBlock('R', 0)) + env.snapshot(t, "s1", "v1", "s1") + for _, v := range targets { + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", v, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + b := env.hosts["n-"+v] + type delResult struct { + out string + code int + } + deleted := make(chan delResult, 1) + d := env.h.start(t, "blockvolume-"+v+"-race", env.h.volume, env.volArgsFor(b)...) + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) + defer cancel() + out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "volume-delete", "--volume", v, "--chunk-filer", env.cluster.filerGRPC, + "--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-"+v+"-race") + if err != nil { + code = -1 + } + deleted <- delResult{out + errOut, code} + }() + r := <-deleted + _ = d.wait(30 * time.Second) + served := d.has("adopted as PRIMARY") || volumeFrontendReady(b.status, v) + shown, _, _ := env.h.run(t, "ops", "chunk", "show", "--volume", v, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + isDeleted := strings.Contains(shown, `"state":"deleted"`) + t.Logf("%s: delete exit %d, served %v, HEAD deleted %v: %s", v, r.code, served, isDeleted, firstLine(r.out)) + switch { + case r.code == 0 && isDeleted && !served: + case r.code != 0 && served && !isDeleted: + default: + t.Errorf("1.0.1: %s: not exactly one winner: delete exit %d, served %v, HEAD deleted %v", v, r.code, served, isDeleted) + } + d.kill(t) + } +} + +func (env *handoffEnv) workspaceShow(t *testing.T, v string) string { + out, errOut, _ := env.h.run(t, "ops", "workspace", "show", "--master", env.h.masterAddr, "--volume", v) + return out + errOut +} + +func (env *handoffEnv) deleteNoRevoke(ctx context.Context, v, request string) (string, int) { + out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "volume-delete", "--volume", v, "--chunk-filer", env.cluster.filerGRPC, + "--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", request) + if err != nil { + code = -1 + } + return out + errOut, code +} + +// lineOf returns the master's durable authority record for v (the line: +// replica, epoch, and any workspace lease), as stored in --authority-store. +func (env *handoffEnv) lineOf(t *testing.T, v string) string { + t.Helper() + dir := "" + for i, a := range env.masterArgs { + if a == "--authority-store" && i+1 < len(env.masterArgs) { + dir = env.masterArgs[i+1] + } + } + data, err := os.ReadFile(filepath.Join(dir, v+".v3auth.json")) + if os.IsNotExist(err) { + return "(no line)" + } + if err != nil { + t.Fatal(err) + } + return strings.Join(strings.Fields(string(data)), " ") +} + +// requireNeverStarted checks the state by its facts: the master's line for +// v is at epoch e (with or without a lease, as lease says) and HEAD is below +// it (epoch headEpoch). +func (env *handoffEnv) requireNeverStarted(t *testing.T, v string, e, headEpoch uint64, lease bool) { + t.Helper() + line, head := env.lineOf(t, v), env.headOf(t, v) + ok := strings.Contains(line, fmt.Sprintf(`"Epoch":%d,`, e)) && strings.Contains(head, fmt.Sprintf(`"epoch":%d,`, headEpoch)) && + strings.Contains(line, `"Lease":`) == lease + if !ok { + t.Fatalf("setup: %s is not a line at epoch %d (lease %v) over HEAD at epoch %d:\nline: %s\nHEAD: %s", v, e, lease, headEpoch, line, head) + } + t.Logf("%s: line %s\nHEAD %s", v, line, head) +} + +// strandStoreDown (S1): v's first start runs with the store (filer) down. +// The process heartbeats and the master writes the line at epoch 1; local +// readiness blocks before the assignment is applied, no lease is granted, +// and the process exits. The filer comes back. Line at 1, no lease, HEAD 0. +func (env *handoffEnv) strandStoreDown(t *testing.T, v string) { + t.Helper() + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", v, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + env.cluster.stopProc(t, "filer") + d := env.h.start(t, "blockvolume-"+v+"-store-down", env.h.volume, env.volArgsFor(env.hosts["n-"+v])...) + err := d.wait(120 * time.Second) + env.cluster.restartProc(t, "filer") + w4WaitTCP(t, env.cluster.filerGRPC, 30*time.Second) + if err == nil || d.has("adopted as PRIMARY") { + t.Fatalf("setup: %s's start with the store down exited %v, adopted %v", v, err, d.has("adopted as PRIMARY")) + } + env.requireNeverStarted(t, v, 1, 0, false) +} + +// strandAtGrant (S2): v's first start with the right flags is stopped +// (SIGSTOP) the moment the master shows its lease granted, after the +// adoption and before the HEAD claim, then killed. Line at 1 with a granted +// lease, HEAD 0. When the claim wins the race the next candidate is tried; +// it returns the stranded volume. +func (env *handoffEnv) strandAtGrant(t *testing.T, candidates ...string) string { + t.Helper() + for _, v := range candidates { + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", v, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + d := env.h.start(t, "blockvolume-"+v+"-stopped-at-grant", env.h.volume, env.volArgsFor(env.hosts["n-"+v])...) + deadline := time.Now().Add(60 * time.Second) + for !d.has("adopted as PRIMARY") && time.Now().Before(deadline) { + time.Sleep(time.Millisecond) + } + for time.Now().Before(deadline) { + out, _, _, _ := runCLI(context.Background(), env.h, "ops", "workspace", "show", "--master", env.h.masterAddr, "--volume", v) + if strings.Contains(out, "lease state: granted") { + break + } + } + if err := d.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatalf("setup: stop %s: %v", v, err) + } + claimed := !strings.Contains(env.headOf(t, v), `"epoch":0,"holder":""`) + _ = d.proc.Signal(syscall.SIGKILL) + _ = d.wait(10 * time.Second) + if claimed { + t.Logf("%s: the claim won the race; trying the next candidate", v) + continue + } + env.requireNeverStarted(t, v, 1, 0, true) + return v + } + t.Fatalf("setup: the claim won the race for every candidate %v", candidates) + return "" +} + +// 1.0.1 red (INV-WS-DELETE-NO-LIVE-HOLDER-001): a line whose epoch HEAD never +// reached has acknowledged nothing, so volume-delete completes WITHOUT a +// revoke; HEAD becomes a deleted tombstone, the source is untouched, and no +// granted lease stays on the deleted volume. Routes, each without root: +// - S1: a first start with the store down (line, no lease); +// - S2: a first start stopped at the lease grant (line and lease), deleted +// at once and again after the lease lapsed (65 s); +// - clean move: the volume moved clean to a target that never starts (a +// line and a lease at the new epoch, HEAD at the old one, detached). +// +// On 1.0 every delete is refused as volume_in_use (live authority needs a +// revocation ACK that no process can give). +func TestNeverStartedLineIsDeletableWithoutARevoke(t *testing.T) { + deleted := func(t *testing.T, env *handoffEnv, v, request string) { + t.Helper() + before := env.workspaceShow(t, v) + out, code := env.deleteNoRevoke(context.Background(), v, request) + var del struct{ Completed bool } + completed := code == 0 && json.Unmarshal([]byte(firstLine(out)), &del) == nil && del.Completed + head, after := env.headOf(t, v), env.workspaceShow(t, v) + t.Logf("delete exit %d, completed %v, HEAD %s\nworkspace show before:\n%s\nafter:\n%s\ndelete output:\n%s", code, completed, head, before, after, out) + if !completed { + t.Fatalf("1.0.1: volume-delete of %s (line above HEAD) must complete without a revoke; exit %d", v, code) + } + if !strings.Contains(head, `"state":"deleted"`) || strings.Contains(after, "lease state: granted") { + t.Fatalf("a completed delete must leave a deleted HEAD and no granted lease") + } + } + t.Run("S1-store-down", func(t *testing.T) { + env := startSourceWithSnapshot(t, "v2") + env.strandStoreDown(t, "v2") + deleted(t, env, "v2", "del-v2-s1") + requireSourceUntouched(t, env) + }) + t.Run("S2-stopped-at-grant", func(t *testing.T) { + env := startSourceWithSnapshot(t, "v3", "v3b", "v3c") + v := env.strandAtGrant(t, "v3", "v3b", "v3c") + deleted(t, env, v, "del-"+v+"-s2") + requireSourceUntouched(t, env) + }) + t.Run("S2-lease-lapsed", func(t *testing.T) { + env := startSourceWithSnapshot(t, "v4", "v4b", "v4c") + v := env.strandAtGrant(t, "v4", "v4b", "v4c") + time.Sleep(65 * time.Second) + deleted(t, env, v, "del-"+v+"-s2-lapsed") + }) + t.Run("clean-move-target-never-started", func(t *testing.T) { + env := startHandoffEnv(t, 2) + must, mustU := fatalOn(t) + old := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, old, "s1") + env.writeBlock(t, "s1", 0, pattern("never-started-move")) + g := env.seal(t, "s1", e) + l := env.sealedLSN(t, e, g) + env.revoke(t, e, g) + must(old.wait(30 * time.Second)) + env.waitAck(t, e, g) + out, _ := env.h.command(t, env.moveClean(e, "s2", "move-v1-1")...) + e2 := mustU(movedEpochTo(out, e, g, l, "s2")) + env.requireNeverStarted(t, "v1", e2, e, true) + deleted(t, env, "v1", "del-v1-moved") + }) +} + +func requireSourceUntouched(t *testing.T, env *handoffEnv) { + t.Helper() + if got := env.readBlock(t, "s1", 0); string(got) != string(cutCrashBlock('A', 0)) { + t.Fatalf("the source's block changed") + } + if snaps := env.snapshots(t, "v1", ""); len(snaps) != 1 { + t.Fatalf("the source has %d snapshots after the target's delete; want 1", len(snaps)) + } +} + +// 1.0.1 red: after that delete, a start of the target with the store up +// must not claim it: it exits without serving and the HEAD stays deleted. +// S1 and S2. +func TestNeverStartedLineDeleteFencesALateStart(t *testing.T) { + for _, c := range []struct { + name string + targets []string + }{ + {"S1-store-down", []string{"v2"}}, + {"S2-stopped-at-grant", []string{"v3", "v3b", "v3c"}}, + } { + t.Run(c.name, func(t *testing.T) { + env := startSourceWithSnapshot(t, c.targets...) + v := c.targets[0] + if c.name == "S1-store-down" { + env.strandStoreDown(t, v) + } else { + v = env.strandAtGrant(t, c.targets...) + } + if out, code := env.deleteNoRevoke(context.Background(), v, "del-"+v+"-late"); code != 0 { + t.Fatalf("1.0.1: volume-delete of %s (line above HEAD): exit %d:\n%s", v, code, out) + } + b := env.hosts["n-"+v] + late := env.h.start(t, "blockvolume-"+v+"-late", env.h.volume, env.volArgsFor(b)...) + err := late.wait(90 * time.Second) + served := volumeFrontendReady(b.status, v) + head := env.headOf(t, v) + if served || err == nil || strings.Contains(fmt.Sprint(err), "still running") || !strings.Contains(head, `"state":"deleted"`) { + t.Fatalf("1.0.1: a start after the delete must exit without claiming or serving; exit %v, served %v, HEAD %s", err, served, head) + } + }) + } +} + +// 1.0.1 red: a start (store up) of an S1 target and its volume-delete race, +// with the start delayed by 0 s to 3 s. Each time exactly one wins: the +// volume is deleted and never served, or it served and the delete was +// refused. With a 3 s lead the delete must win. +func TestNeverStartedLineDeleteRacesAStart(t *testing.T) { + targets := []string{"v2", "v3", "v4", "v5", "v6"} + delays := []time.Duration{0, 0, 200 * time.Millisecond, time.Second, 3 * time.Second} + env := startSourceWithSnapshot(t, targets...) + for i, v := range targets { + env.strandStoreDown(t, v) + b := env.hosts["n-"+v] + type delResult struct { + out string + code int + } + deleted := make(chan delResult, 1) + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) + defer cancel() + out, code := env.deleteNoRevoke(ctx, v, "del-"+v+"-race") + deleted <- delResult{out, code} + }() + time.Sleep(delays[i]) + d := env.h.start(t, "blockvolume-"+v+"-race", env.h.volume, env.volArgsFor(b)...) + r := <-deleted + _ = d.wait(60 * time.Second) + served := volumeFrontendReady(b.status, v) + isDeleted := strings.Contains(env.headOf(t, v), `"state":"deleted"`) + t.Logf("%s (start +%v): delete exit %d, served %v, HEAD deleted %v: %s", v, delays[i], r.code, served, isDeleted, firstLine(r.out)) + switch { + case r.code == 0 && isDeleted && !served: + case r.code != 0 && served && !isDeleted && delays[i] < 3*time.Second: + default: + t.Errorf("1.0.1: %s: want exactly one winner (the delete with a 3 s lead): delete exit %d, served %v, HEAD deleted %v", v, r.code, served, isDeleted) + } + d.kill(t) + } +} + +// 1.0.1 red (master restart, one direction): the master is SIGKILLed and +// restarted between the stranding and the delete; the delete still completes +// without a revoke, from what the master and the HEAD keep durably. S1 and S2. +func TestNeverStartedDeleteAfterAMasterRestart(t *testing.T) { + for _, s2 := range []bool{false, true} { + name := map[bool]string{false: "S1-store-down", true: "S2-stopped-at-grant"}[s2] + t.Run(name, func(t *testing.T) { + env := startSourceWithSnapshot(t, "v2", "v2b", "v2c") + v := "v2" + if s2 { + v = env.strandAtGrant(t, "v2", "v2b", "v2c") + } else { + env.strandStoreDown(t, v) + } + restartKilledMaster(t, env) + out, code := env.deleteNoRevoke(context.Background(), v, "del-"+v+"-after-restart") + if head := env.headOf(t, v); code != 0 || !strings.Contains(head, `"state":"deleted"`) { + t.Fatalf("1.0.1: after a master restart, volume-delete of %s must complete; exit %d, HEAD %s:\n%s", v, code, head, out) + } + }) + } +} + +// Guard, green on 1.0 (master restart, the other direction): a target whose +// holder DID claim its HEAD, was SIGKILLed, and whose lease the restarted +// master no longer holds in memory, is not never-started: volume-delete +// without a revoke and an ACK is refused and the HEAD is not tombstoned. +func TestClaimedTargetAfterAMasterRestartIsNotNeverStarted(t *testing.T) { + env := startSourceWithSnapshot(t, "v2") + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + d := env.startTarget(t, "v2", "blockvolume-v2") + if head := env.headOf(t, "v2"); strings.Contains(head, `"holder":""`) { + t.Fatalf("setup: v2 serves but its HEAD is not claimed: %s", head) + } + d.kill(t) + restartKilledMaster(t, env) + out, code := env.deleteNoRevoke(context.Background(), "v2", "del-v2-claimed") + if head := env.headOf(t, "v2"); code == 0 || strings.Contains(head, `"state":"deleted"`) { + t.Fatalf("a claimed target was deleted without a revoke after a master restart; exit %d, HEAD %s:\n%s", code, head, out) + } +} From 5bf22f98e12da92a2fca126b8cbe61945774bc9e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 06:54:24 -0800 Subject: [PATCH 02/23] fix: a volume whose holder never claimed HEAD is deletable One pure verdict for 'live holder of V' (TERM-LIVE-HOLDER-001): WorkspaceHolderState(line, ACK, HEAD) -> no line, drained, sealed, never started (HEAD below the line's epoch), live, or unknown. The chunk volume delete's admission (MarkVolumeDeleting) reads HEAD before its locks, bounded at 5 s, and admits no line, drained and never started; a sealed HEAD without an ACK, a live one, or an unreadable HEAD is refused as before. The delete's HEAD compare-and-swap to deleting stays the only fence against a claim that lands after the read. The lifecycle DeleteVolume reads no HEAD and keeps refusing a line without an ACK. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/workspace.go | 28 +++++-- .../core/authority/workspace_holder_state.go | 66 +++++++++++++++ .../authority/workspace_holder_state_test.go | 37 +++++++++ seaweed-block/core/host/master/services.go | 35 +++++++- .../workspace_delete_never_started_test.go | 83 +++++++++++++++++++ 5 files changed, 241 insertions(+), 8 deletions(-) create mode 100644 seaweed-block/core/authority/workspace_holder_state.go create mode 100644 seaweed-block/core/authority/workspace_holder_state_test.go create mode 100644 seaweed-block/core/host/master/workspace_delete_never_started_test.go diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 1d6375ceb8..c87f1d031e 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -132,7 +132,16 @@ func (p *Publisher) RecordWorkspacePlacement(ctx context.Context, volume string, // RecordWorkspaceDeletion protects reservation release against live or pending // authority. A current clean ACK is proof of drain; a lease alone is not. -func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string, pendingPlacement bool, persist func() error) error { +// RecordWorkspaceDeletion admits a delete of volume (INV-WS-DELETE-NO-LIVE-HOLDER-001) +// when it has no live holder (TERM-LIVE-HOLDER-001): no line (and no +// placement that may have queued one), a clean revocation ACK for the line, +// or a HEAD below the line's epoch (never started). head is HEAD as the +// caller read it before taking any lock (nil: not read, which refuses a line +// without an ACK, as before); owner is the line's owner "/" +// ("" when unknown), used only to name the refusal. A Sealed HEAD without an +// ACK keeps the ACK rule. The delete's HEAD compare-and-swap to deleting is +// the fence against a claim that lands after the read. +func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string, pendingPlacement bool, head *WorkspaceHead, owner string, persist func() error) error { p.mu.Lock() defer p.mu.Unlock() if err := ctx.Err(); err != nil { @@ -142,12 +151,19 @@ func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string, if s != nil && len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued { return fmt.Errorf("workspace delete: move pending") } - if _, line, ok := p.workspaceLineLocked(volume); ok { - if s == nil || s.Ack == nil || s.Ack.Epoch != line.info.Epoch || s.Ack.ReplicaID != line.info.ReplicaID { - return fmt.Errorf("workspace delete: live authority requires clean revocation ACK: revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete") + _, line, ok := p.workspaceLineLocked(volume) + var ack *WorkspaceRevokeAck + if s != nil { + ack = s.Ack + } + switch v := WorkspaceHolderState(ok, line.info.Epoch, line.info.ReplicaID, owner, ack, head); v { + case HolderNoLine: + if pendingPlacement { + return fmt.Errorf("workspace delete: placement may have queued authority") } - } else if pendingPlacement { - return fmt.Errorf("workspace delete: placement may have queued authority") + case HolderDrained, HolderNeverStarted: + default: + return fmt.Errorf("workspace delete: live authority requires clean revocation ACK: revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete (holder: %s)", v) } return persist() } diff --git a/seaweed-block/core/authority/workspace_holder_state.go b/seaweed-block/core/authority/workspace_holder_state.go new file mode 100644 index 0000000000..779165f527 --- /dev/null +++ b/seaweed-block/core/authority/workspace_holder_state.go @@ -0,0 +1,66 @@ +package authority + +// WorkspaceHolderVerdict is the one answer to "is there a live holder of V" +// (TERM-LIVE-HOLDER-001). The line's holder at epoch e may have acknowledged +// guest writes and may publish exactly when the verdict is Live. +type WorkspaceHolderVerdict int + +const ( + // HolderUnknown: HEAD was not read or could not be read, names a higher + // epoch, or names another holder at the line's epoch. Always refused. + HolderUnknown WorkspaceHolderVerdict = iota + // HolderNoLine: there is no authority line. + HolderNoLine + // HolderDrained: a clean revocation ACK is recorded for the line. + HolderDrained + // HolderSealed: HEAD names the line's holder at its epoch, detached. + HolderSealed + // HolderNeverStarted: HEAD is below the line's epoch. No claim at that + // epoch had applied when HEAD was read, so nothing was acknowledged or + // published under it (no I/O is admitted before the claim), whatever + // lease exists. The delete's HEAD compare-and-swap to deleting fences a + // claim that lands after the read. + HolderNeverStarted + // HolderLive: HEAD names the line's holder at its epoch, active. + HolderLive +) + +func (v WorkspaceHolderVerdict) String() string { + switch v { + case HolderNoLine: + return "no line" + case HolderDrained: + return "drained" + case HolderSealed: + return "sealed" + case HolderNeverStarted: + return "never started" + case HolderLive: + return "live" + } + return "unknown" +} + +// WorkspaceHolderState decides the verdict from durable inputs only: the +// authority line (present, epoch, replica, and its owner "/" +// by the single owner decision; "" when unknown), the recorded revocation +// ACK, and HEAD as read (nil when it was not read or could not be read). +// Pure: no I/O, no state, no clock. It does not depend on master memory, so +// it holds across a blockmaster restart. +func WorkspaceHolderState(linePresent bool, lineEpoch uint64, lineReplica, owner string, ack *WorkspaceRevokeAck, head *WorkspaceHead) WorkspaceHolderVerdict { + switch { + case !linePresent: + return HolderNoLine + case ack != nil && ack.Epoch == lineEpoch && ack.ReplicaID == lineReplica: + return HolderDrained + case head == nil: + return HolderUnknown + case head.Epoch < lineEpoch: + return HolderNeverStarted + case head.Epoch > lineEpoch || owner == "" || head.Holder != owner: + return HolderUnknown + case head.Detached: + return HolderSealed + } + return HolderLive +} diff --git a/seaweed-block/core/authority/workspace_holder_state_test.go b/seaweed-block/core/authority/workspace_holder_state_test.go new file mode 100644 index 0000000000..251b3951cf --- /dev/null +++ b/seaweed-block/core/authority/workspace_holder_state_test.go @@ -0,0 +1,37 @@ +package authority + +import "testing" + +// TERM-LIVE-HOLDER-001: one pure verdict from the line, the ACK and HEAD. +// "Never started" is HEAD below the line's epoch, not "never leased"; every +// doubtful case is Unknown (refused). +func TestWorkspaceHolderState(t *testing.T) { + const owner = "node-a/r1" + head := func(epoch uint64, holder string, detached bool) *WorkspaceHead { + return &WorkspaceHead{Gen: 3, Epoch: epoch, Holder: holder, Detached: detached} + } + for _, c := range []struct { + name string + line bool + ack *WorkspaceRevokeAck + head *WorkspaceHead + owner string + want WorkspaceHolderVerdict + }{ + {"no line", false, nil, nil, owner, HolderNoLine}, + {"ACK for the line", true, &WorkspaceRevokeAck{ReplicaID: "r1", Epoch: 2, HeadGen: 3}, nil, owner, HolderDrained}, + {"ACK for an older epoch", true, &WorkspaceRevokeAck{ReplicaID: "r1", Epoch: 1}, head(2, owner, true), owner, HolderSealed}, + {"HEAD not read", true, nil, nil, owner, HolderUnknown}, + {"HEAD never claimed (epoch 0)", true, nil, head(0, "", false), owner, HolderNeverStarted}, + {"HEAD at an older epoch", true, nil, head(1, "node-b/r1", false), owner, HolderNeverStarted}, + {"HEAD claimed at the line's epoch, active", true, nil, head(2, owner, false), owner, HolderLive}, + {"HEAD claimed at the line's epoch, sealed", true, nil, head(2, owner, true), owner, HolderSealed}, + {"another holder at the line's epoch", true, nil, head(2, "node-b/r1", false), owner, HolderUnknown}, + {"HEAD at a higher epoch", true, nil, head(3, owner, false), owner, HolderUnknown}, + {"owner unknown at the line's epoch", true, nil, head(2, owner, false), "", HolderUnknown}, + } { + if got := WorkspaceHolderState(c.line, 2, "r1", c.owner, c.ack, c.head); got != c.want { + t.Errorf("%s: %s; want %s", c.name, got, c.want) + } + } +} diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index ae22453d36..da59caffab 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -106,7 +106,10 @@ func (s *services) DeleteVolume(ctx context.Context, req *control.DeleteVolumeRe return nil, lifecycleError("delete workspace bindings", err) } _, placed := stores.Placements.GetPlacement(req.GetVolumeId()) - err = s.host.Publisher().RecordWorkspaceDeletion(ctx, req.GetVolumeId(), bound && placed, func() error { + // The lifecycle delete does not read HEAD: a line without an ACK is + // refused here even when it never started (INV-WS-DELETE-NO-LIVE-HOLDER-001 + // admits that only through the chunk volume delete and its HEAD fence). + err = s.host.Publisher().RecordWorkspaceDeletion(ctx, req.GetVolumeId(), bound && placed, nil, "", func() error { if e := stores.Placements.DeletePlacement(req.GetVolumeId()); e != nil { return e } @@ -131,6 +134,11 @@ func (s *services) DeleteVolume(ctx context.Context, req *control.DeleteVolumeRe // workload planner, binding/placement/move RPCs and CreateVolume all refuse // it. func (s *services) MarkVolumeDeleting(ctx context.Context, req *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) { + // HEAD and the line's owner, read before any lock (as MoveWorkspace + // does), bounded: a HEAD below the line's epoch proves the line never + // started (TERM-LIVE-HOLDER-001). A read that fails leaves head nil, + // which refuses a line without an ACK (fail closed). + head, owner := s.deleteHolderEvidence(ctx, req.GetVolumeId()) s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() if err := ctx.Err(); err != nil { @@ -151,7 +159,7 @@ func (s *services) MarkVolumeDeleting(ctx context.Context, req *control.MarkVolu _, placed := stores.Placements.GetPlacement(vol) var res lifecycle.DeletionReservation var persistErr error - err = s.host.Publisher().RecordWorkspaceDeletion(ctx, vol, bound && placed, func() error { + err = s.host.Publisher().RecordWorkspaceDeletion(ctx, vol, bound && placed, head, owner, func() error { res, persistErr = stores.Deletions.Admit(vol, req.GetToken()) return persistErr }) @@ -974,3 +982,26 @@ func (s *services) assignmentFact(info adapter.AssignmentInfo) *control.Assignme fact.PeerSetGeneration = (info.Epoch << 32) | info.EndpointVersion return fact } + +// deleteHolderEvidence reads vol's HEAD with the configured reader, bounded +// at 5 s, and the published line's owner "/". Either may be +// missing: no reader, a failed read or no line gives a nil head or "". +func (s *services) deleteHolderEvidence(ctx context.Context, vol string) (*authority.WorkspaceHead, string) { + owner := "" + if line, ok := s.host.Publisher().PublishedAuthorityLine(vol); ok { + if server := s.host.workspaceLineOwner(line, vol, line.ReplicaID, line.Epoch); server != "" { + owner = server + "/" + line.ReplicaID + } + } + if s.host.cfg.WorkspaceHeadReader == nil || vol == "" { + return nil, owner + } + readCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + head, err := s.host.cfg.WorkspaceHeadReader(readCtx, vol) + if err != nil { + s.host.log.Printf("blockmaster: MarkVolumeDeleting volume=%q: HEAD unreadable (%v); a line without an ACK is refused", vol, err) + return nil, owner + } + return &head, owner +} diff --git a/seaweed-block/core/host/master/workspace_delete_never_started_test.go b/seaweed-block/core/host/master/workspace_delete_never_started_test.go new file mode 100644 index 0000000000..39eae289ec --- /dev/null +++ b/seaweed-block/core/host/master/workspace_delete_never_started_test.go @@ -0,0 +1,83 @@ +package master + +import ( + "context" + "errors" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// INV-WS-DELETE-NO-LIVE-HOLDER-001 on the real master: a line whose holder +// never claimed HEAD at its epoch is admitted for delete without an ACK, on +// HEAD's evidence read before the locks; a HEAD claimed at the line's epoch, +// or one that cannot be read, is refused as before; the lifecycle +// DeleteVolume RPC (which reads no HEAD) refuses even the never-started line. +func TestDeleteAdmitsANeverStartedLine(t *testing.T) { + var headEpoch atomic.Int64 + var headFails atomic.Bool + h, conn, _ := reviewBindingHostBeforeStart(t, func(context.Context, string) (authority.WorkspaceHead, error) { + if headFails.Load() { + return authority.WorkspaceHead{}, errors.New("filer unreachable") + } + e := uint64(headEpoch.Load()) + holder := "" + if e > 0 { + holder = "node-a/r1" + } + return authority.WorkspaceHead{Gen: 2, Epoch: e, Holder: holder}, nil + }, nil) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + t.Cleanup(cancel) + for _, vol := range []string{"v", "w"} { + reviewCreate(t, conn, ctx, vol) + ws := control.NewWorkspaceServiceClient(conn) + b := &control.WorkspaceBinding{VolumeId: vol, ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"} + if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: vol, ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + reviewHeartbeat(t, conn, ctx, vol, "node-a", b.DataAddr, b.CtrlAddr) + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + line := waitAuthorityLine(t, h.Publisher(), "v") + waitAuthorityLine(t, h.Publisher(), "w") + // A lease granted, HEAD never claimed: the stranded state the release + // candidate could not delete. + if _, err := control.NewWorkspaceServiceClient(conn).RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: line.Epoch, ServerId: "node-a"}); err != nil { + t.Fatal(err) + } + lc := control.NewLifecycleServiceClient(conn) + mark := func(vol, token string) error { + _, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: vol, Token: token}) + return err + } + refusedLive := func(what string, err error) { + t.Helper() + if err == nil || !strings.Contains(err.Error(), "live authority requires clean revocation ACK") { + t.Fatalf("%s: %v; want the live-authority refusal", what, err) + } + } + + headEpoch.Store(int64(line.Epoch)) // claimed at the line's epoch: live + refusedLive("HEAD claimed at the line's epoch", mark("v", "del-live")) + headFails.Store(true) // unreadable HEAD: fail closed + refusedLive("HEAD unreadable", mark("v", "del-unreadable")) + headFails.Store(false) + headEpoch.Store(0) // never claimed + _, err := lc.DeleteVolume(ctx, &control.DeleteVolumeRequest{VolumeId: "w"}) + refusedLive("the lifecycle DeleteVolume of a never-started line", err) + res, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-never-started"}) + if err != nil || res.GetState() != lifecycle.ReservationAdmitted { + t.Fatalf("delete of a never-started line: %+v %v; want admitted without an ACK", res, err) + } +} From 63711a5744e09ac71dc075e2a4d71be33b552865 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 07:00:34 -0800 Subject: [PATCH 03/23] test: distinct endpoints for the second volume Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/workspace_delete_never_started_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/host/master/workspace_delete_never_started_test.go b/seaweed-block/core/host/master/workspace_delete_never_started_test.go index 39eae289ec..6e1a836279 100644 --- a/seaweed-block/core/host/master/workspace_delete_never_started_test.go +++ b/seaweed-block/core/host/master/workspace_delete_never_started_test.go @@ -3,6 +3,7 @@ package master import ( "context" "errors" + "fmt" "strings" "sync/atomic" "testing" @@ -34,10 +35,10 @@ func TestDeleteAdmitsANeverStartedLine(t *testing.T) { }, nil) ctx, cancel := context.WithTimeout(context.Background(), time.Minute) t.Cleanup(cancel) - for _, vol := range []string{"v", "w"} { + for i, vol := range []string{"v", "w"} { reviewCreate(t, conn, ctx, vol) ws := control.NewWorkspaceServiceClient(conn) - b := &control.WorkspaceBinding{VolumeId: vol, ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"} + b := &control.WorkspaceBinding{VolumeId: vol, ServerId: "node-a", DataAddr: fmt.Sprintf("127.0.0.1:%d", 10000+2*i), CtrlAddr: fmt.Sprintf("127.0.0.1:%d", 10001+2*i)} if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { t.Fatal(err) } From bd10769811bad39dafa2fb5280e619768c80ccad Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 07:02:29 -0800 Subject: [PATCH 04/23] docs: ledger for the never-started delete TERM-LIVE-HOLDER-001 (the one verdict), INV-WS-DELETE-NO-LIVE-HOLDER-001 replacing INV-WS-DELETE-NEEDS-ACK-001 (ARCHIVED with its reason), and the M2 'none, Granted or Expired -> Deleting' transition. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ace443cffe..3c49d78296 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -171,6 +171,7 @@ a pre-issued publication. | Expired | Granted | Same current primary server/replica/epoch, validated by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) with missing server refused, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); a busy authority writer refuses this attempt, otherwise persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-AUTH-HOLDER-IDENTITY-001` | | Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait or lease fence exits 75 after bounded cleanup; a foreign master fact newer than nonzero observed-own lineage or exact foreign HEAD at or above the assigned epoch permits 78. Planned drain retires startup monitoring before cleanup; ACK and signal retain normal exit. Restart follows the unchanged grant and HEAD-claim gates. | `cmd/blockvolume/process_exit.go` `superviseProcess`, `watchChunkStartup`, `waitWorkspaceStop`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `INV-WS-STARTUP-RETRY-001` | | Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced @`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` | +| none, Granted or Expired | Deleting | the chunk volume delete is admitted with `WorkspaceHolderState` = never started (`TERM-LIVE-HOLDER-001`): HEAD, read by blockmaster before its locks, is below the line's epoch; no move pending; store certain. From then on renewals, grants, re-grants, revocations and moves of the volume are refused; the delete's HEAD compare-and-swap to deleting is its linearization point: a claim applied before it makes the delete refuse `volume_in_use` and give the reservation back, a claim after it fails. The lifecycle `DeleteVolume` reads no HEAD and keeps the ACK rule | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence`; `core/frontend/chunkstore/volume_delete.go` (HEAD to deleting) | `INV-WS-DELETE-NO-LIVE-HOLDER-001`, `INV-WS-CLAIM-BEFORE-SERVE-001` | | Moved | epoch issued | the moved owner is captured with the assignment under pub.mu and persisted with the issuing move journal before publication; the stream uses that captured owner, empty when unknown, with placement fallback only for a move-less epoch; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/workspace_binding.go` `workspaceLineOwner`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` | ### M3 Replica role and peer state @@ -497,7 +498,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -324 rows: 254 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 309 new. +325 rows: 254 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 310 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -756,7 +757,8 @@ Notes: | `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | | `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A clean move may name the source host as its target only when HEAD is sealed by the current holder and the revocation ACK is recorded for that HEAD generation; it issues a higher epoch. A forced move to the source host is refused. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | ACTIVE | -| `INV-WS-DELETE-NEEDS-ACK-001` | A workspace volume with a live authority line is not marked deleting until that line has a clean revocation ACK. | M2 live authority: deletion refused until ACK | `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting` | `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`: refusal, cure and no deletion reservation) | — | ACTIVE | +| `INV-WS-DELETE-NEEDS-ACK-001` | ARCHIVED: replaced by `INV-WS-DELETE-NO-LIVE-HOLDER-001`, which also admits a line whose holder never claimed HEAD at its epoch (HEAD is the proof of "started", not the lease). | — | — | — | — | ARCHIVED | +| `INV-WS-DELETE-NO-LIVE-HOLDER-001` | A workspace volume is marked deleting only with no live holder (`TERM-LIVE-HOLDER-001`): no line, a clean revocation ACK for the line, or HEAD below the line's epoch. A sealed HEAD without an ACK, a live or unreadable one is refused; the HEAD compare-and-swap to deleting fences a later claim. | M2 none/Granted/Expired → Deleting | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence` | `TestWorkspaceHolderState` (`core/authority/workspace_holder_state_test.go`); `TestDeleteAdmitsANeverStartedLine` (`core/host/master/workspace_delete_never_started_test.go`); `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`) | NeverStarted r1 `DeleteNeverStrandsALiveHolder`, `NoServedWriteLost` (exhaustive) | ACTIVE | | `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`); `TestProcedureMasterUnreachableFencesBeforeForcedMove` (`cmd/blockvolume/master_loss_integration_test.go`, tags `subprocess chunkstore_integration`) | — | 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 | @@ -1104,6 +1106,7 @@ 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-LIVE-HOLDER-001` Live holder of a workspace volume | The line's holder at epoch e may have acknowledged guest writes and may publish exactly when: the authority line exists at e for its owner (`TERM-HOLDER-001`), no clean revocation ACK is recorded for (replica, e), and HEAD as read names `/` at e, active. HEAD below e means never started at e: no I/O is admitted before the claim. | the authority line, the recorded ACK, HEAD (`Epoch`, `Holder`, `Detached`) | `authority.WorkspaceHolderState` (pure): no line, drained, sealed, never started, live, unknown | the forced-move admission still reads the lease; a sealed HEAD without an ACK keeps the ACK rule | blockmaster | | `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. No local-root nonce joins it (V1-SPEC r2.45); one live process per volume on a host is the host lock (`TERM-ONE-PROCESS-001`). | `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, capped by the configured TTL. The takeover margin (half the skew bound) exceeds the configured fence-exit budget (watch cadence 50 ms + drain timeout 5 s), assuming normal scheduling; blockmaster refuses a smaller or equal margin at startup, deriving the budget from `durable.ChunkFenceWatchInterval` and `volume.WorkspaceDrainTimeout`. Safety premise for v1.0, alongside one live process per holder (`TERM-ONE-PROCESS-001`): blockmaster's host slews its wall clock, not steps it, while volumes are served; a step larger than the configured skew bound while a lease is live is unsupported (see `docs/operator-guide.md`, Clock safety requirement). This closes coverage gap 8 by a documented premise, not a wall-step test. | `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. Follow-up for 1.0.1: split `workspaceNow` into wall and monotonic sources so the barrier for in-memory lines uses monotonic time, and add a real independent wall-step test. No new clock seam is added in v1.0. | 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 | From 0273c9d8aab6761e0b0b9ee2dd31f9deeea5d77d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 07:12:27 -0800 Subject: [PATCH 05/23] fix: the delete reads a never-claimed initial HEAD as epoch 0 The master's HEAD reader refused the initial HEAD (epoch 0, no holder) as invalid, so the delete saw every never-started line as unreadable. It now returns that HEAD with ErrWorkspaceHeadUnclaimed: every caller that needs an identity still gets an error; the delete evidence reads it as epoch 0. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/workspace.go | 7 ++++ seaweed-block/core/host/master/services.go | 3 ++ .../workspace_delete_never_started_test.go | 7 ++-- .../core/host/master/workspace_head.go | 6 +++ .../core/host/master/workspace_head_test.go | 39 +++++++++++++++++++ 5 files changed, 58 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index c87f1d031e..03bcabb9a0 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -19,6 +19,13 @@ type WorkspaceHead struct { FilerMtimeNS int64 } +// ErrWorkspaceHeadUnclaimed is a HEAD reader's answer for a volume's initial +// HEAD that no holder ever claimed (epoch 0, no holder, active): the head +// returned with it carries its generation and epoch 0. It names no identity, +// so a caller that needs one treats it as any read error; the delete +// admission reads it as never started (TERM-LIVE-HOLDER-001). +var ErrWorkspaceHeadUnclaimed = errors.New("HEAD never claimed: epoch 0, no holder") + // ErrWorkspaceOutcomeUncertain marks a move whose outcome is unknown: its // issuing write failed after it may have reached the store, or the volume's // workspace persistence is already uncertain. Memory shows it unissued, but diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index da59caffab..e094b60936 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -999,6 +999,9 @@ func (s *services) deleteHolderEvidence(ctx context.Context, vol string) (*autho readCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() head, err := s.host.cfg.WorkspaceHeadReader(readCtx, vol) + if errors.Is(err, authority.ErrWorkspaceHeadUnclaimed) { + return &head, owner // the initial HEAD: epoch 0, never claimed + } if err != nil { s.host.log.Printf("blockmaster: MarkVolumeDeleting volume=%q: HEAD unreadable (%v); a line without an ACK is refused", vol, err) return nil, owner diff --git a/seaweed-block/core/host/master/workspace_delete_never_started_test.go b/seaweed-block/core/host/master/workspace_delete_never_started_test.go index 6e1a836279..ad0413c992 100644 --- a/seaweed-block/core/host/master/workspace_delete_never_started_test.go +++ b/seaweed-block/core/host/master/workspace_delete_never_started_test.go @@ -27,11 +27,10 @@ func TestDeleteAdmitsANeverStartedLine(t *testing.T) { return authority.WorkspaceHead{}, errors.New("filer unreachable") } e := uint64(headEpoch.Load()) - holder := "" - if e > 0 { - holder = "node-a/r1" + if e == 0 { // the initial HEAD, as the filer reader returns it + return authority.WorkspaceHead{Gen: 2}, authority.ErrWorkspaceHeadUnclaimed } - return authority.WorkspaceHead{Gen: 2, Epoch: e, Holder: holder}, nil + return authority.WorkspaceHead{Gen: 2, Epoch: e, Holder: "node-a/r1"}, nil }, nil) ctx, cancel := context.WithTimeout(context.Background(), time.Minute) t.Cleanup(cancel) diff --git a/seaweed-block/core/host/master/workspace_head.go b/seaweed-block/core/host/master/workspace_head.go index 5c471123e2..aaf24eb252 100644 --- a/seaweed-block/core/host/master/workspace_head.go +++ b/seaweed-block/core/host/master/workspace_head.go @@ -83,6 +83,12 @@ func NewWorkspaceHEADReader(base string) (func(context.Context, string) (authori return authority.WorkspaceHead{}, err } // DecodeHeadDocument above owns the supported-format checks. + // The initial HEAD of a volume no holder ever claimed: epoch 0, no + // holder, active. It names no identity, so callers that need one get + // an error as before; the delete reads it as "never started". + if doc.Gen > 0 && doc.Epoch == 0 && doc.Holder == "" && doc.LegacyDetached == nil && doc.DetachedBy == nil && (doc.State == "" || doc.State == "active") { + return authority.WorkspaceHead{Gen: doc.Gen, FilerMtimeNS: headFilerMtimeNS(res.Header)}, authority.ErrWorkspaceHeadUnclaimed + } if doc.Gen == 0 || doc.Epoch == 0 || doc.Holder == "" || doc.LegacyDetached != nil || (doc.State != "" && doc.State != "active" && doc.State != "detached") { return authority.WorkspaceHead{}, fmt.Errorf("invalid HEAD identity/state") } diff --git a/seaweed-block/core/host/master/workspace_head_test.go b/seaweed-block/core/host/master/workspace_head_test.go index f48b8c434b..a59fc0cd89 100644 --- a/seaweed-block/core/host/master/workspace_head_test.go +++ b/seaweed-block/core/host/master/workspace_head_test.go @@ -2,9 +2,12 @@ package master import ( "context" + "errors" "net/http" "net/http/httptest" "testing" + + "github.com/seaweedfs/seaweed-block/core/authority" ) // These are decoder controls, not the W2 Detach/filer integration proof. @@ -43,3 +46,39 @@ func TestWorkspaceHEADCanonicalState(t *testing.T) { }) } } + +// The initial HEAD of a volume no holder ever claimed (epoch 0, no holder, +// active) reads as ErrWorkspaceHeadUnclaimed with its generation and epoch 0: +// still an error to every caller that needs an identity, and the delete's +// evidence of "never started". A claimed or detached HEAD is unchanged, and +// an epoch-0 HEAD with a holder or a detach proof stays invalid. +func TestWorkspaceHEADUnclaimed(t *testing.T) { + for _, tc := range []struct { + name, doc string + unclaimed bool + }{ + {"initial", `{"format":1,"gen":1,"epoch":0,"holder":"","remote_lsn":0}`, true}, + {"initial active", `{"format":1,"gen":1,"epoch":0,"holder":"","remote_lsn":0,"state":"active"}`, true}, + {"epoch 0 with a holder", `{"format":1,"gen":1,"epoch":0,"holder":"x/r1","remote_lsn":0}`, false}, + {"epoch 0 detached", `{"format":1,"gen":1,"epoch":0,"holder":"","remote_lsn":0,"state":"detached","detachedBy":{"holder":"","epoch":0,"gen":1}}`, false}, + } { + t.Run(tc.name, func(t *testing.T) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(tc.doc)) })) + defer s.Close() + read, err := NewWorkspaceHEADReader(s.URL) + if err != nil { + t.Fatal(err) + } + h, err := read(context.Background(), "v") + if got := errors.Is(err, authority.ErrWorkspaceHeadUnclaimed); got != tc.unclaimed { + t.Fatalf("unclaimed=%v (err %v); want %v", got, err, tc.unclaimed) + } + if tc.unclaimed && (h.Gen != 1 || h.Epoch != 0) { + t.Fatalf("unclaimed HEAD %+v; want its generation and epoch 0", h) + } + if !tc.unclaimed && err == nil { + t.Fatalf("HEAD %+v accepted; want an error", h) + } + }) + } +} From e1626eb71483e92ad02e6c30510b5a26b7c1d4dd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 07:28:06 -0800 Subject: [PATCH 06/23] test: served means HEAD claimed or frontend ready, not an adopted assignment Adopting the master's assignment comes before the HEAD claim; a start that adopted and then lost the HEAD race to the delete never served. Co-Authored-By: Claude Opus 5.5 --- .../blockvolume/neverstarted_delete_integration_test.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go b/seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go index 24b1000930..faf05ab906 100644 --- a/seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go +++ b/seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go @@ -72,7 +72,7 @@ func TestNeverStartedDeleteFencesALateStart(t *testing.T) { b := env.hosts["n-v2"] late := env.h.start(t, "blockvolume-v2-late", env.h.volume, env.volArgsFor(b)...) err := late.wait(60 * time.Second) - served := late.has("adopted as PRIMARY") || volumeFrontendReady(b.status, "v2") + served := late.has("durable: HEAD claim for volume=v2 done") || volumeFrontendReady(b.status, "v2") shown, _, _ := env.h.run(t, "ops", "chunk", "show", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) t.Logf("late start after the delete: exit %v, served %v, HEAD %s", err, served, firstLine(shown)) if served || err == nil || strings.Contains(fmt.Sprint(err), "still running") || !strings.Contains(shown, `"state":"deleted"`) { @@ -114,7 +114,10 @@ func TestNeverStartedDeleteRacesAStart(t *testing.T) { }() r := <-deleted _ = d.wait(30 * time.Second) - served := d.has("adopted as PRIMARY") || volumeFrontendReady(b.status, v) + // Served means the process claimed HEAD (no I/O is admitted before the + // claim) or its frontend became ready; adopting the assignment comes + // before the claim and is not serving. + served := d.has("durable: HEAD claim for volume="+v+" done") || volumeFrontendReady(b.status, v) shown, _, _ := env.h.run(t, "ops", "chunk", "show", "--volume", v, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) isDeleted := strings.Contains(shown, `"state":"deleted"`) t.Logf("%s: delete exit %d, served %v, HEAD deleted %v: %s", v, r.code, served, isDeleted, firstLine(r.out)) From eb96edc7b6ae7c2aebdbed61687e54ab6d1c5f06 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 07:30:18 -0800 Subject: [PATCH 07/23] test: a 16-byte pattern for the clean-move case Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/neverstarted_delete_integration_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go b/seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go index faf05ab906..0ee99aef8b 100644 --- a/seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go +++ b/seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go @@ -287,7 +287,7 @@ func TestNeverStartedLineIsDeletableWithoutARevoke(t *testing.T) { must, mustU := fatalOn(t) old := env.start(t, "blockvolume-s1", "s1") e := env.adopt(t, old, "s1") - env.writeBlock(t, "s1", 0, pattern("never-started-move")) + env.writeBlock(t, "s1", 0, pattern("never-start-move")) g := env.seal(t, "s1", e) l := env.sealedLSN(t, e, g) env.revoke(t, e, g) From 04a70968fe172694f9c46138d52a6ddea3d5c8f8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 08:09:38 -0800 Subject: [PATCH 08/23] fix: a delete that stopped midway can be run again The HEAD reader refused a deleting, purging or deleted HEAD as invalid, so a never-started delete whose commit timed out (or whose mark's outcome was unknown) was refused on every re-run: the volume stayed unusable and undeletable. Such a HEAD can no longer be claimed, so it is past the fence: the reader returns it with ErrWorkspaceHeadDeleting and the verdict admits it (HolderDeleting). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/workspace.go | 14 +++++++++++-- .../core/authority/workspace_holder_state.go | 9 ++++++++ .../authority/workspace_holder_state_test.go | 2 ++ seaweed-block/core/host/master/services.go | 4 ++-- .../workspace_delete_never_started_test.go | 12 ++++++++++- .../core/host/master/workspace_head.go | 5 +++++ .../core/host/master/workspace_head_test.go | 21 +++++++++++++++++++ 7 files changed, 62 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 03bcabb9a0..3cf7c07e95 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -16,7 +16,10 @@ type WorkspaceHead struct { Gen, Epoch, RemoteLSN uint64 Holder string Detached bool - FilerMtimeNS int64 + // Deleting: HEAD is deleting, purging or deleted (returned with + // ErrWorkspaceHeadDeleting): no claim can move it again. + Deleting bool + FilerMtimeNS int64 } // ErrWorkspaceHeadUnclaimed is a HEAD reader's answer for a volume's initial @@ -26,6 +29,13 @@ type WorkspaceHead struct { // admission reads it as never started (TERM-LIVE-HOLDER-001). var ErrWorkspaceHeadUnclaimed = errors.New("HEAD never claimed: epoch 0, no holder") +// ErrWorkspaceHeadDeleting is a HEAD reader's answer for a HEAD that is +// deleting, purging or deleted: the head returned with it has Deleting set. +// A caller that needs an active or detached identity treats it as any read +// error; the delete admission reads it as past the fence (a re-run of a +// delete that stopped midway). +var ErrWorkspaceHeadDeleting = errors.New("HEAD is deleting, purging or deleted") + // ErrWorkspaceOutcomeUncertain marks a move whose outcome is unknown: its // issuing write failed after it may have reached the store, or the volume's // workspace persistence is already uncertain. Memory shows it unissued, but @@ -168,7 +178,7 @@ func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string, if pendingPlacement { return fmt.Errorf("workspace delete: placement may have queued authority") } - case HolderDrained, HolderNeverStarted: + case HolderDrained, HolderNeverStarted, HolderDeleting: default: return fmt.Errorf("workspace delete: live authority requires clean revocation ACK: revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete (holder: %s)", v) } diff --git a/seaweed-block/core/authority/workspace_holder_state.go b/seaweed-block/core/authority/workspace_holder_state.go index 779165f527..ada9cdc303 100644 --- a/seaweed-block/core/authority/workspace_holder_state.go +++ b/seaweed-block/core/authority/workspace_holder_state.go @@ -23,6 +23,11 @@ const ( HolderNeverStarted // HolderLive: HEAD names the line's holder at its epoch, active. HolderLive + // HolderDeleting: HEAD is deleting, purging or deleted. No claim can + // move it again, so it is past the delete's fence: a delete that stopped + // midway (its commit timed out, its mark's outcome was unknown) is + // admitted again and can finish. + HolderDeleting ) func (v WorkspaceHolderVerdict) String() string { @@ -37,6 +42,8 @@ func (v WorkspaceHolderVerdict) String() string { return "never started" case HolderLive: return "live" + case HolderDeleting: + return "deleting" } return "unknown" } @@ -53,6 +60,8 @@ func WorkspaceHolderState(linePresent bool, lineEpoch uint64, lineReplica, owner return HolderNoLine case ack != nil && ack.Epoch == lineEpoch && ack.ReplicaID == lineReplica: return HolderDrained + case head != nil && head.Deleting: + return HolderDeleting case head == nil: return HolderUnknown case head.Epoch < lineEpoch: diff --git a/seaweed-block/core/authority/workspace_holder_state_test.go b/seaweed-block/core/authority/workspace_holder_state_test.go index 251b3951cf..5fe145e31f 100644 --- a/seaweed-block/core/authority/workspace_holder_state_test.go +++ b/seaweed-block/core/authority/workspace_holder_state_test.go @@ -29,6 +29,8 @@ func TestWorkspaceHolderState(t *testing.T) { {"another holder at the line's epoch", true, nil, head(2, "node-b/r1", false), owner, HolderUnknown}, {"HEAD at a higher epoch", true, nil, head(3, owner, false), owner, HolderUnknown}, {"owner unknown at the line's epoch", true, nil, head(2, owner, false), "", HolderUnknown}, + {"HEAD deleting (a delete that stopped midway)", true, nil, &WorkspaceHead{Gen: 4, Epoch: 0, Deleting: true}, owner, HolderDeleting}, + {"HEAD deleting at the line's epoch", true, nil, &WorkspaceHead{Gen: 4, Epoch: 2, Holder: owner, Deleting: true}, owner, HolderDeleting}, } { if got := WorkspaceHolderState(c.line, 2, "r1", c.owner, c.ack, c.head); got != c.want { t.Errorf("%s: %s; want %s", c.name, got, c.want) diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index e094b60936..9e3d827690 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -999,8 +999,8 @@ func (s *services) deleteHolderEvidence(ctx context.Context, vol string) (*autho readCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() head, err := s.host.cfg.WorkspaceHeadReader(readCtx, vol) - if errors.Is(err, authority.ErrWorkspaceHeadUnclaimed) { - return &head, owner // the initial HEAD: epoch 0, never claimed + if errors.Is(err, authority.ErrWorkspaceHeadUnclaimed) || errors.Is(err, authority.ErrWorkspaceHeadDeleting) { + return &head, owner // the initial HEAD (never claimed), or one past the delete's fence } if err != nil { s.host.log.Printf("blockmaster: MarkVolumeDeleting volume=%q: HEAD unreadable (%v); a line without an ACK is refused", vol, err) diff --git a/seaweed-block/core/host/master/workspace_delete_never_started_test.go b/seaweed-block/core/host/master/workspace_delete_never_started_test.go index ad0413c992..241ef563db 100644 --- a/seaweed-block/core/host/master/workspace_delete_never_started_test.go +++ b/seaweed-block/core/host/master/workspace_delete_never_started_test.go @@ -21,11 +21,14 @@ import ( // DeleteVolume RPC (which reads no HEAD) refuses even the never-started line. func TestDeleteAdmitsANeverStartedLine(t *testing.T) { var headEpoch atomic.Int64 - var headFails atomic.Bool + var headFails, headDeleting atomic.Bool h, conn, _ := reviewBindingHostBeforeStart(t, func(context.Context, string) (authority.WorkspaceHead, error) { if headFails.Load() { return authority.WorkspaceHead{}, errors.New("filer unreachable") } + if headDeleting.Load() { // marked by the delete + return authority.WorkspaceHead{Gen: 3, Deleting: true}, authority.ErrWorkspaceHeadDeleting + } e := uint64(headEpoch.Load()) if e == 0 { // the initial HEAD, as the filer reader returns it return authority.WorkspaceHead{Gen: 2}, authority.ErrWorkspaceHeadUnclaimed @@ -80,4 +83,11 @@ func TestDeleteAdmitsANeverStartedLine(t *testing.T) { if err != nil || res.GetState() != lifecycle.ReservationAdmitted { t.Fatalf("delete of a never-started line: %+v %v; want admitted without an ACK", res, err) } + // The delete marked HEAD deleting, then its commit timed out: the re-run + // is admitted again (HEAD past the fence), not stranded as volume_in_use. + headDeleting.Store(true) + res, err = lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-never-started"}) + if err != nil || res.GetState() != lifecycle.ReservationAdmitted { + t.Fatalf("re-run after a commit that timed out: %+v %v; want admitted again", res, err) + } } diff --git a/seaweed-block/core/host/master/workspace_head.go b/seaweed-block/core/host/master/workspace_head.go index aaf24eb252..72f8771ccf 100644 --- a/seaweed-block/core/host/master/workspace_head.go +++ b/seaweed-block/core/host/master/workspace_head.go @@ -86,6 +86,11 @@ func NewWorkspaceHEADReader(base string) (func(context.Context, string) (authori // The initial HEAD of a volume no holder ever claimed: epoch 0, no // holder, active. It names no identity, so callers that need one get // an error as before; the delete reads it as "never started". + // A HEAD the delete has marked (deleting, purging, deleted): no claim + // can move it again; the delete's re-run reads it as past the fence. + if doc.Gen > 0 && doc.LegacyDetached == nil && (doc.State == "deleting" || doc.State == "purging" || doc.State == "deleted") { + return authority.WorkspaceHead{Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, Deleting: true, FilerMtimeNS: headFilerMtimeNS(res.Header)}, authority.ErrWorkspaceHeadDeleting + } if doc.Gen > 0 && doc.Epoch == 0 && doc.Holder == "" && doc.LegacyDetached == nil && doc.DetachedBy == nil && (doc.State == "" || doc.State == "active") { return authority.WorkspaceHead{Gen: doc.Gen, FilerMtimeNS: headFilerMtimeNS(res.Header)}, authority.ErrWorkspaceHeadUnclaimed } diff --git a/seaweed-block/core/host/master/workspace_head_test.go b/seaweed-block/core/host/master/workspace_head_test.go index a59fc0cd89..0e250e1644 100644 --- a/seaweed-block/core/host/master/workspace_head_test.go +++ b/seaweed-block/core/host/master/workspace_head_test.go @@ -82,3 +82,24 @@ func TestWorkspaceHEADUnclaimed(t *testing.T) { }) } } + +// A HEAD the delete has marked (deleting, purging, deleted) reads as +// ErrWorkspaceHeadDeleting with Deleting set: the delete's re-run sees it as +// past the fence; every other caller still gets an error. +func TestWorkspaceHEADDeleting(t *testing.T) { + for _, state := range []string{"deleting", "purging", "deleted"} { + t.Run(state, func(t *testing.T) { + doc := `{"format":1,"gen":5,"epoch":0,"holder":"","remote_lsn":0,"state":"` + state + `"}` + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(doc)) })) + defer s.Close() + read, err := NewWorkspaceHEADReader(s.URL) + if err != nil { + t.Fatal(err) + } + h, err := read(context.Background(), "v") + if !errors.Is(err, authority.ErrWorkspaceHeadDeleting) || !h.Deleting || h.Gen != 5 { + t.Fatalf("HEAD %s: %+v, %v; want ErrWorkspaceHeadDeleting with Deleting and its generation", state, h, err) + } + }) + } +} From 2733834554bfb75ef79b90e71f0b68cab31a15e8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 08:26:09 -0800 Subject: [PATCH 09/23] test: admission-level verdicts; the M2 row names Revoking and the rerun Co-Authored-By: Claude Opus 5.5 --- .../workspace_delete_admission_test.go | 52 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 4 +- 2 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/authority/workspace_delete_admission_test.go diff --git a/seaweed-block/core/authority/workspace_delete_admission_test.go b/seaweed-block/core/authority/workspace_delete_admission_test.go new file mode 100644 index 0000000000..4283a1ba66 --- /dev/null +++ b/seaweed-block/core/authority/workspace_delete_admission_test.go @@ -0,0 +1,52 @@ +package authority + +import ( + "context" + "strings" + "testing" + "time" +) + +// INV-WS-DELETE-NO-LIVE-HOLDER-001 at the admission itself +// (RecordWorkspaceDeletion), on a line at epoch 2 whose ACK is for epoch 1: a +// HEAD below the line is never started (admitted); an ACK of an older epoch +// does not drain the line, so a HEAD claimed at epoch 2 is refused; a HEAD at +// a higher epoch, another holder at the line's epoch, an unread HEAD and a +// pending move are refused; a HEAD past the fence (deleting) is admitted. +func TestDeleteAdmissionVerdicts(t *testing.T) { + now := time.Unix(1000, 0) + store, _ := newTempStore(t) + p, _ := cleanMoveToGrantee(t, store, &now) + const owner = "new-node/r" + persisted := 0 + admit := func(head *WorkspaceHead) error { + return p.RecordWorkspaceDeletion(context.Background(), "v", false, head, owner, func() error { persisted++; return nil }) + } + refused := func(what string, head *WorkspaceHead) { + t.Helper() + before := persisted + err := admit(head) + if err == nil || !strings.Contains(err.Error(), "live authority requires clean revocation ACK") || persisted != before { + t.Fatalf("%s: %v (persisted %d -> %d); want refused before the reservation", what, err, before, persisted) + } + } + refused("an ACK of epoch 1 with HEAD claimed at epoch 2", &WorkspaceHead{Gen: 8, Epoch: 2, Holder: owner}) + refused("HEAD at a higher epoch", &WorkspaceHead{Gen: 9, Epoch: 3, Holder: owner}) + refused("another holder at the line's epoch", &WorkspaceHead{Gen: 8, Epoch: 2, Holder: "third-node/r"}) + refused("HEAD not read", nil) + head := predecessorHead // epoch 1: the grantee never claimed epoch 2 + if err := admit(&head); err != nil || persisted != 1 { + t.Fatalf("HEAD below the line: %v (persisted %d); want admitted", err, persisted) + } + if err := admit(&WorkspaceHead{Gen: 9, Deleting: true}); err != nil || persisted != 2 { + t.Fatalf("HEAD deleting (a rerun): %v (persisted %d); want admitted", err, persisted) + } + p.mu.Lock() + s := cloneWorkspace(p.workspace["v"]) + s.Moves = append(s.Moves, WorkspaceMoveRecord{RequestID: "pending", VolumeID: "v", Kind: "clean"}) + p.workspace["v"] = s + p.mu.Unlock() + if err := admit(&head); err == nil || !strings.Contains(err.Error(), "move pending") { + t.Fatalf("a pending move: %v; want refused", err) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 3c49d78296..622ac9364f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -171,7 +171,7 @@ a pre-issued publication. | Expired | Granted | Same current primary server/replica/epoch, validated by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) with missing server refused, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); a busy authority writer refuses this attempt, otherwise persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-AUTH-HOLDER-IDENTITY-001` | | Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait or lease fence exits 75 after bounded cleanup; a foreign master fact newer than nonzero observed-own lineage or exact foreign HEAD at or above the assigned epoch permits 78. Planned drain retires startup monitoring before cleanup; ACK and signal retain normal exit. Restart follows the unchanged grant and HEAD-claim gates. | `cmd/blockvolume/process_exit.go` `superviseProcess`, `watchChunkStartup`, `waitWorkspaceStop`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `INV-WS-STARTUP-RETRY-001` | | Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced @`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` | -| none, Granted or Expired | Deleting | the chunk volume delete is admitted with `WorkspaceHolderState` = never started (`TERM-LIVE-HOLDER-001`): HEAD, read by blockmaster before its locks, is below the line's epoch; no move pending; store certain. From then on renewals, grants, re-grants, revocations and moves of the volume are refused; the delete's HEAD compare-and-swap to deleting is its linearization point: a claim applied before it makes the delete refuse `volume_in_use` and give the reservation back, a claim after it fails. The lifecycle `DeleteVolume` reads no HEAD and keeps the ACK rule | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence`; `core/frontend/chunkstore/volume_delete.go` (HEAD to deleting) | `INV-WS-DELETE-NO-LIVE-HOLDER-001`, `INV-WS-CLAIM-BEFORE-SERVE-001` | +| none, Granted, Revoking or Expired | Deleting | the chunk volume delete is admitted with `WorkspaceHolderState` = never started or deleting (`TERM-LIVE-HOLDER-001`): HEAD, read by blockmaster before its locks, is below the line's epoch, or already past the fence (deleting, purging, deleted: the rerun of a delete that stopped midway); no move pending. From then on renewals, grants, re-grants, revocations and moves of the volume are refused; the delete's HEAD compare-and-swap to deleting is its linearization point: a claim applied before it makes the delete refuse `volume_in_use` and give the reservation back, a claim after it fails. The lifecycle `DeleteVolume` reads no HEAD and keeps the ACK rule | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence`; `core/frontend/chunkstore/volume_delete.go` (HEAD to deleting) | `INV-WS-DELETE-NO-LIVE-HOLDER-001`, `INV-WS-CLAIM-BEFORE-SERVE-001` | | Moved | epoch issued | the moved owner is captured with the assignment under pub.mu and persisted with the issuing move journal before publication; the stream uses that captured owner, empty when unknown, with placement fallback only for a move-less epoch; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/workspace_binding.go` `workspaceLineOwner`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` | ### M3 Replica role and peer state @@ -758,7 +758,7 @@ Notes: | `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | | `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A clean move may name the source host as its target only when HEAD is sealed by the current holder and the revocation ACK is recorded for that HEAD generation; it issues a higher epoch. A forced move to the source host is refused. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | ACTIVE | | `INV-WS-DELETE-NEEDS-ACK-001` | ARCHIVED: replaced by `INV-WS-DELETE-NO-LIVE-HOLDER-001`, which also admits a line whose holder never claimed HEAD at its epoch (HEAD is the proof of "started", not the lease). | — | — | — | — | ARCHIVED | -| `INV-WS-DELETE-NO-LIVE-HOLDER-001` | A workspace volume is marked deleting only with no live holder (`TERM-LIVE-HOLDER-001`): no line, a clean revocation ACK for the line, or HEAD below the line's epoch. A sealed HEAD without an ACK, a live or unreadable one is refused; the HEAD compare-and-swap to deleting fences a later claim. | M2 none/Granted/Expired → Deleting | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence` | `TestWorkspaceHolderState` (`core/authority/workspace_holder_state_test.go`); `TestDeleteAdmitsANeverStartedLine` (`core/host/master/workspace_delete_never_started_test.go`); `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`) | NeverStarted r1 `DeleteNeverStrandsALiveHolder`, `NoServedWriteLost` (exhaustive) | ACTIVE | +| `INV-WS-DELETE-NO-LIVE-HOLDER-001` | A workspace volume is marked deleting only with no live holder (`TERM-LIVE-HOLDER-001`): no line, a clean revocation ACK for the line, or HEAD below the line's epoch. A sealed HEAD without an ACK, a live or unreadable one is refused; the HEAD compare-and-swap to deleting fences a later claim. | M2 none/Granted/Revoking/Expired → Deleting | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence` | `TestWorkspaceHolderState` (`core/authority/workspace_holder_state_test.go`); `TestDeleteAdmitsANeverStartedLine` (`core/host/master/workspace_delete_never_started_test.go`); `TestDeleteAdmissionVerdicts` (`core/authority/workspace_delete_admission_test.go`); `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`) | NeverStarted r1 `DeleteNeverStrandsALiveHolder`, `NoServedWriteLost` (exhaustive) | ACTIVE | | `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`); `TestProcedureMasterUnreachableFencesBeforeForcedMove` (`cmd/blockvolume/master_loss_integration_test.go`, tags `subprocess chunkstore_integration`) | — | 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 | From 2efb9131ddfc66ed40b2e73d9b207f1926867dce Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 08:58:06 -0800 Subject: [PATCH 10/23] test: a rerun of an admitted delete after the holder claimed HEAD (red) Co-Authored-By: Claude Opus 5.5 --- .../master/workspace_delete_never_started_test.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/seaweed-block/core/host/master/workspace_delete_never_started_test.go b/seaweed-block/core/host/master/workspace_delete_never_started_test.go index 241ef563db..e745018a00 100644 --- a/seaweed-block/core/host/master/workspace_delete_never_started_test.go +++ b/seaweed-block/core/host/master/workspace_delete_never_started_test.go @@ -83,6 +83,18 @@ func TestDeleteAdmitsANeverStartedLine(t *testing.T) { if err != nil || res.GetState() != lifecycle.ReservationAdmitted { t.Fatalf("delete of a never-started line: %+v %v; want admitted without an ACK", res, err) } + // The delete stopped before it marked HEAD, and the holder then claimed + // HEAD (its lease was still valid): a rerun of the same delete (its token + // holds the reservation) is admitted without a new verdict, so it reaches + // the catalog step, whose HEAD fence refuses the live HEAD and gives the + // reservation back. A different delete is still decided, and refused. + headEpoch.Store(int64(line.Epoch)) + res, err = lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-never-started"}) + if err != nil || res.GetState() != lifecycle.ReservationAdmitted { + t.Fatalf("rerun of an admitted delete after the holder claimed HEAD: %+v %v; want admitted (the catalog step decides)", res, err) + } + refusedLive("a new delete while the holder holds HEAD", mark("v", "del-other")) + headEpoch.Store(0) // The delete marked HEAD deleting, then its commit timed out: the re-run // is admitted again (HEAD past the fence), not stranded as volume_in_use. headDeleting.Store(true) From 51edb0571eda140843c2991ecdec515c1b4740a9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 08:58:44 -0800 Subject: [PATCH 11/23] fix: a rerun of a held delete is not decided again A delete admitted as never started that stopped before it marked HEAD, after which the holder claimed HEAD, was refused at the master on every rerun, before the catalog step that gives the reservation back: the volume stayed reserved for ever. A rerun whose token already holds the reservation (or a committed one) now skips the verdict; the catalog step's HEAD fence refuses the live HEAD and gives back. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/services.go | 15 +++++++++++++++ seaweed-block/docs/design/invariants.md | 1 + 2 files changed, 16 insertions(+) diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index 9e3d827690..3f58f60c4f 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "slices" "sync/atomic" "time" @@ -159,6 +160,20 @@ func (s *services) MarkVolumeDeleting(ctx context.Context, req *control.MarkVolu _, placed := stores.Placements.GetPlacement(vol) var res lifecycle.DeletionReservation var persistErr error + // A rerun of a delete whose token already holds the reservation (or a + // committed one) was decided by its first admission: it is not decided + // again. It goes on to the catalog step, whose HEAD compare-and-swap is + // the fence: a HEAD a holder claimed in between is refused there and the + // reservation given back, so neither the volume nor its id is stranded. + if r, held := stores.Deletions.Get(vol); held && (r.State == lifecycle.ReservationCommitted || slices.Contains(r.Tokens, req.GetToken())) { + res, persistErr = stores.Deletions.Admit(vol, req.GetToken()) + if persistErr != nil { + return nil, status.Errorf(codes.Unavailable, "mark volume deleting: %v", persistErr) + } + _, known := stores.Volumes.GetVolume(vol) + s.host.log.Printf("blockmaster: MarkVolumeDeleting volume=%q known=%t state=%s (rerun of a held delete)", vol, known, res.State) + return &control.MarkVolumeDeletingResponse{Known: known, State: res.State}, nil + } err = s.host.Publisher().RecordWorkspaceDeletion(ctx, vol, bound && placed, head, owner, func() error { res, persistErr = stores.Deletions.Admit(vol, req.GetToken()) return persistErr diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 622ac9364f..7587ca9f29 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -778,6 +778,7 @@ Notes: | `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | | `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry after bounded cleanup. A master fact newer than nonzero observed-own, or an exact foreign HEAD at/above the assigned epoch, permits 78. ACK and signal keep normal exit; lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome` (`core/frontend/durable/provider_startup_outcome_test.go`); `TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake` (`core/frontend/durable/provider_startup_internal_test.go`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE | +- `INV-WS-DELETE-NO-LIVE-HOLDER-001`: the verdict is the first admission's only. A rerun of a delete whose token already holds the reservation (or a committed one) is admitted without a new verdict and goes on to the catalog step, whose HEAD compare-and-swap is the fence: a HEAD a holder claimed in between is refused there and the reservation given back, so an interrupted delete strands neither the volume nor its id. A reservation may hold several tokens (one per delete request); each new token is decided by the verdict. - `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another holder (compared with nonzero observed-own assignment; never-assigned zero retries75), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process. - Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former; fencing compares the latter. Both use `IsSuperseded` with explicit lineage; zero lineage selects retry75 and no fence; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages`, `TestWorkspaceExitLineageIncludesBlockedOwnAssignment`, and `TestWorkspaceObservedLineageNeverTrailsAdoption` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal. - Part T evidence scope: `workspaceRetryOutcome` is the one retry/no-retry decision. Startup `chooseChunkStartupExit` supplies the recovery-generation-bound refused-claim HEAD proof; runtime lease-end supplies none. Both combine that input with a foreign master line newer than nonzero observed-own; absent proof means retry 75. From 70f5fa2acf3674db17f1d00ea4112d410ffc4582 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 09:18:49 -0800 Subject: [PATCH 12/23] docs: a new token on a committed reservation also skips the verdict Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7587ca9f29..e803a4ea9b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -778,7 +778,7 @@ Notes: | `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | | `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry after bounded cleanup. A master fact newer than nonzero observed-own, or an exact foreign HEAD at/above the assigned epoch, permits 78. ACK and signal keep normal exit; lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome` (`core/frontend/durable/provider_startup_outcome_test.go`); `TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake` (`core/frontend/durable/provider_startup_internal_test.go`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE | -- `INV-WS-DELETE-NO-LIVE-HOLDER-001`: the verdict is the first admission's only. A rerun of a delete whose token already holds the reservation (or a committed one) is admitted without a new verdict and goes on to the catalog step, whose HEAD compare-and-swap is the fence: a HEAD a holder claimed in between is refused there and the reservation given back, so an interrupted delete strands neither the volume nor its id. A reservation may hold several tokens (one per delete request); each new token is decided by the verdict. +- `INV-WS-DELETE-NO-LIVE-HOLDER-001`: the verdict is the first admission's only. A rerun of a delete whose token already holds the reservation (or a committed one) is admitted without a new verdict and goes on to the catalog step, whose HEAD compare-and-swap is the fence: a HEAD a holder claimed in between is refused there and the reservation given back, so an interrupted delete strands neither the volume nor its id. A reservation may hold several tokens (one per delete request); a new token on an admitted reservation is decided by the verdict; on a committed one it skips the verdict too (committed only once the HEAD is being purged, so no holder can claim it). The HEAD read before the lock still runs for a rerun, and its result is then unused: it is kept outside the workspace lock on purpose. - `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another holder (compared with nonzero observed-own assignment; never-assigned zero retries75), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process. - Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former; fencing compares the latter. Both use `IsSuperseded` with explicit lineage; zero lineage selects retry75 and no fence; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages`, `TestWorkspaceExitLineageIncludesBlockedOwnAssignment`, and `TestWorkspaceObservedLineageNeverTrailsAdoption` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal. - Part T evidence scope: `workspaceRetryOutcome` is the one retry/no-retry decision. Startup `chooseChunkStartupExit` supplies the recovery-generation-bound refused-claim HEAD proof; runtime lease-end supplies none. Both combine that input with a foreign master line newer than nonzero observed-own; absent proof means retry 75. From 39ebfe2a811668adac6a3985735442d711e3594c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 10:16:21 -0800 Subject: [PATCH 13/23] docs: the live-holder delete row cites the exhaustive r2 model and what it leaves out Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e803a4ea9b..46b516b68c 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -758,7 +758,7 @@ Notes: | `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | | `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A clean move may name the source host as its target only when HEAD is sealed by the current holder and the revocation ACK is recorded for that HEAD generation; it issues a higher epoch. A forced move to the source host is refused. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | ACTIVE | | `INV-WS-DELETE-NEEDS-ACK-001` | ARCHIVED: replaced by `INV-WS-DELETE-NO-LIVE-HOLDER-001`, which also admits a line whose holder never claimed HEAD at its epoch (HEAD is the proof of "started", not the lease). | — | — | — | — | ARCHIVED | -| `INV-WS-DELETE-NO-LIVE-HOLDER-001` | A workspace volume is marked deleting only with no live holder (`TERM-LIVE-HOLDER-001`): no line, a clean revocation ACK for the line, or HEAD below the line's epoch. A sealed HEAD without an ACK, a live or unreadable one is refused; the HEAD compare-and-swap to deleting fences a later claim. | M2 none/Granted/Revoking/Expired → Deleting | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence` | `TestWorkspaceHolderState` (`core/authority/workspace_holder_state_test.go`); `TestDeleteAdmitsANeverStartedLine` (`core/host/master/workspace_delete_never_started_test.go`); `TestDeleteAdmissionVerdicts` (`core/authority/workspace_delete_admission_test.go`); `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`) | NeverStarted r1 `DeleteNeverStrandsALiveHolder`, `NoServedWriteLost` (exhaustive) | ACTIVE | +| `INV-WS-DELETE-NO-LIVE-HOLDER-001` | A workspace volume is marked deleting only with no live holder (`TERM-LIVE-HOLDER-001`): no line, a clean revocation ACK for the line, or HEAD below the line's epoch. A sealed HEAD without an ACK, a live or unreadable one is refused; the HEAD compare-and-swap to deleting fences a later claim. | M2 none/Granted/Revoking/Expired → Deleting | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence` | `TestWorkspaceHolderState` (`core/authority/workspace_holder_state_test.go`); `TestDeleteAdmitsANeverStartedLine` (`core/host/master/workspace_delete_never_started_test.go`); `TestDeleteAdmissionVerdicts` (`core/authority/workspace_delete_admission_test.go`); `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`) | NeverStarted r2 `DeleteNeverStrandsALiveHolder`, `NoServedWriteLost`, re-run can finish, re-run can settle (exhaustive, 21 of 21 configurations as expected). Not modelled: two delete processes at the same instant; the gap between HEAD deleted and the volume marked deleted | ACTIVE | | `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`); `TestProcedureMasterUnreachableFencesBeforeForcedMove` (`cmd/blockvolume/master_loss_integration_test.go`, tags `subprocess chunkstore_integration`) | — | 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 | From aa53f203b3ba82df6f783dbdd5b36952da9b7d1e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 10:19:52 -0800 Subject: [PATCH 14/23] test: a new delete token meeting a deleting HEAD is admitted by the verdict Co-Authored-By: Claude Opus 5.5 --- .../host/master/workspace_delete_never_started_test.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/seaweed-block/core/host/master/workspace_delete_never_started_test.go b/seaweed-block/core/host/master/workspace_delete_never_started_test.go index e745018a00..c2d2bb19f4 100644 --- a/seaweed-block/core/host/master/workspace_delete_never_started_test.go +++ b/seaweed-block/core/host/master/workspace_delete_never_started_test.go @@ -102,4 +102,11 @@ func TestDeleteAdmitsANeverStartedLine(t *testing.T) { if err != nil || res.GetState() != lifecycle.ReservationAdmitted { t.Fatalf("re-run after a commit that timed out: %+v %v; want admitted again", res, err) } + // A NEW delete request (another token, so no held-token skip) meeting the + // deleting HEAD is decided by the verdict, and the verdict admits it: a + // HEAD past the fence is HolderDeleting, not a live holder. + res, err = lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-second-request"}) + if err != nil || res.GetState() != lifecycle.ReservationAdmitted { + t.Fatalf("a new delete request meeting a deleting HEAD: %+v %v; want admitted by the verdict", res, err) + } } From 0d51336a282093b766d29bcf9cb6ff1d6e34fed0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 10:20:48 -0800 Subject: [PATCH 15/23] docs: the availability window of an interrupted never-started delete Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 46b516b68c..efea9f0889 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -778,7 +778,7 @@ Notes: | `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | | `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry after bounded cleanup. A master fact newer than nonzero observed-own, or an exact foreign HEAD at/above the assigned epoch, permits 78. ACK and signal keep normal exit; lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome` (`core/frontend/durable/provider_startup_outcome_test.go`); `TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake` (`core/frontend/durable/provider_startup_internal_test.go`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE | -- `INV-WS-DELETE-NO-LIVE-HOLDER-001`: the verdict is the first admission's only. A rerun of a delete whose token already holds the reservation (or a committed one) is admitted without a new verdict and goes on to the catalog step, whose HEAD compare-and-swap is the fence: a HEAD a holder claimed in between is refused there and the reservation given back, so an interrupted delete strands neither the volume nor its id. A reservation may hold several tokens (one per delete request); a new token on an admitted reservation is decided by the verdict; on a committed one it skips the verdict too (committed only once the HEAD is being purged, so no holder can claim it). The HEAD read before the lock still runs for a rerun, and its result is then unused: it is kept outside the workspace lock on purpose. +- `INV-WS-DELETE-NO-LIVE-HOLDER-001`: the verdict is the first admission's only. A rerun of a delete whose token already holds the reservation (or a committed one) is admitted without a new verdict and goes on to the catalog step, whose HEAD compare-and-swap is the fence: a HEAD a holder claimed in between is refused there and the reservation given back, so an interrupted delete strands neither the volume nor its id. A reservation may hold several tokens (one per delete request); a new token on an admitted reservation is decided by the verdict; on a committed one it skips the verdict too (committed only once the HEAD is being purged, so no holder can claim it). The HEAD read before the lock still runs for a rerun, and its result is then unused: it is kept outside the workspace lock on purpose. Availability window: a delete admitted for a never-started line that stops before it marks HEAD leaves the volume reserved for deletion; if the holder then claims HEAD, the volume cannot be used until that delete is re-run (the catalog step then refuses the live HEAD and gives the reservation back). Re-run an interrupted delete. - `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another holder (compared with nonzero observed-own assignment; never-assigned zero retries75), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process. - Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former; fencing compares the latter. Both use `IsSuperseded` with explicit lineage; zero lineage selects retry75 and no fence; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages`, `TestWorkspaceExitLineageIncludesBlockedOwnAssignment`, and `TestWorkspaceObservedLineageNeverTrailsAdoption` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal. - Part T evidence scope: `workspaceRetryOutcome` is the one retry/no-retry decision. Startup `chooseChunkStartupExit` supplies the recovery-generation-bound refused-claim HEAD proof; runtime lease-end supplies none. Both combine that input with a foreign master line newer than nonzero observed-own; absent proof means retry 75. From af8473c561abb3b87f601508bae32f3dc1312b0a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 10:28:00 -0800 Subject: [PATCH 16/23] test: red: the unsupported path reassigns when the current primary does not answer its status probe Co-Authored-By: Claude Opus 5.5 --- .../master/primary_boot_grace_gate_test.go | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/host/master/primary_boot_grace_gate_test.go b/seaweed-block/core/host/master/primary_boot_grace_gate_test.go index 7c2721ce3b..926b566b72 100644 --- a/seaweed-block/core/host/master/primary_boot_grace_gate_test.go +++ b/seaweed-block/core/host/master/primary_boot_grace_gate_test.go @@ -64,6 +64,9 @@ func ingestRF3Incarnations(t *testing.T, h *Host, r1, r2, r3 rf3Slot) { type switchProbe struct { mu sync.Mutex currentReady bool + // currentUnknown: the current primary did not answer (status GET + // refused or timed out), so CurrentKnown is false. + currentUnknown bool // When hold is set, a probe signals entered and then blocks until // release is closed. hold bool @@ -99,7 +102,7 @@ func (p *switchProbe) ProbePromotionCandidates(volumeID string, current authorit // Only r2 is seen, so its promotion needs a known frontier // it covers (#181); r3 is silent in these tests. SyncAckLSN: 70, - CurrentKnown: true, + CurrentKnown: !p.currentUnknown, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: p.currentReady, DurableLSN: 70}, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 70}}, }, nil @@ -213,6 +216,24 @@ func TestBootGrace_UnsupportedPathHonorsGraceThenFailsOver(t *testing.T) { expectFailoverToR2(t, h, "unready past its boot grace") } +// A current primary that did not answer its status probe is UNKNOWN, not +// failed: the unsupported path never reassigns on it, however ready the +// survivor (an unknown fact is never read as failed). Only a positive +// not-ready report from the primary itself moves the line. +func TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary(t *testing.T) { + h := newBootGraceMaster(t, Config{}) + defer closeTestMaster(t, h) + p := probeOf(t, h) + + p.mu.Lock() + p.currentUnknown = true + p.mu.Unlock() + unsupportedTick(t, h, readySlot("r1-a")) + expectLineStaysR1(t, h, "status probe of the current primary timed out") + unsupportedTick(t, h, readySlot("r1-a")) + expectLineStaysR1(t, h, "still unanswered on the next tick") +} + // An explicit unhealthy current primary gets no grace on this path. func TestBootGrace_UnsupportedPathUnhealthyCurrentFailsOverAtOnce(t *testing.T) { h := newBootGraceMaster(t, Config{}) From 3aafd4e1f180f100fbf299daf7083b2461e64eaa Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 10:28:49 -0800 Subject: [PATCH 17/23] fix(master): never reassign on a primary that did not answer its status probe An unknown fact is not a failed one: the unsupported promotion path now moves the line only on the current primary's own not-ready report, like the supported path. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/product_loop.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/host/master/product_loop.go b/seaweed-block/core/host/master/product_loop.go index e7e546bc62..6ce027a580 100644 --- a/seaweed-block/core/host/master/product_loop.go +++ b/seaweed-block/core/host/master/product_loop.go @@ -336,7 +336,9 @@ func (h *Host) applyUnsupportedPromotionEvidenceGate(placements []lifecycle.Plac break } } - if enabledCandidate && (!result.CurrentKnown || !result.Current.Ready) { + // Only a positive not-ready report from the current primary moves the + // line. A primary that did not answer is unknown, never failed. + if enabledCandidate && result.CurrentKnown && !result.Current.Ready { // Unsupported does not mean the current primary is unhealthy: // a different slot may be stale. Judge the current primary // from its own fresh heartbeat slot, never from placement. From 3bb1cfb1e961a7a96aba4d4ae02b9616f82bd1a7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 10:37:36 -0800 Subject: [PATCH 18/23] test, docs: a missing primary pod is unknown: no automatic reassign; Kubernetes alpha failover is manual Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/product_loop_test.go | 28 ++++++++----------- seaweed-block/deploy/k8s/alpha/README.md | 1 + .../docs/design/kubernetes-block-design.md | 4 ++- 3 files changed, 15 insertions(+), 18 deletions(-) diff --git a/seaweed-block/core/host/master/product_loop_test.go b/seaweed-block/core/host/master/product_loop_test.go index b8d9cbeed9..c52a824938 100644 --- a/seaweed-block/core/host/master/product_loop_test.go +++ b/seaweed-block/core/host/master/product_loop_test.go @@ -544,7 +544,7 @@ func TestMountedFailover_ProductLoopRF3ProbeCanAuthorizeStaleHeartbeatReadiness( } } -func TestMountedFailover_ProductLoopRF3PromotesWhenCurrentSlotMissingButSurvivorProbeReady(t *testing.T) { +func TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing(t *testing.T) { h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ ExpectedSlotsPerVolume: 3, }) @@ -570,28 +570,22 @@ func TestMountedFailover_ProductLoopRF3PromotesWhenCurrentSlotMissingButSurvivor } // K8s can keep the server/node fresh while the generated primary - // blockvolume pod is gone. That produces PartialInventory and excludes - // the volume from the normal supported snapshot; the product loop must - // still use placement + probe evidence to promote an eligible survivor. + // blockvolume pod is gone: PartialInventory, and the current primary's + // status cannot be read (CurrentKnown false). That is UNKNOWN, not + // failed: on a partition the primary may still be serving, so no + // automatic reassign happens, however ready the survivors. Failover is + // an admin forced move with its barrier. ingestRF3PartialInventoryMissingCurrent(t, h, "vol-rf3", "node-a", "node-b", "node-c") placements := h.Lifecycle().Placements.ListPlacements() report := authority.SupportabilityReport{Unsupported: map[string]authority.VolumeUnsupportedEvidence{ "vol-rf3": {VolumeID: "vol-rf3", Reasons: []string{authority.ReasonPartialInventory}}, }} - probes, blocked, asks := h.applyUnsupportedPromotionEvidenceGate(placements, report, nil) - if probes != 1 || blocked != 0 || len(asks) != 1 { - line, _ := h.Publisher().VolumeAuthorityLine("vol-rf3") - t.Fatalf("probes=%d blocked=%d asks=%+v placements=%+v line=%+v want one direct unsupported promotion ask", probes, blocked, asks, placements, line) + probes, _, asks := h.applyUnsupportedPromotionEvidenceGate(placements, report, nil) + if probes != 1 || len(asks) != 0 { + t.Fatalf("probes=%d asks=%+v; want one probe and no reassign for an unanswered current primary", probes, asks) } - if asks[0].ReplicaID != "r3" || asks[0].Intent != authority.IntentReassign { - t.Fatalf("ask=%+v want highest durable survivor r3 reassign", asks[0]) - } - if err := h.ctrl.SubmitAssignmentAsk(asks[0]); err != nil { - t.Fatalf("submit unsupported promotion ask: %v", err) - } - failover := waitAuthorityReplica(t, h.Publisher(), "vol-rf3", "r3") - if failover.Epoch != 2 || failover.EndpointVersion != 1 { - t.Fatalf("failover line=%+v want highest durable survivor r3@2/1", failover) + if line, _ := h.Publisher().VolumeAuthorityLine("vol-rf3"); line.ReplicaID != "r1" || line.Epoch != initial.Epoch { + t.Fatalf("line=%+v; want r1@%d unchanged", line, initial.Epoch) } } diff --git a/seaweed-block/deploy/k8s/alpha/README.md b/seaweed-block/deploy/k8s/alpha/README.md index c873c61db2..93a8fc33ff 100644 --- a/seaweed-block/deploy/k8s/alpha/README.md +++ b/seaweed-block/deploy/k8s/alpha/README.md @@ -205,6 +205,7 @@ This alpha MVP does not yet claim: - production-ready durability - multi-node Kubernetes operation - failover while a pod remains mounted +- automatic failover when the primary node or pod is lost: blockmaster does not reassign on a primary it cannot read; failover is a manual admin action - real operator reconciliation - backend data shredding on delete - snapshots, clone, resize, block mode, topology spread, or NVMe-oF diff --git a/seaweed-block/docs/design/kubernetes-block-design.md b/seaweed-block/docs/design/kubernetes-block-design.md index f414c1838f..b12b036e9b 100644 --- a/seaweed-block/docs/design/kubernetes-block-design.md +++ b/seaweed-block/docs/design/kubernetes-block-design.md @@ -210,7 +210,9 @@ The volume computes whether it may become primary; blockmaster decides; only the **RF=3 gate** (`core/host/master/promotion_probe.go`, `promotionAllowedReplicas`, `chooseAllowedPromotionTarget`): no promotion when the probe failed or is not installed, or the ack profile is unknown; a candidate is skipped when it is not `replica_ready` with a known frontier, or its durable LSN is below the required frontier. The decision is recorded as an ops event (`candidate_covers_required_frontier`, `candidate_frontier_behind`, `no_promotion_ready_candidate`). The required frontier per volume (`RequiredLSNByVolume`) is not set by `cmd/blockmaster` today, so the frontier is unknown and coverage is proven from the survivors instead: with `sync_quorum` or `sync_all`, the ready candidate with the highest durable LSN is promoted only when at least P-K+1 of the P peers are probed ready (known durable LSN) and have a fresh heartbeat, where K is the number of peer acks a write needs (`waitForSyncAcks`: P for `sync_all`, (P+1)/2 for `sync_quorum`). Any P-K+1 peers include one that holds every acknowledged write that their sampled frontiers represent. The probes of one tick are snapshots, not a fence: a primary that is still running can acknowledge after a sample was taken (for example, r3 reports 70 in a held probe response, the old primary then acknowledges 71, and r2 at 70 is still selected). That is the missing primary lease below (§12, #195). For RF=3 that is both peers under `sync_quorum` and one under `sync_all`; with fewer, nothing is promoted. An unknown frontier is never read as zero. `best_effort` is unchanged (§12). -**What blocks a promotion:** any engine reason above; `unhealthy_reason` set or withdrawn; an unreachable or ineligible server; boot grace still holding; a current primary whose probe is ready; a snapshot rejected for slot count; slots that changed while the probe ran. +**A current primary that does not answer is unknown, not failed.** When its status cannot be read (a pod gone, a partition), blockmaster does not reassign on either path, however ready the survivors: on a partition the primary may still be serving. Only the primary's own not-ready report moves the line automatically; otherwise failover is a manual admin action in this release. + +**What blocks a promotion:** any engine reason above; a current primary whose status cannot be read; `unhealthy_reason` set or withdrawn; an unreachable or ineligible server; boot grace still holding; a current primary whose probe is ready; a snapshot rejected for slot count; slots that changed while the probe ran. ```mermaid stateDiagram-v2 From 6c620a4165d902ce339d436335f3f872f16f42cc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 10:45:02 -0800 Subject: [PATCH 19/23] docs: the Kubernetes alpha manual failover names the failback path Co-Authored-By: Claude Opus 5.5 --- seaweed-block/deploy/k8s/alpha/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/deploy/k8s/alpha/README.md b/seaweed-block/deploy/k8s/alpha/README.md index 93a8fc33ff..50f78bb880 100644 --- a/seaweed-block/deploy/k8s/alpha/README.md +++ b/seaweed-block/deploy/k8s/alpha/README.md @@ -205,7 +205,7 @@ This alpha MVP does not yet claim: - production-ready durability - multi-node Kubernetes operation - failover while a pod remains mounted -- automatic failover when the primary node or pod is lost: blockmaster does not reassign on a primary it cannot read; failover is a manual admin action +- automatic failover when the primary node or pod is lost: blockmaster does not reassign on a primary it cannot read; failover is a manual admin action (a `SwBlockReplicaFailback` with the expected current line, applied for the failback executor, which calls blockmaster's admin `ExecuteFailback`) - real operator reconciliation - backend data shredding on delete - snapshots, clone, resize, block mode, topology spread, or NVMe-oF From d74944ae2e5ca3905096eec906c26581378aff17 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 11:57:02 -0800 Subject: [PATCH 20/23] docs: the delete and re-run edges in M2; pinned NeverStarted r2 results in the spec index Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 18 +++++++ .../docs/spec/NeverStarted-r2-results.md | 54 +++++++++++++++++++ seaweed-block/docs/spec/README.md | 6 +++ 3 files changed, 78 insertions(+) create mode 100644 seaweed-block/docs/spec/NeverStarted-r2-results.md diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index efea9f0889..41ee6525cf 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -150,6 +150,24 @@ flowchart LR Stream --> Initial[Move-less epoch: placement owner] ``` +**Chunk volume delete and its re-run.** + +```mermaid +flowchart LR + Ask[MarkVolumeDeleting with token] --> Held{Token holds the reservation, or it is committed?} + Held -->|yes: re-run| Catalog[Catalog step: HEAD compare-and-swap to deleting] + Held -->|no| Verdict{WorkspaceHolderState} + Verdict -->|never started or deleting| Admit[Reservation admitted] + Verdict -->|live, sealed, unknown| Refuse[Refused: volume_in_use] + Admit --> Catalog + Catalog -->|HEAD not held| Mark[HEAD deleting, then purge, then commit] + Catalog -->|a holder claimed HEAD| GiveBack[Refused; reservation given back] + Mark -->|stopped before commit| Ask + Admit -->|stopped before the mark| Ask +``` + +Model: [NeverStarted r2 exhaustive results](../spec/NeverStarted-r2-results.md). + Model trace: [WorkspaceRegrant round 4 pins and simulation results](../spec/WorkspaceRegrant-owner-label-results.md) binds the owner-label switch, five configurations and reported results to exact hashes. Captured labels use StreamLabelFromStore=FALSE; the mutant models a diff --git a/seaweed-block/docs/spec/NeverStarted-r2-results.md b/seaweed-block/docs/spec/NeverStarted-r2-results.md new file mode 100644 index 0000000000..d579ab379c --- /dev/null +++ b/seaweed-block/docs/spec/NeverStarted-r2-results.md @@ -0,0 +1,54 @@ +# NeverStarted r2: exhaustive results for the never-started delete + +A chunk volume whose line was granted but whose HEAD was never claimed can be +deleted (`INV-WS-DELETE-NO-LIVE-HOLDER-001`, `TERM-LIVE-HOLDER-001`). A rerun +of a delete whose token already holds the reservation (or a committed one) is +admitted without a new verdict; the catalog's HEAD compare-and-swap is the +fence. The model checks this head behaviour, the earlier heads it replaces, and +mutations of each guard. + +Assumptions (not modelled): one delete process per volume at a time; the gap +between HEAD deleted and the volume marked deleted; an interrupted delete is +re-run by the operator. + +## Results + +Status: **EXHAUSTIVE** (TLC, every configuration finished). Depth and distinct +state counts are as reported by TLC. + +**Must not violate** (the head's behaviour: FixDeleting + FixToken). Invariants +checked: TypeOK, NoTwoHolders, NoValidityBehindLine, NoServedWriteLost, +DeleteNeverStrandsALiveHolder, NoRefusalContradiction, +NoLiveHolderWhileDeleting, RerunCanFinish, RerunCanSettle, +SkipOnlyReplaysADecision. + +| Configuration | Distinct states | Depth | Result | +|---|---|---|---| +| `safe_head_nosnap` | 25,831,776 | 50 | No error | +| `safe_head` (snapshot revert on) | 48,737,939 | 50 | No error | + +**Must violate** (each fires as expected): + +| Configuration | What it is | Violated | +|---|---|---| +| `f1_head_stuck` | earlier head: a delete stopped after its HEAD mark | RerunCanFinish | +| `f1b_fix_deleting_settle` | earlier head: a delete stopped before its mark, then the holder claims | RerunCanSettle | +| `mut_no_head_fence` | the catalog's mark is a blind write | NoServedWriteLost | +| `mut_fix_mark_no_fence` | HEAD marked without its fence | NoLiveHolderWhileDeleting | +| `mut_blind_claim` | a claim that ignores deleting | DeleteNeverStrandsALiveHolder | +| `mut_admit_claimed` | a claimed HEAD admitted | NoServedWriteLost | +| `mut_lc_admits_ns` | the lifecycle delete admits a never-started line | DeleteNeverStrandsALiveHolder | +| `mut_token_any` | the skip for any token while admitted | SkipOnlyReplaysADecision | +| `mut_token_rerun_trusts` | a skipped rerun's catalog step trusts the admission | NoLiveHolderWhileDeleting | +| `mut_mem_restart`, `mut_mem_restart_two_holders` | empty lease memory after restart plus a barrier-less move | NoValidityBehindLine | +| `mut_mem_restart_nth` | the same, NoTwoHolders alone | NoTwoHolders | +| `mut_move_ignores_lease` | a move on HEAD alone while a lease is valid | NoValidityBehindLine | +| `mut_move_ignores_lease_nth` | the same, NoTwoHolders alone | NoTwoHolders | +| `wit_fix_other_token_admitted` | witness: a new token is decided by the verdict | WitnessOtherTokenAdmitted | +| `wit_fix_stale_deleting_admits_live` | witness: a stale deleting read admits; the catalog refuses | WitnessStaleDeletingAdmitsLive | +| `wit_fix_stale_read_joins_deleting` | witness: a stale read joins the mark | WitnessStaleReadJoinsDeleting | +| `wit_fix_rerun_after_mark_finished` | witness: a delete stopped after its mark is finished by a rerun | WitnessRerunAfterMarkFinished | +| `wit_token_rerun_admits_live` | witness: the skip admits over a live HEAD; the catalog gives it back | WitnessRerunAdmittedLive | + +21 of 21 configurations as expected. A violated witness shows that the state +it names is reachable (the fix is not vacuous); it is not a defect. diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 6be254496d..203ad500fe 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -103,6 +103,12 @@ Two kinds of config are **expected to violate**: Each `.cfg` names its spec on its first line. +## Never-started delete results + +[NeverStarted r2 exhaustive results](NeverStarted-r2-results.md): 21 of 21 +configurations as expected; the two must-not-violate configurations finished +with no error (25,831,776 and 48,737,939 distinct states, depth 50). + ## Owner-label simulation results [Workspace owner-label simulation results](WorkspaceRegrant-owner-label-results.md) From 08266ff2cf347647d0a8391f83193913f42510fe Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 11:57:20 -0800 Subject: [PATCH 21/23] docs: NeverStarted r2 results keep the exact configuration names Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/spec/NeverStarted-r2-results.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/seaweed-block/docs/spec/NeverStarted-r2-results.md b/seaweed-block/docs/spec/NeverStarted-r2-results.md index d579ab379c..509d6d243c 100644 --- a/seaweed-block/docs/spec/NeverStarted-r2-results.md +++ b/seaweed-block/docs/spec/NeverStarted-r2-results.md @@ -16,7 +16,7 @@ re-run by the operator. Status: **EXHAUSTIVE** (TLC, every configuration finished). Depth and distinct state counts are as reported by TLC. -**Must not violate** (the head's behaviour: FixDeleting + FixToken). Invariants +**Must not violate** (the code at 72efeb3a, unchanged since: FixDeleting + FixToken). Invariants checked: TypeOK, NoTwoHolders, NoValidityBehindLine, NoServedWriteLost, DeleteNeverStrandsALiveHolder, NoRefusalContradiction, NoLiveHolderWhileDeleting, RerunCanFinish, RerunCanSettle, @@ -24,8 +24,8 @@ SkipOnlyReplaysADecision. | Configuration | Distinct states | Depth | Result | |---|---|---|---| -| `safe_head_nosnap` | 25,831,776 | 50 | No error | -| `safe_head` (snapshot revert on) | 48,737,939 | 50 | No error | +| `safe_head_72efeb3a_nosnap` | 25,831,776 | 50 | No error | +| `safe_head_72efeb3a` (snapshot revert on) | 48,737,939 | 50 | No error | **Must violate** (each fires as expected): From a70893e6f2dcfc545fd106dcb88bd284c92b505e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 11:58:01 -0800 Subject: [PATCH 22/23] docs: ledger row INV-PROMOTE-UNKNOWN-CURRENT-001 with its regression tests Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ace443cffe..58e0a16181 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -497,7 +497,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -324 rows: 254 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 309 new. +325 rows: 255 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 310 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -963,6 +963,7 @@ Notes: | `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | | `INV-PROMOTE-FRONTIER-001` | With a known required acknowledgement frontier under `sync_quorum` or `sync_all`, the RF=3 promotion gate allows only probed-ready candidates whose durable LSN is at least the required LSN. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `applyPromotionEvidenceGate`; `core/host/master/promotion_probe.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-PROBE-001` | For a volume with three or more slots, the gate allows no candidate unless this tick's promotion probe succeeded with a known ack profile. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe` (`core/host/master/product_loop_test.go`); `TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | +| `INV-PROMOTE-UNKNOWN-CURRENT-001` | A current primary whose status cannot be read (probe refused, timed out, pod gone) is unknown, never failed: no promotion path reassigns on it; a direct reassign needs the primary's own not-ready report. | M3 Primary → promotion candidate (both promotion paths) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` (supported path), `applyUnsupportedPromotionEvidenceGate` (unsupported path) | `TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary` (`core/host/master/primary_boot_grace_gate_test.go`); `TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing` (`core/host/master/product_loop_test.go`). Limits: Kubernetes alpha failover on node or pod loss is a manual admin action in this release | — | ACTIVE | | `INV-PROMOTE-FRONTIER-UNKNOWN-001` | With an unknown frontier under `sync_quorum` or `sync_all`, the gate allows the highest-durable ready candidate only if at least N_peers-K+1 of the N_peers peers are probed ready this tick and have a fresh heartbeat (K as in `waitForSyncAcks`); else none. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/replication/async_ack.go` `waitForSyncAcks` | `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-BEST-EFFORT-001` | Under `best_effort`, the gate allows no candidate when a nonzero required frontier is given, and otherwise allows the highest-durable ready candidate. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BestEffortUnknownRequiredLSNCanSelectHighestDurableLSN`, `TestMountedFailover_ProductLoopRF3RejectsBestEffortProbeForHA` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE | From 7581ad778175c06e713553ab76933fcf44f4931d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 12:14:26 -0800 Subject: [PATCH 23/23] layout: resolve an image root -> segment -> chunk Reader opens a root of a volume and resolves a chunk index through the shard's segment to its ref, then reads the bytes from the pool of the volume the ref names (a restore's source for a foreign chunk). An index the root does not name reads as zeros; a root, segment or chunk the root reaches but the store lacks is ErrMissing, never zeros; bytes that do not hash to their name, or a segment holding another shard, are ErrCorrupt; a failed fetch is neither. DecodeRoot now checks the error of its re-encoding as DecodeSegment does. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/layout.go | 5 +- .../core/frontend/chunkstore/layout/read.go | 138 ++++++++++ .../frontend/chunkstore/layout/read_test.go | 245 ++++++++++++++++++ 3 files changed, 387 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/read.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/read_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout/layout.go b/seaweed-block/core/frontend/chunkstore/layout/layout.go index b43d4cfcc0..c4b470dfff 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/layout.go +++ b/seaweed-block/core/frontend/chunkstore/layout/layout.go @@ -341,7 +341,10 @@ func DecodeRoot(b []byte) (Root, error) { if r.err != nil { return Root{}, r.err } - again, _ := out.Encode() + again, err := out.Encode() + if err != nil { + return Root{}, err + } if !bytes.Equal(again, b) { return Root{}, fmt.Errorf("%w: root bytes are not canonical", ErrMalformed) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/read.go b/seaweed-block/core/frontend/chunkstore/layout/read.go new file mode 100644 index 0000000000..8ed871c4cc --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/read.go @@ -0,0 +1,138 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "path" +) + +// ErrMissing reports an object a root reaches that is not in the store: a +// root, a segment or a chunk. It is never read as zeros. +var ErrMissing = errors.New("layout: object missing") + +// ErrCorrupt reports an object whose bytes do not match its name. +var ErrCorrupt = errors.New("layout: object corrupt") + +// Fetch reads the whole object at p. A missing object is (nil, false, nil); +// any other failure is an error. +type Fetch func(ctx context.Context, p string) (data []byte, found bool, err error) + +// Reader resolves images of one volume: its roots and segments are read +// from //, each chunk from the pool of the volume its root +// entry names. +type Reader struct { + base, vol string + fetch Fetch +} + +// NewReader returns a Reader of vol under base. +func NewReader(base, vol string, fetch Fetch) (*Reader, error) { + if err := checkOwner(vol); err != nil { + return nil, err + } + if fetch == nil { + return nil, errors.New("layout: reader needs a fetch") + } + return &Reader{base: base, vol: vol, fetch: fetch}, nil +} + +// get fetches the object at rel under volume vol and checks its bytes hash +// to want. +func (r *Reader) get(ctx context.Context, vol, rel string, want Hash) ([]byte, error) { + p := path.Join(r.base, vol, rel) + b, ok, err := r.fetch(ctx, p) + if err != nil { + return nil, fmt.Errorf("layout: read %s: %w", p, err) + } + if !ok { + return nil, fmt.Errorf("%w: %s", ErrMissing, p) + } + if got := Sum(b); got != want { + return nil, fmt.Errorf("%w: %s hashes to %s", ErrCorrupt, p, got) + } + return b, nil +} + +// Image is one root of the volume, opened. +type Image struct { + r *Reader + root Root +} + +// Open reads and checks the root rn. +func (r *Reader) Open(ctx context.Context, rn RootName) (*Image, error) { + b, err := r.get(ctx, r.vol, rn.Path(), rn.Hash) + if err != nil { + return nil, err + } + root, err := DecodeRoot(b) + if err != nil { + return nil, fmt.Errorf("%w: root %s: %v", ErrCorrupt, rn, err) + } + return &Image{r: r, root: root}, nil +} + +// Segment reads the segment of shard; ok is false when the root names no +// segment for it (every index of the shard reads as zeros). +func (img *Image) Segment(ctx context.Context, shard uint64) (seg Segment, ok bool, err error) { + n, ok := img.root.Segments[shard] + if !ok { + return Segment{}, false, nil + } + b, err := img.r.get(ctx, img.r.vol, n.Path(), n.Hash) + if err != nil { + return Segment{}, false, err + } + seg, err = DecodeSegment(b) + if err != nil { + return Segment{}, false, fmt.Errorf("%w: segment %s: %v", ErrCorrupt, n, err) + } + if seg.Shard != shard { + return Segment{}, false, fmt.Errorf("%w: segment %s holds shard %d", ErrCorrupt, n, seg.Shard) + } + return seg, true, nil +} + +// Chunk is a resolved chunk: zeros, or the bytes of Ref. +type Chunk struct { + Zero bool + Ref Ref + Data []byte +} + +// Resolve finds the entry of index: root -> segment -> ref. An index the +// root does not name is zeros; a segment the root names but the store lacks +// is ErrMissing. +func (img *Image) Resolve(ctx context.Context, index uint64) (ref Ref, zero bool, err error) { + seg, ok, err := img.Segment(ctx, Shard(index)) + if err != nil { + return Ref{}, false, err + } + if !ok { + return Ref{}, true, nil + } + ref, ok = seg.Chunks[index] + if !ok { + return Ref{}, true, nil + } + return ref, false, nil +} + +// Chunk resolves index and reads its bytes from the pool of the volume +// that owns it. A chunk the root names but the owner's pool lacks is +// ErrMissing. +func (img *Image) Chunk(ctx context.Context, index uint64) (Chunk, error) { + ref, zero, err := img.Resolve(ctx, index) + if err != nil { + return Chunk{}, err + } + if zero { + return Chunk{Zero: true}, nil + } + b, err := img.r.get(ctx, ref.Owner, ref.Chunk.Path(), ref.Chunk.Hash) + if err != nil { + return Chunk{}, err + } + return Chunk{Ref: ref, Data: b}, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/read_test.go b/seaweed-block/core/frontend/chunkstore/layout/read_test.go new file mode 100644 index 0000000000..b3bd1c94ee --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/read_test.go @@ -0,0 +1,245 @@ +package layout + +import ( + "bytes" + "context" + "errors" + "path" + "strings" + "testing" +) + +// objStore is a fake store of whole objects by full path. +type objStore struct { + obj map[string][]byte + fail string // a path whose fetch fails + asked []string +} + +func (s *objStore) fetch(_ context.Context, p string) ([]byte, bool, error) { + s.asked = append(s.asked, p) + if p == s.fail { + return nil, false, errors.New("filer unavailable") + } + b, ok := s.obj[p] + return b, ok, nil +} + +const base = "/swblock/chunks" + +// readFixture: volume "t" (a restore target) whose root names chunk 3 +// ("own") in its own pool, chunk 10002 ("src data") in the pool of "src", +// and nothing else; every object is written. +func readFixture(t *testing.T) (*objStore, RootName, map[uint64]Ref) { + t.Helper() + s := &objStore{obj: map[string][]byte{}} + put := func(vol, rel string, b []byte) { s.obj[path.Join(base, vol, rel)] = b } + own := NameChunk(3, []byte("own")) + foreign := NameChunk(10002, []byte("src data")) + put("t", own.Path(), []byte("own")) + put("src", foreign.Path(), []byte("src data")) + m := map[uint64]Ref{3: {Owner: "t", Chunk: own}, 10002: {Owner: "src", Chunk: foreign}} + root, segs, err := Build(m) + if err != nil { + t.Fatal(err) + } + for n, b := range segs { + put("t", n.Path(), b) + } + rn, rb, err := NameRoot(root) + if err != nil { + t.Fatal(err) + } + put("t", rn.Path(), rb) + return s, rn, m +} + +func newReader(t *testing.T, s *objStore) *Reader { + t.Helper() + r, err := NewReader(base, "t", s.fetch) + if err != nil { + t.Fatal(err) + } + return r +} + +func TestRead_OwnChunk(t *testing.T) { + s, rn, _ := readFixture(t) + r := newReader(t, s) + img, err := r.Open(context.Background(), rn) + if err != nil { + t.Fatal(err) + } + c, err := img.Chunk(context.Background(), 3) + if err != nil || c.Zero || !bytes.Equal(c.Data, []byte("own")) || c.Ref.Owner != "t" { + t.Fatalf("chunk 3: %+v %v", c, err) + } +} + +// An index the root does not name reads as zeros: in a shard with a +// segment, and in a shard with none. Zeros never touch the pool. +func TestRead_AbsentIndexIsZeros(t *testing.T) { + s, rn, _ := readFixture(t) + r := newReader(t, s) + img, err := r.Open(context.Background(), rn) + if err != nil { + t.Fatal(err) + } + for _, idx := range []uint64{4, 9999, 10001, 50000} { + s.asked = nil + c, err := img.Chunk(context.Background(), idx) + if err != nil || !c.Zero || c.Data != nil { + t.Fatalf("index %d: %+v %v; want zeros", idx, c, err) + } + for _, p := range s.asked { + if strings.Contains(p, "/"+PoolDir+"/") { + t.Fatalf("index %d read the pool (%s) for a zero chunk", idx, p) + } + } + } +} + +// A foreign name resolves in the source volume's pool, never in the +// reading volume's. +func TestRead_ForeignChunkFromSourcePool(t *testing.T) { + s, rn, m := readFixture(t) + // A same-named object in t's own pool must not be what is read. + s.obj[path.Join(base, "t", m[10002].Chunk.Path())] = []byte("decoy") + r := newReader(t, s) + img, err := r.Open(context.Background(), rn) + if err != nil { + t.Fatal(err) + } + s.asked = nil + c, err := img.Chunk(context.Background(), 10002) + if err != nil || c.Zero || !bytes.Equal(c.Data, []byte("src data")) || c.Ref.Owner != "src" { + t.Fatalf("chunk 10002: %+v %v", c, err) + } + want := path.Join(base, "src", m[10002].Chunk.Path()) + if got := s.asked[len(s.asked)-1]; got != want { + t.Fatalf("read %s; want the source pool path %s", got, want) + } +} + +// A missing segment or chunk is an error, never zeros; so is a missing +// root. +func TestRead_MissingObjectIsAnErrorNeverZeros(t *testing.T) { + ctx := context.Background() + t.Run("root", func(t *testing.T) { + s, rn, _ := readFixture(t) + delete(s.obj, path.Join(base, "t", rn.Path())) + if _, err := newReader(t, s).Open(ctx, rn); !errors.Is(err, ErrMissing) { + t.Fatalf("open of a missing root: %v; want ErrMissing", err) + } + }) + t.Run("segment", func(t *testing.T) { + s, rn, _ := readFixture(t) + img, err := newReader(t, s).Open(ctx, rn) + if err != nil { + t.Fatal(err) + } + delete(s.obj, path.Join(base, "t", img.root.Segments[1].Path())) + for _, idx := range []uint64{10002, 10003} { // named, and not named, in that shard + c, err := img.Chunk(ctx, idx) + if !errors.Is(err, ErrMissing) || c.Zero { + t.Fatalf("index %d with its segment missing: %+v %v; want ErrMissing", idx, c, err) + } + } + }) + t.Run("own chunk", func(t *testing.T) { + s, rn, m := readFixture(t) + delete(s.obj, path.Join(base, "t", m[3].Chunk.Path())) + img, err := newReader(t, s).Open(ctx, rn) + if err != nil { + t.Fatal(err) + } + if c, err := img.Chunk(ctx, 3); !errors.Is(err, ErrMissing) || c.Zero { + t.Fatalf("missing own chunk: %+v %v; want ErrMissing", c, err) + } + }) + t.Run("foreign chunk", func(t *testing.T) { + s, rn, m := readFixture(t) + delete(s.obj, path.Join(base, "src", m[10002].Chunk.Path())) + img, err := newReader(t, s).Open(ctx, rn) + if err != nil { + t.Fatal(err) + } + if c, err := img.Chunk(ctx, 10002); !errors.Is(err, ErrMissing) || c.Zero { + t.Fatalf("missing foreign chunk: %+v %v; want ErrMissing", c, err) + } + }) +} + +// A failed fetch is an error and not ErrMissing; bytes that do not match +// their name are ErrCorrupt. +func TestRead_FetchFailureAndCorruption(t *testing.T) { + ctx := context.Background() + s, rn, m := readFixture(t) + r := newReader(t, s) + img, err := r.Open(ctx, rn) + if err != nil { + t.Fatal(err) + } + s.fail = path.Join(base, "t", m[3].Chunk.Path()) + if _, err := img.Chunk(ctx, 3); err == nil || errors.Is(err, ErrMissing) { + t.Fatalf("failed fetch: %v; want an error that is not ErrMissing", err) + } + s.fail = "" + for name, p := range map[string]string{ + "chunk": path.Join(base, "t", m[3].Chunk.Path()), + "segment": path.Join(base, "t", img.root.Segments[0].Path()), + } { + s2, rn2, _ := readFixture(t) + s2.obj[p] = append(append([]byte(nil), s2.obj[p]...), 'x') + img2, err := newReader(t, s2).Open(ctx, rn2) + if err != nil { + t.Fatal(err) + } + if _, err := img2.Chunk(ctx, 3); !errors.Is(err, ErrCorrupt) { + t.Errorf("%s altered: %v; want ErrCorrupt", name, err) + } + } + s3, rn3, _ := readFixture(t) + rp := path.Join(base, "t", rn3.Path()) + s3.obj[rp] = append(append([]byte(nil), s3.obj[rp]...), 0) + if _, err := newReader(t, s3).Open(ctx, rn3); !errors.Is(err, ErrCorrupt) { + t.Errorf("root altered: %v; want ErrCorrupt", err) + } +} + +// A segment stored under one shard's name but holding another shard is +// refused (its bytes match its hash, so only the shard check catches it). +func TestRead_SegmentOfAnotherShardRefused(t *testing.T) { + ctx := context.Background() + s := &objStore{obj: map[string][]byte{}} + seg := Segment{Shard: 2, Chunks: map[uint64]Ref{20000: {Owner: "t", Chunk: NameChunk(20000, []byte("z"))}}} + sn, sb, err := NameSegment(seg) + if err != nil { + t.Fatal(err) + } + lie := SegName{Shard: 0, Hash: sn.Hash} + s.obj[path.Join(base, "t", lie.Path())] = sb + root := Root{Segments: map[uint64]SegName{0: lie}} + rn, rb, err := NameRoot(root) + if err != nil { + t.Fatal(err) + } + s.obj[path.Join(base, "t", rn.Path())] = rb + img, err := newReader(t, s).Open(ctx, rn) + if err != nil { + t.Fatal(err) + } + if _, err := img.Chunk(ctx, 5); !errors.Is(err, ErrCorrupt) { + t.Fatalf("segment of shard 2 under shard 0: %v; want ErrCorrupt", err) + } +} + +func TestNewReader_RefusesBadInput(t *testing.T) { + f := func(context.Context, string) ([]byte, bool, error) { return nil, false, nil } + if _, err := NewReader(base, "a/b", f); err == nil { + t.Error("volume with a slash accepted") + } + if _, err := NewReader(base, "t", nil); err == nil { + t.Error("nil fetch accepted") + } +}