From 69cd920b13280ccd97f380eeaeee776a7de86981 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 12:57:02 -0800 Subject: [PATCH 01/20] Add snapshot incarnation codecs and target-qualified delete helpers --- .../frontend/chunkstore/layout/guard_test.go | 2 +- .../core/frontend/chunkstore/layout/head.go | 24 ++- .../chunkstore/layout/kernel_table_test.go | 14 +- .../chunkstore/layout/snapshot_generation.go | 77 ++++++++ .../layout/snapshot_generation_test.go | 182 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 6 + .../docs/design/snapshot-incarnations.md | 31 +++ 7 files changed, 330 insertions(+), 6 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/snapshot_generation.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/snapshot_generation_test.go create mode 100644 seaweed-block/docs/design/snapshot-incarnations.md diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index f8343ef538..69b1bebf18 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -211,7 +211,7 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) bad = append(bad, "OperatorReleaseDependent does not read the target's HEAD before releasing") } for name, by := range code { - if name == "DeleteSnapshot" { + if name == "DeleteSnapshot" || name == "DeleteSnapshotAt" { continue // a HEAD transition (a snapshot's name leaves HEAD), not a store remover } if strings.HasPrefix(name, "Delete") || strings.HasPrefix(name, "Remove") { diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index 4f345a8058..c11d772473 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -45,8 +45,12 @@ type Dependent struct { // that named it (the cut LSN of its image), and the restore targets that // still name its chunks, ordered by target id. type Snapshot struct { - Root RootName - Position uint64 + Root RootName + Position uint64 + // Gen identifies this incarnation of the name: its publishing HEAD + // generation, immutable after publication. Zero means legacy, not yet + // stamped by a v1.1 writer; it is never a valid delete target. + Gen uint64 Meta SnapshotMeta Dependents []Dependent // ManifestBytes is the size of the snapshot's manifest (its root and @@ -205,6 +209,7 @@ type headDoc struct { type snapDoc struct { Root string `json:"root"` Position uint64 `json:"position,omitempty"` + Gen *uint64 `json:"gen,omitempty"` CreatedNs int64 `json:"created_ns,omitempty"` Class string `json:"class,omitempty"` ExpiresNs int64 `json:"expires_ns,omitempty"` @@ -309,6 +314,9 @@ func (h Head) check() error { return fmt.Errorf("%w: %d dependents in HEAD, at most %d", ErrMalformed, n, MaxDependentsPerHead) } for n, s := range h.Snapshots { + if s.Gen != 0 && h.Version == 0 { + return fmt.Errorf("%w: v1.0 snapshot %q carries a publishing generation", ErrMalformed, n) + } if n == "" { return fmt.Errorf("%w: unnamed snapshot", ErrMalformed) } @@ -363,6 +371,10 @@ func (h Head) Encode() ([]byte, error) { d.Snapshots = map[string]snapDoc{} for n, s := range h.Snapshots { sd := snapDoc{Root: s.Root.String(), Position: s.Position, CreatedNs: s.Meta.CreatedNs, Class: s.Meta.Class, ExpiresNs: s.Meta.ExpiresNs, ManifestBytes: s.ManifestBytes} + if s.Gen != 0 { + gen := s.Gen + sd.Gen = &gen + } if len(s.Meta.Labels) > 0 { sd.Labels = s.Meta.Labels } @@ -428,11 +440,17 @@ func DecodeHead(b []byte, gen uint64, volume VolumeID) (Head, error) { if len(d.Snapshots) > 0 { h.Snapshots = map[string]Snapshot{} for n, s := range d.Snapshots { + if s.Gen != nil && *s.Gen == 0 { + return Head{}, fmt.Errorf("%w: snapshot %q explicitly carries generation zero", ErrMalformed, n) + } rn, err := ParseRootName(s.Root) if err != nil { return Head{}, err } snap := Snapshot{Root: rn, Position: s.Position, Meta: SnapshotMeta{CreatedNs: s.CreatedNs, Class: s.Class, ExpiresNs: s.ExpiresNs, Labels: s.Labels}, ManifestBytes: s.ManifestBytes} + if s.Gen != nil { + snap.Gen = *s.Gen + } for _, dep := range s.Dependents { tid, err := ParseVolumeID(dep.TargetID) if err != nil { @@ -540,7 +558,7 @@ func (h Head) clone() Head { if h.Snapshots != nil { c.Snapshots = make(map[string]Snapshot, len(h.Snapshots)) for n, s := range h.Snapshots { - c.Snapshots[n] = Snapshot{Root: s.Root, Position: s.Position, Meta: s.Meta.clone(), Dependents: append([]Dependent(nil), s.Dependents...), ManifestBytes: cloneSize(s.ManifestBytes)} + c.Snapshots[n] = Snapshot{Root: s.Root, Position: s.Position, Gen: s.Gen, Meta: s.Meta.clone(), Dependents: append([]Dependent(nil), s.Dependents...), ManifestBytes: cloneSize(s.ManifestBytes)} } } return c diff --git a/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go b/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go index 9a6d66de8e..590084fff6 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go @@ -29,7 +29,7 @@ var kernelStates = []string{"absent", "unclaimed", "idle", "snap", "clean", "det var kernelEntries = []string{ "CreateVolume", "CreateTarget", "StartHigher", "StartHigherCannotStart", "StartOwn", "StartOwnOtherFresh", "StartOwnOtherFreshCannotStart", "StartOwnOtherOld", "Claim", "Begin", "Commit", "CommitNew", "CommitLower", "Abort", "BeginClean", "EndClean", - "RemoveUnreachable", "DeleteSnapshot", "RetireSnapshot", "AddDependent", "ReleaseDependent", + "RemoveUnreachable", "DeleteSnapshot", "DeleteSnapshotAt", "RetireSnapshot", "AddDependent", "ReleaseDependent", "MarkDeleting", "MarkDeleted", "DeletedHeadCreate", } @@ -102,6 +102,13 @@ func kernelCell(t *testing.T, state, entry string) string { d.Dependents = []Dependent{{Target: "t", TargetID: idFor("t"), Root: d.Root}} h.Snapshots["daily"] = d } + if entry == "DeleteSnapshotAt" { + h.Version = HeadVersion1 + if s, ok := h.Snapshots["daily"]; ok { + s.Gen = 7 + h.Snapshots["daily"] = s + } + } nv := newMemNewVolume() vol := Volume{ID: idFor("v1"), Name: "v1", Geometry: tableGeometry, Format: VolumeFormat} if state != "absent" { @@ -217,6 +224,8 @@ func kernelCell(t *testing.T, state, entry string) string { _, err = RemoveUnreachable(ctx, nv, r, o, me, "c1", 0, orphans) case "DeleteSnapshot": _, err = RunDeleteSnapshot(ctx, nv, "daily") + case "DeleteSnapshotAt": + _, err = RunDeleteSnapshotAt(ctx, nv, "daily", 7) case "RetireSnapshot": _, err = RunRetireSnapshot(ctx, nv, "daily", 1) case "AddDependent": @@ -265,6 +274,7 @@ var kernelExpected = map[string]map[string]string{ "EndClean": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "noop", "snap": "NoSession", "clean": "write", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, "RemoveUnreachable": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "NoSession", "snap": "NoSession", "clean": "write", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, "DeleteSnapshot": {"absent": "HeadAbsent", "unclaimed": "noop", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "DeleteSnapshotAt": {"absent": "HeadAbsent", "unclaimed": "noop", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, "RetireSnapshot": {"absent": "HeadAbsent", "unclaimed": "noop", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, "AddDependent": {"absent": "HeadAbsent", "unclaimed": "NoSnapshot", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, "ReleaseDependent": {"absent": "HeadAbsent", "unclaimed": "noop", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "unreachable", "deleted": "unreachable"}, @@ -304,7 +314,7 @@ var kernelEntryFuncs = map[string]string{ "CreateVolume": "CreateVolume", "CreateTarget": "CreateTarget", "StartHigher": "Start", "StartOwn": "Start", "StartOwnOtherFresh": "Start", "StartOwnOtherOld": "Start", "StartHigherCannotStart": "Start", "StartOwnOtherFreshCannotStart": "Start", "Claim": "RunClaim", "Begin": "RunBegin", "Commit": "RunCommit", "CommitNew": "RunCommit", "CommitLower": "RunCommit", "Abort": "RunAbort", "BeginClean": "RunBeginClean", "EndClean": "RunEndClean", - "RemoveUnreachable": "RemoveUnreachable", "DeleteSnapshot": "RunDeleteSnapshot", "RetireSnapshot": "RunRetireSnapshot", + "RemoveUnreachable": "RemoveUnreachable", "DeleteSnapshot": "RunDeleteSnapshot", "DeleteSnapshotAt": "RunDeleteSnapshotAt", "RetireSnapshot": "RunRetireSnapshot", "AddDependent": "RunAddDependent", "ReleaseDependent": "RunReleaseDependent", "MarkDeleting": "RunMarkDeleting", "MarkDeleted": "RunMarkDeleted", "DeletedHeadCreate": "OperatorReleaseDependent", } diff --git a/seaweed-block/core/frontend/chunkstore/layout/snapshot_generation.go b/seaweed-block/core/frontend/chunkstore/layout/snapshot_generation.go new file mode 100644 index 0000000000..f51b980b3f --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/snapshot_generation.go @@ -0,0 +1,77 @@ +package layout + +import ( + "context" + "errors" + "fmt" +) + +// ErrSnapshotGenerationMissing refuses admission against an unstamped legacy +// snapshot. Zero is not an incarnation and cannot be a delete target. +var ErrSnapshotGenerationMissing = errors.New("layout: snapshot needs its v1.1 publishing generation: start a v1.1 holder to upgrade HEAD") + +// ErrHeadGenerationExhausted refuses publication instead of wrapping an +// incarnation to zero. +var ErrHeadGenerationExhausted = errors.New("layout: HEAD generation exhausted") + +// StampSnapshotGenerations prepares the first v1.1 write of legacy snapshots. +// The caller must publish the returned HEAD conditional on h.Gen, under the +// normal transition's authority checks. This pure step grants no authority +// and writes nothing. A lost CAS must reread and recompute; a lost reply keeps +// every identity already persisted by that CAS. +func (h Head) StampSnapshotGenerations() (Head, bool, error) { + if err := h.check(); err != nil { + return Head{}, false, err + } + changed := h.Version == 0 + for _, s := range h.Snapshots { + changed = changed || s.Gen == 0 + } + if !changed { + return h, false, nil + } + if h.Gen == ^uint64(0) { + return Head{}, false, ErrHeadGenerationExhausted + } + next := h.clone() + next.Version = HeadVersion1 + for name, s := range next.Snapshots { + if s.Gen == 0 { + s.Gen = h.Gen + 1 + next.Snapshots[name] = s + } + } + return next, true, nil +} + +// DeleteSnapshotAt removes only an already admitted incarnation. Admission +// resolves initial absence separately; a retained target that has since gone +// or been replaced succeeds without removing anything. Existing dependent +// and volume-state checks still apply to an actual removal. +func (h Head) DeleteSnapshotAt(name string, gen uint64) (Head, bool, error) { + if gen == 0 { + return Head{}, false, ErrSnapshotGenerationMissing + } + if h.State != StateLive && h.State != StateDetached { + return Head{}, false, fmt.Errorf("%w: HEAD is %s", ErrVolumeDeleting, h.State) + } + s, found := h.Snapshots[name] + if !found { + return h, false, nil + } + if s.Gen == 0 { + return Head{}, false, ErrSnapshotGenerationMissing + } + if s.Gen != gen { + return h, false, nil + } + return h.DeleteSnapshot(name) +} + +// RunDeleteSnapshotAt preserves the captured target across the conditional +// update; the caller never resolves the current name to a replacement target. +func RunDeleteSnapshotAt(ctx context.Context, st HeadStore, name string, gen uint64) (Head, error) { + return runTransition(ctx, st, CauseSnapshotDelete, func(h Head) (Head, bool, error) { + return h.DeleteSnapshotAt(name, gen) + }) +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/snapshot_generation_test.go b/seaweed-block/core/frontend/chunkstore/layout/snapshot_generation_test.go new file mode 100644 index 0000000000..48783a16bf --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/snapshot_generation_test.go @@ -0,0 +1,182 @@ +package layout + +import ( + "bytes" + "testing" +) + +// Fixed bytes cover an unbound snapshot: its identity does not depend on +// request-id metadata, the current image, a timestamp, or the current HEAD gen. +func TestSnapshotPublishingGenerationGolden(t *testing.T) { + raw := []byte(`{"version":1,"volume_id":"00000000000000000000000000000001","epoch":0,"holder":"","activity":{"kind":"idle"},"position":0,"snapshots":{"daily":{"root":"0000000000000000000000000000000000000000000000000000000000000000","gen":42}}}`) + id, err := ParseVolumeID("00000000000000000000000000000001") + if err != nil { + t.Fatal(err) + } + h, err := DecodeHead(raw, 50, id) + if err != nil { + t.Fatal(err) + } + got, err := h.Encode() + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, raw) { + t.Fatalf("publishing identity lost: %s", got) + } +} + +func TestLegacySnapshotStampKeepsOneIdentityAcrossRetry(t *testing.T) { + h := idleHead() + h.Snapshots = map[string]Snapshot{"daily": {Root: RootName{}}, "scheduled": {Root: RootName{}}} + next, changed, err := h.StampSnapshotGenerations() + if err != nil || !changed { + t.Fatalf("stamp: changed=%v err=%v", changed, err) + } + if next.Version != HeadVersion1 || next.Snapshots["daily"].Gen != 8 || next.Snapshots["scheduled"].Gen != 8 { + t.Fatalf("stamp: %+v", next) + } + if h.Snapshots["daily"].Gen != 0 || h.Version != 0 { + t.Fatal("input mutated before CAS") + } + raw, err := next.Encode() + if err != nil { + t.Fatal(err) + } + persisted, err := DecodeHead(raw, 8, h.VolumeID) + if err != nil { + t.Fatal(err) + } + again, changed, err := persisted.StampSnapshotGenerations() + if err != nil || changed || again.Snapshots["daily"].Gen != 8 { + t.Fatalf("lost answer reminted identity: %+v changed=%v err=%v", again, changed, err) + } + // An unrelated HEAD write changes the CAS generation, never snapshot identity. + persisted.Gen = 19 + again, changed, err = persisted.StampSnapshotGenerations() + if err != nil || changed || again.Snapshots["daily"].Gen != 8 { + t.Fatal("unrelated HEAD update changed incarnation") + } +} + +func TestSnapshotDeleteTargetSparesAnUnchangedImageRecreation(t *testing.T) { + h := idleHead() + h.Version = HeadVersion1 + h.Snapshots = map[string]Snapshot{"daily": {Root: RootName{}, Gen: 8}} + // The image and position are unchanged, only the publication is new. + recreated := h.clone() + s := recreated.Snapshots["daily"] + s.Gen = 12 + recreated.Snapshots["daily"] = s + next, changed, err := recreated.DeleteSnapshotAt("daily", 8) + if err != nil || changed || next.Snapshots["daily"].Gen != 12 { + t.Fatalf("stale target removed replacement: %+v %v %v", next, changed, err) + } + next, changed, err = h.DeleteSnapshotAt("daily", 8) + if err != nil || !changed || len(next.Snapshots) != 0 { + t.Fatalf("exact target not removed: %+v %v %v", next, changed, err) + } + _, changed, err = next.DeleteSnapshotAt("daily", 8) + if err != nil || changed { + t.Fatal("admitted target already gone must succeed without removal") + } + legacy := idleHead() + legacy.Snapshots = map[string]Snapshot{"daily": {Root: RootName{}}} + if _, _, err = legacy.DeleteSnapshotAt("daily", 8); err != ErrSnapshotGenerationMissing { + t.Fatalf("legacy admission must require stamp: %v", err) + } + if _, _, err = h.DeleteSnapshotAt("daily", 0); err != ErrSnapshotGenerationMissing { + t.Fatalf("zero became an identity: %v", err) + } +} + +func TestSnapshotGenerationRefusesInvalidBytesAndKeepsLegacyBytes(t *testing.T) { + h := idleHead() + h.Snapshots = map[string]Snapshot{"legacy": {Root: RootName{}}} + raw, err := h.Encode() + if err != nil { + t.Fatal(err) + } + decoded, err := DecodeHead(raw, h.Gen, h.VolumeID) + if err != nil || decoded.Snapshots["legacy"].Gen != 0 { + t.Fatalf("legacy: %v", err) + } + again, err := decoded.Encode() + if err != nil || !bytes.Equal(again, raw) { + t.Fatal("legacy bytes changed") + } + h.Version = HeadVersion1 + s := h.Snapshots["legacy"] + s.Gen = 8 + h.Snapshots["legacy"] = s + raw, err = h.Encode() + if err != nil { + t.Fatal(err) + } + zero := bytes.Replace(raw, []byte(`"gen":8`), []byte(`"gen":0`), 1) + if _, err = DecodeHead(zero, 8, h.VolumeID); err == nil { + t.Fatal("explicit zero accepted") + } + oldVersion := bytes.Replace(raw, []byte(`"version":1,`), nil, 1) + if _, err = DecodeHead(oldVersion, 8, h.VolumeID); err == nil { + t.Fatal("v1.0 accepted publishing generation") + } + exhausted := idleHead() + exhausted.Gen = ^uint64(0) + exhausted.Snapshots = map[string]Snapshot{"legacy": {Root: RootName{}}} + if _, _, err = exhausted.StampSnapshotGenerations(); err != ErrHeadGenerationExhausted { + t.Fatalf("exhaustion: %v", err) + } +} + +func TestSnapshotDeleteTargetKeepsDependentAndStateGuards(t *testing.T) { + h := idleHead() + h.Version = HeadVersion1 + h.Snapshots = map[string]Snapshot{"daily": {Root: RootName{}, Gen: 8, Dependents: deps(RootName{}, "target")}} + if _, _, err := h.DeleteSnapshotAt("daily", 8); err == nil { + t.Fatal("dependent bypassed") + } + h.State = StateDeleting + if _, _, err := h.DeleteSnapshotAt("daily", 8); err == nil { + t.Fatal("volume deleting bypassed") + } +} + +func TestSnapshotDeleteCASConflictKeepsCapturedIncarnation(t *testing.T) { + h := idleHead() + h.Version = HeadVersion1 + h.Snapshots = map[string]Snapshot{"daily": {Root: RootName{}, Gen: 7}} + st := &memHead{h: &h} + st.hook = func() { s := st.h.Snapshots["daily"]; s.Gen = 9; st.h.Snapshots["daily"] = s; st.h.Gen = 9 } + if _, err := RunDeleteSnapshotAt(t.Context(), st, "daily", 7); err != ErrPrecondition { + t.Fatalf("CAS race: %v", err) + } + next, err := RunDeleteSnapshotAt(t.Context(), st, "daily", 7) + if err != nil || next.Snapshots["daily"].Gen != 9 { + t.Fatalf("retry removed replacement: %+v %v", next, err) + } +} + +func TestDeleteSnapshotAt_Closure(t *testing.T) { + h := idleHead() + h.Version = HeadVersion1 + h.Snapshots = map[string]Snapshot{"daily": {Root: RootName{}, Gen: 7}} + next, changed, err := h.DeleteSnapshotAt("daily", 7) + if err != nil || !changed { + t.Fatalf("removal: %v %v", changed, err) + } + if _, err := next.Encode(); err != nil { + t.Fatalf("result cannot encode: %v", err) + } +} + +func TestRunDeleteSnapshotAt_InterruptAtEveryStep(t *testing.T) { + h := idleHead() + h.Version = HeadVersion1 + h.Snapshots = map[string]Snapshot{"daily": {Root: RootName{}, Gen: 7}} + interruptHead(t, h, func(st HeadStore) error { _, err := RunDeleteSnapshotAt(t.Context(), st, "daily", 7); return err }, func(t *testing.T, next Head) { + if _, found := next.Snapshots["daily"]; found { + t.Fatal("target still present") + } + }) +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d1ee250300..e06e2ff5c9 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1395,3 +1395,9 @@ same-process retries; a repeated or earlier frontier is not progress. Late progress cannot clear an already elapsed inactivity window. The existing same-epoch promotion-ready fact alone clears the timeout latch. C.L's start rows remain STUB until recovery and attach controls are qualified together. + +### Snapshot incarnation format integration + +| ID | Statement | Transition | Enforced in | Guard | Model | Status | +|---|---|---|---|---|---|---| +| `INV-SNAPSHOT-INCARNATION-001` | A snapshot identity is its name and immutable publishing HEAD generation within the volume ID. A resumed delete removes only its admitted incarnation; a recreated name is preserved. Zero requires legacy stamping. | M9 snapshot publication and target-qualified removal | `layout/head.go`, `layout/snapshot_generation.go`; producer integration pending | `TestSnapshotPublishingGenerationGolden`, `TestLegacySnapshotStampKeepsOneIdentityAcrossRetry`, `TestSnapshotDeleteTargetSparesAnUnchangedImageRecreation`, `TestSnapshotDeleteCASConflictKeepsCapturedIncarnation` | SnapDelete rows 241-245 | STUB until production stamping and receipt integration | diff --git a/seaweed-block/docs/design/snapshot-incarnations.md b/seaweed-block/docs/design/snapshot-incarnations.md new file mode 100644 index 0000000000..50fb0025d3 --- /dev/null +++ b/seaweed-block/docs/design/snapshot-incarnations.md @@ -0,0 +1,31 @@ +# Snapshot incarnation identities + +A v1.1 snapshot entry carries `gen`, its publishing HEAD generation. The +identity is the enclosing volume's full ID, the snapshot name and this +immutable generation. Name, root, position and wall-clock creation time +alone cannot distinguish recreation on an unchanged image. + +An absent field is a legacy, unstamped snapshot. Zero is not a delete target; +an explicit zero is refused. The first v1.1 write stamps every legacy entry +with that write's generation. Different names may receive the same stamp. +An older binary refuses the new known field, preventing a gen-less replacement. + +`Head.StampSnapshotGenerations` prepares this conversion without changing its +input or writing anything. Its caller must retain the ordinary holder and +transition guards and publish conditional on the observed HEAD generation. +After a CAS conflict it rereads and recomputes; after a lost reply it keeps +already persisted identities. Generation exhaustion refuses rather than wraps. + +`Head.DeleteSnapshotAt` and `RunDeleteSnapshotAt` act on a previously admitted +`(name, gen)`. They remove only that incarnation, retain dependent and volume +state guards, and succeed without removal if the target has disappeared or +been replaced. An unstamped current entry refuses. New admission is separate: +an initially absent target is not found, and a retained receipt supplies its +original target on every retry without resolving the current name again. + +This first slice supplies the format reader/encoder and kernel helpers. It +does not enable the production stamp writer or asynchronous delete executor. +The v1.1 writer integration must stamp every newly published scheduled, +unbound and operation-bound snapshot and preserve all existing nonzero gens. +Any duplicate operation-binding generation must match the entry. These remain +requirements for the producer integration before format declaration. \ No newline at end of file From ee3c3e493df09440cd13f68a0ceddc0713bcf1d7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 12:58:27 -0800 Subject: [PATCH 02/20] Register snapshot incarnation trace in invariant ledger --- seaweed-block/docs/design/invariants.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e06e2ff5c9..a0cfcfb50d 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1258,6 +1258,12 @@ Notes: - B.10 rows are enforced in a library with no production caller; they say nothing about a running volume until a caller is added and its own rows name these. +### Snapshot incarnation format integration + +| ID | Statement | Transition | Enforced in | Guard | Model | Status | +|---|---|---|---|---|---|---| +| `INV-SNAPSHOT-INCARNATION-001` | A snapshot identity is its name and immutable publishing HEAD generation within the volume ID. A resumed delete removes only its admitted incarnation; a recreated name is preserved. Zero requires legacy stamping. | M9 snapshot publication and target-qualified removal | `layout/head.go`, `layout/snapshot_generation.go`; producer integration pending | `TestSnapshotPublishingGenerationGolden`, `TestLegacySnapshotStampKeepsOneIdentityAcrossRetry`, `TestSnapshotDeleteTargetSparesAnUnchangedImageRecreation`, `TestSnapshotDeleteCASConflictKeepsCapturedIncarnation` | SnapDelete rows 241-245 | STUB | + ## Part C. Change rules How a fix or a feature is calibrated against this model: @@ -1395,9 +1401,3 @@ same-process retries; a repeated or earlier frontier is not progress. Late progress cannot clear an already elapsed inactivity window. The existing same-epoch promotion-ready fact alone clears the timeout latch. C.L's start rows remain STUB until recovery and attach controls are qualified together. - -### Snapshot incarnation format integration - -| ID | Statement | Transition | Enforced in | Guard | Model | Status | -|---|---|---|---|---|---|---| -| `INV-SNAPSHOT-INCARNATION-001` | A snapshot identity is its name and immutable publishing HEAD generation within the volume ID. A resumed delete removes only its admitted incarnation; a recreated name is preserved. Zero requires legacy stamping. | M9 snapshot publication and target-qualified removal | `layout/head.go`, `layout/snapshot_generation.go`; producer integration pending | `TestSnapshotPublishingGenerationGolden`, `TestLegacySnapshotStampKeepsOneIdentityAcrossRetry`, `TestSnapshotDeleteTargetSparesAnUnchangedImageRecreation`, `TestSnapshotDeleteCASConflictKeepsCapturedIncarnation` | SnapDelete rows 241-245 | STUB until production stamping and receipt integration | From 0a6d952817562149fa504e5b07dd1d19bd0e9d65 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:05:27 -0800 Subject: [PATCH 03/20] Guard mixed snapshot stamps and surviving sibling identities --- .../chunkstore/layout/snapshot_generation.go | 2 +- .../layout/snapshot_generation_test.go | 56 +++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/snapshot_generation.go b/seaweed-block/core/frontend/chunkstore/layout/snapshot_generation.go index f51b980b3f..9ebe018162 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/snapshot_generation.go +++ b/seaweed-block/core/frontend/chunkstore/layout/snapshot_generation.go @@ -47,7 +47,7 @@ func (h Head) StampSnapshotGenerations() (Head, bool, error) { // DeleteSnapshotAt removes only an already admitted incarnation. Admission // resolves initial absence separately; a retained target that has since gone // or been replaced succeeds without removing anything. Existing dependent -// and volume-state checks still apply to an actual removal. +// checks apply to actual removal; volume-state checks also apply to no-ops. func (h Head) DeleteSnapshotAt(name string, gen uint64) (Head, bool, error) { if gen == 0 { return Head{}, false, ErrSnapshotGenerationMissing diff --git a/seaweed-block/core/frontend/chunkstore/layout/snapshot_generation_test.go b/seaweed-block/core/frontend/chunkstore/layout/snapshot_generation_test.go index 48783a16bf..47aac90c73 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/snapshot_generation_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/snapshot_generation_test.go @@ -180,3 +180,59 @@ func TestRunDeleteSnapshotAt_InterruptAtEveryStep(t *testing.T) { } }) } + +func TestMixedLegacyStampPreservesPublishedSibling(t *testing.T) { + h := idleHead() + h.Version = HeadVersion1 + h.Snapshots = map[string]Snapshot{"old": {Root: RootName{}, Gen: 4}, "legacy": {Root: RootName{}}} + next, changed, err := h.StampSnapshotGenerations() + if err != nil || !changed { + t.Fatalf("mixed stamp: %v %v", changed, err) + } + if next.Snapshots["old"].Gen != 4 || next.Snapshots["legacy"].Gen != 8 { + t.Fatalf("published identity reminted: %+v", next.Snapshots) + } + if h.Snapshots["old"].Gen != 4 || h.Snapshots["legacy"].Gen != 0 { + t.Fatal("pre-CAS input changed") + } + raw, err := next.Encode() + if err != nil { + t.Fatal(err) + } + reread, err := DecodeHead(raw, 8, h.VolumeID) + if err != nil { + t.Fatal(err) + } + retry, changed, err := reread.StampSnapshotGenerations() + if err != nil || changed || retry.Snapshots["old"].Gen != 4 || retry.Snapshots["legacy"].Gen != 8 { + t.Fatalf("mixed stamp reply-loss retry: %+v %v %v", retry.Snapshots, changed, err) + } +} + +func TestSnapshotDeletePreservesPublishedSibling(t *testing.T) { + h := idleHead() + h.Version = HeadVersion1 + h.Snapshots = map[string]Snapshot{"remove": {Root: RootName{}, Gen: 7}, "keep": {Root: RootName{}, Gen: 4}} + st := &memHead{h: &h} + next, err := RunDeleteSnapshotAt(t.Context(), st, "remove", 7) + if err != nil { + t.Fatal(err) + } + if len(next.Snapshots) != 1 || next.Snapshots["keep"].Gen != 4 { + t.Fatalf("survivor identity lost: %+v", next.Snapshots) + } + if len(h.Snapshots) != 2 || h.Snapshots["keep"].Gen != 4 || h.Snapshots["remove"].Gen != 7 { + t.Fatal("source HEAD mutated") + } + raw, err := next.Encode() + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(raw, []byte(`"gen":4`)) { + t.Fatalf("survivor bytes lost generation: %s", raw) + } + reread, err := DecodeHead(raw, next.Gen, h.VolumeID) + if err != nil || reread.Snapshots["keep"].Gen != 4 { + t.Fatalf("persisted survivor: %v", err) + } +} From ad9663bfe0b93ee64f0b421e867139708c4e4b45 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:11:19 -0800 Subject: [PATCH 04/20] Add bounded immutable list page codecs and golden vectors --- .../frontend/chunkstore/layout/list_page.go | 243 ++++++++++++++++++ .../chunkstore/layout/list_page_test.go | 171 ++++++++++++ .../testdata/list-page-v1/delete-head.json | 1 + .../testdata/list-page-v1/delete-tail.json | 1 + .../layout/testdata/list-page-v1/drop.json | 1 + .../testdata/list-page-v1/upload-intent.json | 1 + .../docs/design/immutable-list-pages.md | 43 ++++ 7 files changed, 461 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/list_page.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/list_page_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/delete-head.json create mode 100644 seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/delete-tail.json create mode 100644 seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/drop.json create mode 100644 seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/upload-intent.json create mode 100644 seaweed-block/docs/design/immutable-list-pages.md diff --git a/seaweed-block/core/frontend/chunkstore/layout/list_page.go b/seaweed-block/core/frontend/chunkstore/layout/list_page.go new file mode 100644 index 0000000000..24b23e8b75 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/list_page.go @@ -0,0 +1,243 @@ +package layout + +import ( + "bytes" + "encoding/json" + "fmt" + "strings" +) + +// These are format ceilings, not work timeouts. Reading one page never +// requires materializing its chain. A producer must stop before exceeding +// them; it may not truncate a list or omit required candidates. +const ( + ListPageVersion = 1 + ListDir = "lists" + MaxListPageBytes = 1 << 20 + MaxListPageEntries = 4096 + MaxListPages = 4096 + MaxListProducerBytes = 256 +) + +type ListKind string + +const ( + ListDrop ListKind = "drop" + ListUploadIntent ListKind = "upload-intent" + ListSnapshotDeleteIntent ListKind = "snapshot-delete-intent" +) + +// ListRef binds the exact bytes and remaining page count. Pages decreases +// strictly along Next, so a reader never follows an unbounded/cyclic chain. +type ListRef struct { + Hash string `json:"hash"` + Pages uint32 `json:"pages"` +} + +func (r ListRef) check() error { + h, err := parseHash(r.Hash) + if err != nil || h.String() != r.Hash || r.Pages == 0 || r.Pages > MaxListPages { + return fmt.Errorf("%w: invalid list reference", ErrMalformed) + } + return nil +} +func (r ListRef) Path() (string, error) { + if err := r.check(); err != nil { + return "", err + } + return ListDir + "/" + r.Hash, nil +} + +// SnapshotTarget is an admitted snapshot incarnation, never a resolution +// of the name made again by a later executor. VolumeID is on its page. +type SnapshotTarget struct { + Name string `json:"name"` + Gen uint64 `json:"gen"` +} + +// ListPage is immutable metadata. Its presence grants no delete/upload +// authority. A writer publishes its reference through HEAD only after the +// page is durable; producer and consumer wiring is a separate transition. +type ListPage struct { + VolumeID VolumeID + Kind ListKind + Producer string + Generation uint64 + Pages uint32 + Next *ListRef + Target *SnapshotTarget + Entries []string +} + +type listPageDoc struct { + Version int `json:"version"` + VolumeID string `json:"volume_id"` + Kind ListKind `json:"kind"` + Producer string `json:"producer"` + Generation uint64 `json:"generation"` + Pages uint32 `json:"pages"` + Next *ListRef `json:"next,omitempty"` + Target *SnapshotTarget `json:"target,omitempty"` + Entries []string `json:"entries"` +} + +func (p ListPage) check() error { + if p.VolumeID.IsZero() || p.Generation == 0 || p.Pages == 0 || p.Pages > MaxListPages { + return fmt.Errorf("%w: list page identity or page count", ErrMalformed) + } + if p.Producer == "" || len(p.Producer) > MaxListProducerBytes { + return fmt.Errorf("%w: list page producer", ErrMalformed) + } + if err := validName("list producer", p.Producer); err != nil { + return err + } + switch p.Kind { + case ListDrop: + case ListUploadIntent: + if p.Target != nil { + return fmt.Errorf("%w: upload intent has a snapshot target", ErrMalformed) + } + case ListSnapshotDeleteIntent: + if p.Target == nil { + return fmt.Errorf("%w: snapshot-delete intent needs its captured target", ErrMalformed) + } + default: + return fmt.Errorf("%w: unknown list kind %q", ErrMalformed, p.Kind) + } + if p.Target != nil { + if p.Target.Gen == 0 { + return fmt.Errorf("%w: list snapshot target generation zero", ErrMalformed) + } + if err := CheckSnapshot(p.Target.Name, SnapshotMeta{}); err != nil { + return err + } + } + if p.Next == nil { + if p.Pages != 1 { + return fmt.Errorf("%w: list chain ends before its declared count", ErrMalformed) + } + } else { + if err := p.Next.check(); err != nil { + return err + } + if p.Pages != p.Next.Pages+1 { + return fmt.Errorf("%w: list page count does not decrease by one", ErrMalformed) + } + } + if len(p.Entries) == 0 || len(p.Entries) > MaxListPageEntries { + return fmt.Errorf("%w: list page entry count", ErrMalformed) + } + for i, rel := range p.Entries { + if i > 0 && p.Entries[i-1] >= rel { + return fmt.Errorf("%w: list names not sorted and unique", ErrMalformed) + } + if err := checkListObjectPath(rel); err != nil { + return err + } + } + return nil +} + +// checkListObjectPath accepts canonical content-named data objects only. +// HEAD, VOLUME, another list, arbitrary paths and foreign directories are +// never candidates merely because a page contains a string naming them. +func checkListObjectPath(rel string) error { + parts := strings.Split(rel, "/") + if len(parts) == 2 { + switch parts[0] { + case RootDir: + n, err := ParseRootName(parts[1]) + if err == nil && n.Path() == rel { + return nil + } + case SegDir: + n, err := ParseSegName(parts[1]) + if err == nil && n.Path() == rel { + return nil + } + } + } + if len(parts) == 3 && parts[0] == PoolDir { + n, err := ParseChunkName(parts[2]) + if err == nil && n.Path() == rel { + return nil + } + } + return fmt.Errorf("%w: list candidate %q is not a canonical object path", ErrMalformed, rel) +} + +func (p ListPage) Encode() ([]byte, error) { + if err := p.check(); err != nil { + return nil, err + } + d := listPageDoc{Version: ListPageVersion, VolumeID: p.VolumeID.String(), Kind: p.Kind, Producer: p.Producer, Generation: p.Generation, Pages: p.Pages, Next: p.Next, Target: p.Target, Entries: p.Entries} + b, err := json.Marshal(d) + if err == nil && len(b) > MaxListPageBytes { + return nil, fmt.Errorf("%w: list page exceeds byte limit", ErrMalformed) + } + return b, err +} + +func listPageHash(raw []byte) string { + return Sum(append([]byte("swblock:list-page:v1\x00"), raw...)).String() +} +func (p ListPage) Ref() (ListRef, error) { + raw, err := p.Encode() + if err != nil { + return ListRef{}, err + } + return ListRef{Hash: listPageHash(raw), Pages: p.Pages}, nil +} + +var ErrListPageNewerVersion = fmt.Errorf("%w: list page written by a newer version: use a newer binary", ErrMalformed) + +// DecodeListPage checks one bounded page against the reference and full +// volume identity before any consumer can interpret its candidates. +func DecodeListPage(raw []byte, ref ListRef, volume VolumeID) (ListPage, error) { + if len(raw) > MaxListPageBytes { + return ListPage{}, fmt.Errorf("%w: list page exceeds byte limit", ErrMalformed) + } + if err := ref.check(); err != nil { + return ListPage{}, err + } + if listPageHash(raw) != ref.Hash { + return ListPage{}, fmt.Errorf("%w: list page content hash mismatch", ErrCorrupt) + } + var probe struct { + Version int `json:"version"` + } + if err := json.Unmarshal(raw, &probe); err != nil { + return ListPage{}, fmt.Errorf("%w: list page: %v", ErrMalformed, err) + } + if probe.Version > ListPageVersion { + return ListPage{}, ErrListPageNewerVersion + } + if probe.Version != ListPageVersion { + return ListPage{}, fmt.Errorf("%w: list page version %d", ErrMalformed, probe.Version) + } + var d listPageDoc + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.DisallowUnknownFields() + if err := dec.Decode(&d); err != nil { + return ListPage{}, fmt.Errorf("%w: list page: %v", ErrMalformed, err) + } + id, err := ParseVolumeID(d.VolumeID) + if err != nil { + return ListPage{}, err + } + if volume.IsZero() || id != volume { + return ListPage{}, ErrIdentity + } + p := ListPage{VolumeID: id, Kind: d.Kind, Producer: d.Producer, Generation: d.Generation, Pages: d.Pages, Next: d.Next, Target: d.Target, Entries: d.Entries} + if p.Pages != ref.Pages { + return ListPage{}, fmt.Errorf("%w: list reference page count mismatch", ErrMalformed) + } + canon, err := p.Encode() + if err != nil { + return ListPage{}, err + } + if !bytes.Equal(canon, raw) { + return ListPage{}, fmt.Errorf("%w: list page is not canonical", ErrMalformed) + } + return p, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/list_page_test.go b/seaweed-block/core/frontend/chunkstore/layout/list_page_test.go new file mode 100644 index 0000000000..6e026f0287 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/list_page_test.go @@ -0,0 +1,171 @@ +package layout + +import ( + "bytes" + "errors" + "fmt" + "os" + "sort" + "strings" + "testing" +) + +const dropPageGolden = `{"version":1,"volume_id":"00000000000000000000000000000001","kind":"drop","producer":"cut-a","generation":42,"pages":1,"entries":["root/0000000000000000000000000000000000000000000000000000000000000000"]}` + +func TestListPageGoldenAndContentBinding(t *testing.T) { + id, err := ParseVolumeID("00000000000000000000000000000001") + if err != nil { + t.Fatal(err) + } + // Fixed expected bytes are independent of the encoder under test. + p := ListPage{VolumeID: id, Kind: ListDrop, Producer: "cut-a", Generation: 42, Pages: 1, Entries: []string{"root/" + strings.Repeat("0", 64)}} + raw, err := p.Encode() + if err != nil { + t.Fatal(err) + } + if string(raw) != dropPageGolden { + t.Fatalf("format changed: %s", raw) + } + ref, err := p.Ref() + if err != nil { + t.Fatal(err) + } + decoded, err := DecodeListPage([]byte(dropPageGolden), ref, id) + if err != nil { + t.Fatal(err) + } + again, err := decoded.Encode() + if err != nil || !bytes.Equal(raw, again) { + t.Fatalf("round trip: %s %v", again, err) + } + corrupted := bytes.Replace(raw, []byte(`"cut-a"`), []byte(`"cut-b"`), 1) + if _, err := DecodeListPage(corrupted, ref, id); err == nil { + t.Fatal("content-name corruption accepted") + } + other := idFor("other") + if _, err := DecodeListPage(raw, ref, other); err == nil { + t.Fatal("cross-volume page accepted") + } +} + +func TestListPageGoldenVectors(t *testing.T) { + id, _ := ParseVolumeID("00000000000000000000000000000001") + for _, tc := range []struct { + name, hash string + pages uint32 + }{ + {"drop", "c63e99b5835669e4e46b4efb780e0a4fd4f55a088d78f9fb871d4caa0ed49294", 1}, + {"upload-intent", "d4ad26a9e72cfd6533188e130584ff12a45f3d402f4907a934e7ada0ad909db8", 1}, + {"delete-tail", "d30f6462321c2b060f6d3972bb01c8b70c978d3b46c1cd3752f393b429b0b548", 1}, + {"delete-head", "b6ad6d5f8d8f47fd9dd7c17b0184ae684949f7cf1f0bc13001b777e6b9b9c23a", 2}, + } { + t.Run(tc.name, func(t *testing.T) { + raw, err := os.ReadFile("testdata/list-page-v1/" + tc.name + ".json") + if err != nil { + t.Fatal(err) + } + ref := ListRef{Hash: tc.hash, Pages: tc.pages} + p, err := DecodeListPage(raw, ref, id) + if err != nil { + t.Fatal(err) + } + encoded, err := p.Encode() + if err != nil || !bytes.Equal(encoded, raw) { + t.Fatalf("golden encoding changed: %s %v", encoded, err) + } + got, err := p.Ref() + if err != nil || got != ref { + t.Fatalf("golden content name: %+v %v", got, err) + } + }) + } +} + +// Give each deliberately invalid document its own correct hash, so schema +// validation, not an unrelated hash mismatch, is what rejects it. +func TestListPageRefusesMalformedDocuments(t *testing.T) { + id, _ := ParseVolumeID("00000000000000000000000000000001") + z := strings.Repeat("0", 64) + for name, raw := range map[string]string{ + "truncated": dropPageGolden[:len(dropPageGolden)-1], + "unknown field": strings.Replace(dropPageGolden, `"version":1,`, `"version":1,"unexpected":1,`, 1), + "duplicate field": strings.Replace(dropPageGolden, `"version":1,`, `"version":1,"version":1,`, 1), + "whitespace": dropPageGolden + "\n", + "unknown kind": strings.Replace(dropPageGolden, `"kind":"drop"`, `"kind":"other"`, 1), + "zero generation": strings.Replace(dropPageGolden, `"generation":42`, `"generation":0`, 1), + "zero pages": strings.Replace(dropPageGolden, `"pages":1`, `"pages":0`, 1), + "too many pages": strings.Replace(dropPageGolden, `"pages":1`, `"pages":4097`, 1), + "early tail": strings.Replace(dropPageGolden, `"pages":1`, `"pages":2`, 1), + "bad next count": strings.Replace(dropPageGolden, `"entries":`, `"next":{"hash":"`+z+`","pages":1},"entries":`, 1), + "unbound delete": strings.Replace(dropPageGolden, `"kind":"drop"`, `"kind":"snapshot-delete-intent"`, 1), + "HEAD candidate": strings.Replace(dropPageGolden, "root/"+z, "HEAD", 1), + "list candidate": strings.Replace(dropPageGolden, "root/"+z, "lists/"+z, 1), + "wrong shard": strings.Replace(dropPageGolden, "root/"+z, "pool/1/0-"+z, 1), + "parent traversal": strings.Replace(dropPageGolden, "root/"+z, "root/../HEAD", 1), + "duplicate name": strings.Replace(dropPageGolden, `"root/`+z+`"`, `"root/`+z+`","root/`+z+`"`, 1), + "unsorted names": strings.Replace(dropPageGolden, `"root/`+z+`"`, `"root/`+strings.Repeat("1", 64)+`","root/`+z+`"`, 1), + } { + t.Run(name, func(t *testing.T) { + b := []byte(raw) + ref := ListRef{Hash: Sum(append([]byte("swblock:list-page:v1\x00"), b...)).String(), Pages: 1} + if _, err := DecodeListPage(b, ref, id); err == nil { + t.Fatal("invalid page accepted") + } + }) + } +} + +func TestListPageLimitsAndKinds(t *testing.T) { + id, _ := ParseVolumeID("00000000000000000000000000000001") + p := ListPage{VolumeID: id, Kind: ListDrop, Producer: "cut-a", Generation: 42, Pages: 1} + for i := 0; i < MaxListPageEntries; i++ { + p.Entries = append(p.Entries, fmt.Sprintf("pool/0/%d-%s", i, strings.Repeat("0", 64))) + } + // Codec requires lexical order, independent of numeric chunk order. + sort.Strings(p.Entries) + if _, err := p.Encode(); err != nil { + t.Fatalf("entry ceiling refused: %v", err) + } + p.Entries = append(p.Entries, "root/"+strings.Repeat("0", 64)) + if _, err := p.Encode(); err == nil { + t.Fatal("entry ceiling bypassed") + } + if _, err := DecodeListPage(bytes.Repeat([]byte("x"), MaxListPageBytes+1), ListRef{}, id); err == nil { + t.Fatal("oversized input accepted") + } + newer := bytes.Replace([]byte(dropPageGolden), []byte(`"version":1`), []byte(`"version":2`), 1) + r := ListRef{Hash: Sum(append([]byte("swblock:list-page:v1\x00"), newer...)).String(), Pages: 1} + if _, err := DecodeListPage(newer, r, id); !errors.Is(err, ErrListPageNewerVersion) { + t.Fatalf("newer format not named: %v", err) + } + p = ListPage{VolumeID: id, Kind: ListSnapshotDeleteIntent, Producer: "delete-a", Generation: 42, Pages: 1, Target: &SnapshotTarget{Name: "daily", Gen: 8}, Entries: []string{"root/" + strings.Repeat("0", 64)}} + if _, err := p.Encode(); err != nil { + t.Fatal(err) + } + p.Target.Gen = 0 + if _, err := p.Encode(); err == nil { + t.Fatal("legacy zero snapshot target accepted") + } + p.Target.Gen = 8 + p.Kind = ListUploadIntent + if _, err := p.Encode(); err == nil { + t.Fatal("upload intent confused with snapshot delete") + } +} + +func TestListReferenceCannotEscapeItsDirectory(t *testing.T) { + if _, err := (ListRef{Hash: "../HEAD", Pages: 1}).Path(); err == nil { + t.Fatal("unvalidated reference became a path") + } + r := ListRef{Hash: "c63e99b5835669e4e46b4efb780e0a4fd4f55a088d78f9fb871d4caa0ed49294", Pages: 1} + p, err := r.Path() + if err != nil || p != "lists/c63e99b5835669e4e46b4efb780e0a4fd4f55a088d78f9fb871d4caa0ed49294" { + t.Fatalf("path: %q %v", p, err) + } + raw := []byte(dropPageGolden) + id, _ := ParseVolumeID("00000000000000000000000000000001") + r.Pages = 2 + if _, err := DecodeListPage(raw, r, id); err == nil { + t.Fatal("HEAD page-count binding ignored") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/delete-head.json b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/delete-head.json new file mode 100644 index 0000000000..e2aa4b3e51 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/delete-head.json @@ -0,0 +1 @@ +{"version":1,"volume_id":"00000000000000000000000000000001","kind":"snapshot-delete-intent","producer":"delete-a","generation":44,"pages":2,"next":{"hash":"d30f6462321c2b060f6d3972bb01c8b70c978d3b46c1cd3752f393b429b0b548","pages":1},"target":{"name":"daily","gen":42},"entries":["pool/0/0-0000000000000000000000000000000000000000000000000000000000000000"]} \ No newline at end of file diff --git a/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/delete-tail.json b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/delete-tail.json new file mode 100644 index 0000000000..f3977830f0 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/delete-tail.json @@ -0,0 +1 @@ +{"version":1,"volume_id":"00000000000000000000000000000001","kind":"snapshot-delete-intent","producer":"delete-a","generation":44,"pages":1,"target":{"name":"daily","gen":42},"entries":["root/0000000000000000000000000000000000000000000000000000000000000000"]} \ No newline at end of file diff --git a/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/drop.json b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/drop.json new file mode 100644 index 0000000000..c41d586e55 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/drop.json @@ -0,0 +1 @@ +{"version":1,"volume_id":"00000000000000000000000000000001","kind":"drop","producer":"cut-a","generation":42,"pages":1,"entries":["root/0000000000000000000000000000000000000000000000000000000000000000"]} \ No newline at end of file diff --git a/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/upload-intent.json b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/upload-intent.json new file mode 100644 index 0000000000..cc829cf38a --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/upload-intent.json @@ -0,0 +1 @@ +{"version":1,"volume_id":"00000000000000000000000000000001","kind":"upload-intent","producer":"cut-b","generation":43,"pages":1,"entries":["pool/0/0-0000000000000000000000000000000000000000000000000000000000000000"]} \ No newline at end of file diff --git a/seaweed-block/docs/design/immutable-list-pages.md b/seaweed-block/docs/design/immutable-list-pages.md new file mode 100644 index 0000000000..39e3577061 --- /dev/null +++ b/seaweed-block/docs/design/immutable-list-pages.md @@ -0,0 +1,43 @@ +# Immutable cleaning and intent list pages + +This Draft codec prepares persisted metadata; it has no storage writer, +HEAD publication, retirement or cleaner caller. Those transitions require +the page-chain crash refinement before integration. + +Version 1 is compact canonical JSON with keys in this order: +`version, volume_id, kind, producer, generation, pages, next?, target?, entries`. +Each reference is `{hash, pages}`. A snapshot target is `{name, gen}`. +Kinds are `drop`, `upload-intent`, and `snapshot-delete-intent`; the last +requires a captured nonzero snapshot incarnation. The enclosing full volume +ID binds it to its volume. The producer is an opaque identifier, not authority. + +The object name is SHA-256 of `swblock:list-page:v1` followed by a NUL and +the exact canonical bytes, stored under `lists/`. +The decoder checks the reference hash, full volume ID and remaining-page +count. Entries are strictly sorted unique canonical owned root/segment/chunk +paths, not HEAD, VOLUME, another list or arbitrary paths. Consumers must still +check live roots and retain the existing Stat/HEAD/conditional Mark/Delete +ordering; listing a name gives no right to remove it. + +Format ceilings (not time limits): 1 MiB per encoded page, 4,096 entries per +page, 4,096 pages per chain, 256 producer bytes. A tail has pages=1 and no next; +a non-tail has pages=next.pages+1. One read/encode allocates one bounded page, +not a volume-sized chain. A producer reaching a ceiling must refuse before +its effect, never truncate or omit required work. These explicit ceilings +are proposed for format review and must be confirmed before declaration. + +A chain reader also validates producer/kind/target/generation consistency +across pages; this codec checks one page only. The future consumer may +advance progress only after completing its effects. An unread continuation +must remain reachable until retirement is authorized. Neither an absent page +nor malformed metadata may mean empty/completed work. + +Fixed files in `layout/testdata/list-page-v1` cover a drop page, upload intent, +and a two-page snapshot-delete intent. Their independent SHA-256 names are +pinned in tests. Negative controls exercise truncation, unknown/duplicate +fields, kind confusion, identity/hash mismatch, counts, canonical ordering, +forbidden paths and size/entry limits. Unknown newer versions are refused. + +The fallback cleaner stays a full mark/sweep until a separately reviewed +switch, made safe for reachable list/intent objects. Nothing in this codec +starts that switch or weakens existing reclamation protections. \ No newline at end of file From f3167d7f7f4b74870a5d00db6a5f4f187ed48781 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:23:00 -0800 Subject: [PATCH 05/20] Isolate list page boundary controls and pin their guards --- .../chunkstore/layout/list_page_test.go | 104 +++++++++++++++++- 1 file changed, 98 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/list_page_test.go b/seaweed-block/core/frontend/chunkstore/layout/list_page_test.go index 6e026f0287..a56bde6576 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/list_page_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/list_page_test.go @@ -2,6 +2,7 @@ package layout import ( "bytes" + "encoding/json" "errors" "fmt" "os" @@ -93,9 +94,6 @@ func TestListPageRefusesMalformedDocuments(t *testing.T) { "whitespace": dropPageGolden + "\n", "unknown kind": strings.Replace(dropPageGolden, `"kind":"drop"`, `"kind":"other"`, 1), "zero generation": strings.Replace(dropPageGolden, `"generation":42`, `"generation":0`, 1), - "zero pages": strings.Replace(dropPageGolden, `"pages":1`, `"pages":0`, 1), - "too many pages": strings.Replace(dropPageGolden, `"pages":1`, `"pages":4097`, 1), - "early tail": strings.Replace(dropPageGolden, `"pages":1`, `"pages":2`, 1), "bad next count": strings.Replace(dropPageGolden, `"entries":`, `"next":{"hash":"`+z+`","pages":1},"entries":`, 1), "unbound delete": strings.Replace(dropPageGolden, `"kind":"drop"`, `"kind":"snapshot-delete-intent"`, 1), "HEAD candidate": strings.Replace(dropPageGolden, "root/"+z, "HEAD", 1), @@ -130,9 +128,6 @@ func TestListPageLimitsAndKinds(t *testing.T) { if _, err := p.Encode(); err == nil { t.Fatal("entry ceiling bypassed") } - if _, err := DecodeListPage(bytes.Repeat([]byte("x"), MaxListPageBytes+1), ListRef{}, id); err == nil { - t.Fatal("oversized input accepted") - } newer := bytes.Replace([]byte(dropPageGolden), []byte(`"version":1`), []byte(`"version":2`), 1) r := ListRef{Hash: Sum(append([]byte("swblock:list-page:v1\x00"), newer...)).String(), Pages: 1} if _, err := DecodeListPage(newer, r, id); !errors.Is(err, ErrListPageNewerVersion) { @@ -169,3 +164,100 @@ func TestListReferenceCannotEscapeItsDirectory(t *testing.T) { t.Fatal("HEAD page-count binding ignored") } } + +func decodeListControl(raw []byte, pages uint32) error { + id, _ := ParseVolumeID("00000000000000000000000000000001") + ref := ListRef{Hash: Sum(append([]byte("swblock:list-page:v1\x00"), raw...)).String(), Pages: pages} + _, err := DecodeListPage(raw, ref, id) + return err +} + +func TestListPageTailAndDecrementChecksAreIndependent(t *testing.T) { + early := []byte(strings.Replace(dropPageGolden, `"pages":1`, `"pages":2`, 1)) + // Ref pages2 matches the document. Its missing Next is the sole fault. + if err := decodeListControl(early, 2); err == nil || !strings.Contains(err.Error(), "chain ends before its declared count") { + t.Fatalf("early tail reached wrong check: %v", err) + } + bad := strings.Replace(dropPageGolden, `"pages":1`, `"pages":3`, 1) + bad = strings.Replace(bad, `"entries":`, `"next":{"hash":"`+strings.Repeat("0", 64)+`","pages":1},"entries":`, 1) + if err := decodeListControl([]byte(bad), 3); err == nil || !strings.Contains(err.Error(), "does not decrease by one") { + t.Fatalf("decrement reached wrong check: %v", err) + } + id, _ := ParseVolumeID("00000000000000000000000000000001") + for _, pages := range []uint32{2, 4096} { + p := ListPage{VolumeID: id, Kind: ListDrop, Producer: "cut-a", Generation: 42, Pages: pages, Next: &ListRef{Hash: strings.Repeat("0", 64), Pages: pages - 1}, Entries: []string{"root/" + strings.Repeat("0", 64)}} + raw, err := p.Encode() + if err != nil { + t.Fatalf("valid decrement%d: %v", pages, err) + } + if err := decodeListControl(raw, pages); err != nil { + t.Fatalf("valid page boundary%d: %v", pages, err) + } + } +} + +func TestListReferencePageCeilingsAreIndependent(t *testing.T) { + for _, pages := range []uint32{0, 4097} { + r := ListRef{Hash: "c63e99b5835669e4e46b4efb780e0a4fd4f55a088d78f9fb871d4caa0ed49294", Pages: pages} + // No decoded-page mismatch can mask the reference's own bound here. + if _, err := r.Path(); err == nil { + t.Fatalf("invalid reference pages%d accepted", pages) + } + } + for _, pages := range []uint32{1, 4096} { + r := ListRef{Hash: "c63e99b5835669e4e46b4efb780e0a4fd4f55a088d78f9fb871d4caa0ed49294", Pages: pages} + if _, err := r.Path(); err != nil { + t.Fatalf("valid reference pages%d: %v", pages, err) + } + } +} + +func TestListPageDecodeProducerAndEntryCeilings(t *testing.T) { + for _, n := range []int{256, 257} { + raw := []byte(strings.Replace(dropPageGolden, `"cut-a"`, `"`+strings.Repeat("a", n)+`"`, 1)) + err := decodeListControl(raw, 1) + if n == 256 && err != nil { + t.Fatalf("producer256 refused: %v", err) + } + if n == 257 && (err == nil || !strings.Contains(err.Error(), "list page producer")) { + t.Fatalf("producer257 reached wrong check: %v", err) + } + } + var entries []string + for i := 0; i < 4097; i++ { + entries = append(entries, fmt.Sprintf("pool/0/%d-%s", i, strings.Repeat("0", 64))) + } + sort.Strings(entries) + for _, n := range []int{4096, 4097} { + encoded, err := json.Marshal(entries[:n]) + if err != nil { + t.Fatal(err) + } + raw := []byte(dropPageGolden[:strings.Index(dropPageGolden, `"entries":`)] + `"entries":` + string(encoded) + `}`) + err = decodeListControl(raw, 1) + if n == 4096 && err != nil { + t.Fatalf("decode entries4096 refused: %v", err) + } + if n == 4097 && (err == nil || !strings.Contains(err.Error(), "list page entry count")) { + t.Fatalf("decode entries4097 reached wrong check: %v", err) + } + } +} + +func TestListPageRawByteLimitPrecedesParsingAndSchema(t *testing.T) { + for _, size := range []int{1 << 20, (1 << 20) + 1} { + producer := strings.Repeat("a", size-len(dropPageGolden)+len("cut-a")) + raw := []byte(strings.Replace(dropPageGolden, `"cut-a"`, `"`+producer+`"`, 1)) + if len(raw) != size || !json.Valid(raw) { + t.Fatal("control is not the exact-sized valid JSON document") + } + err := decodeListControl(raw, 1) + want := "list page producer" // At the byte ceiling the later producer guard runs. + if size > (1 << 20) { + want = "list page exceeds byte limit" + } + if err == nil || !strings.Contains(err.Error(), want) { + t.Fatalf("bytes%d: %v; want early check %q", size, err, want) + } + } +} From 18094785e382de37caa9da8f50948a4432f71589 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 14:57:51 -0800 Subject: [PATCH 06/20] Add session-owned list publication and persisted continuation --- .../frontend/chunkstore/head_readers_test.go | 3 + .../chunkstore/layout/head-write-census.json | 18 +- .../core/frontend/chunkstore/layout/head.go | 26 +- .../frontend/chunkstore/layout/head_cause.go | 3 + .../layout/head_cause_census_test.go | 1 + .../layout/head_census_export_test.go | 8 +- .../chunkstore/layout/kernel_table_test.go | 21 + .../frontend/chunkstore/layout/list_chain.go | 234 +++++++++++ .../chunkstore/layout/list_chain_test.go | 366 ++++++++++++++++++ .../frontend/chunkstore/layout/list_page.go | 60 +-- .../core/frontend/chunkstore/layout/remove.go | 24 +- .../frontend/chunkstore/layout/stale_test.go | 20 +- .../frontend/chunkstore/layout_list_test.go | 132 +++++++ .../core/frontend/chunkstore/layout_store.go | 59 ++- .../docs/design/immutable-list-pages.md | 79 +++- seaweed-block/docs/design/invariants.md | 18 +- seaweed-block/docs/spec/README.md | 19 + .../docs/spec/pagechain/PageChain.tla | 173 +++++++++ .../docs/spec/pagechain/cfg/EXPECTED.txt | 12 + .../pagechain/cfg/mut_abandon_unsettled.cfg | 9 + .../spec/pagechain/cfg/mut_absent_is_end.cfg | 9 + .../cfg/mut_cursor_before_effects.cfg | 9 + .../pagechain/cfg/mut_head_before_durable.cfg | 9 + .../cfg/mut_retire_before_cursor.cfg | 9 + .../cfg/mut_retire_by_membership.cfg | 9 + .../cfg/mut_sweep_ignores_session.cfg | 9 + .../docs/spec/pagechain/cfg/safe_chain.cfg | 9 + .../spec/pagechain/cfg/wit_WitConsumed.cfg | 9 + .../spec/pagechain/cfg/wit_WitOrphanSwept.cfg | 9 + .../pagechain/cfg/wit_WitRefusedLanded.cfg | 9 + .../pagechain/cfg/wit_WitSecondAttempt.cfg | 9 + .../docs/spec/pagechain/model-code-trace.tsv | 9 + 32 files changed, 1346 insertions(+), 47 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/list_chain.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_list_test.go create mode 100644 seaweed-block/docs/spec/pagechain/PageChain.tla create mode 100644 seaweed-block/docs/spec/pagechain/cfg/EXPECTED.txt create mode 100644 seaweed-block/docs/spec/pagechain/cfg/mut_abandon_unsettled.cfg create mode 100644 seaweed-block/docs/spec/pagechain/cfg/mut_absent_is_end.cfg create mode 100644 seaweed-block/docs/spec/pagechain/cfg/mut_cursor_before_effects.cfg create mode 100644 seaweed-block/docs/spec/pagechain/cfg/mut_head_before_durable.cfg create mode 100644 seaweed-block/docs/spec/pagechain/cfg/mut_retire_before_cursor.cfg create mode 100644 seaweed-block/docs/spec/pagechain/cfg/mut_retire_by_membership.cfg create mode 100644 seaweed-block/docs/spec/pagechain/cfg/mut_sweep_ignores_session.cfg create mode 100644 seaweed-block/docs/spec/pagechain/cfg/safe_chain.cfg create mode 100644 seaweed-block/docs/spec/pagechain/cfg/wit_WitConsumed.cfg create mode 100644 seaweed-block/docs/spec/pagechain/cfg/wit_WitOrphanSwept.cfg create mode 100644 seaweed-block/docs/spec/pagechain/cfg/wit_WitRefusedLanded.cfg create mode 100644 seaweed-block/docs/spec/pagechain/cfg/wit_WitSecondAttempt.cfg create mode 100644 seaweed-block/docs/spec/pagechain/model-code-trace.tsv diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 92280b3bba..cd778df244 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -24,6 +24,9 @@ import ( // pins it. "GAP" marks a reader that takes an absent HEAD for an empty // one; a change that treats an absent HEAD as unknown flips those probes. var headReaders = map[string]string{ + "core/frontend/chunkstore/layout/list_chain.go StageListPage -> ReadHead": "refuses ErrHeadAbsent before any object write (probe TestLayoutListAbsentHEAD)", + "core/frontend/chunkstore/layout/list_chain.go RunPublishList -> ReadHead": "settlement absence preserves original error, never abandons pages (probe TestLayoutListAbsentHEAD and TestRunPublishList_InterruptAtEveryStep)", + "core/frontend/chunkstore/layout/list_chain.go RunAdvanceList -> ReadHead": "settlement absence never confirms progress (probe TestLayoutListAbsentHEAD and TestRunAdvanceList_InterruptAtEveryStep)", "core/frontend/chunkstore/layout_verify.go verifyHead -> LookupEntry": "absent or unknown generation makes verify incomplete and suppresses MISSING/ORPHAN (TestVerifyLayoutRequiresStableHeadForMissingAndOrphans)", "core/frontend/chunkstore/layout_verify.go verifyHead -> DecodeLayoutHeadEntry": "invalid inline envelope supplies no generation and cannot confirm findings (TestVerifyLayoutRequiresStableHeadForMissingAndOrphans)", "core/frontend/chunkstore/startup_head_probe.go checkConditionalHead -> ReadHead": "absent/unreadable/changed disposable HEAD refuses startup; no volume HEAD is read (TestCatalogStartupRequiresWrongGenerationHeadRefusal)", diff --git a/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json b/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json index afc85ccf56..d004cf3221 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json +++ b/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json @@ -19,7 +19,8 @@ "snapshots[].Dependents": "Dependents of retained snapshot entries, including target name, target id and root; excludes snapshot membership and other snapshot fields", "version": "Head.Version (0 absent: the v1.0 format; 1: v1.1)", "current_bytes": "Head.CurrentBytes, the manifest size of Current (including nil: unknown)", - "ext": "Head.Ext, the v1.1 extension object, written back verbatim by every writer that does not own an entry in it" + "ext": "Head.Ext, the v1.1 extension object, written back verbatim by every writer that does not own an entry in it", + "list": "Head.List: admitted immutable chain context and current continuation; nil only after all page effects complete" }, "notes": [ "snapshots removal includes removal of its empty dependent list; snapshots with dependents cannot be removed.", @@ -193,6 +194,21 @@ "current_bytes", "ext" ] + }, + { + "cause": "list-publish", + "kind": "update", + "may_change": [ + "version", + "list" + ] + }, + { + "cause": "list-advance", + "kind": "update", + "may_change": [ + "list" + ] } ] } diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index c11d772473..c2ce74f122 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -150,6 +150,10 @@ func (m SnapshotMeta) check(name string) error { // with the epoch identifies the holder's local data (the holder's name // repeats across restarts and same-host moves). type Head struct { + // List is the single admitted list continuation. A producer must finish + // or settle it before publishing another; HEAD stays bounded. + List *ListCursor `json:",omitempty"` + Gen uint64 VolumeID VolumeID Epoch uint64 @@ -166,8 +170,7 @@ type Head struct { CurrentBytes *uint64 // Version is HEAD's format version: 0 (absent in the bytes) is the v1.0 // format, decoded strictly; HeadVersion1 is v1.1, whose own fields are - // CurrentBytes and snapshots' ManifestBytes, and whose Ext carries every - // later field. A writer keeps the version and Ext it read. + // all v1.1 fields explicitly. Ext carries only later additive facts. A writer keeps the version and Ext it read. Version int // Ext is a v1.1 HEAD's extension object, kept as raw bytes and written // back verbatim (the ext contract: only additive facts that a writer @@ -203,6 +206,7 @@ type headDoc struct { Snapshots map[string]snapDoc `json:"snapshots,omitempty"` State string `json:"state,omitempty"` CurrentBytes *uint64 `json:"current_bytes,omitempty"` + List *ListCursor `json:"list,omitempty"` Ext json.RawMessage `json:"ext,omitempty"` } @@ -261,6 +265,15 @@ func checkExt(version int, ext json.RawMessage) error { var ErrNoNextPosition = fmt.Errorf("%w: HEAD position leaves no room for a next LSN", ErrMalformed) func (h Head) check() error { + if h.List != nil { + if h.Version != HeadVersion1 { + return fmt.Errorf("%w: legacy HEAD carries a list", ErrMalformed) + } + if err := h.List.check(); err != nil { + return err + } + } + if h.VolumeID.IsZero() { return fmt.Errorf("%w: HEAD without a volume id", ErrMalformed) } @@ -363,7 +376,7 @@ func (h Head) Encode() ([]byte, error) { if err := h.check(); err != nil { return nil, err } - d := headDoc{Version: h.Version, VolumeID: h.VolumeID.String(), Epoch: h.Epoch, Holder: h.Holder, ClaimID: h.ClaimID, Activity: h.Activity, Position: h.Position, State: h.State, CurrentBytes: h.CurrentBytes, Ext: h.Ext} + d := headDoc{List: h.List, Version: h.Version, VolumeID: h.VolumeID.String(), Epoch: h.Epoch, Holder: h.Holder, ClaimID: h.ClaimID, Activity: h.Activity, Position: h.Position, State: h.State, CurrentBytes: h.CurrentBytes, Ext: h.Ext} if h.Current != nil { d.Current = h.Current.String() } @@ -422,14 +435,14 @@ func DecodeHead(b []byte, gen uint64, volume VolumeID) (Head, error) { if err := dec.Decode(&d); err != nil { return Head{}, fmt.Errorf("%w: HEAD: %v", ErrMalformed, err) } - if d.Version == 0 && (d.CurrentBytes != nil || d.Ext != nil || snapshotsSized(d.Snapshots)) { + if d.Version == 0 && (d.List != nil || d.CurrentBytes != nil || d.Ext != nil || snapshotsSized(d.Snapshots)) { return Head{}, fmt.Errorf("%w: HEAD of the v1.0 format carries v1.1 fields", ErrMalformed) } vid, err := ParseVolumeID(d.VolumeID) if err != nil { return Head{}, err } - h := Head{Gen: gen, VolumeID: vid, Epoch: d.Epoch, Holder: d.Holder, ClaimID: d.ClaimID, Activity: d.Activity, Position: d.Position, State: d.State, CurrentBytes: d.CurrentBytes, Version: d.Version, Ext: d.Ext} + h := Head{List: d.List, Gen: gen, VolumeID: vid, Epoch: d.Epoch, Holder: d.Holder, ClaimID: d.ClaimID, Activity: d.Activity, Position: d.Position, State: d.State, CurrentBytes: d.CurrentBytes, Version: d.Version, Ext: d.Ext} if d.Current != "" { rn, err := ParseRootName(d.Current) if err != nil { @@ -547,6 +560,9 @@ func (h Head) Begin(me HolderID, session string) (next Head, changed bool, err e func (h Head) clone() Head { c := h + if h.List != nil { + c.List = h.List.clone() + } if h.Current != nil { rn := *h.Current c.Current = &rn diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_cause.go b/seaweed-block/core/frontend/chunkstore/layout/head_cause.go index a5150bbd6d..a698f1146e 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_cause.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_cause.go @@ -9,6 +9,8 @@ type HeadWriteCause string // The census rows. A new HEAD writer needs a new row here, in the census // test and in the design's table. const ( + CauseListPublish HeadWriteCause = "list-publish" + CauseListAdvance HeadWriteCause = "list-advance" // CauseCreate: a new volume's or restore target's first HEAD. CauseCreate HeadWriteCause = "create" // CauseClaim: a holder's claim at attach (layout.Start). @@ -52,6 +54,7 @@ const ( // HeadWriteCauses is the census: every cause, in table order. var HeadWriteCauses = []HeadWriteCause{ + CauseListPublish, CauseListAdvance, CauseCreate, CauseClaim, CauseStartRollbackSnap, CauseStartRollbackClean, CauseSessionBegin, CauseSessionRollback, CauseCommit, CauseSnapshotUnchanged, CauseStopAbort, CauseCleanBegin, CauseCleanEnd, CauseSnapshotRetire, diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_cause_census_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_cause_census_test.go index 23ca1f53bb..8ff51ecce3 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_cause_census_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_cause_census_test.go @@ -193,6 +193,7 @@ func causeRebound(body *ast.BlockStmt) string { // causeByName maps each census constant's name to its value. var causeByName = map[string]HeadWriteCause{ + "CauseListPublish": CauseListPublish, "CauseListAdvance": CauseListAdvance, "CauseCreate": CauseCreate, "CauseClaim": CauseClaim, "CauseStartRollbackSnap": CauseStartRollbackSnap, "CauseStartRollbackClean": CauseStartRollbackClean, "CauseSessionBegin": CauseSessionBegin, "CauseSessionRollback": CauseSessionRollback, "CauseCommit": CauseCommit, diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_census_export_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_census_export_test.go index 73b96419c6..97a431abc6 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_census_export_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_census_export_test.go @@ -31,13 +31,13 @@ func TestMachineReadableHeadCensusNamesExactlyTheTypedCauses(t *testing.T) { if census.SchemaVersion != 1 { t.Fatalf("schema=%d", census.SchemaVersion) } - observable := map[string]bool{"volume_id": true, "epoch": true, "holder": true, "claim_id": true, "activity": true, "current": true, "position": true, "state": true, "snapshots": true, "snapshots[].Dependents": true, "version": true, "current_bytes": true, "ext": true} + observable := map[string]bool{"list": true, "volume_id": true, "epoch": true, "holder": true, "claim_id": true, "activity": true, "current": true, "position": true, "state": true, "snapshots": true, "snapshots[].Dependents": true, "version": true, "current_bytes": true, "ext": true} for field := range census.FieldGroups { if !observable[field] { t.Fatalf("unobservable census field %s", field) } } - headFields := map[string]bool{"Gen": true, "VolumeID": true, "Epoch": true, "Holder": true, "ClaimID": true, "Activity": true, "Current": true, "Position": true, "Snapshots": true, "State": true, "Version": true, "CurrentBytes": true, "Ext": true} + headFields := map[string]bool{"List": true, "Gen": true, "VolumeID": true, "Epoch": true, "Holder": true, "ClaimID": true, "Activity": true, "Current": true, "Position": true, "Snapshots": true, "State": true, "Version": true, "CurrentBytes": true, "Ext": true} typ := reflect.TypeOf(Head{}) for n := 0; n < typ.NumField(); n++ { if !headFields[typ.Field(n).Name] { @@ -83,8 +83,8 @@ func TestMachineReadableHeadCensusNamesExactlyTheTypedCauses(t *testing.T) { func changedCensusGroups(before, after Head) []string { var out []string a, b := reflect.ValueOf(before), reflect.ValueOf(after) - jsonKeys := map[string]string{"VolumeID": "volume_id", "Epoch": "epoch", "Holder": "holder", "ClaimID": "claim_id", "Activity": "activity", "Current": "current", "Position": "position", "State": "state", "Version": "version", "CurrentBytes": "current_bytes", "Ext": "ext"} - for _, name := range []string{"VolumeID", "Epoch", "Holder", "ClaimID", "Activity", "Current", "Position", "State", "Version", "CurrentBytes", "Ext"} { + jsonKeys := map[string]string{"List": "list", "VolumeID": "volume_id", "Epoch": "epoch", "Holder": "holder", "ClaimID": "claim_id", "Activity": "activity", "Current": "current", "Position": "position", "State": "state", "Version": "version", "CurrentBytes": "current_bytes", "Ext": "ext"} + for _, name := range []string{"List", "VolumeID", "Epoch", "Holder", "ClaimID", "Activity", "Current", "Position", "State", "Version", "CurrentBytes", "Ext"} { if !reflect.DeepEqual(a.FieldByName(name).Interface(), b.FieldByName(name).Interface()) { out = append(out, jsonKeys[name]) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go b/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go index 590084fff6..bb309b246d 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go @@ -27,6 +27,7 @@ var kernelStates = []string{"absent", "unclaimed", "idle", "snap", "clean", "det // kernelEntries are the kernel's entry points (DeleteVolume is their // composition: Reserve, MarkDeleting, release, objects, MarkDeleted). var kernelEntries = []string{ + "PublishList", "AdvanceList", "CreateVolume", "CreateTarget", "StartHigher", "StartHigherCannotStart", "StartOwn", "StartOwnOtherFresh", "StartOwnOtherFreshCannotStart", "StartOwnOtherOld", "Claim", "Begin", "Commit", "CommitNew", "CommitLower", "Abort", "BeginClean", "EndClean", "RemoveUnreachable", "DeleteSnapshot", "DeleteSnapshotAt", "RetireSnapshot", "AddDependent", "ReleaseDependent", @@ -131,6 +132,23 @@ func kernelCell(t *testing.T, state, entry string) string { src.memHead.h, src.vol = sh, &vol switch entry { + case "PublishList", "AdvanceList": + cs := &chainStore{memHead: nv.memHead, memObjects: o} + p := ListPage{VolumeID: h.VolumeID, Kind: ListDrop, Producer: "s1", Generation: h.Gen + 1, Pages: 1, Entries: []string{RootName{Hash: Sum([]byte("page item"))}.Path()}} + ref, _ := p.Ref() + raw, _ := p.Encode() + rel, _ := ref.Path() + o.put(rel, raw, "s1") + cursor := ListCursor{Ref: ref, Kind: p.Kind, Producer: p.Producer, Generation: p.Generation} + if entry == "PublishList" { + _, err = RunPublishList(ctx, cs, me, "s1", h.Gen, cursor) + } else { + if nv.memHead.h != nil { + nv.memHead.h.Version = HeadVersion1 + nv.memHead.h.List = cursor.clone() + } + _, err = RunAdvanceList(ctx, cs, me, "c1", func(context.Context, ListPage) error { return nil }) + } case "CreateVolume": _, err = CreateVolume(ctx, nv, vol) case "CreateTarget": @@ -256,6 +274,8 @@ func kernelCell(t *testing.T, state, entry string) string { // source) and a claim; an unclaimed HEAD takes only the first claim and // the creates' replays. var kernelExpected = map[string]map[string]string{ + "PublishList": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "NoSession", "snap": "write", "clean": "NoSession", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "AdvanceList": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "NoSession", "snap": "NoSession", "clean": "write", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, "CreateVolume": {"absent": "write", "unclaimed": "noop", "idle": "noop", "snap": "noop", "clean": "noop", "detached": "noop", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, "CreateTarget": {"absent": "write", "unclaimed": "Exists", "idle": "Exists", "snap": "Exists", "clean": "Exists", "detached": "Exists", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, "StartHigher": {"absent": "HeadAbsent", "unclaimed": "write", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, @@ -311,6 +331,7 @@ func TestKernelTable(t *testing.T) { // kernelEntryFuncs maps each table row to the exported function it calls; // kernelComposed are exported entry points that only compose the rows. var kernelEntryFuncs = map[string]string{ + "PublishList": "RunPublishList", "AdvanceList": "RunAdvanceList", "CreateVolume": "CreateVolume", "CreateTarget": "CreateTarget", "StartHigher": "Start", "StartOwn": "Start", "StartOwnOtherFresh": "Start", "StartOwnOtherOld": "Start", "StartHigherCannotStart": "Start", "StartOwnOtherFreshCannotStart": "Start", "Claim": "RunClaim", "Begin": "RunBegin", "Commit": "RunCommit", "CommitNew": "RunCommit", "CommitLower": "RunCommit", "Abort": "RunAbort", "BeginClean": "RunBeginClean", "EndClean": "RunEndClean", diff --git a/seaweed-block/core/frontend/chunkstore/layout/list_chain.go b/seaweed-block/core/frontend/chunkstore/layout/list_chain.go new file mode 100644 index 0000000000..8d0e4e7b4c --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/list_chain.go @@ -0,0 +1,234 @@ +package layout + +import ( + "context" + "errors" + "fmt" +) + +// ListCursor is HEAD's bounded continuation. Generation identifies the +// publishing attempt, not subsequent cursor writes. The immutable page repeats +// these facts, so a valid page from another chain is never executable here. +type ListCursor struct { + Ref ListRef `json:"ref"` + Kind ListKind `json:"kind"` + Producer string `json:"producer"` + Generation uint64 `json:"generation"` + Target *SnapshotTarget `json:"target,omitempty"` +} + +func (c ListCursor) check() error { + if err := c.Ref.check(); err != nil { + return err + } + return checkListContext(c.Kind, c.Producer, c.Generation, c.Target) +} +func (c ListCursor) clone() *ListCursor { + if c.Target != nil { + t := *c.Target + c.Target = &t + } + return &c +} +func sameTarget(a, b *SnapshotTarget) bool { + return a == nil && b == nil || a != nil && b != nil && *a == *b +} +func sameList(a, b *ListCursor) bool { + return a == nil && b == nil || a != nil && b != nil && a.Ref == b.Ref && + a.Kind == b.Kind && a.Producer == b.Producer && a.Generation == b.Generation && sameTarget(a.Target, b.Target) +} + +// ListPageReader must bound allocation to MaxListPageBytes before returning. +// Missing is distinct from an empty, successfully completed chain. +type ListPageReader interface { + ReadListPage(context.Context, ListRef) ([]byte, bool, error) +} + +var ErrListPageMissing = errors.New("layout: list continuation is missing; work remains pending") + +func readListPage(ctx context.Context, r ListPageReader, volume VolumeID, c ListCursor) (ListPage, error) { + if err := c.check(); err != nil { + return ListPage{}, err + } + raw, found, err := r.ReadListPage(ctx, c.Ref) + if err != nil { + return ListPage{}, err + } + if !found { + return ListPage{}, ErrListPageMissing + } + p, err := DecodeListPage(raw, c.Ref, volume) + if err != nil { + return ListPage{}, err + } + if p.Kind != c.Kind || p.Producer != c.Producer || p.Generation != c.Generation || !sameTarget(p.Target, c.Target) { + return ListPage{}, fmt.Errorf("%w: list continuation context", ErrIdentity) + } + return p, nil +} + +// ReadListChain walks at most MaxListPages bounded pages, holding one page at +// a time. visit observes reachability; it must not execute candidate effects. +func ReadListChain(ctx context.Context, r ListPageReader, volume VolumeID, c ListCursor, visit func(ListRef, ListPage) error) error { + for { + if err := ctx.Err(); err != nil { + return err + } + p, err := readListPage(ctx, r, volume, c) + if err != nil { + return err + } + if visit != nil { + if err := visit(c.Ref, p); err != nil { + return err + } + } + if p.Next == nil { + return nil + } + c.Ref = *p.Next + } +} + +// ListChainStore uses the same exclusive data-first object writes, session +// tags and conditional HEAD as manifest publication. No separate authority. +type ListChainStore interface { + HeadStore + ObjectStore + ListPageReader +} + +func listSession(h Head, me HolderID, session, kind string) error { + if err := h.holderErr(me); err != nil { + return err + } + if session == "" || h.Activity != (Activity{Kind: kind, Session: session}) { + return ErrNoSession + } + return nil +} + +// StageListPage writes a bounded page in the already-open snap session. +// Ending the session during I/O may leave an orphan, but cannot authorize +// its later publication: that CAS checks the original generation/session. +func StageListPage(ctx context.Context, st ListChainStore, me HolderID, session string, p ListPage) (ListRef, error) { + h, found, err := st.ReadHead(ctx) + if err != nil { + return ListRef{}, err + } + if !found { + return ListRef{}, ErrHeadAbsent + } + if err := listSession(h, me, session, ActSnap); err != nil { + return ListRef{}, err + } + if h.Gen == ^uint64(0) || p.VolumeID != h.VolumeID || p.Producer != session || p.Generation != h.Gen+1 { + return ListRef{}, ErrIdentity + } + raw, err := p.Encode() + if err != nil { + return ListRef{}, err + } + ref, _ := p.Ref() + rel, _ := ref.Path() + if err := EnsureObject(ctx, st, rel, raw, session); err != nil { + return ListRef{}, err + } + return ref, nil +} + +// RunPublishList authenticates every durable page before sending the one HEAD +// CAS. The caller retains the same base/cursor after an unknown reply. This +// function never abandons a session, removes pages, or turns absence at the +// original generation into proof that an outstanding CAS cannot land. +func RunPublishList(ctx context.Context, st ListChainStore, me HolderID, session string, base uint64, c ListCursor) (Head, error) { + h, err := runTransition(ctx, st, CauseListPublish, func(h Head) (Head, bool, error) { + if err := listSession(h, me, session, ActSnap); err != nil { + return Head{}, false, err + } + if sameList(h.List, &c) { + return h, false, nil + } + if h.Gen != base || base == ^uint64(0) || c.Generation != base+1 || c.Producer != session { + return Head{}, false, ErrPrecondition + } + if h.List != nil { + return Head{}, false, ErrBusy + } + if err := ReadListChain(ctx, st, h.VolumeID, c, nil); err != nil { + return Head{}, false, err + } + next := h.clone() + next.Version, next.List = HeadVersion1, c.clone() + return next, true, nil + }) + if err == nil { + return h, nil + } + // A refused resend may follow an earlier landed send. Reachability wins + // over the reply; no cleanup is performed even if settlement cannot read. + observed, found, readErr := st.ReadHead(ctx) + if readErr == nil && found && sameList(observed.List, &c) { + return observed, nil + } + return Head{}, err +} + +// ConsumeListPage executes one authenticated page under the existing cleaning +// exclusion, then advances its persisted cursor. apply must finish idempotent, +// independently authorized effects before returning nil: a crash or refused +// CAS repeats the page. It must not treat candidate membership as delete +// authority. No object retirement occurs here. +func ConsumeListPage(ctx context.Context, st ListChainStore, me HolderID, session string, apply func(context.Context, ListPage) error) (bool, error) { + h, err := RunAdvanceList(ctx, st, me, session, apply) + return err == nil && h.List == nil, err +} + +// RunAdvanceList reads an authenticated page, finishes its idempotent effects, +// then conditionally advances the exact observed continuation. A lost reply is +// settled before reporting success. Retirement is a separate reachable-set check. +func RunAdvanceList(ctx context.Context, st ListChainStore, me HolderID, session string, apply func(context.Context, ListPage) error) (Head, error) { + var next *ListCursor + attempted := false + h, err := runTransition(ctx, st, CauseListAdvance, func(h Head) (Head, bool, error) { + if err := listSession(h, me, session, ActClean); err != nil { + return Head{}, false, err + } + if h.List == nil { + return h, false, nil + } + if h.Gen == ^uint64(0) { + return Head{}, false, ErrPrecondition + } + if apply == nil { + return Head{}, false, fmt.Errorf("%w: list consumer needs an executor", ErrMalformed) + } + c := *h.List.clone() + p, err := readListPage(ctx, st, h.VolumeID, c) + if err != nil { + return Head{}, false, err + } + // Keep the authenticated continuation independent of executor memory. + if p.Next != nil { + next = c.clone() + next.Ref = *p.Next + } + if err := apply(ctx, p); err != nil { + return Head{}, false, err + } + n := h.clone() + n.List = next + attempted = true + return n, true, nil + }) + if err == nil { + return h, nil + } + if attempted { + observed, found, readErr := st.ReadHead(ctx) + if readErr == nil && found && sameList(observed.List, next) && listSession(observed, me, session, ActClean) == nil { + return observed, nil + } + } + return Head{}, err +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go b/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go new file mode 100644 index 0000000000..57251f03d3 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go @@ -0,0 +1,366 @@ +package layout + +import ( + "bytes" + "context" + "errors" + "testing" +) + +func TestListCursorGoldenBytes(t *testing.T) { + const golden = `{"version":1,"volume_id":"00112233445566778899aabbccddeeff","epoch":1,"holder":"a","claim_id":"k","activity":{"kind":"idle"},"position":0,"list":{"ref":{"hash":"1111111111111111111111111111111111111111111111111111111111111111","pages":1},"kind":"drop","producer":"s1","generation":8}}` + id, _ := ParseVolumeID("00112233445566778899aabbccddeeff") + h, err := DecodeHead([]byte(golden), 8, id) + if err != nil { + t.Fatal(err) + } + if h.List == nil || h.List.Generation != 8 || h.List.Ref.Pages != 1 || h.List.Producer != "s1" { + t.Fatalf("wrong golden facts: %+v", h.List) + } + raw, err := h.Encode() + if err != nil || !bytes.Equal(raw, []byte(golden)) { + t.Fatalf("golden changed: %s %v", raw, err) + } +} + +// A public chain read must authenticate the context, not only each page's hash. +func TestReadListChainRejectsMissingAndForeignContinuation(t *testing.T) { + ctx := context.Background() + tail := ListPage{VolumeID: idFor("v1"), Kind: ListDrop, Producer: "s1", Generation: 8, Pages: 1, + Entries: []string{RootName{Hash: Sum([]byte("tail"))}.Path()}} + tr, _ := tail.Ref() + head := tail + head.Pages, head.Next = 2, &tr + head.Entries = []string{RootName{Hash: Sum([]byte("head"))}.Path()} + hr, _ := head.Ref() + raw, _ := head.Encode() + f := &chainFiles{data: map[string][]byte{hr.Hash: raw}} + cursor := ListCursor{Ref: hr, Kind: ListDrop, Producer: "s1", Generation: 8} + if err := ReadListChain(ctx, f, idFor("v1"), cursor, nil); !errors.Is(err, ErrListPageMissing) { + t.Fatalf("missing continuation: %v", err) + } + // The new continuation has valid bytes/hash but belongs to another producer. + tail.Producer = "other" + tr, _ = tail.Ref() + head.Next = &tr + hr, _ = head.Ref() + raw, _ = head.Encode() + f.data[hr.Hash] = raw + raw, _ = tail.Encode() + f.data[tr.Hash] = raw + cursor.Ref = hr + if err := ReadListChain(ctx, f, idFor("v1"), cursor, nil); !errors.Is(err, ErrIdentity) { + t.Fatalf("foreign continuation: %v", err) + } +} + +type chainFiles struct{ data map[string][]byte } + +func (f *chainFiles) ReadListPage(_ context.Context, ref ListRef) ([]byte, bool, error) { + b, ok := f.data[ref.Hash] + return b, ok, nil +} + +func TestListCursorHeadBytes(t *testing.T) { + h := idleHead() + h.Version = HeadVersion1 + h.List = &ListCursor{Ref: ListRef{Hash: Sum([]byte("page")).String(), Pages: 1}, Kind: ListDrop, Producer: "s1", Generation: 7} + raw, err := h.Encode() + if err != nil { + t.Fatal(err) + } + got, err := DecodeHead(raw, h.Gen, h.VolumeID) + if err != nil || !sameList(got.List, h.List) { + t.Fatalf("roundtrip: %+v %v", got.List, err) + } + got.List.Producer = "changed" + if h.List.Producer != "s1" { + t.Fatal("decode aliases source") + } + h.Version = 0 + if _, err := h.Encode(); err == nil { + t.Fatal("legacy writer accepted list field") + } +} + +type chainStore struct { + *memHead + *memObjects +} + +func (s *chainStore) ReadListPage(_ context.Context, ref ListRef) ([]byte, bool, error) { + rel, err := ref.Path() + if err != nil { + return nil, false, err + } + o, ok := s.objs[s.full(rel)] + if !ok { + return nil, false, nil + } + return append([]byte(nil), o.data...), true, nil +} +func chainFixture(t *testing.T) (*chainStore, ListCursor, ListPage) { + t.Helper() + h := snapHead("s1") + h.Version = HeadVersion1 + s := &chainStore{memHead: &memHead{h: &h}, memObjects: newMemObjects(volRoot)} + s.volume = h.VolumeID + p := ListPage{VolumeID: h.VolumeID, Kind: ListDrop, Producer: "s1", Generation: h.Gen + 1, Pages: 1, + Entries: []string{RootName{Hash: Sum([]byte("candidate"))}.Path()}} + r, _ := p.Ref() + return s, ListCursor{Ref: r, Kind: p.Kind, Producer: p.Producer, Generation: p.Generation}, p +} + +func TestPublishList_Closure(t *testing.T) { + s, c, p := chainFixture(t) + ctx := context.Background() + base := s.h.Gen + if _, err := RunPublishList(ctx, s, me, "s1", base, c); !errors.Is(err, ErrListPageMissing) || s.updates != 0 { + t.Fatalf("HEAD named unwritten page: %v updates=%d", err, s.updates) + } + if _, err := StageListPage(ctx, s, me, "s1", p); err != nil { + t.Fatal(err) + } + h, err := RunPublishList(ctx, s, me, "s1", base, c) + if err != nil || !sameList(h.List, &c) { + t.Fatalf("publish: %+v %v", h.List, err) + } + if _, err := RunPublishList(ctx, s, me, "s1", base, c); err != nil || s.updates != 1 { + t.Fatalf("replay: %v updates=%d", err, s.updates) + } +} + +func publishedChain(t *testing.T) (*chainStore, ListCursor) { + t.Helper() + s, c, p := chainFixture(t) + ctx := context.Background() + if _, err := StageListPage(ctx, s, me, "s1", p); err != nil { + t.Fatal(err) + } + if _, err := RunPublishList(ctx, s, me, "s1", s.h.Gen, c); err != nil { + t.Fatal(err) + } + if _, err := RunAbort(ctx, s, me, "s1", CauseSessionRollback); err != nil { + t.Fatal(err) + } + if _, err := RunBeginClean(ctx, s, me, "clean"); err != nil { + t.Fatal(err) + } + return s, c +} + +func TestAdvanceList_Closure(t *testing.T) { + s, c := publishedChain(t) + ctx := context.Background() + writes := s.updates + _, err := ConsumeListPage(ctx, s, me, "clean", func(context.Context, ListPage) error { return errKilled }) + if !errors.Is(err, errKilled) || !sameList(s.h.List, &c) || s.updates != writes { + t.Fatalf("failed effects moved cursor: %v", err) + } + applied := 0 + done, err := ConsumeListPage(ctx, s, me, "clean", func(context.Context, ListPage) error { applied++; return nil }) + if err != nil || !done || applied != 1 || s.h.List != nil { + t.Fatalf("consume: done=%v applied=%d err=%v", done, applied, err) + } + if _, found, _ := s.ReadListPage(ctx, c.Ref); !found { + t.Fatal("consumer retired before reachability sweep") + } +} + +func TestListSweepSpareSessionAndReachableTail(t *testing.T) { + ctx := context.Background() + s, c, p := chainFixture(t) + if _, err := StageListPage(ctx, s, me, "s1", p); err != nil { + t.Fatal(err) + } + // A cleanup pass cannot coexist with the publication's session, including + // when its CAS result is unknown. No page may disappear in that interval. + cleaner := NewCleaner(s, nil, s, me, "clean") + if _, err := cleaner.Page(ctx, ListDir, 0, []string{c.Ref.Hash}); !errors.Is(err, ErrNoSession) { + t.Fatalf("open-session sweep: %v", err) + } + if _, err := RunPublishList(ctx, s, me, "s1", s.h.Gen, c); err != nil { + t.Fatal(err) + } + if _, err := RunAbort(ctx, s, me, "s1", CauseSessionRollback); err != nil { + t.Fatal(err) + } + if _, err := RunBeginClean(ctx, s, me, "clean"); err != nil { + t.Fatal(err) + } + if out, err := cleaner.Page(ctx, ListDir, 0, []string{c.Ref.Hash}); err != nil || len(out.Names) != 0 { + t.Fatalf("reached page removed: %+v %v", out, err) + } + if _, err := ConsumeListPage(ctx, s, me, "clean", func(context.Context, ListPage) error { return nil }); err != nil { + t.Fatal(err) + } + if out, err := cleaner.Page(ctx, ListDir, 0, []string{c.Ref.Hash}); err != nil || len(out.Names) != 1 { + t.Fatalf("retired page not reclaimed: %+v %v", out, err) + } +} + +func TestRunPublishList_InterruptAtEveryStep(t *testing.T) { + for _, after := range []bool{false, true} { + t.Run(map[bool]string{false: "before", true: "lost-reply"}[after], func(t *testing.T) { + ctx := context.Background() + s, c, p := chainFixture(t) + base := s.h.Gen + if _, err := StageListPage(ctx, s, me, "s1", p); err != nil { + t.Fatal(err) + } + s.memHead.killAt, s.memHead.after = 1, after + if _, err := RunPublishList(ctx, s, me, "s1", base, c); !errors.Is(err, errKilled) { + t.Fatalf("kill: %v", err) + } + if _, found, _ := s.ReadListPage(ctx, c.Ref); !found { + t.Fatal("unknown publish discarded page") + } + s.memHead.dead, s.memHead.killAt = false, 0 + if _, err := RunPublishList(ctx, s, me, "s1", base, c); err != nil { + t.Fatal(err) + } + if !sameList(s.h.List, &c) { + t.Fatal("restart did not settle publication") + } + }) + } +} + +func TestRunAdvanceList_InterruptAtEveryStep(t *testing.T) { + for _, after := range []bool{false, true} { + t.Run(map[bool]string{false: "before", true: "lost-reply"}[after], func(t *testing.T) { + ctx := context.Background() + s, c := publishedChain(t) + s.memHead.killAt, s.memHead.after = s.updates+1, after + applied := 0 + effect := func(context.Context, ListPage) error { applied++; return nil } + if _, err := ConsumeListPage(ctx, s, me, "clean", effect); !errors.Is(err, errKilled) { + t.Fatalf("kill: %v", err) + } + if _, found, _ := s.ReadListPage(ctx, c.Ref); !found { + t.Fatal("unknown cursor discarded page") + } + s.memHead.dead, s.memHead.killAt = false, 0 + if done, err := ConsumeListPage(ctx, s, me, "clean", effect); err != nil || !done { + t.Fatalf("restart: %v %v", done, err) + } + want := 2 + if after { + want = 1 + } + if applied != want { + t.Fatalf("effects=%d want%d", applied, want) + } + }) + } +} + +func TestListSharedTailSurvivesAbandonedChainAndResumes(t *testing.T) { + ctx := context.Background() + s, c, tail := chainFixture(t) + tr, err := StageListPage(ctx, s, me, "s1", tail) + if err != nil { + t.Fatal(err) + } + head := tail + head.Pages, head.Next = 2, &tr + head.Entries = []string{RootName{Hash: Sum([]byte("head-candidate"))}.Path()} + hr, err := StageListPage(ctx, s, me, "s1", head) + if err != nil { + t.Fatal(err) + } + abandoned := head + abandoned.Entries = []string{RootName{Hash: Sum([]byte("abandoned-candidate"))}.Path()} + ar, err := StageListPage(ctx, s, me, "s1", abandoned) + if err != nil { + t.Fatal(err) + } + c.Ref = hr + if _, err := RunPublishList(ctx, s, me, "s1", s.h.Gen, c); err != nil { + t.Fatal(err) + } + if _, err := RunAbort(ctx, s, me, "s1", CauseSessionRollback); err != nil { + t.Fatal(err) + } + if _, err := RunBeginClean(ctx, s, me, "clean"); err != nil { + t.Fatal(err) + } + cleaner := NewCleaner(s, nil, s, me, "clean") + // The abandoned chain contains the live chain's tail. Membership in the + // abandoned attempt cannot authorize deleting that shared tail. + for _, ref := range []ListRef{ar, tr} { + out, err := cleaner.Page(ctx, ListDir, 0, []string{ref.Hash}) + if err != nil { + t.Fatal(err) + } + want := 0 + if ref == ar { + want = 1 + } + if len(out.Names) != want { + t.Fatalf("sweep %s: %+v want%d", ref.Hash, out, want) + } + } + seen := map[string]int{} + effect := func(_ context.Context, p ListPage) error { + for _, rel := range p.Entries { + seen[rel]++ + } + return nil + } + done, err := ConsumeListPage(ctx, s, me, "clean", effect) + if err != nil || done || s.h.List.Ref != tr { + t.Fatalf("first page: done=%v err=%v", done, err) + } + // No process memory survives here: reconstruct the cleaner and reread HEAD. + cleaner = NewCleaner(s, nil, s, me, "clean") + if out, err := cleaner.Page(ctx, ListDir, 0, []string{hr.Hash}); err != nil || len(out.Names) != 1 { + t.Fatalf("retire head: %+v %v", out, err) + } + if _, found, _ := s.ReadListPage(ctx, tr); !found { + t.Fatal("unread tail lost") + } + done, err = ConsumeListPage(ctx, s, me, "clean", effect) + if err != nil || !done || seen[head.Entries[0]] != 1 || seen[tail.Entries[0]] != 1 { + t.Fatalf("resume: %+v %v %v", seen, done, err) + } +} + +func TestListMissingConsumerPageNeverCompletes(t *testing.T) { + s, c := publishedChain(t) + rel, _ := c.Ref.Path() + delete(s.objs, s.full(rel)) + writes := s.updates + called := false + _, err := ConsumeListPage(context.Background(), s, me, "clean", func(context.Context, ListPage) error { called = true; return nil }) + if !errors.Is(err, ErrListPageMissing) || called || s.updates != writes || !sameList(s.h.List, &c) { + t.Fatalf("missing consumed: %v called=%v", err, called) + } +} + +func TestListSessionEndedDuringPageWriteCannotPublish(t *testing.T) { + ctx := context.Background() + s, c, p := chainFixture(t) + base := s.h.Gen + s.memObjects.hook = func(_, _ string) { + s.memObjects.hook = nil + if _, err := RunAbort(ctx, s, me, "s1", CauseSessionRollback); err != nil { + t.Fatal(err) + } + } + if _, err := StageListPage(ctx, s, me, "s1", p); err != nil { + t.Fatal(err) + } + if _, err := RunPublishList(ctx, s, me, "s1", base, c); !errors.Is(err, ErrNoSession) { + t.Fatalf("ended session published: %v", err) + } + if s.h.List != nil { + t.Fatal("orphan published") + } + if _, err := RunBeginClean(ctx, s, me, "clean"); err != nil { + t.Fatal(err) + } + if out, err := NewCleaner(s, nil, s, me, "clean").Page(ctx, ListDir, 0, []string{c.Ref.Hash}); err != nil || len(out.Names) != 1 { + t.Fatalf("orphan not swept: %+v %v", out, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/list_page.go b/seaweed-block/core/frontend/chunkstore/layout/list_page.go index 24b23e8b75..8285b91977 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/list_page.go +++ b/seaweed-block/core/frontend/chunkstore/layout/list_page.go @@ -85,33 +85,9 @@ func (p ListPage) check() error { if p.VolumeID.IsZero() || p.Generation == 0 || p.Pages == 0 || p.Pages > MaxListPages { return fmt.Errorf("%w: list page identity or page count", ErrMalformed) } - if p.Producer == "" || len(p.Producer) > MaxListProducerBytes { - return fmt.Errorf("%w: list page producer", ErrMalformed) - } - if err := validName("list producer", p.Producer); err != nil { + if err := checkListContext(p.Kind, p.Producer, p.Generation, p.Target); err != nil { return err } - switch p.Kind { - case ListDrop: - case ListUploadIntent: - if p.Target != nil { - return fmt.Errorf("%w: upload intent has a snapshot target", ErrMalformed) - } - case ListSnapshotDeleteIntent: - if p.Target == nil { - return fmt.Errorf("%w: snapshot-delete intent needs its captured target", ErrMalformed) - } - default: - return fmt.Errorf("%w: unknown list kind %q", ErrMalformed, p.Kind) - } - if p.Target != nil { - if p.Target.Gen == 0 { - return fmt.Errorf("%w: list snapshot target generation zero", ErrMalformed) - } - if err := CheckSnapshot(p.Target.Name, SnapshotMeta{}); err != nil { - return err - } - } if p.Next == nil { if p.Pages != 1 { return fmt.Errorf("%w: list chain ends before its declared count", ErrMalformed) @@ -241,3 +217,37 @@ func DecodeListPage(raw []byte, ref ListRef, volume VolumeID) (ListPage, error) } return p, nil } + +func checkListContext(kind ListKind, producer string, generation uint64, target *SnapshotTarget) error { + if generation == 0 { + return fmt.Errorf("%w: list generation zero", ErrMalformed) + } + if producer == "" || len(producer) > MaxListProducerBytes { + return fmt.Errorf("%w: list page producer", ErrMalformed) + } + if err := validName("list producer", producer); err != nil { + return err + } + switch kind { + case ListDrop: + case ListUploadIntent: + if target != nil { + return fmt.Errorf("%w: upload intent has a snapshot target", ErrMalformed) + } + case ListSnapshotDeleteIntent: + if target == nil { + return fmt.Errorf("%w: snapshot-delete intent needs its captured target", ErrMalformed) + } + default: + return fmt.Errorf("%w: unknown list kind %q", ErrMalformed, kind) + } + if target != nil { + if target.Gen == 0 { + return fmt.Errorf("%w: list snapshot target generation zero", ErrMalformed) + } + if err := CheckSnapshot(target.Name, SnapshotMeta{}); err != nil { + return err + } + } + return nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove.go b/seaweed-block/core/frontend/chunkstore/layout/remove.go index 7f22387baf..a8332e0840 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove.go @@ -66,6 +66,12 @@ func (c *Cleaner) Page(ctx context.Context, kind string, shard uint64, names []s return RemovalResult{}, ErrMalformed } rel = n.Path() + case ListDir: + p, err := (ListRef{Hash: name, Pages: 1}).Path() + if err != nil { + return RemovalResult{}, err + } + rel = p default: return RemovalResult{}, ErrMalformed } @@ -78,7 +84,7 @@ func (c *Cleaner) Page(ctx context.Context, kind string, shard uint64, names []s // tags -> HEAD + holder/clean validation -> reachability -> conditional mark -> // conditional delete. A reuse after planning or marking defeats the late write. func (c *Cleaner) removePlanned(ctx context.Context, rels []string, kind string, shard uint64) (out RemovalResult, err error) { - if c.os == nil || c.r == nil { + if c.os == nil || kind != ListDir && c.r == nil { return out, errors.New("layout: removal needs a reader and an object store") } type tag struct { @@ -145,7 +151,21 @@ func (c *Cleaner) removePlanned(ctx context.Context, rels []string, kind string, } } live := map[string]bool{} - if kind == PoolDir { + if kind == ListDir { + r, ok := c.os.(ListPageReader) + if !ok { + return out, errors.New("layout: list removal needs a bounded page reader") + } + if h.List != nil { + if err := ReadListChain(ctx, r, h.VolumeID, *h.List, func(ref ListRef, _ ListPage) error { + p, _ := ref.Path() + live[p] = true + return nil + }); err != nil { + return out, err + } + } + } else if kind == PoolDir { if c.chunks == nil || c.shard != shard { c.chunks, err = reachable(ctx, c.r, c.roots, shard) c.shard = shard diff --git a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go index 0a4423998e..871acce751 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go @@ -116,7 +116,25 @@ func TestHolderFunctions_RefuseAStaleHolder(t *testing.T) { t.Errorf("Cleaner by %s: %v writes=%v", who, err, o.writes) } } - covered := map[string]bool{"NewCleaner": true, "RemoveUnreachable": true, "Start": true, "startCheck": true, "DetachedBy": true, "CheckCommitObjects": true, "commitChecked": true} + for _, caller := range callers { + s, c, p := chainFixture(t) + if err := listSession(*s.h, caller, "s1", ActSnap); !errors.Is(err, ErrNotHolder) { + t.Fatal(err) + } + if _, err := StageListPage(context.Background(), s, caller, "s1", p); !errors.Is(err, ErrNotHolder) { + t.Fatal(err) + } + if _, err := RunPublishList(context.Background(), s, caller, "s1", s.h.Gen, c); !errors.Is(err, ErrNotHolder) { + t.Fatal(err) + } + if _, err := ConsumeListPage(context.Background(), s, caller, "clean", func(context.Context, ListPage) error { t.Fatal("stale executor called"); return nil }); !errors.Is(err, ErrNotHolder) { + t.Fatal(err) + } + if len(s.writes) != 0 || s.updates != 0 { + t.Fatal("stale list caller wrote") + } + } + covered := map[string]bool{"listSession": true, "StageListPage": true, "ConsumeListPage": true, "NewCleaner": true, "RemoveUnreachable": true, "Start": true, "startCheck": true, "DetachedBy": true, "CheckCommitObjects": true, "commitChecked": true} var missing []string for fname, src := range packageSources(t, false) { file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0) diff --git a/seaweed-block/core/frontend/chunkstore/layout_list_test.go b/seaweed-block/core/frontend/chunkstore/layout_list_test.go new file mode 100644 index 0000000000..d52f9897a7 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_list_test.go @@ -0,0 +1,132 @@ +package chunkstore + +import ( + "bytes" + "context" + "errors" + "path" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +func TestLayoutListAbsentHEAD(t *testing.T) { + s, f, b := layoutStoreFixture(t) + ctx := context.Background() + me := layout.HolderID{Epoch: 1, Holder: "holder", ClaimID: "claim"} + if _, err := layout.StageListPage(ctx, s, me, "s1", layout.ListPage{}); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatal(err) + } + if _, err := layout.RunPublishList(ctx, s, me, "s1", 1, layout.ListCursor{}); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatal(err) + } + if _, err := layout.ConsumeListPage(ctx, s, me, "clean", func(context.Context, layout.ListPage) error { t.Fatal("executor ran"); return nil }); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatal(err) + } + puts, _, _ := b.counts() + if len(f.written) != 0 || puts != 0 { + t.Fatal("absent HEAD was recreated or uploaded") + } +} + +func TestLayoutStoreListPageDataBeforeEntryAndBoundedRead(t *testing.T) { + s, f, b := layoutStoreFixture(t) + ctx := context.Background() + p := layout.ListPage{VolumeID: s.id, Kind: layout.ListDrop, Producer: "s1", Generation: 2, Pages: 1, + Entries: []string{(layout.RootName{Hash: layout.Sum([]byte("candidate"))}).Path()}} + raw, _ := p.Encode() + ref, _ := p.Ref() + rel, _ := ref.Path() + if err := layout.EnsureObject(ctx, s, rel, raw, "s1"); err != nil { + t.Fatal(err) + } + got, found, err := s.ReadListPage(ctx, ref) + if err != nil || !found || !bytes.Equal(got, raw) { + t.Fatalf("readback: %v %v", found, err) + } + if _, err := layout.DecodeListPage(got, ref, s.id); err != nil { + t.Fatal(err) + } + puts, _, _ := b.counts() + if err := layout.EnsureObject(ctx, s, rel, raw, "s1"); err != nil { + t.Fatal(err) + } + after, _, _ := b.counts() + if puts != after { + t.Fatal("replayed page reuploaded") + } + e, err := f.LookupEntry(ctx, path.Join(s.root, layout.ListDir), ref.Hash) + if err != nil { + t.Fatal(err) + } + if len(e.Chunks) != 1 || len(e.Content) != 0 || string(e.Extended[layoutSession]) != "s1" { + t.Fatalf("not a session-owned filer file: %+v", e) + } + // A dishonest size declaration is rejected before fetching its payload. + e.Chunks[0].Size = layout.MaxListPageBytes + 1 + e.Attributes.FileSize = e.Chunks[0].Size + if err := f.UpdateEntry(ctx, path.Join(s.root, layout.ListDir), e, nil); err != nil { + t.Fatal(err) + } + _, gets, _ := b.counts() + if _, _, err := s.ReadListPage(ctx, ref); err == nil { + t.Fatal("accepted excessive blob") + } + _, nextGets, _ := b.counts() + if gets != nextGets { + t.Fatal("fetched excessive blob before bound check") + } +} + +func TestLayoutStoreListPublishConsumeAndRetire(t *testing.T) { + s, _, _ := layoutStoreFixture(t) + ctx := context.Background() + h := layout.Unclaimed(s.id, nil) + h.Epoch, h.Holder, h.ClaimID = 1, "holder", "claim" + h.Activity = layout.Activity{Kind: layout.ActSnap, Session: "s1"} + if err := s.UpdateHead(ctx, 0, h, layout.CauseCreate); err != nil { + t.Fatal(err) + } + me := layout.HolderID{Epoch: 1, Holder: "holder", ClaimID: "claim"} + p := layout.ListPage{VolumeID: s.id, Kind: layout.ListDrop, Producer: "s1", Generation: 2, Pages: 1, + Entries: []string{(layout.RootName{Hash: layout.Sum([]byte("candidate"))}).Path()}} + r, err := layout.StageListPage(ctx, s, me, "s1", p) + if err != nil { + t.Fatal(err) + } + c := layout.ListCursor{Ref: r, Kind: p.Kind, Producer: p.Producer, Generation: p.Generation} + if _, err := layout.RunPublishList(ctx, s, me, "s1", 1, c); err != nil { + t.Fatal(err) + } + if _, err := layout.RunAbort(ctx, s, me, "s1", layout.CauseSessionRollback); err != nil { + t.Fatal(err) + } + if _, err := layout.RunBeginClean(ctx, s, me, "clean"); err != nil { + t.Fatal(err) + } + cleaner := layout.NewCleaner(s, nil, s, me, "clean") + if out, err := cleaner.Page(ctx, layout.ListDir, 0, []string{r.Hash}); err != nil || len(out.Names) != 0 { + t.Fatalf("early retirement: %+v %v", out, err) + } + applied := false + done, err := layout.ConsumeListPage(ctx, s, me, "clean", func(_ context.Context, got layout.ListPage) error { + if got.Entries[0] != p.Entries[0] { + t.Fatal("wrong work") + } + applied = true + return nil + }) + if err != nil || !done || !applied { + t.Fatalf("consume: %v %v", done, err) + } + if out, err := cleaner.Page(ctx, layout.ListDir, 0, []string{r.Hash}); err != nil || len(out.Names) != 1 { + t.Fatalf("retirement: %+v %v", out, err) + } + if _, found, err := s.ReadListPage(ctx, r); err != nil || found { + t.Fatalf("not retired: %v %v", found, err) + } + h, found, err := s.ReadHead(ctx) + if err != nil || !found || h.Gen != 5 || h.List != nil { + t.Fatalf("final HEAD: %+v %v", h, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_store.go b/seaweed-block/core/frontend/chunkstore/layout_store.go index 5d39340226..075c13b669 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_store.go +++ b/seaweed-block/core/frontend/chunkstore/layout_store.go @@ -2,6 +2,7 @@ package chunkstore import ( "context" + "encoding/json" "errors" "fmt" "math" @@ -176,6 +177,9 @@ func (s *LayoutStore) object(rel string) (string, string, error) { case len(parts) == 2 && parts[0] == layout.RootDir: n, err := layout.ParseRootName(parts[1]) valid = err == nil && n.Path() == rel + case len(parts) == 2 && parts[0] == layout.ListDir: + p, err := (layout.ListRef{Hash: parts[1], Pages: 1}).Path() + valid = err == nil && p == rel } if !valid { return "", "", layout.ErrMalformed @@ -253,7 +257,20 @@ func (s *LayoutStore) Create(ctx context.Context, rel string, raw []byte, sessio } // All object names end in their bytes' SHA-256; do not create a name // for bytes it does not identify. - if !strings.HasSuffix(name, layout.Sum(raw).String()) { + if strings.HasPrefix(rel, layout.ListDir+"/") { + if len(raw) > layout.MaxListPageBytes { + return layout.ErrMalformed + } + var count struct { + Pages uint32 `json:"pages"` + } + if err := json.Unmarshal(raw, &count); err != nil { + return layout.ErrMalformed + } + if _, err := layout.DecodeListPage(raw, layout.ListRef{Hash: name, Pages: count.Pages}, s.id); err != nil { + return err + } + } else if !strings.HasSuffix(name, layout.Sum(raw).String()) { return layout.ErrCorrupt } fid, err := s.b.Put(ctx, raw) @@ -281,6 +298,46 @@ func (s *LayoutStore) Create(ctx context.Context, rel string, raw []byte, sessio return err } +// ReadListPage checks the declared bound and identity before fetching a blob. +// The codec checks the returned bytes/hash/count before any consumer effect. +func (s *LayoutStore) ReadListPage(ctx context.Context, ref layout.ListRef) ([]byte, bool, error) { + rel, err := ref.Path() + if err != nil { + return nil, false, err + } + dir, name, err := s.object(rel) + if err != nil { + return nil, false, err + } + e, err := s.f.LookupEntry(ctx, dir, name) + if errors.Is(err, ErrNotFound) { + return nil, false, nil + } + if err != nil { + return nil, false, err + } + if e.IsDirectory || string(e.Extended[layoutVolume]) != s.id.String() || string(e.Extended[layoutKind]) != "object" || len(e.Extended[layoutSession]) == 0 { + return nil, false, layout.ErrCorrupt + } + if len(e.Content) > layout.MaxListPageBytes || e.GetAttributes().GetFileSize() > layout.MaxListPageBytes { + return nil, false, layout.ErrMalformed + } + if len(e.Chunks) == 0 { + return append([]byte(nil), e.Content...), true, nil + } + if len(e.Content) != 0 || len(e.Chunks) != 1 || e.Chunks[0].Offset != 0 || e.Chunks[0].FileId == "" || e.Chunks[0].Size > layout.MaxListPageBytes || e.GetAttributes().GetFileSize() != e.Chunks[0].Size { + return nil, false, layout.ErrCorrupt + } + raw, err := s.b.Get(ctx, e.Chunks[0].FileId) + if err != nil { + return nil, false, err + } + if uint64(len(raw)) != e.Chunks[0].Size { + return nil, false, layout.ErrCorrupt + } + return raw, true, nil +} + func objectExpected(meta layout.ObjectMeta) map[string][]byte { return map[string][]byte{layoutVolume: []byte(meta.Volume.String()), layoutSession: []byte(meta.Session), layoutMark: []byte(meta.Mark)} } diff --git a/seaweed-block/docs/design/immutable-list-pages.md b/seaweed-block/docs/design/immutable-list-pages.md index 39e3577061..272abe9cb7 100644 --- a/seaweed-block/docs/design/immutable-list-pages.md +++ b/seaweed-block/docs/design/immutable-list-pages.md @@ -1,8 +1,9 @@ # Immutable cleaning and intent list pages -This Draft codec prepares persisted metadata; it has no storage writer, -HEAD publication, retirement or cleaner caller. Those transitions require -the page-chain crash refinement before integration. +This Draft integrates the immutable codec with the existing filer/blob store, +HEAD CAS and cleaning exclusion. It is dormant: no cut/restore/delete driver +calls the producer or consumer yet, and no automatic cleaner policy changes. +This is not the final format declaration or the complete V8 producer wiring. Version 1 is compact canonical JSON with keys in this order: `version, volume_id, kind, producer, generation, pages, next?, target?, entries`. @@ -26,9 +27,9 @@ not a volume-sized chain. A producer reaching a ceiling must refuse before its effect, never truncate or omit required work. These explicit ceilings are proposed for format review and must be confirmed before declaration. -A chain reader also validates producer/kind/target/generation consistency -across pages; this codec checks one page only. The future consumer may -advance progress only after completing its effects. An unread continuation +ReadListChain validates producer/kind/target/generation consistency across +pages, holding one bounded page at a time. The consumer advances progress +only after completing the page executor's idempotent effects. An unread continuation must remain reachable until retirement is authorized. Neither an absent page nor malformed metadata may mean empty/completed work. @@ -40,4 +41,68 @@ forbidden paths and size/entry limits. Unknown newer versions are refused. The fallback cleaner stays a full mark/sweep until a separately reviewed switch, made safe for reachable list/intent objects. Nothing in this codec -starts that switch or weakens existing reclamation protections. \ No newline at end of file +starts that switch or weakens existing reclamation protections. +## Publication, continuation and retirement + +```mermaid +sequenceDiagram + participant Producer + participant Store + participant HEAD + participant Consumer + Producer->>Store: StageListPage (data before exclusive entry, session-owned) + Producer->>Store: read and validate complete chain + Producer->>HEAD: CAS base generation + open snap session -> list cursor + Note over Producer,HEAD: unknown reply retains ownership; reread/retry same attempt + Consumer->>Store: read authenticated current page under clean session + Consumer->>Consumer: finish idempotent, independently guarded effects + Consumer->>HEAD: CAS observed continuation -> next page or none + Note over Consumer,HEAD: lost reply settled from HEAD before success + Consumer->>Store: tags -> current HEAD reachability -> conditional mark/delete +``` + +HEAD has one optional `list` field, containing `ref`, `kind`, `producer`, +`generation`, and optional captured `target`. It is a serialized admission +slot: a second outstanding chain is refused, never overwrites unfinished +work. The slot is bounded and admitted only in version 1; a legacy encoding +cannot carry it. This slot is for reviewing the chain integration, not an +approval of final multi-producer queue capacity. The version remains 1; +all v1.1 fields belong to the final schema, never to `ext`. + +Pages are staged by the already-open snap session. The original base +HEAD generation and the full holder identity gate publication. Ending a +session while an upload runs may leave an orphan, but its publication +cannot land afterward. No failed/unknown publish path discards pages or +ends its session. A replay that observes its exact live cursor settles a +landed send even if a resend was refused. Otherwise the error remains +unknown/refused, with no cleanup side effect. + +`ConsumeListPage` authenticates one page, invokes an idempotent executor, +and advances only after that executor returns success. The executor must +use existing authority, reachability and conditional mutation rules; a list +is a set of candidates, not permission to remove an object or a snapshot. +A crash or refused cursor CAS can repeat that page's effects. Only a +confirmed persisted continuation is progress. Page retirement is separate: +`Cleaner.Page(ListDir, ...)` reads tags before HEAD, requires the existing +clean session, walks the current live chain and conditionally marks/deletes +only unreached pages. An open snap session refuses cleaning altogether, +protecting unsettled publication. A shared tail remains live even if an +abandoned attempt also contains it. A missing/corrupt live continuation +stops retirement, never means empty or complete. + +Storage uses ordinary data-first exclusive filer objects with session and +volume metadata. Reads check declared inline/blob sizes before payload +fetch; the blob interface returns one object, so a dishonest blob backend +that returns more than its declared size can allocate before the final size +check. No stronger streaming allocation guarantee is claimed. Existing +full-volume deletion remains the authority for namespace removal; this +slice does not replace its sweep with the dormant list consumer. + +Model trace: PageChain rows 246-253 (`NoDangling`, `NoLostWork`). Seven +mutations cover premature HEAD publication, loss of session protection, +unsettled abandonment, membership-based retirement, retirement before +cursor settlement, cursor before effects, and absent-as-end. Tests also +cover session end during upload and shared-tail continuation after restart. +Snapshot producer stamping/binding integration, complete restore ancestry, +volume-delete cursor, final queue layout, driver activation and release +qualification remain separate required work before the v1.1 declaration. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a0cfcfb50d..35ad2d0499 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -569,7 +569,9 @@ stateDiagram-v2 clean --> idle: Claim(e, claim id), c void idle --> clean: BeginClean(c) clean --> idle: EndClean(c) - clean --> clean: roots, segments, chunk shards (conditional removal) + snap --> snap: PublishList (durable session pages, base CAS) + clean --> clean: AdvanceList (effects then cursor CAS) + clean --> clean: roots, segments, chunk shards and unreached list pages (conditional removal) idle --> deleting: MarkDeleting (no holder, no dependents) deleting --> deleted: MarkDeleted (after release and pool) ``` @@ -578,6 +580,9 @@ stateDiagram-v2 |---|---|---|---|---| | no lifecycle record | named volume with immutable layout id | master lifecycle create mints the id once; a lost directory-sync reply settles the same record on retry. Lookup resolves the durable name/id without creating one; workload launch carries both and selects a local directory keyed by id | `core/lifecycle/store.go` `CreateVolume`; master `CreateVolume`, `GetVolume`; `core/rpc/lifecycleclient` `ResolveVolume`; launcher `blockVolumeArgs`; blockvolume `parseFlags` | `INV-SNAPK-VOLUME-DIR-001` | | pending ordinary create with a proved id8 collision | pending create with a fresh durable layout id | rejected exclusive VOLUME create, valid foreign full identity belongs to the selected name/id8 directory; not ready, not attached, not a restore; persist replacement before retry, settle unknown rename on replay; never modify the colliding volume | `LayoutStore.CreateVolumeRecord`; `FileStore.RedrawPendingLayoutID`; master `createLifecycleVolume` | `INV-CREATE-DIR-COLLISION-001` | +| snap(s), list slot empty | snap(s), list cursor published | same full holder, open session and original base generation; every referenced page durable and authenticated; unknown reply retains session and pages | `list_chain.go` `StageListPage`, `RunPublishList` | `INV-LIST-PUBLISH-001` | +| clean(c), current list page | clean(c), next continuation or none | exact observed cursor CAS only after authenticated page effects succeed; failed reads and failed effects leave cursor unchanged | `list_chain.go` `RunAdvanceList` | `INV-LIST-CURSOR-001` | +| clean(c), stored list page | clean(c), unreached page removed | tags before HEAD; current clean session; spare all current-chain pages; conditional mark then delete | `remove.go` `Cleaner.Page` | `INV-LIST-RETIRE-001` | | idle | snap(s) | caller is the holder at HEAD's epoch (epoch, server and claim id); HEAD present; snap(s) again is a replay, any other activity is refused | head.go `Head.Begin`, `runTransition` | `INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-BEGIN-001` | | snap(s) | idle | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); over idle it succeeds without a write and means only that no activity remains; before resuming a failed stop, abort its still-open session and re-read HEAD: only matching live/idle resumes, detached goes Down, absent/unknown stays stopped | head.go `Head.Abort`; durable/provider_layout.go `settleLayoutStop` | `INV-SNAPK-ABORT-001` | | snap(s) | idle, current = root | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); the previous manifest builds to HEAD's current root; the new own chunks, every segment and the root are present; a new snapshot name records bounded retention facts once, while replay preserves them | commit.go `Head.Commit`, `RunCommit` | `INV-SNAPK-COMMIT-REACH-001`, `INV-SNAPK-TXN-INTERRUPT-001`, `INV-SNAPK-SNAPSHOT-META-001` | @@ -1264,6 +1269,17 @@ Notes: |---|---|---|---|---|---|---| | `INV-SNAPSHOT-INCARNATION-001` | A snapshot identity is its name and immutable publishing HEAD generation within the volume ID. A resumed delete removes only its admitted incarnation; a recreated name is preserved. Zero requires legacy stamping. | M9 snapshot publication and target-qualified removal | `layout/head.go`, `layout/snapshot_generation.go`; producer integration pending | `TestSnapshotPublishingGenerationGolden`, `TestLegacySnapshotStampKeepsOneIdentityAcrossRetry`, `TestSnapshotDeleteTargetSparesAnUnchangedImageRecreation`, `TestSnapshotDeleteCASConflictKeepsCapturedIncarnation` | SnapDelete rows 241-245 | STUB | +### Immutable list continuation integration + +| ID | Statement | Transition | Enforced in | Guard | Model | Status | +|---|---|---|---|---|---|---| +| `INV-LIST-PUBLISH-001` | A list publication names only durable authenticated pages of its open session; an unknown reply never abandons their protection. | M9 snap -> snap | `list_chain.go` `StageListPage`, `RunPublishList` | `TestPublishList_Closure`, `TestRunPublishList_InterruptAtEveryStep`, `TestListSessionEndedDuringPageWriteCannotPublish` | PageChain 246-250; NoDangling | DORMANT | +| `INV-LIST-CURSOR-001` | The persisted list cursor advances only after its authenticated page's idempotent effects finish; a missing page never completes work. | M9 clean -> clean | `list_chain.go` `RunAdvanceList` | `TestAdvanceList_Closure`, `TestRunAdvanceList_InterruptAtEveryStep`, `TestListMissingConsumerPageNeverCompletes` | PageChain 246,251-253; NoLostWork | DORMANT | +| `INV-LIST-RETIRE-001` | List-page removal requires a clean session and the existing conditional mark/delete order; every page reached by HEAD is spared, including shared tails. | M9 clean removal | `remove.go` `Cleaner.removePlanned` | `TestListSweepSpareSessionAndReachableTail`, `TestListSharedTailSurvivesAbandonedChainAndResumes`, `TestLayoutStoreListPublishConsumeAndRetire` | PageChain 246,248-251; NoDangling | DORMANT | + +These three list rows are dormant until producer/consumer driver wiring and +final queue-layout/format review. They do not declare by-change cleaning active. + ## Part C. Change rules How a fix or a feature is calibrated against this model: diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index b373a136fa..adb4170ac3 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -692,3 +692,22 @@ The provider dispatch control `TestPlainSealReplayDuringDeferredAuthorityStartup sets Healthy=false before RecoverVolume, witnesses the no-layer authority wait, and checks fresh proof replay without CAS or enabling cuts. This is native integration coverage of the existing RemoteProof transition; the model is unchanged. + + +### Immutable list publication and continuation + +[PageChain](pagechain/PageChain.tla) refines an immutable two-page list behind +a conditional HEAD cursor. Model source SHA-256: +`1c8d9ad20ae1f27b90b2d3f759229e64501f6fdb4321ef5cbe340841e00feca8`. +The recorded Linux run of this exact model passed safe_chain (150,260 +states), seven must-violate mutations and four reachability witnesses; +coverage exit 0. This records the model owner's run, not a rerun by this PR. +Configurations and expected results are committed in `pagechain/cfg`. +Trace: [model to code](pagechain/model-code-trace.tsv), rows 246-253. + +The model abstracts effect execution as idempotent completion and relies on +conditional HEAD and object writes. The Go adapter/consumer controls are a +separate refinement obligation: full volume identity, hash/context checking, +read bounds, session exclusion, and the original mark/delete guards remain. +Producer driver activation and final queue layout are not claimed by this +integration; its new protocol rows remain dormant. diff --git a/seaweed-block/docs/spec/pagechain/PageChain.tla b/seaweed-block/docs/spec/pagechain/PageChain.tla new file mode 100644 index 0000000000..311fdf1de8 --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/PageChain.tla @@ -0,0 +1,173 @@ +------------------------------ MODULE PageChain ------------------------------ +(***************************************************************************) +(* V8 page-chain crash rows (claude06, 2026-12-01; #894's list pages). *) +(* CleanList kept a list inside HEAD; here it is a chain of immutable *) +(* content-named page objects that HEAD names by its head page. *) +(* *) +(* One list of two pages: "h" (entry e2) names "t" (entry e1). A holder *) +(* publishes it in attempts; an attempt's pages have the attempt's bytes, *) +(* so a resend of one attempt names the same objects. It writes the pages *) +(* (owned by its session), then sends a CAS conditional on its base *) +(* generation and on HEAD naming no list; a CAS may be delayed, and its *) +(* reply lost. A consumer reads the page at HEAD's cursor, applies its *) +(* entries (idempotent effects), moves the cursor by CAS (reply may be *) +(* lost), then retires the page. A fallback sweep removes pages HEAD does *) +(* not reach and no open session owns. A metadata writer steps HEAD's *) +(* generation. A holder crash is followed by its session's abort, a HEAD *) +(* write; a consumer crash loses its memory. *) +(* *) +(* Break = "none", or ONE of: *) +(* "head_before_durable" the CAS is sent before every page is written *) +(* "sweep_ignores_session" the sweep removes session-owned pages *) +(* "abandon_unsettled" an attempt is abandoned (its unreached pages *) +(* removed) while its CAS may still land *) +(* "retire_by_membership" an abandoned attempt's pages are removed *) +(* although HEAD reaches them *) +(* "cursor_before_effects" the cursor moves before the page's effects *) +(* "retire_before_cursor" a page is retired on a lost cursor reply *) +(* "absent_is_end" a failed page read ends the chain *) +(***************************************************************************) +EXTENDS Integers, FiniteSets + +CONSTANTS MaxAtt, MaxSend, MaxMeta, MaxCrashH, MaxCrashC, Break + +Pg == {"h", "t"} +Pages(k) == {<>, <>} +Ent(x) == IF x = "h" THEN {"e2"} ELSE {"e1"} +AllEnt == {"e1", "e2"} + +VARIABLES head, store, owned, hp, att, base, nsend, net, reply, + cp, cobj, done, published, nmeta, nch, ncc, swept +vars == <> + +\* the pages HEAD reaches: from its cursor to the tail +Reach == IF head.list = 0 THEN {} + ELSE IF head.cur = "h" THEN Pages(head.list) ELSE {<>} +ReachEnt == UNION {Ent(o[2]) : o \in Reach} + +Init == /\ head = [gen |-> 0, list |-> 0, cur |-> "h"] + /\ store = {} /\ owned = {} /\ hp = "idle" /\ att = 0 /\ base = 0 /\ nsend = 0 + /\ net = {} /\ reply = "none" /\ cp = "idle" /\ cobj = <<0, "h">> /\ done = {} + /\ published = FALSE /\ nmeta = 0 /\ nch = 0 /\ ncc = 0 /\ swept = FALSE + +CVars == <> + +\* ---- the holder ---- +Start == /\ hp = "idle" /\ att < MaxAtt /\ head.list = 0 + /\ att' = att + 1 /\ base' = head.gen /\ nsend' = 0 /\ hp' = "write" /\ reply' = "none" + /\ UNCHANGED <> /\ UNCHANGED CVars + +WritePage(x) == /\ hp = "write" + /\ store' = store \cup {<>} /\ owned' = owned \cup {<>} + /\ UNCHANGED <> /\ UNCHANGED CVars + +Send == /\ hp = "write" /\ nsend < MaxSend + /\ (Pages(att) \subseteq store \/ Break = "head_before_durable") + /\ nsend' = nsend + 1 /\ net' = net \cup {[k |-> att, b |-> base, s |-> nsend + 1]} /\ hp' = "sent" + /\ UNCHANGED <> /\ UNCHANGED CVars + +\* a CAS is delivered at any time; its reply reaches the holder or is lost +Deliver(m) == + /\ m \in net /\ net' = net \ {m} + /\ LET ok == head.gen = m.b /\ head.list = 0 IN + /\ head' = IF ok THEN [gen |-> head.gen + 1, list |-> m.k, cur |-> "h"] ELSE head + /\ published' = (published \/ ok) + /\ \E lost \in BOOLEAN : + reply' = IF ~lost /\ m.k = att /\ m.b = base /\ hp = "sent" /\ reply = "none" + THEN (IF ok THEN "ok" ELSE "fail") ELSE reply + /\ UNCHANGED <> /\ UNCHANGED CVars + +Landed == /\ hp \in {"sent", "unk"} /\ (reply = "ok" \/ head.list = att) + /\ hp' = "done" /\ owned' = owned \ Pages(att) + /\ UNCHANGED <> /\ UNCHANGED CVars + +TimeOut == /\ hp = "sent" /\ reply = "none" /\ hp' = "unk" + /\ UNCHANGED <> /\ UNCHANGED CVars + +\* HEAD still at the base, naming another list or none: the CAS may still land; send it again +Resend == /\ hp = "unk" /\ head.list # att /\ head.gen = base /\ nsend < MaxSend + /\ nsend' = nsend + 1 /\ net' = net \cup {[k |-> att, b |-> base, s |-> nsend + 1]} /\ hp' = "sent" + /\ UNCHANGED <> /\ UNCHANGED CVars + +\* the attempt can never land (HEAD moved past its base), or a refusal came back: +\* remove its pages HEAD does not reach, release the session's hold +Abandon == /\ \/ hp \in {"sent", "unk"} /\ reply = "fail" + \/ hp = "unk" /\ head.list # att /\ (head.gen > base \/ Break = "abandon_unsettled") + /\ store' = IF Break = "retire_by_membership" THEN store \ Pages(att) ELSE store \ (Pages(att) \ Reach) + /\ owned' = owned \ Pages(att) /\ hp' = "idle" /\ reply' = "none" + /\ UNCHANGED <> /\ UNCHANGED CVars + +\* a crash, then the session's abort: a HEAD write that ends the session's hold +CrashH == /\ nch < MaxCrashH /\ nch' = nch + 1 + /\ hp' = "idle" /\ reply' = "none" /\ owned' = {} /\ head' = [head EXCEPT !.gen = @ + 1] + /\ UNCHANGED <> /\ UNCHANGED CVars + +HVars == <> + +\* ---- the consumer ---- +CRead == /\ cp = "idle" /\ head.list # 0 + /\ LET o == <> IN + \E fail \in BOOLEAN : + IF o \in store /\ ~fail + THEN /\ cp' = "read" /\ cobj' = o /\ UNCHANGED head + ELSE IF Break = "absent_is_end" + THEN /\ head' = [gen |-> head.gen + 1, list |-> 0, cur |-> "h"] /\ UNCHANGED <> + ELSE /\ UNCHANGED <> \* stop; read again later + /\ UNCHANGED <> /\ UNCHANGED HVars + +CApply == /\ cp \in {"read", "advread"} /\ done' = done \cup Ent(cobj[2]) + /\ cp' = IF cp = "read" THEN "applied" ELSE "adv" + /\ UNCHANGED <> /\ UNCHANGED HVars + +Advanced(h) == IF cobj[2] = "h" THEN [h EXCEPT !.gen = @ + 1, !.cur = "t"] + ELSE [gen |-> h.gen + 1, list |-> 0, cur |-> "h"] + +CAdvance == /\ \/ cp = "applied" + \/ cp = "read" /\ Break = "cursor_before_effects" + /\ head.list = cobj[1] /\ head.cur = cobj[2] + /\ \E applied, lost \in BOOLEAN : + /\ applied \/ lost \* only this consumer moves the cursor: no refusal + /\ head' = IF applied THEN Advanced(head) ELSE head + /\ cp' = IF lost THEN "unk" + ELSE IF cp = "read" THEN "advread" ELSE "adv" + /\ UNCHANGED <> /\ UNCHANGED HVars + +CResolve == /\ cp = "unk" + /\ cp' = IF head.list = cobj[1] /\ head.cur = cobj[2] THEN "applied" ELSE "adv" + /\ UNCHANGED <> /\ UNCHANGED HVars + +\* the cursor passed the page: retire it +CRetire == /\ \/ cp = "adv" + \/ cp = "unk" /\ Break = "retire_before_cursor" + /\ store' = store \ {cobj} /\ cp' = "idle" + /\ UNCHANGED <> /\ UNCHANGED HVars + +CrashC == /\ ncc < MaxCrashC /\ ncc' = ncc + 1 /\ cp' = "idle" + /\ UNCHANGED <> /\ UNCHANGED HVars + +\* ---- the environment ---- +Sweep(o) == /\ o \in store /\ o \notin Reach /\ (o \notin owned \/ Break = "sweep_ignores_session") + /\ store' = store \ {o} /\ swept' = TRUE + /\ UNCHANGED <> /\ UNCHANGED HVars /\ UNCHANGED CVars + +Meta == /\ nmeta < MaxMeta /\ nmeta' = nmeta + 1 /\ head' = [head EXCEPT !.gen = @ + 1] + /\ UNCHANGED <> /\ UNCHANGED HVars /\ UNCHANGED CVars + +Next == \/ Start \/ \E x \in Pg : WritePage(x) \/ Send \/ \E m \in net : Deliver(m) + \/ Landed \/ TimeOut \/ Resend \/ Abandon \/ CrashH + \/ CRead \/ CApply \/ CAdvance \/ CResolve \/ CRetire \/ CrashC + \/ \E o \in store : Sweep(o) \/ Meta + +Spec == Init /\ [][Next]_vars + +\* ---- rules ---- +NoDangling == Reach \subseteq store +NoLostWork == published => (AllEnt \ done) \subseteq ReachEnt + +\* ---- witnesses (each expected reachable: its negation is violated) ---- +WitConsumed == ~(published /\ done = AllEnt /\ head.list = 0 /\ cp = "idle" /\ store \cap Pages(1) = {}) +WitRefusedLanded == ~(att = 1 /\ hp = "idle" /\ head.list = 1 /\ nsend = 2) \* a resend refused, the first landed; pages kept +WitSecondAttempt == ~(att = 2 /\ published /\ head.list = 2) +WitOrphanSwept == ~(swept /\ published) +============================================================================= diff --git a/seaweed-block/docs/spec/pagechain/cfg/EXPECTED.txt b/seaweed-block/docs/spec/pagechain/cfg/EXPECTED.txt new file mode 100644 index 0000000000..87a706c81e --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/cfg/EXPECTED.txt @@ -0,0 +1,12 @@ +safe_chain OK +mut_head_before_durable NoDangling +mut_sweep_ignores_session NoDangling +mut_abandon_unsettled NoDangling +mut_retire_by_membership NoDangling +mut_retire_before_cursor NoDangling +mut_cursor_before_effects NoLostWork +mut_absent_is_end NoLostWork +wit_WitConsumed reachable +wit_WitRefusedLanded reachable +wit_WitSecondAttempt reachable +wit_WitOrphanSwept reachable diff --git a/seaweed-block/docs/spec/pagechain/cfg/mut_abandon_unsettled.cfg b/seaweed-block/docs/spec/pagechain/cfg/mut_abandon_unsettled.cfg new file mode 100644 index 0000000000..80f52ef606 --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/cfg/mut_abandon_unsettled.cfg @@ -0,0 +1,9 @@ +CONSTANTS + MaxAtt = 2 + MaxSend = 2 + MaxMeta = 1 + MaxCrashH = 1 + MaxCrashC = 1 + Break = "abandon_unsettled" +SPECIFICATION Spec +INVARIANTS NoDangling NoLostWork diff --git a/seaweed-block/docs/spec/pagechain/cfg/mut_absent_is_end.cfg b/seaweed-block/docs/spec/pagechain/cfg/mut_absent_is_end.cfg new file mode 100644 index 0000000000..d593d48b30 --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/cfg/mut_absent_is_end.cfg @@ -0,0 +1,9 @@ +CONSTANTS + MaxAtt = 2 + MaxSend = 2 + MaxMeta = 1 + MaxCrashH = 1 + MaxCrashC = 1 + Break = "absent_is_end" +SPECIFICATION Spec +INVARIANTS NoDangling NoLostWork diff --git a/seaweed-block/docs/spec/pagechain/cfg/mut_cursor_before_effects.cfg b/seaweed-block/docs/spec/pagechain/cfg/mut_cursor_before_effects.cfg new file mode 100644 index 0000000000..0ce81d32a0 --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/cfg/mut_cursor_before_effects.cfg @@ -0,0 +1,9 @@ +CONSTANTS + MaxAtt = 2 + MaxSend = 2 + MaxMeta = 1 + MaxCrashH = 1 + MaxCrashC = 1 + Break = "cursor_before_effects" +SPECIFICATION Spec +INVARIANTS NoDangling NoLostWork diff --git a/seaweed-block/docs/spec/pagechain/cfg/mut_head_before_durable.cfg b/seaweed-block/docs/spec/pagechain/cfg/mut_head_before_durable.cfg new file mode 100644 index 0000000000..39c1df1ebb --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/cfg/mut_head_before_durable.cfg @@ -0,0 +1,9 @@ +CONSTANTS + MaxAtt = 2 + MaxSend = 2 + MaxMeta = 1 + MaxCrashH = 1 + MaxCrashC = 1 + Break = "head_before_durable" +SPECIFICATION Spec +INVARIANTS NoDangling NoLostWork diff --git a/seaweed-block/docs/spec/pagechain/cfg/mut_retire_before_cursor.cfg b/seaweed-block/docs/spec/pagechain/cfg/mut_retire_before_cursor.cfg new file mode 100644 index 0000000000..8318e6cfae --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/cfg/mut_retire_before_cursor.cfg @@ -0,0 +1,9 @@ +CONSTANTS + MaxAtt = 2 + MaxSend = 2 + MaxMeta = 1 + MaxCrashH = 1 + MaxCrashC = 1 + Break = "retire_before_cursor" +SPECIFICATION Spec +INVARIANTS NoDangling NoLostWork diff --git a/seaweed-block/docs/spec/pagechain/cfg/mut_retire_by_membership.cfg b/seaweed-block/docs/spec/pagechain/cfg/mut_retire_by_membership.cfg new file mode 100644 index 0000000000..c5e6ad68a2 --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/cfg/mut_retire_by_membership.cfg @@ -0,0 +1,9 @@ +CONSTANTS + MaxAtt = 2 + MaxSend = 2 + MaxMeta = 1 + MaxCrashH = 1 + MaxCrashC = 1 + Break = "retire_by_membership" +SPECIFICATION Spec +INVARIANTS NoDangling NoLostWork diff --git a/seaweed-block/docs/spec/pagechain/cfg/mut_sweep_ignores_session.cfg b/seaweed-block/docs/spec/pagechain/cfg/mut_sweep_ignores_session.cfg new file mode 100644 index 0000000000..373b05dbaf --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/cfg/mut_sweep_ignores_session.cfg @@ -0,0 +1,9 @@ +CONSTANTS + MaxAtt = 2 + MaxSend = 2 + MaxMeta = 1 + MaxCrashH = 1 + MaxCrashC = 1 + Break = "sweep_ignores_session" +SPECIFICATION Spec +INVARIANTS NoDangling NoLostWork diff --git a/seaweed-block/docs/spec/pagechain/cfg/safe_chain.cfg b/seaweed-block/docs/spec/pagechain/cfg/safe_chain.cfg new file mode 100644 index 0000000000..e39fbc54b8 --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/cfg/safe_chain.cfg @@ -0,0 +1,9 @@ +CONSTANTS + MaxAtt = 2 + MaxSend = 2 + MaxMeta = 1 + MaxCrashH = 1 + MaxCrashC = 1 + Break = "none" +SPECIFICATION Spec +INVARIANTS NoDangling NoLostWork diff --git a/seaweed-block/docs/spec/pagechain/cfg/wit_WitConsumed.cfg b/seaweed-block/docs/spec/pagechain/cfg/wit_WitConsumed.cfg new file mode 100644 index 0000000000..59548511f3 --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/cfg/wit_WitConsumed.cfg @@ -0,0 +1,9 @@ +CONSTANTS + MaxAtt = 2 + MaxSend = 2 + MaxMeta = 1 + MaxCrashH = 1 + MaxCrashC = 1 + Break = "none" +SPECIFICATION Spec +INVARIANTS WitConsumed diff --git a/seaweed-block/docs/spec/pagechain/cfg/wit_WitOrphanSwept.cfg b/seaweed-block/docs/spec/pagechain/cfg/wit_WitOrphanSwept.cfg new file mode 100644 index 0000000000..57fb180c43 --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/cfg/wit_WitOrphanSwept.cfg @@ -0,0 +1,9 @@ +CONSTANTS + MaxAtt = 2 + MaxSend = 2 + MaxMeta = 1 + MaxCrashH = 1 + MaxCrashC = 1 + Break = "none" +SPECIFICATION Spec +INVARIANTS WitOrphanSwept diff --git a/seaweed-block/docs/spec/pagechain/cfg/wit_WitRefusedLanded.cfg b/seaweed-block/docs/spec/pagechain/cfg/wit_WitRefusedLanded.cfg new file mode 100644 index 0000000000..1e59da41d2 --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/cfg/wit_WitRefusedLanded.cfg @@ -0,0 +1,9 @@ +CONSTANTS + MaxAtt = 2 + MaxSend = 2 + MaxMeta = 1 + MaxCrashH = 1 + MaxCrashC = 1 + Break = "none" +SPECIFICATION Spec +INVARIANTS WitRefusedLanded diff --git a/seaweed-block/docs/spec/pagechain/cfg/wit_WitSecondAttempt.cfg b/seaweed-block/docs/spec/pagechain/cfg/wit_WitSecondAttempt.cfg new file mode 100644 index 0000000000..7776be4fae --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/cfg/wit_WitSecondAttempt.cfg @@ -0,0 +1,9 @@ +CONSTANTS + MaxAtt = 2 + MaxSend = 2 + MaxMeta = 1 + MaxCrashH = 1 + MaxCrashC = 1 + Break = "none" +SPECIFICATION Spec +INVARIANTS WitSecondAttempt diff --git a/seaweed-block/docs/spec/pagechain/model-code-trace.tsv b/seaweed-block/docs/spec/pagechain/model-code-trace.tsv new file mode 100644 index 0000000000..fea76b3a3a --- /dev/null +++ b/seaweed-block/docs/spec/pagechain/model-code-trace.tsv @@ -0,0 +1,9 @@ +row model transition code control +246 PageChain WritePage Send Deliver CApply CAdvance Sweep layout/list_chain.go; layout_store.go; layout/remove.go TestLayoutStoreListPublishConsumeAndRetire +247 PageChain Send layout/list_chain.go RunPublishList TestPublishList_Closure +248 PageChain Sweep layout/remove.go Cleaner.removePlanned TestListSweepSpareSessionAndReachableTail +249 PageChain TimeOut Resend Abandon layout/list_chain.go RunPublishList TestRunPublishList_InterruptAtEveryStep +250 PageChain Abandon Sweep layout/remove.go Cleaner.removePlanned TestListSharedTailSurvivesAbandonedChainAndResumes +251 PageChain CAdvance CResolve CRetire layout/list_chain.go RunAdvanceList; layout/remove.go TestRunAdvanceList_InterruptAtEveryStep +252 PageChain CApply CAdvance layout/list_chain.go RunAdvanceList TestAdvanceList_Closure +253 PageChain CRead layout/list_chain.go readListPage TestListMissingConsumerPageNeverCompletes From 0646ecacc96294e299393a833523a9138448cf40 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:03:48 -0800 Subject: [PATCH 07/20] Stamp legacy snapshots in the list publication CAS --- .../chunkstore/layout/head-write-census.json | 3 +- .../frontend/chunkstore/layout/list_chain.go | 5 +- .../chunkstore/layout/list_chain_test.go | 99 +++++++++++++++++++ .../docs/design/immutable-list-pages.md | 4 +- seaweed-block/docs/spec/README.md | 2 +- 5 files changed, 109 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json b/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json index d004cf3221..993351ae78 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json +++ b/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json @@ -200,7 +200,8 @@ "kind": "update", "may_change": [ "version", - "list" + "list", + "snapshots" ] }, { diff --git a/seaweed-block/core/frontend/chunkstore/layout/list_chain.go b/seaweed-block/core/frontend/chunkstore/layout/list_chain.go index 8d0e4e7b4c..7cb258682b 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/list_chain.go +++ b/seaweed-block/core/frontend/chunkstore/layout/list_chain.go @@ -158,7 +158,10 @@ func RunPublishList(ctx context.Context, st ListChainStore, me HolderID, session if err := ReadListChain(ctx, st, h.VolumeID, c, nil); err != nil { return Head{}, false, err } - next := h.clone() + next, _, err := h.StampSnapshotGenerations() + if err != nil { + return Head{}, false, err + } next.Version, next.List = HeadVersion1, c.clone() return next, true, nil }) diff --git a/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go b/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go index 57251f03d3..b3c84f8554 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go @@ -3,7 +3,9 @@ package layout import ( "bytes" "context" + "encoding/json" "errors" + "os" "testing" ) @@ -54,6 +56,33 @@ func TestReadListChainRejectsMissingAndForeignContinuation(t *testing.T) { } } +func TestReadListChainContextBeforeConsumerEffects(t *testing.T) { + for name, change := range map[string]func(*ListPage){ + "kind": func(p *ListPage) { p.Kind = ListUploadIntent }, + "generation": func(p *ListPage) { p.Generation++ }, + "target": func(p *ListPage) { p.Target = &SnapshotTarget{Name: "other", Gen: 4} }, + } { + t.Run(name, func(t *testing.T) { + s, c, p := chainFixture(t) + change(&p) + ref, err := p.Ref() + if err != nil { + t.Fatal(err) + } + raw, _ := p.Encode() + rel, _ := ref.Path() + s.put(rel, raw, "s1") + c.Ref = ref // correct content hash/count, deliberately wrong HEAD context + s.h.List, s.h.Activity = c.clone(), Activity{Kind: ActClean, Session: "clean"} + called := false + _, err = ConsumeListPage(context.Background(), s, me, "clean", func(context.Context, ListPage) error { called = true; return nil }) + if !errors.Is(err, ErrIdentity) || called || s.updates != 0 { + t.Fatalf("context mismatch executed: %v called%v", err, called) + } + }) + } +} + type chainFiles struct{ data map[string][]byte } func (f *chainFiles) ReadListPage(_ context.Context, ref ListRef) ([]byte, bool, error) { @@ -364,3 +393,73 @@ func TestListSessionEndedDuringPageWriteCannotPublish(t *testing.T) { t.Fatalf("orphan not swept: %+v %v", out, err) } } + +func TestListPublicationStampsLegacyInSameCAS(t *testing.T) { + s, c, p := chainFixture(t) + old := s.h.Snapshots["daily"] + old.Gen = 4 + s.h.Snapshots["published"] = old + ctx := context.Background() + if _, err := StageListPage(ctx, s, me, "s1", p); err != nil { + t.Fatal(err) + } + h, err := RunPublishList(ctx, s, me, "s1", s.h.Gen, c) + if err != nil { + t.Fatal(err) + } + if h.Snapshots["daily"].Gen != h.Gen || h.Snapshots["published"].Gen != 4 || s.updates != 1 { + t.Fatalf("stamp must share publication CAS without remint: %+v writes%d", h.Snapshots, s.updates) + } +} + +func TestListWritesMatchExportedCensus(t *testing.T) { + raw, err := os.ReadFile("head-write-census.json") + if err != nil { + t.Fatal(err) + } + var census exportedHeadCensus + if err := json.Unmarshal(raw, &census); err != nil { + t.Fatal(err) + } + masks := map[HeadWriteCause]map[string]bool{} + for _, r := range census.Rows { + masks[r.Cause] = map[string]bool{} + for _, k := range r.MayChange { + masks[r.Cause][k] = true + } + } + check := func(cause HeadWriteCause, before, after Head) { + t.Helper() + if after.Gen != before.Gen+1 { + t.Fatal("missing generation step") + } + for _, field := range changedCensusGroups(before, after) { + if !masks[cause][field] { + t.Fatalf("%s changes undeclared %s", cause, field) + } + } + } + ctx := context.Background() + s, c, p := chainFixture(t) + if _, err := StageListPage(ctx, s, me, "s1", p); err != nil { + t.Fatal(err) + } + before := s.h.clone() + after, err := RunPublishList(ctx, s, me, "s1", before.Gen, c) + if err != nil { + t.Fatal(err) + } + check(CauseListPublish, before, after) + if _, err := RunAbort(ctx, s, me, "s1", CauseSessionRollback); err != nil { + t.Fatal(err) + } + if _, err := RunBeginClean(ctx, s, me, "clean"); err != nil { + t.Fatal(err) + } + before = s.h.clone() + after, err = RunAdvanceList(ctx, s, me, "clean", func(context.Context, ListPage) error { return nil }) + if err != nil { + t.Fatal(err) + } + check(CauseListAdvance, before, after) +} diff --git a/seaweed-block/docs/design/immutable-list-pages.md b/seaweed-block/docs/design/immutable-list-pages.md index 272abe9cb7..97ecb83b6f 100644 --- a/seaweed-block/docs/design/immutable-list-pages.md +++ b/seaweed-block/docs/design/immutable-list-pages.md @@ -103,6 +103,8 @@ mutations cover premature HEAD publication, loss of session protection, unsettled abandonment, membership-based retirement, retirement before cursor settlement, cursor before effects, and absent-as-end. Tests also cover session end during upload and shared-tail continuation after restart. -Snapshot producer stamping/binding integration, complete restore ancestry, +The list publishing CAS also stamps legacy snapshot entries through the +shared helper; already stamped entries keep their generation. General snapshot +producer/binding integration, complete restore ancestry, volume-delete cursor, final queue layout, driver activation and release qualification remain separate required work before the v1.1 declaration. diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index adb4170ac3..46dfd049f6 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -697,7 +697,7 @@ integration coverage of the existing RemoteProof transition; the model is unchan ### Immutable list publication and continuation [PageChain](pagechain/PageChain.tla) refines an immutable two-page list behind -a conditional HEAD cursor. Model source SHA-256: +a conditional HEAD cursor. Recorded run input and committed model SHA-256: `1c8d9ad20ae1f27b90b2d3f759229e64501f6fdb4321ef5cbe340841e00feca8`. The recorded Linux run of this exact model passed safe_chain (150,260 states), seven must-violate mutations and four reachability witnesses; From b26b4eddea2e89b29c600dfb7dbc9715042c1126 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:06:30 -0800 Subject: [PATCH 08/20] Document list model provenance and typed object names --- seaweed-block/core/frontend/chunkstore/layout_store.go | 4 ++-- seaweed-block/docs/spec/README.md | 6 ++++-- seaweed-block/docs/spec/pagechain/PageChain.tla | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout_store.go b/seaweed-block/core/frontend/chunkstore/layout_store.go index 075c13b669..0b51d793d9 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_store.go +++ b/seaweed-block/core/frontend/chunkstore/layout_store.go @@ -255,8 +255,8 @@ func (s *LayoutStore) Create(ctx context.Context, rel string, raw []byte, sessio if session == "" { return errors.New("chunkstore: object needs a writer session") } - // All object names end in their bytes' SHA-256; do not create a name - // for bytes it does not identify. + // Data names bind their bytes' SHA-256; list names additionally bind + // the page domain. Refuse bytes not authenticated by their typed name. if strings.HasPrefix(rel, layout.ListDir+"/") { if len(raw) > layout.MaxListPageBytes { return layout.ErrMalformed diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 46dfd049f6..b6b0e6061c 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -697,9 +697,11 @@ integration coverage of the existing RemoteProof transition; the model is unchan ### Immutable list publication and continuation [PageChain](pagechain/PageChain.tla) refines an immutable two-page list behind -a conditional HEAD cursor. Recorded run input and committed model SHA-256: +a conditional HEAD cursor. Recorded run input SHA-256: `1c8d9ad20ae1f27b90b2d3f759229e64501f6fdb4321ef5cbe340841e00feca8`. -The recorded Linux run of this exact model passed safe_chain (150,260 +The committed copy removes an internal provenance name from a comment; its +LF-normalized SHA-256 is `ab298e07298d84fe326cb0d1d8626b4bcd479ea5c8be9b15fbab5f22922d6d9b`. Executable model statements and +configurations are unchanged. The recorded Linux run passed safe_chain (150,260 states), seven must-violate mutations and four reachability witnesses; coverage exit 0. This records the model owner's run, not a rerun by this PR. Configurations and expected results are committed in `pagechain/cfg`. diff --git a/seaweed-block/docs/spec/pagechain/PageChain.tla b/seaweed-block/docs/spec/pagechain/PageChain.tla index 311fdf1de8..eda36db2ff 100644 --- a/seaweed-block/docs/spec/pagechain/PageChain.tla +++ b/seaweed-block/docs/spec/pagechain/PageChain.tla @@ -1,6 +1,6 @@ ------------------------------ MODULE PageChain ------------------------------ (***************************************************************************) -(* V8 page-chain crash rows (claude06, 2026-12-01; #894's list pages). *) +(* V8 page-chain crash rows (2026-12-01; #894's list pages). *) (* CleanList kept a list inside HEAD; here it is a chain of immutable *) (* content-named page objects that HEAD names by its head page. *) (* *) From f819d1f3b329f4708d731b534e05e1c2f48ee7c8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:30:28 -0800 Subject: [PATCH 09/20] Persist snapshot deletion intent with its atomic unlink --- .../frontend/chunkstore/head_readers_test.go | 4 + .../chunkstore/layout/delete_intent.go | 209 ++++++++++ .../chunkstore/layout/delete_intent_test.go | 371 ++++++++++++++++++ .../chunkstore/layout/head-write-census.json | 9 + .../frontend/chunkstore/layout/head_cause.go | 6 +- .../layout/head_cause_census_test.go | 3 +- .../chunkstore/layout/kernel_table_test.go | 30 ++ .../frontend/chunkstore/layout/list_chain.go | 12 +- .../chunkstore/layout/list_chain_test.go | 17 + .../core/frontend/chunkstore/layout/remove.go | 25 +- .../frontend/chunkstore/layout_list_test.go | 92 +++++ .../docs/design/immutable-list-pages.md | 50 +++ seaweed-block/docs/design/invariants.md | 13 +- seaweed-block/docs/spec/README.md | 3 +- .../docs/spec/pagechain/model-code-trace.tsv | 3 + 15 files changed, 835 insertions(+), 12 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/delete_intent.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index cd778df244..433d02afba 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -24,6 +24,10 @@ import ( // pins it. "GAP" marks a reader that takes an absent HEAD for an empty // one; a change that treats an absent HEAD as unknown flips those probes. var headReaders = map[string]string{ + "core/frontend/chunkstore/layout/delete_intent.go StageSnapshotDeletePage -> ReadHead": "refuses ErrHeadAbsent before staging (probe TestLayoutDeleteIntentAbsentHEAD)", + "core/frontend/chunkstore/layout/delete_intent.go RunDeleteSnapshotWithIntent -> ReadHead": "absence cannot settle unknown unlink (probe TestLayoutDeleteIntentAbsentHEAD and TestRunDeleteSnapshotWithIntent_InterruptAtEveryStep)", + "core/frontend/chunkstore/layout/delete_intent.go RunConsumeSnapshotDeleteIntent -> ReadHead": "absence never confirms a cursor update (probe TestLayoutDeleteIntentAbsentHEAD and TestRunConsumeSnapshotDeleteIntent_InterruptAtEveryStep)", + "core/frontend/chunkstore/layout/list_chain.go StageListPage -> ReadHead": "refuses ErrHeadAbsent before any object write (probe TestLayoutListAbsentHEAD)", "core/frontend/chunkstore/layout/list_chain.go RunPublishList -> ReadHead": "settlement absence preserves original error, never abandons pages (probe TestLayoutListAbsentHEAD and TestRunPublishList_InterruptAtEveryStep)", "core/frontend/chunkstore/layout/list_chain.go RunAdvanceList -> ReadHead": "settlement absence never confirms progress (probe TestLayoutListAbsentHEAD and TestRunAdvanceList_InterruptAtEveryStep)", diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete_intent.go b/seaweed-block/core/frontend/chunkstore/layout/delete_intent.go new file mode 100644 index 0000000000..71240bfbb4 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/delete_intent.go @@ -0,0 +1,209 @@ +package layout + +import ( + "context" + "fmt" + "path" + "strings" +) + +// deleteIntentWindow is a metadata operation, including on a detached volume. +// No new holder is claimed. An idle/snap -> clean transition changes HEAD's +// generation, fencing every outstanding publication at the original base. +func deleteIntentWindow(h Head, base uint64) error { + if h.State != StateLive && h.State != StateDetached { + return ErrVolumeDeleting + } + if h.Activity.Kind == ActClean { + return ErrBusy + } + if h.Gen != base || base == ^uint64(0) { + return ErrPrecondition + } + return nil +} + +// StageSnapshotDeletePage stages immutable intent metadata without a holder +// lease or a receipt dependency. A cleaner cannot act in this same HEAD +// generation: starting one fences the publishing CAS. A write that finishes +// after that fence is merely an orphan; it cannot later authorize an unlink. +// The page generation identifies the stable attempt, independently of base; +// retries after unrelated metadata CASes reuse these same durable bytes. +func StageSnapshotDeletePage(ctx context.Context, st ListChainStore, base uint64, p ListPage) (ListRef, error) { + if p.Kind != ListSnapshotDeleteIntent { + return ListRef{}, ErrIdentity + } + raw, err := p.Encode() + if err != nil { + return ListRef{}, err + } + h, found, err := st.ReadHead(ctx) + if err != nil { + return ListRef{}, err + } + if !found { + return ListRef{}, ErrHeadAbsent + } + if err := deleteIntentWindow(h, base); err != nil { + return ListRef{}, err + } + if p.VolumeID != h.VolumeID { + return ListRef{}, ErrIdentity + } + ref, _ := p.Ref() + rel, _ := ref.Path() + if err := EnsureObject(ctx, st, rel, raw, p.Producer); err != nil { + return ListRef{}, err + } + return ref, nil +} + +// RunDeleteSnapshotWithIntent removes a retained incarnation and publishes +// its independently resumable reclamation intent in ONE HEAD CAS. Receipt +// retirement is not an input to this transition or to the intent consumer. +// Initial-absence admission remains the catalog's responsibility; this API +// receives the already captured (name, gen), never re-resolves a replacement. +func RunDeleteSnapshotWithIntent(ctx context.Context, st ListChainStore, base uint64, c ListCursor) (Head, error) { + if c.Kind != ListSnapshotDeleteIntent { + return Head{}, ErrIdentity + } + if err := c.check(); err != nil { + return Head{}, err + } + c = *c.clone() + h, err := runTransition(ctx, st, CauseSnapshotDeleteIntent, func(h Head) (Head, bool, error) { + next, changed, err := h.DeleteSnapshotAt(c.Target.Name, c.Target.Gen) + if err != nil || !changed { + return next, changed, err + } + if err := deleteIntentWindow(h, base); err != nil { + return Head{}, false, err + } + if h.List != nil { + return Head{}, false, ErrBusy + } + // The intent must retain the removed root, not just an operation id. + // Its complete candidate plan is authenticated before publication. + root := h.Snapshots[c.Target.Name].Root.Path() + hasRoot := false + if err := ReadListChain(ctx, st, h.VolumeID, c, func(_ ListRef, p ListPage) error { + for _, rel := range p.Entries { + hasRoot = hasRoot || rel == root + } + return nil + }); err != nil { + return Head{}, false, err + } + if !hasRoot { + return Head{}, false, fmt.Errorf("%w: delete intent omits its snapshot root", ErrMalformed) + } + next, _, err = next.StampSnapshotGenerations() + if err != nil { + return Head{}, false, err + } + next.List = c.clone() + return next, true, nil + }) + if err == nil { + return h, nil + } + // A lost reply can be settled even after the intent finished: the retained + // incarnation is gone/replaced. Never resolve that name to a new target. + observed, found, readErr := st.ReadHead(ctx) + if readErr == nil && found { + if _, changed, checkErr := observed.DeleteSnapshotAt(c.Target.Name, c.Target.Gen); checkErr == nil && !changed { + return observed, nil + } + } + return Head{}, err +} + +// pendingDeleteIntent grants continuation from the CURRENT persisted intent, +// independent of receipt lifetime, process/host and holder epoch. It never +// authorizes a namespace delete, a second snapshot unlink, or deleting live +// data. Open activity excludes intent effects; late writes retain the existing +// tag -> HEAD -> conditional mark/delete protection against a subsequent cut. +func pendingDeleteIntent(h Head, expected *ListCursor) error { + if h.State != StateLive && h.State != StateDetached { + return ErrVolumeDeleting + } + if h.Activity.Kind != ActIdle { + return ErrBusy + } + if expected == nil || expected.Kind != ListSnapshotDeleteIntent || !sameList(h.List, expected) { + return ErrPrecondition + } + return expected.check() +} + +// RunConsumeSnapshotDeleteIntent resumes one physical reclamation page solely +// from HEAD + immutable pages. The old receipt need not exist. Like other +// metadata operations it works offline; it does not claim a volume or take +// over guest writes. Every object still passes the normal live-root and +// conditional removal checks in Cleaner.removePlanned. +func RunConsumeSnapshotDeleteIntent(ctx context.Context, st ListChainStore, r *Reader) (Head, error) { + var after *ListCursor + attempted := false + h, err := runTransition(ctx, st, CauseListAdvance, func(h Head) (Head, bool, error) { + if h.List == nil { + return h, false, nil + } + before := h.List.clone() + if err := pendingDeleteIntent(h, before); err != nil { + return Head{}, false, err + } + if h.Gen == ^uint64(0) { + return Head{}, false, ErrPrecondition + } + p, err := readListPage(ctx, st, h.VolumeID, *before) + if err != nil { + return Head{}, false, err + } + if p.Next != nil { + after = before.clone() + after.Ref = *p.Next + } + cleaner := &Cleaner{st: st, os: st, r: r, session: "intent-" + before.Ref.Hash, tagParallel: 32, intent: before} + if err := cleaner.applyIntentPage(ctx, p); err != nil { + return Head{}, false, err + } + next := h.clone() + next.List = after + attempted = true + return next, true, nil + }) + if err == nil { + return h, nil + } + if attempted { + observed, found, readErr := st.ReadHead(ctx) + if readErr == nil && found && sameList(observed.List, after) && (observed.State == StateLive || observed.State == StateDetached) { + return observed, nil + } + } + return Head{}, err +} + +func (c *Cleaner) applyIntentPage(ctx context.Context, p ListPage) error { + // One bounded page, metadata first. Candidate membership is not liveness. + for _, kind := range []string{RootDir, SegDir, PoolDir} { + for _, rel := range p.Entries { + if !strings.HasPrefix(rel, kind+"/") { + continue + } + name := path.Base(rel) + var shard uint64 + if kind == PoolDir { + n, err := ParseChunkName(name) + if err != nil { + return err + } + shard = Shard(n.Index) + } + if _, err := c.Page(ctx, kind, shard, []string{name}); err != nil { + return err + } + } + } + return nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go b/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go new file mode 100644 index 0000000000..69bcda6b4e --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go @@ -0,0 +1,371 @@ +package layout + +import ( + "context" + "errors" + "sort" + "testing" +) + +func deleteIntentFixture(t *testing.T) (*chainStore, ListCursor, ListPage) { + t.Helper() + s, _, _ := chainFixture(t) + s.h.Activity = Activity{Kind: ActIdle} + s.h.Current = nil + raw := []byte("old payload") + n := NameChunk(1, raw) + root, segs, err := Build(map[uint64]Ref{1: {Owner: "v1", OwnerID: s.volume, Chunk: n}}) + if err != nil { + t.Fatal(err) + } + rn, rb, err := NameRoot(root) + if err != nil { + t.Fatal(err) + } + s.put(n.Path(), raw, "old") + entries := []string{n.Path(), rn.Path()} + for sn, data := range segs { + s.put(sn.Path(), data, "old") + entries = append(entries, sn.Path()) + } + s.put(rn.Path(), rb, "old") + s.h.Snapshots = map[string]Snapshot{"daily": {Root: rn, Gen: 4}} + sort.Strings(entries) + p := ListPage{VolumeID: s.volume, Kind: ListSnapshotDeleteIntent, Producer: "delete-1", Generation: s.h.Gen + 1, Pages: 1, Target: &SnapshotTarget{Name: "daily", Gen: 4}, Entries: entries} + ref, err := p.Ref() + if err != nil { + t.Fatal(err) + } + c := ListCursor{Ref: ref, Kind: p.Kind, Producer: p.Producer, Generation: p.Generation, Target: p.Target} + return s, c, p +} + +func TestDeleteSnapshotWithIntent_Closure(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + base := s.h.Gen + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); !errors.Is(err, ErrListPageMissing) || s.updates != 0 { + t.Fatalf("unname without durable intent: %v", err) + } + if _, err := StageSnapshotDeletePage(ctx, s, base, p); err != nil { + t.Fatal(err) + } + h, err := RunDeleteSnapshotWithIntent(ctx, s, base, c) + if err != nil || h.Snapshots["daily"].Gen != 0 || !sameList(h.List, &c) || s.updates != 1 { + t.Fatalf("not one unlink+intent CAS: %+v writes%d %v", h, s.updates, err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); err != nil || s.updates != 1 { + t.Fatalf("replay: %v", err) + } +} + +func deleteIntentReader(t *testing.T, s *chainStore) *Reader { + t.Helper() + v := Volume{ID: s.volume, Name: "v1", Geometry: tableGeometry, Format: VolumeFormat} + raw, err := v.Encode() + if err != nil { + t.Fatal(err) + } + s.put(VolumeName, raw, "volume") + r, err := NewReader("/swblock/chunks", "v1", s.fetch) + if err != nil { + t.Fatal(err) + } + return r +} + +func TestConsumeSnapshotDeleteIntent_Closure(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + r := deleteIntentReader(t, s) + base := s.h.Gen + if _, err := StageSnapshotDeletePage(ctx, s, base, p); err != nil { + t.Fatal(err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); err != nil { + t.Fatal(err) + } + // Only durable HEAD/pages and the store remain. No receipt, owner token, + // holder identity, original CLI or process memory is supplied to resume. + h, err := RunConsumeSnapshotDeleteIntent(ctx, s, r) + if err != nil || h.List != nil { + t.Fatalf("resume: %+v %v", h.List, err) + } + for _, rel := range p.Entries { + if _, found, _ := s.Stat(ctx, rel); found { + t.Fatalf("unfinished physical work %s", rel) + } + } + if _, found, _ := s.ReadListPage(ctx, c.Ref); !found { + t.Fatal("consumer retired its own page before cursor settlement") + } +} + +func TestRunDeleteSnapshotWithIntent_InterruptAtEveryStep(t *testing.T) { + for _, after := range []bool{false, true} { + t.Run(map[bool]string{false: "before", true: "lost-reply"}[after], func(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + base := s.h.Gen + if _, err := StageSnapshotDeletePage(ctx, s, base, p); err != nil { + t.Fatal(err) + } + s.memHead.killAt, s.memHead.after = 1, after + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); !errors.Is(err, errKilled) { + t.Fatal(err) + } + _, row := s.h.Snapshots["daily"] + if row == after || (s.h.List != nil) != after { + t.Fatalf("torn row/intent: row%v intent%v", row, s.h.List != nil) + } + s.memHead.dead, s.memHead.killAt = false, 0 + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); err != nil { + t.Fatal(err) + } + }) + } +} + +func TestRunConsumeSnapshotDeleteIntent_InterruptAtEveryStep(t *testing.T) { + for _, after := range []bool{false, true} { + t.Run(map[bool]string{false: "before", true: "lost-reply"}[after], func(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + r := deleteIntentReader(t, s) + base := s.h.Gen + if _, err := StageSnapshotDeletePage(ctx, s, base, p); err != nil { + t.Fatal(err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); err != nil { + t.Fatal(err) + } + s.memHead.killAt, s.memHead.after = s.updates+1, after + if _, err := RunConsumeSnapshotDeleteIntent(ctx, s, r); !errors.Is(err, errKilled) { + t.Fatal(err) + } + if _, found, _ := s.ReadListPage(ctx, c.Ref); !found { + t.Fatal("intent page retired on unknown cursor") + } + s.memHead.dead, s.memHead.killAt = false, 0 + if h, err := RunConsumeSnapshotDeleteIntent(ctx, s, r); err != nil || h.List != nil { + t.Fatalf("resume: %+v %v", h.List, err) + } + }) + } +} + +func TestDeleteIntentOfflineAndReplacementPreserved(t *testing.T) { + for _, detached := range []bool{false, true} { + t.Run(map[bool]string{false: "same-name-replacement", true: "detached-no-holder-claim"}[detached], func(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + r := deleteIntentReader(t, s) + oldRoot := s.h.Snapshots["daily"].Root + if detached { + empty, _, _ := Build(nil) + rn, raw, _ := NameRoot(empty) + s.put(rn.Path(), raw, "current") + s.h.Current, s.h.State = &rn, StateDetached + } + base := s.h.Gen + if _, err := StageSnapshotDeletePage(ctx, s, base, p); err != nil { + t.Fatal(err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); err != nil { + t.Fatal(err) + } + if !detached { + next := s.h.clone() + next.Snapshots["daily"] = Snapshot{Root: oldRoot, Gen: next.Gen + 1} + if err := s.UpdateHead(ctx, s.h.Gen, next, CauseSnapshotUnchanged); err != nil { + t.Fatal(err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); err != nil { + t.Fatal(err) + } + } + h, err := RunConsumeSnapshotDeleteIntent(ctx, s, r) + if err != nil || h.List != nil { + t.Fatalf("consume: %v", err) + } + if detached { + if h.State != StateDetached || h.Epoch != me.Epoch || h.Holder != me.Holder { + t.Fatal("intent claimed ownership") + } + } else { + if h.Snapshots["daily"].Gen != base+2 { + t.Fatal("replacement incarnation changed") + } + for _, rel := range p.Entries { + if _, found, _ := s.Stat(ctx, rel); !found { + t.Fatalf("replacement lost %s", rel) + } + } + } + }) + } +} + +type intentMarkConflict struct { + *chainStore + conflicted bool +} + +func (s *intentMarkConflict) Mark(ctx context.Context, rel string, expect ObjectMeta, mark string) error { + if !s.conflicted { + s.conflicted = true + if err := s.chainStore.Mark(ctx, rel, expect, "other-executor"); err != nil { + return err + } + return ErrPrecondition + } + return s.chainStore.Mark(ctx, rel, expect, mark) +} + +func TestDeleteIntentMarkConflictKeepsUnfinishedPage(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + r := deleteIntentReader(t, s) + base := s.h.Gen + if _, err := StageSnapshotDeletePage(ctx, s, base, p); err != nil { + t.Fatal(err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); err != nil { + t.Fatal(err) + } + contended := &intentMarkConflict{chainStore: s} + if _, err := RunConsumeSnapshotDeleteIntent(ctx, contended, r); !errors.Is(err, ErrPrecondition) || !sameList(s.h.List, &c) { + t.Fatalf("unfinished mark advanced: %v", err) + } + if h, err := RunConsumeSnapshotDeleteIntent(ctx, contended, r); err != nil || h.List != nil { + t.Fatalf("retry: %v", err) + } +} + +func TestDeleteIntentMissingPageAndRootRefuseBeforeUnlinkOrEffects(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + r := deleteIntentReader(t, s) + base := s.h.Gen + p.Entries = p.Entries[:1] // a chunk, deliberately omit the captured root + ref, err := StageSnapshotDeletePage(ctx, s, base, p) + if err != nil { + t.Fatal(err) + } + bad := *c.clone() + bad.Ref = ref + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, bad); !errors.Is(err, ErrMalformed) || s.updates != 0 { + t.Fatalf("incomplete identity unlinked: %v", err) + } + _, c, p = deleteIntentFixture(t) // same fixed target/context; restore complete plan + if _, err := StageSnapshotDeletePage(ctx, s, base, p); err != nil { + t.Fatal(err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); err != nil { + t.Fatal(err) + } + rel, _ := c.Ref.Path() + delete(s.objs, s.full(rel)) + writes := len(s.writes) + updates := s.updates + if _, err := RunConsumeSnapshotDeleteIntent(ctx, s, r); !errors.Is(err, ErrListPageMissing) || len(s.writes) != writes || s.updates != updates { + t.Fatalf("missing page executed: %v", err) + } +} + +func TestDeleteIntentRetryKeepsDurablePagesAcrossMetadataCAS(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + base := s.h.Gen + if _, err := StageSnapshotDeletePage(ctx, s, base, p); err != nil { + t.Fatal(err) + } + writes := len(s.writes) + // An unrelated metadata write changes the CAS base, not this captured + // operation/target or its durable page bytes. + next := s.h.clone() + if err := s.UpdateHead(ctx, base, next, CauseDependentRelease); err != nil { + t.Fatal(err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); !errors.Is(err, ErrPrecondition) { + t.Fatalf("old base: %v", err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, s.h.Gen, c); err != nil { + t.Fatalf("retry reminted/rejected durable intent: %v", err) + } + if len(s.writes) != writes || !sameList(s.h.List, &c) { + t.Fatal("retry rewrote durable pages") + } +} + +func TestDeleteIntentCannotUseGenericListTransitions(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + base := s.h.Gen + if _, err := StageSnapshotDeletePage(ctx, s, base, p); err != nil { + t.Fatal(err) + } + if _, err := RunPublishList(ctx, s, me, c.Producer, base, c); !errors.Is(err, ErrIdentity) || s.updates != 0 { + t.Fatalf("generic publication admitted delete intent: %v", err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); err != nil { + t.Fatal(err) + } + if _, err := RunBeginClean(ctx, s, me, "generic"); err != nil { + t.Fatal(err) + } + called := false + if _, err := RunAdvanceList(ctx, s, me, "generic", func(context.Context, ListPage) error { called = true; return nil }); !errors.Is(err, ErrIdentity) || called || !sameList(s.h.List, &c) { + t.Fatalf("generic executor consumed delete intent: %v", err) + } +} + +func TestDeleteIntentOpenActivityRefusesEffects(t *testing.T) { + for _, activity := range []Activity{{Kind: ActSnap, Session: "cut"}, {Kind: ActClean, Session: "clean"}} { + t.Run(string(activity.Kind), func(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + r := deleteIntentReader(t, s) + base := s.h.Gen + if _, err := StageSnapshotDeletePage(ctx, s, base, p); err != nil { + t.Fatal(err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); err != nil { + t.Fatal(err) + } + s.h.Activity = activity + writes, updates := len(s.writes), s.updates + if _, err := RunConsumeSnapshotDeleteIntent(ctx, s, r); !errors.Is(err, ErrBusy) || len(s.writes) != writes || s.updates != updates || !sameList(s.h.List, &c) { + t.Fatalf("active work allowed reclamation: %v", err) + } + }) + } +} + +func TestDeleteIntentPublicationIsFencedBeforeAnOrdinarySweep(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + base := s.h.Gen + if _, err := StageSnapshotDeletePage(ctx, s, base, p); err != nil { + t.Fatal(err) + } + // Publication has read durable pages, then stalls before its CAS. A + // cleaning can remove them only after its Begin changed the generation. + s.memHead.hook = func() { + if _, err := RunBeginClean(ctx, s, me, "ordinary"); err != nil { + t.Fatal(err) + } + if out, err := NewCleaner(s, nil, s, me, "ordinary").Page(ctx, ListDir, 0, []string{c.Ref.Hash}); err != nil || len(out.Names) != 1 { + t.Fatalf("sweep: %+v %v", out, err) + } + if _, err := RunEndClean(ctx, s, me, "ordinary", CauseCleanEnd); err != nil { + t.Fatal(err) + } + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); !errors.Is(err, ErrPrecondition) { + t.Fatalf("fenced publish landed: %v", err) + } + if s.h.Snapshots["daily"].Gen != 4 || s.h.List != nil { + t.Fatal("row removed after page sweep") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json b/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json index 993351ae78..790905b08f 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json +++ b/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json @@ -210,6 +210,15 @@ "may_change": [ "list" ] + }, + { + "cause": "snapshot-delete-intent", + "kind": "update", + "may_change": [ + "version", + "snapshots", + "list" + ] } ] } diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_cause.go b/seaweed-block/core/frontend/chunkstore/layout/head_cause.go index a698f1146e..446ccde311 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_cause.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_cause.go @@ -9,8 +9,9 @@ type HeadWriteCause string // The census rows. A new HEAD writer needs a new row here, in the census // test and in the design's table. const ( - CauseListPublish HeadWriteCause = "list-publish" - CauseListAdvance HeadWriteCause = "list-advance" + CauseListPublish HeadWriteCause = "list-publish" + CauseListAdvance HeadWriteCause = "list-advance" + CauseSnapshotDeleteIntent HeadWriteCause = "snapshot-delete-intent" // CauseCreate: a new volume's or restore target's first HEAD. CauseCreate HeadWriteCause = "create" // CauseClaim: a holder's claim at attach (layout.Start). @@ -55,6 +56,7 @@ const ( // HeadWriteCauses is the census: every cause, in table order. var HeadWriteCauses = []HeadWriteCause{ CauseListPublish, CauseListAdvance, + CauseSnapshotDeleteIntent, CauseCreate, CauseClaim, CauseStartRollbackSnap, CauseStartRollbackClean, CauseSessionBegin, CauseSessionRollback, CauseCommit, CauseSnapshotUnchanged, CauseStopAbort, CauseCleanBegin, CauseCleanEnd, CauseSnapshotRetire, diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_cause_census_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_cause_census_test.go index 8ff51ecce3..c5e34fa17d 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_cause_census_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_cause_census_test.go @@ -193,7 +193,8 @@ func causeRebound(body *ast.BlockStmt) string { // causeByName maps each census constant's name to its value. var causeByName = map[string]HeadWriteCause{ - "CauseListPublish": CauseListPublish, "CauseListAdvance": CauseListAdvance, + "CauseSnapshotDeleteIntent": CauseSnapshotDeleteIntent, + "CauseListPublish": CauseListPublish, "CauseListAdvance": CauseListAdvance, "CauseCreate": CauseCreate, "CauseClaim": CauseClaim, "CauseStartRollbackSnap": CauseStartRollbackSnap, "CauseStartRollbackClean": CauseStartRollbackClean, "CauseSessionBegin": CauseSessionBegin, "CauseSessionRollback": CauseSessionRollback, "CauseCommit": CauseCommit, diff --git a/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go b/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go index bb309b246d..65876b0c37 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go @@ -27,6 +27,7 @@ var kernelStates = []string{"absent", "unclaimed", "idle", "snap", "clean", "det // kernelEntries are the kernel's entry points (DeleteVolume is their // composition: Reserve, MarkDeleting, release, objects, MarkDeleted). var kernelEntries = []string{ + "DeleteSnapshotWithIntent", "ConsumeSnapshotDeleteIntent", "PublishList", "AdvanceList", "CreateVolume", "CreateTarget", "StartHigher", "StartHigherCannotStart", "StartOwn", "StartOwnOtherFresh", "StartOwnOtherFreshCannotStart", "StartOwnOtherOld", "Claim", "Begin", "Commit", "CommitNew", "CommitLower", "Abort", "BeginClean", "EndClean", @@ -132,6 +133,31 @@ func kernelCell(t *testing.T, state, entry string) string { src.memHead.h, src.vol = sh, &vol switch entry { + case "DeleteSnapshotWithIntent", "ConsumeSnapshotDeleteIntent": + cs := &chainStore{memHead: nv.memHead, memObjects: o} + p := ListPage{VolumeID: h.VolumeID, Kind: ListSnapshotDeleteIntent, Producer: "delete-1", Generation: h.Gen + 1, Pages: 1, Target: &SnapshotTarget{Name: "daily", Gen: 4}, Entries: []string{h.Snapshots["daily"].Root.Path()}} + ref, _ := p.Ref() + raw, _ := p.Encode() + rel, _ := ref.Path() + o.put(rel, raw, "delete-1") + cursor := ListCursor{Ref: ref, Kind: p.Kind, Producer: p.Producer, Generation: p.Generation, Target: p.Target} + if nv.memHead.h != nil { + nv.memHead.h.Version = HeadVersion1 + if sn, found := nv.memHead.h.Snapshots["daily"]; found { + sn.Gen = 4 + sn.Dependents = nil + nv.memHead.h.Snapshots["daily"] = sn + } + } + if entry == "DeleteSnapshotWithIntent" { + _, err = RunDeleteSnapshotWithIntent(ctx, cs, h.Gen, cursor) + } else { + if nv.memHead.h != nil { + nv.memHead.h.List = cursor.clone() + delete(nv.memHead.h.Snapshots, "daily") + } + _, err = RunConsumeSnapshotDeleteIntent(ctx, cs, r) + } case "PublishList", "AdvanceList": cs := &chainStore{memHead: nv.memHead, memObjects: o} p := ListPage{VolumeID: h.VolumeID, Kind: ListDrop, Producer: "s1", Generation: h.Gen + 1, Pages: 1, Entries: []string{RootName{Hash: Sum([]byte("page item"))}.Path()}} @@ -274,6 +300,9 @@ func kernelCell(t *testing.T, state, entry string) string { // source) and a claim; an unclaimed HEAD takes only the first claim and // the creates' replays. var kernelExpected = map[string]map[string]string{ + "DeleteSnapshotWithIntent": {"absent": "HeadAbsent", "unclaimed": "noop", "idle": "write", "snap": "write", "clean": "Busy", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "ConsumeSnapshotDeleteIntent": {"absent": "HeadAbsent", "unclaimed": "write", "idle": "write", "snap": "Busy", "clean": "Busy", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "PublishList": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "NoSession", "snap": "write", "clean": "NoSession", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, "AdvanceList": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "NoSession", "snap": "NoSession", "clean": "write", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, "CreateVolume": {"absent": "write", "unclaimed": "noop", "idle": "noop", "snap": "noop", "clean": "noop", "detached": "noop", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, @@ -331,6 +360,7 @@ func TestKernelTable(t *testing.T) { // kernelEntryFuncs maps each table row to the exported function it calls; // kernelComposed are exported entry points that only compose the rows. var kernelEntryFuncs = map[string]string{ + "DeleteSnapshotWithIntent": "RunDeleteSnapshotWithIntent", "ConsumeSnapshotDeleteIntent": "RunConsumeSnapshotDeleteIntent", "PublishList": "RunPublishList", "AdvanceList": "RunAdvanceList", "CreateVolume": "CreateVolume", "CreateTarget": "CreateTarget", "StartHigher": "Start", "StartOwn": "Start", "StartOwnOtherFresh": "Start", "StartOwnOtherOld": "Start", "StartHigherCannotStart": "Start", "StartOwnOtherFreshCannotStart": "Start", "Claim": "RunClaim", diff --git a/seaweed-block/core/frontend/chunkstore/layout/list_chain.go b/seaweed-block/core/frontend/chunkstore/layout/list_chain.go index 7cb258682b..74ef01a072 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/list_chain.go +++ b/seaweed-block/core/frontend/chunkstore/layout/list_chain.go @@ -38,8 +38,10 @@ func sameList(a, b *ListCursor) bool { a.Kind == b.Kind && a.Producer == b.Producer && a.Generation == b.Generation && sameTarget(a.Target, b.Target) } -// ListPageReader must bound allocation to MaxListPageBytes before returning. -// Missing is distinct from an empty, successfully completed chain. +// ListPageReader preflights declared size and rejects returned bytes above +// MaxListPageBytes. The blob adapter trusts its backend for allocation during +// GET; this interface does not promise a capped streaming read. Missing is +// distinct from an empty, successfully completed chain. type ListPageReader interface { ReadListPage(context.Context, ListRef) ([]byte, bool, error) } @@ -142,6 +144,9 @@ func StageListPage(ctx context.Context, st ListChainStore, me HolderID, session // function never abandons a session, removes pages, or turns absence at the // original generation into proof that an outstanding CAS cannot land. func RunPublishList(ctx context.Context, st ListChainStore, me HolderID, session string, base uint64, c ListCursor) (Head, error) { + if c.Kind == ListSnapshotDeleteIntent { + return Head{}, fmt.Errorf("%w: snapshot deletion requires the atomic intent transition", ErrIdentity) + } h, err := runTransition(ctx, st, CauseListPublish, func(h Head) (Head, bool, error) { if err := listSession(h, me, session, ActSnap); err != nil { return Head{}, false, err @@ -203,6 +208,9 @@ func RunAdvanceList(ctx context.Context, st ListChainStore, me HolderID, session if h.Gen == ^uint64(0) { return Head{}, false, ErrPrecondition } + if h.List.Kind == ListSnapshotDeleteIntent { + return Head{}, false, fmt.Errorf("%w: use the persisted delete-intent consumer", ErrIdentity) + } if apply == nil { return Head{}, false, fmt.Errorf("%w: list consumer needs an executor", ErrMalformed) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go b/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go index b3c84f8554..12823bcfa8 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go @@ -462,4 +462,21 @@ func TestListWritesMatchExportedCensus(t *testing.T) { t.Fatal(err) } check(CauseListAdvance, before, after) + s, c, p = deleteIntentFixture(t) + r := deleteIntentReader(t, s) + before = s.h.clone() + if _, err := StageSnapshotDeletePage(ctx, s, before.Gen, p); err != nil { + t.Fatal(err) + } + after, err = RunDeleteSnapshotWithIntent(ctx, s, before.Gen, c) + if err != nil { + t.Fatal(err) + } + check(CauseSnapshotDeleteIntent, before, after) + before = s.h.clone() + after, err = RunConsumeSnapshotDeleteIntent(ctx, s, r) + if err != nil { + t.Fatal(err) + } + check(CauseListAdvance, before, after) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove.go b/seaweed-block/core/frontend/chunkstore/layout/remove.go index a8332e0840..6814dfeb6d 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove.go @@ -12,6 +12,9 @@ import ( // authoritative HEAD view; only immutable reachability is cached between pages. // It is used serially, and never survives a cleaning session or process restart. type Cleaner struct { + // intent is set only by the persisted delete-intent consumer. Ordinary + // full-sweep cleaners retain their holder + clean-session authority. + intent *ListCursor tagParallel int st HeadStore r *Reader @@ -123,11 +126,17 @@ func (c *Cleaner) removePlanned(ctx context.Context, rels []string, kind string, if !found { return out, ErrHeadAbsent } - if err := h.holderErr(c.me); err != nil { - return out, err - } - if h.Activity != (Activity{Kind: ActClean, Session: c.session}) { - return out, fmt.Errorf("%w: HEAD has %s(%s), not clean(%s)", ErrNoSession, h.Activity.Kind, h.Activity.Session, c.session) + if c.intent != nil { + if err := pendingDeleteIntent(h, c.intent); err != nil { + return out, err + } + } else { + if err := h.holderErr(c.me); err != nil { + return out, err + } + if h.Activity != (Activity{Kind: ActClean, Session: c.session}) { + return out, fmt.Errorf("%w: HEAD has %s(%s), not clean(%s)", ErrNoSession, h.Activity.Kind, h.Activity.Session, c.session) + } } roots := HeadRoots(h) if !c.rootsRead { @@ -204,6 +213,9 @@ func (c *Cleaner) removePlanned(ctx context.Context, rels []string, kind string, } if err := c.os.Mark(ctx, rel, tag.meta, c.session); err != nil { if errors.Is(err, ErrPrecondition) { + if c.intent != nil { + return out, err + } out.After = rel continue } @@ -211,6 +223,9 @@ func (c *Cleaner) removePlanned(ctx context.Context, rels []string, kind string, } if err := c.os.DeleteMarked(ctx, rel, c.session); err != nil { if errors.Is(err, ErrPrecondition) { + if c.intent != nil { + return out, err + } out.After = rel continue } diff --git a/seaweed-block/core/frontend/chunkstore/layout_list_test.go b/seaweed-block/core/frontend/chunkstore/layout_list_test.go index d52f9897a7..fb1e738682 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_list_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_list_test.go @@ -5,6 +5,7 @@ import ( "context" "errors" "path" + "sort" "testing" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" @@ -29,6 +30,97 @@ func TestLayoutListAbsentHEAD(t *testing.T) { } } +func TestLayoutDeleteIntentAbsentHEAD(t *testing.T) { + s, f, b := layoutStoreFixture(t) + ctx := context.Background() + p := layout.ListPage{VolumeID: s.id, Kind: layout.ListSnapshotDeleteIntent, Producer: "delete-1", Generation: 1, Pages: 1, Target: &layout.SnapshotTarget{Name: "daily", Gen: 1}, Entries: []string{(layout.RootName{Hash: layout.Sum([]byte("root"))}).Path()}} + ref, _ := p.Ref() + c := layout.ListCursor{Ref: ref, Kind: p.Kind, Producer: p.Producer, Generation: p.Generation, Target: p.Target} + if _, err := layout.StageSnapshotDeletePage(ctx, s, 0, p); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatal(err) + } + if _, err := layout.RunDeleteSnapshotWithIntent(ctx, s, 0, c); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatal(err) + } + if _, err := layout.RunConsumeSnapshotDeleteIntent(ctx, s, nil); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatal(err) + } + puts, _, _ := b.counts() + if len(f.written) != 0 || puts != 0 { + t.Fatal("absent HEAD created metadata") + } +} + +func TestLayoutSnapshotDeleteIntentResumesWithoutReceipt(t *testing.T) { + s, f, _ := layoutStoreFixture(t) + ctx := context.Background() + n := layout.NameChunk(1, []byte("old")) + root, segs, err := layout.Build(map[uint64]layout.Ref{1: {Owner: "v", OwnerID: s.id, Chunk: n}}) + if err != nil { + t.Fatal(err) + } + rn, rb, err := layout.NameRoot(root) + if err != nil { + t.Fatal(err) + } + entries := []string{n.Path(), rn.Path()} + if err := s.Create(ctx, n.Path(), []byte("old"), "seed"); err != nil { + t.Fatal(err) + } + if err := s.Create(ctx, rn.Path(), rb, "seed"); err != nil { + t.Fatal(err) + } + for sn, raw := range segs { + if err := s.Create(ctx, sn.Path(), raw, "seed"); err != nil { + t.Fatal(err) + } + entries = append(entries, sn.Path()) + } + sort.Strings(entries) + v := layout.Volume{ID: s.id, Name: "v", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: layout.VolumeFormat} + vr, err := v.Encode() + if err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, s.root, layoutEntry(layout.VolumeName, vr), true); err != nil { + t.Fatal(err) + } + h := layout.Unclaimed(s.id, nil) + h.Version = layout.HeadVersion1 + h.Snapshots = map[string]layout.Snapshot{"daily": {Root: rn, Gen: 1}} + if err := s.UpdateHead(ctx, 0, h, layout.CauseCreate); err != nil { + t.Fatal(err) + } + p := layout.ListPage{VolumeID: s.id, Kind: layout.ListSnapshotDeleteIntent, Producer: "delete-1", Generation: 2, Pages: 1, Target: &layout.SnapshotTarget{Name: "daily", Gen: 1}, Entries: entries} + ref, err := layout.StageSnapshotDeletePage(ctx, s, 1, p) + if err != nil { + t.Fatal(err) + } + c := layout.ListCursor{Ref: ref, Kind: p.Kind, Producer: p.Producer, Generation: p.Generation, Target: p.Target} + h, err = layout.RunDeleteSnapshotWithIntent(ctx, s, 1, c) + if err != nil || h.List == nil || len(h.Snapshots) != 0 { + t.Fatalf("unlink/intent: %+v %v", h, err) + } + // A fresh adapter/reader has no receipt store or original executor state. + reopened, err := NewLayoutStore(s.f, s.b, s.root, s.id) + if err != nil { + t.Fatal(err) + } + r, err := layout.NewReader("/blocks", "v", reopened.Fetch) + if err != nil { + t.Fatal(err) + } + h, err = layout.RunConsumeSnapshotDeleteIntent(ctx, reopened, r) + if err != nil || h.List != nil || h.Holder != "" || h.Epoch != 0 { + t.Fatalf("resume claimed or incomplete: %+v %v", h, err) + } + for _, rel := range entries { + if _, found, err := reopened.Stat(ctx, rel); err != nil || found { + t.Fatalf("not reclaimed %s: %v %v", rel, found, err) + } + } +} + func TestLayoutStoreListPageDataBeforeEntryAndBoundedRead(t *testing.T) { s, f, b := layoutStoreFixture(t) ctx := context.Background() diff --git a/seaweed-block/docs/design/immutable-list-pages.md b/seaweed-block/docs/design/immutable-list-pages.md index 97ecb83b6f..e015c6c00f 100644 --- a/seaweed-block/docs/design/immutable-list-pages.md +++ b/seaweed-block/docs/design/immutable-list-pages.md @@ -108,3 +108,53 @@ shared helper; already stamped entries keep their generation. General snapshot producer/binding integration, complete restore ancestry, volume-delete cursor, final queue layout, driver activation and release qualification remain separate required work before the v1.1 declaration. + +## Snapshot deletion owns an intent before removing its row + +The dormant delete seam is separate from the generic session API: + +```mermaid +sequenceDiagram + participant Catalog + participant Store + participant HEAD + participant LaterExecutor + Catalog->>Store: StageSnapshotDeletePage (captured name/gen, durable pages) + Catalog->>HEAD: RunDeleteSnapshotWithIntent (one CAS: remove exact row + name intent) + Note over Catalog,HEAD: receipt may retire after this step + LaterExecutor->>HEAD: read current snapshot-delete intent, require idle live/detached + LaterExecutor->>Store: authenticate page; live roots; conditional mark/delete + LaterExecutor->>HEAD: CAS continuation only after effects finish +``` + +The target is the retained `(name, publishing gen)` in this volume, never a +new lookup by name. Its root must occur in the authenticated candidate chain. +The chain's producer/generation is a stable attempt identity, independent of +the HEAD CAS base: a retry after an unrelated metadata write reuses durable +pages and the original target. Admission of a new request against an absent +name and receipt ownership remain catalog responsibilities. + +The unlink and intent publication are one HEAD write. Losing its reply cannot +leave an unlinked row without its reclamation facts. After publication, +`RunConsumeSnapshotDeleteIntent` needs only current HEAD and its immutable +pages, not the receipt, original host or holder lease. It can resume offline +on live/detached volumes and never claims a volume or changes its holder epoch. +Open snapshot or cleaning activity refuses these effects. Candidate membership +is not liveness: every removal still checks tags before current HEAD roots, +then conditionally marks and deletes. A conflicting mark or delete leaves +the intent page pending for retry; routine full-sweep skip behavior is unchanged. +This is an explicit additional authority branch inside `Cleaner.removePlanned`, +not a weakening of the holder's routine cleaning guard. + +Before publication, an ordinary cleaner must begin at a later HEAD generation; +that fences an outstanding delete CAS before it can name swept pages. An +unsettled upload finishing after the fence is merely an orphan. After +publication, page retirement uses current-chain reachability as before. Missing +pages and unfinished effects never advance the intent. A same-name replacement +is preserved both by the retained target and by current live-root checks. + +PageChain rows 246-253 cover publication and effect/cursor ordering; SnapDelete +241-245 cover incarnation identity. The offline consumer refinement and its +new authority branch require exact-head model/code review before activation. +No product delete driver calls this seam yet. The one-slot admission capacity, +remaining producer wiring and Linux/race qualification remain outstanding. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 35ad2d0499..bf00cfd1ce 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -583,6 +583,8 @@ stateDiagram-v2 | snap(s), list slot empty | snap(s), list cursor published | same full holder, open session and original base generation; every referenced page durable and authenticated; unknown reply retains session and pages | `list_chain.go` `StageListPage`, `RunPublishList` | `INV-LIST-PUBLISH-001` | | clean(c), current list page | clean(c), next continuation or none | exact observed cursor CAS only after authenticated page effects succeed; failed reads and failed effects leave cursor unchanged | `list_chain.go` `RunAdvanceList` | `INV-LIST-CURSOR-001` | | clean(c), stored list page | clean(c), unreached page removed | tags before HEAD; current clean session; spare all current-chain pages; conditional mark then delete | `remove.go` `Cleaner.Page` | `INV-LIST-RETIRE-001` | +| idle/snap, retained snapshot | same activity, row removed and intent published | one CAS removes only the captured name/gen and names its durable candidate chain; clean activity refuses | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `INV-SNAPSHOT-DELETE-INTENT-001` | +| idle live/detached, persisted delete intent | idle live/detached, next intent page or none | receipt-independent continuation from current HEAD; live-root and conditional effect guards; cursor follows completed effects | `delete_intent.go` `RunConsumeSnapshotDeleteIntent` | `INV-SNAPSHOT-DELETE-CONSUME-001` | | idle | snap(s) | caller is the holder at HEAD's epoch (epoch, server and claim id); HEAD present; snap(s) again is a replay, any other activity is refused | head.go `Head.Begin`, `runTransition` | `INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-BEGIN-001` | | snap(s) | idle | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); over idle it succeeds without a write and means only that no activity remains; before resuming a failed stop, abort its still-open session and re-read HEAD: only matching live/idle resumes, detached goes Down, absent/unknown stays stopped | head.go `Head.Abort`; durable/provider_layout.go `settleLayoutStop` | `INV-SNAPK-ABORT-001` | | snap(s) | idle, current = root | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); the previous manifest builds to HEAD's current root; the new own chunks, every segment and the root are present; a new snapshot name records bounded retention facts once, while replay preserves them | commit.go `Head.Commit`, `RunCommit` | `INV-SNAPK-COMMIT-REACH-001`, `INV-SNAPK-TXN-INTERRUPT-001`, `INV-SNAPK-SNAPSHOT-META-001` | @@ -1222,7 +1224,7 @@ Notes: | `INV-SCHEDULE-DUE-NOW-001` | The local opt-in due-now request queues only a running configured schedule, using its existing worker and admission. A cancelled or ended snapshot worker refuses even while the aggregate background group remains alive. | M9 scheduled capture (K: HEAD) | `core/frontend/durable/chunk_snapshot_schedule.go`; `core/host/volume/chunk_control.go` | `TestScheduledSnapshotDueNowUsesExistingLoop`, `TestScheduledSnapshotDueNowRefusesEndedWorkerWithBackgroundAlive` (`core/frontend/durable/snapshot_due_now_test.go`); `TestChunkScheduleNowRunsOnlyThroughEnabledLocalControl` (`core/host/volume/chunk_schedule_now_test.go`) | EngineAdapter.StartStop; CommitReach WCommit (ordinary capture) | ACTIVE | | `INV-CLEAN-METADATA-001` | Cleaning preserves Current and snapshot roots and their segments. Dependents keep their snapshot in HEAD. Unnamed roots go before segments and chunks; reuse defeats conditional removal. | M9 clean | `core/frontend/chunkstore/layout/remove.go`; `core/frontend/chunkstore/clean_b.go` | `TestCleanerMetadataRetainsCurrentSnapshotAndDependent`, `TestCleanerMetadataReuseDefeatsLateMarkAndDelete`, `TestCleanerRecreatesRemovedRootBeforeRenamingIt` (`core/frontend/chunkstore/layout/clean_metadata_test.go`); `TestCleaningInterruptsAfterMetadataBeforeChunks` (`core/frontend/chunkstore/clean_cursor_test.go`) ; `TestCleaningSegmentResumeReplansRootsBeforeRemovingSegments` (`core/frontend/chunkstore/clean_cursor_test.go`) | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | | `INV-CLEAN-CURSOR-001` | Every new session scans roots first, preserves segment/chunk progress, and wraps after the final shard. Each page validates HEAD after parallel tags; reachability caches a conservative root set only within that session. | M9 clean (liveness) | `core/frontend/chunkstore/clean_b.go`; `core/frontend/chunkstore/layout/remove.go` | `TestCleaningCursorResumesAfterTimeoutAndWraps` (`core/frontend/chunkstore/clean_cursor_test.go`); `TestCleanerReachableOncePerShardAndRechecksHead`, `TestCleanerPlansTagsInBoundedParallelBeforeHead` (`core/frontend/chunkstore/layout/clean_scale_test.go`) | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | -| `INV-SNAPK-REMOVE-MARK-001` | A content-named object is removed only inside the holder's own cleaning, when no root in HEAD names it: tags read first, HEAD read and validated after, then a mark conditional on the tag and a delete conditional on the mark. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | +| `INV-SNAPK-REMOVE-MARK-001` | Routine full-sweep removal requires the holder's own cleaning and no live HEAD root: tags precede HEAD validation, then mark conditional on the tag and delete conditional on the mark. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | | `INV-SNAPK-REMOVE-STOP-001` | A reuse of an object after the plan, or after the mark, makes the remover's mark or delete fail its condition, however late it lands; an unreadable root stops the pass before any write; an open snapshot refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ASuccessorAfterTheHeadViewDefeatsTheMark`, `TestRemoveUnreachable_ASuccessorBeforeTheHeadViewStopsThePass`, `TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark`, `TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | | `INV-SNAPK-REMOVE-CONVERGE-001` | A name a cleaning marked and did not delete (the remover died in between) is planned again by the next cleaning: the re-mark replaces the old mark, so the dead remover's late delete fails, and every unreachable name goes once a cleaning completes. | M9 clean → clean | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ReclaimsAnAbandonedMark`, `TestCleaningPass_InterruptAtEveryStep`, `TestLayoutStoreCleaningReclaimsAnAbandonedMark` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | | `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires DeleteMarked as Cleaner.removePlanned's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | @@ -1276,6 +1278,15 @@ Notes: | `INV-LIST-PUBLISH-001` | A list publication names only durable authenticated pages of its open session; an unknown reply never abandons their protection. | M9 snap -> snap | `list_chain.go` `StageListPage`, `RunPublishList` | `TestPublishList_Closure`, `TestRunPublishList_InterruptAtEveryStep`, `TestListSessionEndedDuringPageWriteCannotPublish` | PageChain 246-250; NoDangling | DORMANT | | `INV-LIST-CURSOR-001` | The persisted list cursor advances only after its authenticated page's idempotent effects finish; a missing page never completes work. | M9 clean -> clean | `list_chain.go` `RunAdvanceList` | `TestAdvanceList_Closure`, `TestRunAdvanceList_InterruptAtEveryStep`, `TestListMissingConsumerPageNeverCompletes` | PageChain 246,251-253; NoLostWork | DORMANT | | `INV-LIST-RETIRE-001` | List-page removal requires a clean session and the existing conditional mark/delete order; every page reached by HEAD is spared, including shared tails. | M9 clean removal | `remove.go` `Cleaner.removePlanned` | `TestListSweepSpareSessionAndReachableTail`, `TestListSharedTailSurvivesAbandonedChainAndResumes`, `TestLayoutStoreListPublishConsumeAndRetire` | PageChain 246,248-251; NoDangling | DORMANT | +| `INV-SNAPSHOT-DELETE-INTENT-001` | Removing a captured snapshot incarnation and publishing its durable intent are one HEAD CAS; an unrelated metadata retry keeps the same target and durable pages. | M9 metadata delete | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `TestDeleteSnapshotWithIntent_Closure`, `TestRunDeleteSnapshotWithIntent_InterruptAtEveryStep`, `TestDeleteIntentRetryKeepsDurablePagesAcrossMetadataCAS` | SnapDelete 241-245; PageChain 246-249 | DORMANT | +| `INV-SNAPSHOT-DELETE-CONSUME-001` | Only current persisted delete intent authorizes offline reclamation; live roots remain protected, failed effects retain the cursor, and receipt retirement cannot erase work. | M9 idle intent continuation | `delete_intent.go`; `remove.go` `Cleaner.removePlanned` | `TestConsumeSnapshotDeleteIntent_Closure`, `TestDeleteIntentOfflineAndReplacementPreserved`, `TestDeleteIntentMarkConflictKeepsUnfinishedPage`, `TestLayoutSnapshotDeleteIntentResumesWithoutReceipt` | PageChain 246,251-253; offline authority refinement awaits model/code read | DORMANT | + +The routine full-sweep scope of `INV-SNAPK-REMOVE-MARK-001` is explicit here: +its holder/session guard and all existing controls remain unchanged. The new +dormant snapshot-intent branch instead requires the exact current HEAD intent, +idle activity and live/detached state, with the same live-root and conditional +mutation order. It cannot remove namespaces or unname another snapshot. It +requires separate review/activation; no production driver reaches it yet. These three list rows are dormant until producer/consumer driver wiring and final queue-layout/format review. They do not declare by-change cleaning active. diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index b6b0e6061c..2f8a917a2c 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -705,7 +705,8 @@ configurations are unchanged. The recorded Linux run passed safe_chain (150,260 states), seven must-violate mutations and four reachability witnesses; coverage exit 0. This records the model owner's run, not a rerun by this PR. Configurations and expected results are committed in `pagechain/cfg`. -Trace: [model to code](pagechain/model-code-trace.tsv), rows 246-253. +Trace: [model to code](pagechain/model-code-trace.tsv), keyed to the committed +`safe_chain`, `mut_*` and `wit_*` configurations. The model abstracts effect execution as idempotent completion and relies on conditional HEAD and object writes. The Go adapter/consumer controls are a diff --git a/seaweed-block/docs/spec/pagechain/model-code-trace.tsv b/seaweed-block/docs/spec/pagechain/model-code-trace.tsv index fea76b3a3a..f38da0ab47 100644 --- a/seaweed-block/docs/spec/pagechain/model-code-trace.tsv +++ b/seaweed-block/docs/spec/pagechain/model-code-trace.tsv @@ -7,3 +7,6 @@ row model transition code control 251 PageChain CAdvance CResolve CRetire layout/list_chain.go RunAdvanceList; layout/remove.go TestRunAdvanceList_InterruptAtEveryStep 252 PageChain CApply CAdvance layout/list_chain.go RunAdvanceList TestAdvanceList_Closure 253 PageChain CRead layout/list_chain.go readListPage TestListMissingConsumerPageNeverCompletes +246 PageChain WritePage Send Deliver layout/delete_intent.go StageSnapshotDeletePage RunDeleteSnapshotWithIntent TestDeleteSnapshotWithIntent_Closure; TestRunDeleteSnapshotWithIntent_InterruptAtEveryStep; TestDeleteIntentPublicationIsFencedBeforeAnOrdinarySweep +252 PageChain CApply CAdvance layout/delete_intent.go RunConsumeSnapshotDeleteIntent; layout/remove.go TestDeleteIntentMarkConflictKeepsUnfinishedPage; TestRunConsumeSnapshotDeleteIntent_InterruptAtEveryStep; TestLayoutSnapshotDeleteIntentResumesWithoutReceipt +253 PageChain CRead layout/delete_intent.go RunConsumeSnapshotDeleteIntent TestDeleteIntentMissingPageAndRootRefuseBeforeUnlinkOrEffects From d3a0975aef9866d50eb6573181cf9270823ad168 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:43:16 -0800 Subject: [PATCH 10/20] Adopt intent pages before refreshed-base publication --- .../frontend/chunkstore/head_readers_test.go | 1 + .../chunkstore/layout/delete_intent.go | 64 ++++++- .../chunkstore/layout/delete_intent_test.go | 156 +++++++++++++++++- .../chunkstore/layout/kernel_table_test.go | 1 + .../docs/design/immutable-list-pages.md | 16 +- seaweed-block/docs/design/invariants.md | 1 + .../docs/spec/pagechain/model-code-trace.tsv | 1 + 7 files changed, 232 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 433d02afba..b0a96728fe 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -24,6 +24,7 @@ import ( // pins it. "GAP" marks a reader that takes an absent HEAD for an empty // one; a change that treats an absent HEAD as unknown flips those probes. var headReaders = map[string]string{ + "core/frontend/chunkstore/layout/delete_intent.go adoptDeleteIntentPage -> ReadHead": "absence refuses adoption (probe TestDeleteIntentAdoptionCannotRestoreStaleTags)", "core/frontend/chunkstore/layout/delete_intent.go StageSnapshotDeletePage -> ReadHead": "refuses ErrHeadAbsent before staging (probe TestLayoutDeleteIntentAbsentHEAD)", "core/frontend/chunkstore/layout/delete_intent.go RunDeleteSnapshotWithIntent -> ReadHead": "absence cannot settle unknown unlink (probe TestLayoutDeleteIntentAbsentHEAD and TestRunDeleteSnapshotWithIntent_InterruptAtEveryStep)", "core/frontend/chunkstore/layout/delete_intent.go RunConsumeSnapshotDeleteIntent -> ReadHead": "absence never confirms a cursor update (probe TestLayoutDeleteIntentAbsentHEAD and TestRunConsumeSnapshotDeleteIntent_InterruptAtEveryStep)", diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete_intent.go b/seaweed-block/core/frontend/chunkstore/layout/delete_intent.go index 71240bfbb4..ab9b40111f 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete_intent.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete_intent.go @@ -2,6 +2,7 @@ package layout import ( "context" + "errors" "fmt" "path" "strings" @@ -52,12 +53,69 @@ func StageSnapshotDeletePage(ctx context.Context, st ListChainStore, base uint64 } ref, _ := p.Ref() rel, _ := ref.Path() - if err := EnsureObject(ctx, st, rel, raw, p.Producer); err != nil { + // Staging never changes an existing entry's tags: a delayed staging call + // must not restore an older producer tag after a newer publication adopted + // this page. Authentication and CAS-base-specific adoption happen below. + meta, exists, err := st.Stat(ctx, rel) + if err != nil { + return ListRef{}, err + } + if exists { + if meta.Volume != h.VolumeID { + return ListRef{}, ErrIdentity + } + } else if err := st.Create(ctx, rel, raw, p.Producer); err != nil && !errors.Is(err, ErrExists) { return ListRef{}, err } return ref, nil } +// adoptDeleteIntentPage invalidates outstanding removals from an earlier CAS +// base without changing page bytes or their stable attempt identity. Stat +// precedes the HEAD check, which precedes conditional Reuse: a stale adopter +// cannot read a newer tag and roll it back after that newer base is published. +func adoptDeleteIntentPage(ctx context.Context, st ListChainStore, volume VolumeID, base uint64, ref ListRef) error { + rel, err := ref.Path() + if err != nil { + return err + } + writer := fmt.Sprintf("delete-intent/%d/%s", base, ref.Hash) + for round := 0; round < maxEnsureRounds; round++ { + meta, found, err := st.Stat(ctx, rel) + if err != nil { + return err + } + if !found { + return ErrListPageMissing + } + if meta.Volume != volume { + return ErrIdentity + } + h, exists, err := st.ReadHead(ctx) + if err != nil { + return err + } + if !exists { + return ErrHeadAbsent + } + if h.VolumeID != volume { + return ErrIdentity + } + if err := deleteIntentWindow(h, base); err != nil { + return err + } + if meta.Session == writer && meta.Mark == "" { + return nil + } + err = st.Reuse(ctx, rel, meta, writer) + if errors.Is(err, ErrPrecondition) { + continue + } + return err + } + return fmt.Errorf("%w: delete intent page kept moving during adoption", ErrPrecondition) +} + // RunDeleteSnapshotWithIntent removes a retained incarnation and publishes // its independently resumable reclamation intent in ONE HEAD CAS. Receipt // retirement is not an input to this transition or to the intent consumer. @@ -86,11 +144,11 @@ func RunDeleteSnapshotWithIntent(ctx context.Context, st ListChainStore, base ui // Its complete candidate plan is authenticated before publication. root := h.Snapshots[c.Target.Name].Root.Path() hasRoot := false - if err := ReadListChain(ctx, st, h.VolumeID, c, func(_ ListRef, p ListPage) error { + if err := ReadListChain(ctx, st, h.VolumeID, c, func(ref ListRef, p ListPage) error { for _, rel := range p.Entries { hasRoot = hasRoot || rel == root } - return nil + return adoptDeleteIntentPage(ctx, st, h.VolumeID, base, ref) }); err != nil { return Head{}, false, err } diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go b/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go index 69bcda6b4e..35c7a3196c 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go @@ -293,8 +293,8 @@ func TestDeleteIntentRetryKeepsDurablePagesAcrossMetadataCAS(t *testing.T) { if _, err := RunDeleteSnapshotWithIntent(ctx, s, s.h.Gen, c); err != nil { t.Fatalf("retry reminted/rejected durable intent: %v", err) } - if len(s.writes) != writes || !sameList(s.h.List, &c) { - t.Fatal("retry rewrote durable pages") + if len(s.writes) != writes+1 || s.writes[writes] != "reuse "+ListDir+"/"+c.Ref.Hash || !sameList(s.h.List, &c) { + t.Fatal("retry must adopt metadata without rewriting page bytes") } } @@ -369,3 +369,155 @@ func TestDeleteIntentPublicationIsFencedBeforeAnOrdinarySweep(t *testing.T) { t.Fatal("row removed after page sweep") } } + +type delayedIntentMark struct { + *chainStore + pending func() error +} + +type delayedIntentDelete struct { + *chainStore + pending func() error +} + +func (s *delayedIntentDelete) DeleteMarked(ctx context.Context, rel, mark string) error { + s.pending = func() error { return s.chainStore.DeleteMarked(ctx, rel, mark) } + return errKilled +} + +func TestDeleteIntentRefreshedBaseFencesDelayedCleanerDelete(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + if _, err := StageSnapshotDeletePage(ctx, s, s.h.Gen, p); err != nil { + t.Fatal(err) + } + if _, err := RunBeginClean(ctx, s, me, "delayed-delete"); err != nil { + t.Fatal(err) + } + delayed := &delayedIntentDelete{chainStore: s} + if _, err := NewCleaner(delayed, nil, delayed, me, "delayed-delete").Page(ctx, ListDir, 0, []string{c.Ref.Hash}); !errors.Is(err, errKilled) || delayed.pending == nil { + t.Fatalf("capture delayed delete: %v", err) + } + if _, err := RunEndClean(ctx, s, me, "delayed-delete", CauseCleanEnd); err != nil { + t.Fatal(err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, s.h.Gen, c); err != nil { + t.Fatal(err) + } + if err := delayed.pending(); !errors.Is(err, ErrPrecondition) { + t.Fatalf("old delete removed published page: %v", err) + } + if _, found, err := s.ReadListPage(ctx, c.Ref); err != nil || !found { + t.Fatalf("published page missing: %v", err) + } +} + +func (s *delayedIntentMark) Mark(ctx context.Context, rel string, meta ObjectMeta, mark string) error { + // The caller loses its reply while the backend request remains pending. + // Ending the clean session cannot retract this conditional operation. + s.pending = func() error { + if err := s.chainStore.Mark(ctx, rel, meta, mark); err != nil { + return err + } + return s.chainStore.DeleteMarked(ctx, rel, mark) + } + return errKilled +} + +func TestDeleteIntentRefreshedBaseFencesDelayedCleanerMark(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + if _, err := StageSnapshotDeletePage(ctx, s, s.h.Gen, p); err != nil { + t.Fatal(err) + } + // An earlier attempt adopted the page but did not publish. Merely using + // a fixed adoption tag would repeat that tag at the refreshed base. + if err := adoptDeleteIntentPage(ctx, s, s.volume, s.h.Gen, c.Ref); err != nil { + t.Fatal(err) + } + if _, err := RunBeginClean(ctx, s, me, "delayed"); err != nil { + t.Fatal(err) + } + delayed := &delayedIntentMark{chainStore: s} + if _, err := NewCleaner(delayed, nil, delayed, me, "delayed").Page(ctx, ListDir, 0, []string{c.Ref.Hash}); !errors.Is(err, errKilled) || delayed.pending == nil { + t.Fatalf("did not capture delayed mark: %v", err) + } + if _, err := RunEndClean(ctx, s, me, "delayed", CauseCleanEnd); err != nil { + t.Fatal(err) + } + if _, err := StageSnapshotDeletePage(ctx, s, s.h.Gen, p); err != nil { + t.Fatal(err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, s.h.Gen, c); err != nil { + t.Fatal(err) + } + if err := delayed.pending(); !errors.Is(err, ErrPrecondition) { + t.Fatalf("old cleaner removed newly reachable intent: %v", err) + } + if _, found, err := s.ReadListPage(ctx, c.Ref); err != nil || !found || !sameList(s.h.List, &c) { + t.Fatalf("HEAD reaches missing intent: found%v %v", found, err) + } +} + +func TestDeleteIntentAdoptionCannotRestoreStaleTags(t *testing.T) { + for _, absent := range []bool{false, true} { + t.Run(map[bool]string{false: "newer-base", true: "absent"}[absent], func(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + base := s.h.Gen + if _, err := StageSnapshotDeletePage(ctx, s, base, p); err != nil { + t.Fatal(err) + } + rel, _ := c.Ref.Path() + newWriter := "newer-adopter" + s.afterStat = func(got string) { + if got != rel { + return + } + s.afterStat = nil + // A newer HEAD lands while the old adopter is paused after Stat. + s.h.Gen++ + meta, _, _ := s.Stat(ctx, rel) + if err := s.Reuse(ctx, rel, meta, newWriter); err != nil { + t.Fatal(err) + } + if absent { + s.memHead.h = nil + } + } + want := ErrPrecondition + if absent { + want = ErrHeadAbsent + } + if err := adoptDeleteIntentPage(ctx, s, s.volume, base, c.Ref); !errors.Is(err, want) { + t.Fatalf("stale adopter: %v", err) + } + meta, _, _ := s.Stat(ctx, rel) + if meta.Session != newWriter { + t.Fatal("stale adopter restored old tags") + } + }) + } +} + +func TestDeleteIntentStagingNeverRevertsPublishedTags(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + base := s.h.Gen + if _, err := StageSnapshotDeletePage(ctx, s, base, p); err != nil { + t.Fatal(err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, base, c); err != nil { + t.Fatal(err) + } + rel, _ := c.Ref.Path() + before, _, _ := s.Stat(ctx, rel) + writes := len(s.writes) + if _, err := StageSnapshotDeletePage(ctx, s, s.h.Gen, p); err != nil { + t.Fatal(err) + } + after, _, _ := s.Stat(ctx, rel) + if before != after || len(s.writes) != writes { + t.Fatal("restaging undid publication protection") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go b/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go index 65876b0c37..3c02d0cafb 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go @@ -134,6 +134,7 @@ func kernelCell(t *testing.T, state, entry string) string { switch entry { case "DeleteSnapshotWithIntent", "ConsumeSnapshotDeleteIntent": + o.volume = h.VolumeID cs := &chainStore{memHead: nv.memHead, memObjects: o} p := ListPage{VolumeID: h.VolumeID, Kind: ListSnapshotDeleteIntent, Producer: "delete-1", Generation: h.Gen + 1, Pages: 1, Target: &SnapshotTarget{Name: "daily", Gen: 4}, Entries: []string{h.Snapshots["daily"].Root.Path()}} ref, _ := p.Ref() diff --git a/seaweed-block/docs/design/immutable-list-pages.md b/seaweed-block/docs/design/immutable-list-pages.md index e015c6c00f..527ad031af 100644 --- a/seaweed-block/docs/design/immutable-list-pages.md +++ b/seaweed-block/docs/design/immutable-list-pages.md @@ -131,7 +131,11 @@ The target is the retained `(name, publishing gen)` in this volume, never a new lookup by name. Its root must occur in the authenticated candidate chain. The chain's producer/generation is a stable attempt identity, independent of the HEAD CAS base: a retry after an unrelated metadata write reuses durable -pages and the original target. Admission of a new request against an absent +page bytes and the original target. Before publication, every page is +conditionally adopted with a writer tag specific to its page hash and current +CAS base, clearing old removal marks. This metadata update invalidates both a +delayed Mark planned at an earlier base and a delayed DeleteMarked from that +cleaning. Admission of a new request against an absent name and receipt ownership remain catalog responsibilities. The unlink and intent publication are one HEAD write. Losing its reply cannot @@ -147,8 +151,14 @@ This is an explicit additional authority branch inside `Cleaner.removePlanned`, not a weakening of the holder's routine cleaning guard. Before publication, an ordinary cleaner must begin at a later HEAD generation; -that fences an outstanding delete CAS before it can name swept pages. An -unsettled upload finishing after the fence is merely an orphan. After +that fences an outstanding delete CAS before it can name swept pages. A +refreshed-base retry additionally adopts every page; a base fence alone cannot +invalidate an earlier cleaner's outstanding conditional object operations. +Adoption orders Stat -> validate current HEAD/base -> conditional Reuse, so an +old adopter cannot read a new tag and then restore an old one. Staging only +creates missing entries and never changes existing tags; a delayed staging +request cannot undo adoption. An unsettled upload finishing after the fence +is merely an orphan. After publication, page retirement uses current-chain reachability as before. Missing pages and unfinished effects never advance the intent. A same-name replacement is preserved both by the retained target and by current live-root checks. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index bf00cfd1ce..c622824e9a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1280,6 +1280,7 @@ Notes: | `INV-LIST-RETIRE-001` | List-page removal requires a clean session and the existing conditional mark/delete order; every page reached by HEAD is spared, including shared tails. | M9 clean removal | `remove.go` `Cleaner.removePlanned` | `TestListSweepSpareSessionAndReachableTail`, `TestListSharedTailSurvivesAbandonedChainAndResumes`, `TestLayoutStoreListPublishConsumeAndRetire` | PageChain 246,248-251; NoDangling | DORMANT | | `INV-SNAPSHOT-DELETE-INTENT-001` | Removing a captured snapshot incarnation and publishing its durable intent are one HEAD CAS; an unrelated metadata retry keeps the same target and durable pages. | M9 metadata delete | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `TestDeleteSnapshotWithIntent_Closure`, `TestRunDeleteSnapshotWithIntent_InterruptAtEveryStep`, `TestDeleteIntentRetryKeepsDurablePagesAcrossMetadataCAS` | SnapDelete 241-245; PageChain 246-249 | DORMANT | | `INV-SNAPSHOT-DELETE-CONSUME-001` | Only current persisted delete intent authorizes offline reclamation; live roots remain protected, failed effects retain the cursor, and receipt retirement cannot erase work. | M9 idle intent continuation | `delete_intent.go`; `remove.go` `Cleaner.removePlanned` | `TestConsumeSnapshotDeleteIntent_Closure`, `TestDeleteIntentOfflineAndReplacementPreserved`, `TestDeleteIntentMarkConflictKeepsUnfinishedPage`, `TestLayoutSnapshotDeleteIntentResumesWithoutReceipt` | PageChain 246,251-253; offline authority refinement awaits model/code read | DORMANT | +| `INV-SNAPSHOT-DELETE-ADOPT-001` | Publication adopts every intent page with a CAS-base-specific tag after Stat and HEAD validation; stale cleaners and adopters cannot remove or retag a newly published page, and staging never restores old tags. | M9 delete intent publication | `delete_intent.go` `adoptDeleteIntentPage`, `StageSnapshotDeletePage` | `TestDeleteIntentRefreshedBaseFencesDelayedCleanerMark`, `TestDeleteIntentRefreshedBaseFencesDelayedCleanerDelete`, `TestDeleteIntentAdoptionCannotRestoreStaleTags`, `TestDeleteIntentStagingNeverRevertsPublishedTags` | PageChain NoDangling; conditional object adoption refinement awaits model/code read | DORMANT | The routine full-sweep scope of `INV-SNAPK-REMOVE-MARK-001` is explicit here: its holder/session guard and all existing controls remain unchanged. The new diff --git a/seaweed-block/docs/spec/pagechain/model-code-trace.tsv b/seaweed-block/docs/spec/pagechain/model-code-trace.tsv index f38da0ab47..87c0ad27b9 100644 --- a/seaweed-block/docs/spec/pagechain/model-code-trace.tsv +++ b/seaweed-block/docs/spec/pagechain/model-code-trace.tsv @@ -10,3 +10,4 @@ row model transition code control 246 PageChain WritePage Send Deliver layout/delete_intent.go StageSnapshotDeletePage RunDeleteSnapshotWithIntent TestDeleteSnapshotWithIntent_Closure; TestRunDeleteSnapshotWithIntent_InterruptAtEveryStep; TestDeleteIntentPublicationIsFencedBeforeAnOrdinarySweep 252 PageChain CApply CAdvance layout/delete_intent.go RunConsumeSnapshotDeleteIntent; layout/remove.go TestDeleteIntentMarkConflictKeepsUnfinishedPage; TestRunConsumeSnapshotDeleteIntent_InterruptAtEveryStep; TestLayoutSnapshotDeleteIntentResumesWithoutReceipt 253 PageChain CRead layout/delete_intent.go RunConsumeSnapshotDeleteIntent TestDeleteIntentMissingPageAndRootRefuseBeforeUnlinkOrEffects +246 PageChain NoDangling (conditional object adoption refinement) layout/delete_intent.go adoptDeleteIntentPage TestDeleteIntentRefreshedBaseFencesDelayedCleanerMark; TestDeleteIntentAdoptionCannotRestoreStaleTags; TestDeleteIntentStagingNeverRevertsPublishedTags From 848effb9aa290c084360ec825db08f9cbc828d18 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:55:01 -0800 Subject: [PATCH 11/20] Check adopted intent ownership before publication --- .../chunkstore/layout/delete_intent.go | 21 +++++++++-- .../chunkstore/layout/delete_intent_test.go | 36 +++++++++++++++++++ .../docs/design/immutable-list-pages.md | 12 +++++-- seaweed-block/docs/design/invariants.md | 4 +-- .../docs/spec/pagechain/model-code-trace.tsv | 2 +- 5 files changed, 67 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete_intent.go b/seaweed-block/core/frontend/chunkstore/layout/delete_intent.go index ab9b40111f..a4dce5affe 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete_intent.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete_intent.go @@ -79,7 +79,7 @@ func adoptDeleteIntentPage(ctx context.Context, st ListChainStore, volume Volume if err != nil { return err } - writer := fmt.Sprintf("delete-intent/%d/%s", base, ref.Hash) + writer := deleteIntentWriter(base, ref) for round := 0; round < maxEnsureRounds; round++ { meta, found, err := st.Stat(ctx, rel) if err != nil { @@ -116,6 +116,12 @@ func adoptDeleteIntentPage(ctx context.Context, st ListChainStore, volume Volume return fmt.Errorf("%w: delete intent page kept moving during adoption", ErrPrecondition) } +func deleteIntentWriter(base uint64, ref ListRef) string { + // The page hash binds its producer, generation and bytes. The CAS base + // makes the protection tag fresh when that stable page is re-adopted. + return fmt.Sprintf("delete-intent/%d/%s", base, ref.Hash) +} + // RunDeleteSnapshotWithIntent removes a retained incarnation and publishes // its independently resumable reclamation intent in ONE HEAD CAS. Receipt // retirement is not an input to this transition or to the intent consumer. @@ -148,7 +154,18 @@ func RunDeleteSnapshotWithIntent(ctx context.Context, st ListChainStore, base ui for _, rel := range p.Entries { hasRoot = hasRoot || rel == root } - return adoptDeleteIntentPage(ctx, st, h.VolumeID, base, ref) + if err := adoptDeleteIntentPage(ctx, st, h.VolumeID, base, ref); err != nil { + return err + } + rel, _ := ref.Path() + meta, found, err := st.Stat(ctx, rel) + if err != nil { + return err + } + if !found || meta.Volume != h.VolumeID || meta.Session != deleteIntentWriter(base, ref) || meta.Mark != "" { + return ErrPrecondition + } + return nil }); err != nil { return Head{}, false, err } diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go b/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go index 35c7a3196c..2090fc58d3 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go @@ -521,3 +521,39 @@ func TestDeleteIntentStagingNeverRevertsPublishedTags(t *testing.T) { t.Fatal("restaging undid publication protection") } } + +type changedAfterIntentAdoption struct { + *chainStore + change string +} + +func (s *changedAfterIntentAdoption) Reuse(ctx context.Context, rel string, meta ObjectMeta, writer string) error { + if err := s.chainStore.Reuse(ctx, rel, meta, writer); err != nil { + return err + } + switch s.change { + case "missing": + delete(s.objs, s.full(rel)) + case "writer": + s.objs[s.full(rel)].meta.Session = "other-attempt" + case "marked": + s.objs[s.full(rel)].meta.Mark = "interference" + } + return nil +} + +func TestDeleteIntentPublicationChecksAdoptedPageMetadata(t *testing.T) { + for _, change := range []string{"missing", "writer", "marked"} { + t.Run(change, func(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + if _, err := StageSnapshotDeletePage(ctx, s, s.h.Gen, p); err != nil { + t.Fatal(err) + } + changed := &changedAfterIntentAdoption{chainStore: s, change: change} + if _, err := RunDeleteSnapshotWithIntent(ctx, changed, s.h.Gen, c); !errors.Is(err, ErrPrecondition) || s.updates != 0 || s.h.Snapshots["daily"].Gen != 4 { + t.Fatalf("published without this attempt's unmarked page: %v", err) + } + }) + } +} diff --git a/seaweed-block/docs/design/immutable-list-pages.md b/seaweed-block/docs/design/immutable-list-pages.md index 527ad031af..49584c3d04 100644 --- a/seaweed-block/docs/design/immutable-list-pages.md +++ b/seaweed-block/docs/design/immutable-list-pages.md @@ -135,7 +135,11 @@ page bytes and the original target. Before publication, every page is conditionally adopted with a writer tag specific to its page hash and current CAS base, clearing old removal marks. This metadata update invalidates both a delayed Mark planned at an earlier base and a delayed DeleteMarked from that -cleaning. Admission of a new request against an absent +cleaning. The publishing transition then explicitly checks every page is +present, belongs to the full volume ID, carries this attempt's writer tag and +has no removal mark; a failed check refuses the HEAD write. The page hash in +that tag binds its immutable producer/generation, and the CAS base makes it +fresh for a refreshed attempt. Admission of a new request against an absent name and receipt ownership remain catalog responsibilities. The unlink and intent publication are one HEAD write. Losing its reply cannot @@ -163,8 +167,10 @@ publication, page retirement uses current-chain reachability as before. Missing pages and unfinished effects never advance the intent. A same-name replacement is preserved both by the retained target and by current live-root checks. -PageChain rows 246-253 cover publication and effect/cursor ordering; SnapDelete -241-245 cover incarnation identity. The offline consumer refinement and its +StaleClean rows 159-161 cover conditional adoption and stale removal (including +the no-metadata-change Reuse mutant); PageChain rows 246-253 cover publication +and effect/cursor ordering; SnapDelete 241-245 cover incarnation identity. +The offline consumer refinement and its new authority branch require exact-head model/code review before activation. No product delete driver calls this seam yet. The one-slot admission capacity, remaining producer wiring and Linux/race qualification remain outstanding. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index c622824e9a..a1e0a0160c 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -583,7 +583,7 @@ stateDiagram-v2 | snap(s), list slot empty | snap(s), list cursor published | same full holder, open session and original base generation; every referenced page durable and authenticated; unknown reply retains session and pages | `list_chain.go` `StageListPage`, `RunPublishList` | `INV-LIST-PUBLISH-001` | | clean(c), current list page | clean(c), next continuation or none | exact observed cursor CAS only after authenticated page effects succeed; failed reads and failed effects leave cursor unchanged | `list_chain.go` `RunAdvanceList` | `INV-LIST-CURSOR-001` | | clean(c), stored list page | clean(c), unreached page removed | tags before HEAD; current clean session; spare all current-chain pages; conditional mark then delete | `remove.go` `Cleaner.Page` | `INV-LIST-RETIRE-001` | -| idle/snap, retained snapshot | same activity, row removed and intent published | one CAS removes only the captured name/gen and names its durable candidate chain; clean activity refuses | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `INV-SNAPSHOT-DELETE-INTENT-001` | +| idle/snap, retained snapshot | same activity, row removed and intent published | one CAS removes only captured name/gen and names its durable chain; each page present, this attempt's tag, unmarked; clean activity refuses | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `INV-SNAPSHOT-DELETE-INTENT-001`, `INV-SNAPSHOT-DELETE-ADOPT-001` | | idle live/detached, persisted delete intent | idle live/detached, next intent page or none | receipt-independent continuation from current HEAD; live-root and conditional effect guards; cursor follows completed effects | `delete_intent.go` `RunConsumeSnapshotDeleteIntent` | `INV-SNAPSHOT-DELETE-CONSUME-001` | | idle | snap(s) | caller is the holder at HEAD's epoch (epoch, server and claim id); HEAD present; snap(s) again is a replay, any other activity is refused | head.go `Head.Begin`, `runTransition` | `INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-BEGIN-001` | | snap(s) | idle | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); over idle it succeeds without a write and means only that no activity remains; before resuming a failed stop, abort its still-open session and re-read HEAD: only matching live/idle resumes, detached goes Down, absent/unknown stays stopped | head.go `Head.Abort`; durable/provider_layout.go `settleLayoutStop` | `INV-SNAPK-ABORT-001` | @@ -1280,7 +1280,7 @@ Notes: | `INV-LIST-RETIRE-001` | List-page removal requires a clean session and the existing conditional mark/delete order; every page reached by HEAD is spared, including shared tails. | M9 clean removal | `remove.go` `Cleaner.removePlanned` | `TestListSweepSpareSessionAndReachableTail`, `TestListSharedTailSurvivesAbandonedChainAndResumes`, `TestLayoutStoreListPublishConsumeAndRetire` | PageChain 246,248-251; NoDangling | DORMANT | | `INV-SNAPSHOT-DELETE-INTENT-001` | Removing a captured snapshot incarnation and publishing its durable intent are one HEAD CAS; an unrelated metadata retry keeps the same target and durable pages. | M9 metadata delete | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `TestDeleteSnapshotWithIntent_Closure`, `TestRunDeleteSnapshotWithIntent_InterruptAtEveryStep`, `TestDeleteIntentRetryKeepsDurablePagesAcrossMetadataCAS` | SnapDelete 241-245; PageChain 246-249 | DORMANT | | `INV-SNAPSHOT-DELETE-CONSUME-001` | Only current persisted delete intent authorizes offline reclamation; live roots remain protected, failed effects retain the cursor, and receipt retirement cannot erase work. | M9 idle intent continuation | `delete_intent.go`; `remove.go` `Cleaner.removePlanned` | `TestConsumeSnapshotDeleteIntent_Closure`, `TestDeleteIntentOfflineAndReplacementPreserved`, `TestDeleteIntentMarkConflictKeepsUnfinishedPage`, `TestLayoutSnapshotDeleteIntentResumesWithoutReceipt` | PageChain 246,251-253; offline authority refinement awaits model/code read | DORMANT | -| `INV-SNAPSHOT-DELETE-ADOPT-001` | Publication adopts every intent page with a CAS-base-specific tag after Stat and HEAD validation; stale cleaners and adopters cannot remove or retag a newly published page, and staging never restores old tags. | M9 delete intent publication | `delete_intent.go` `adoptDeleteIntentPage`, `StageSnapshotDeletePage` | `TestDeleteIntentRefreshedBaseFencesDelayedCleanerMark`, `TestDeleteIntentRefreshedBaseFencesDelayedCleanerDelete`, `TestDeleteIntentAdoptionCannotRestoreStaleTags`, `TestDeleteIntentStagingNeverRevertsPublishedTags` | PageChain NoDangling; conditional object adoption refinement awaits model/code read | DORMANT | +| `INV-SNAPSHOT-DELETE-ADOPT-001` | Publication adopts every intent page with a fresh CAS-base tag and checks it is present, this attempt's and unmarked; stale cleaners/adopters cannot remove or retag a published page, and staging never restores old tags. | M9 delete intent publication | `delete_intent.go` `adoptDeleteIntentPage`, `RunDeleteSnapshotWithIntent`, `StageSnapshotDeletePage` | `TestDeleteIntentRefreshedBaseFencesDelayedCleanerMark`, `TestDeleteIntentRefreshedBaseFencesDelayedCleanerDelete`, `TestDeleteIntentAdoptionCannotRestoreStaleTags`, `TestDeleteIntentStagingNeverRevertsPublishedTags`, `TestDeleteIntentPublicationChecksAdoptedPageMetadata` | StaleClean 159-161; exact-head refinement read required | DORMANT | The routine full-sweep scope of `INV-SNAPK-REMOVE-MARK-001` is explicit here: its holder/session guard and all existing controls remain unchanged. The new diff --git a/seaweed-block/docs/spec/pagechain/model-code-trace.tsv b/seaweed-block/docs/spec/pagechain/model-code-trace.tsv index 87c0ad27b9..456ab5a07e 100644 --- a/seaweed-block/docs/spec/pagechain/model-code-trace.tsv +++ b/seaweed-block/docs/spec/pagechain/model-code-trace.tsv @@ -10,4 +10,4 @@ row model transition code control 246 PageChain WritePage Send Deliver layout/delete_intent.go StageSnapshotDeletePage RunDeleteSnapshotWithIntent TestDeleteSnapshotWithIntent_Closure; TestRunDeleteSnapshotWithIntent_InterruptAtEveryStep; TestDeleteIntentPublicationIsFencedBeforeAnOrdinarySweep 252 PageChain CApply CAdvance layout/delete_intent.go RunConsumeSnapshotDeleteIntent; layout/remove.go TestDeleteIntentMarkConflictKeepsUnfinishedPage; TestRunConsumeSnapshotDeleteIntent_InterruptAtEveryStep; TestLayoutSnapshotDeleteIntentResumesWithoutReceipt 253 PageChain CRead layout/delete_intent.go RunConsumeSnapshotDeleteIntent TestDeleteIntentMissingPageAndRootRefuseBeforeUnlinkOrEffects -246 PageChain NoDangling (conditional object adoption refinement) layout/delete_intent.go adoptDeleteIntentPage TestDeleteIntentRefreshedBaseFencesDelayedCleanerMark; TestDeleteIntentAdoptionCannotRestoreStaleTags; TestDeleteIntentStagingNeverRevertsPublishedTags +159-161 StaleClean conditional adoption and stale removals (separate from PageChain Sweep) layout/delete_intent.go adoptDeleteIntentPage RunDeleteSnapshotWithIntent TestDeleteIntentRefreshedBaseFencesDelayedCleanerMark; TestDeleteIntentRefreshedBaseFencesDelayedCleanerDelete; TestDeleteIntentAdoptionCannotRestoreStaleTags; TestDeleteIntentStagingNeverRevertsPublishedTags; TestDeleteIntentPublicationChecksAdoptedPageMetadata From e0cbd1198d4c5690d9b9c51023f397ede84de8a7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:58:06 -0800 Subject: [PATCH 12/20] Refuse generic staging of snapshot delete intents --- .../chunkstore/layout/delete_intent_test.go | 53 +++++++++++++++++++ .../frontend/chunkstore/layout/list_chain.go | 3 ++ .../docs/design/immutable-list-pages.md | 7 +++ seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 64 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go b/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go index 2090fc58d3..c9ab24d99e 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete_intent_test.go @@ -557,3 +557,56 @@ func TestDeleteIntentPublicationChecksAdoptedPageMetadata(t *testing.T) { }) } } + +type heldGenericIntentStage struct { + *chainStore + beforeStat func() +} + +func (s *heldGenericIntentStage) Stat(ctx context.Context, rel string) (ObjectMeta, bool, error) { + if s.beforeStat != nil { + f := s.beforeStat + s.beforeStat = nil + f() + } + return s.chainStore.Stat(ctx, rel) +} + +func TestGenericIntentStagingCannotUndoRefreshedPublication(t *testing.T) { + s, c, p := deleteIntentFixture(t) + ctx := context.Background() + s.h.Activity = Activity{Kind: ActSnap, Session: p.Producer} + if _, err := StageSnapshotDeletePage(ctx, s, s.h.Gen, p); err != nil { + t.Fatal(err) + } + var pending func() error + held := &heldGenericIntentStage{chainStore: s} + held.beforeStat = func() { + if _, err := RunAbort(ctx, s, me, p.Producer, CauseSessionRollback); err != nil { + t.Fatal(err) + } + if _, err := RunBeginClean(ctx, s, me, "old-clean"); err != nil { + t.Fatal(err) + } + delayed := &delayedIntentMark{chainStore: s} + if _, err := NewCleaner(delayed, nil, delayed, me, "old-clean").Page(ctx, ListDir, 0, []string{c.Ref.Hash}); !errors.Is(err, errKilled) { + t.Fatal(err) + } + pending = delayed.pending + if _, err := RunEndClean(ctx, s, me, "old-clean", CauseCleanEnd); err != nil { + t.Fatal(err) + } + if _, err := RunDeleteSnapshotWithIntent(ctx, s, s.h.Gen, c); err != nil { + t.Fatal(err) + } + } + _, err := StageListPage(ctx, held, me, p.Producer, p) + if pending != nil { + if removal := pending(); !errors.Is(removal, ErrPrecondition) { + t.Fatalf("generic staging restored old cleaner authority: %v", removal) + } + } + if !errors.Is(err, ErrIdentity) || pending != nil { + t.Fatalf("generic intent staging reached object I/O: %v", err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/list_chain.go b/seaweed-block/core/frontend/chunkstore/layout/list_chain.go index 74ef01a072..7f9c392f06 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/list_chain.go +++ b/seaweed-block/core/frontend/chunkstore/layout/list_chain.go @@ -114,6 +114,9 @@ func listSession(h Head, me HolderID, session, kind string) error { // Ending the session during I/O may leave an orphan, but cannot authorize // its later publication: that CAS checks the original generation/session. func StageListPage(ctx context.Context, st ListChainStore, me HolderID, session string, p ListPage) (ListRef, error) { + if p.Kind == ListSnapshotDeleteIntent { + return ListRef{}, fmt.Errorf("%w: use non-retagging snapshot-delete staging", ErrIdentity) + } h, found, err := st.ReadHead(ctx) if err != nil { return ListRef{}, err diff --git a/seaweed-block/docs/design/immutable-list-pages.md b/seaweed-block/docs/design/immutable-list-pages.md index 49584c3d04..8c261af777 100644 --- a/seaweed-block/docs/design/immutable-list-pages.md +++ b/seaweed-block/docs/design/immutable-list-pages.md @@ -174,3 +174,10 @@ The offline consumer refinement and its new authority branch require exact-head model/code review before activation. No product delete driver calls this seam yet. The one-slot admission capacity, remaining producer wiring and Linux/race qualification remain outstanding. + +The generic `StageListPage` rejects snapshot-delete intent before any HEAD or +object I/O, just as generic publication and consumption reject that kind. Its +ordinary EnsureObject adoption must never restore a snapshot-intent producer +tag after dedicated publication protected it. The held-generic-staging control +crosses snap end, cleaner planning and refreshed publication and proves this +door cannot recreate an earlier cleaner's removal authority. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a1e0a0160c..5fae105ef8 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1280,7 +1280,7 @@ Notes: | `INV-LIST-RETIRE-001` | List-page removal requires a clean session and the existing conditional mark/delete order; every page reached by HEAD is spared, including shared tails. | M9 clean removal | `remove.go` `Cleaner.removePlanned` | `TestListSweepSpareSessionAndReachableTail`, `TestListSharedTailSurvivesAbandonedChainAndResumes`, `TestLayoutStoreListPublishConsumeAndRetire` | PageChain 246,248-251; NoDangling | DORMANT | | `INV-SNAPSHOT-DELETE-INTENT-001` | Removing a captured snapshot incarnation and publishing its durable intent are one HEAD CAS; an unrelated metadata retry keeps the same target and durable pages. | M9 metadata delete | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `TestDeleteSnapshotWithIntent_Closure`, `TestRunDeleteSnapshotWithIntent_InterruptAtEveryStep`, `TestDeleteIntentRetryKeepsDurablePagesAcrossMetadataCAS` | SnapDelete 241-245; PageChain 246-249 | DORMANT | | `INV-SNAPSHOT-DELETE-CONSUME-001` | Only current persisted delete intent authorizes offline reclamation; live roots remain protected, failed effects retain the cursor, and receipt retirement cannot erase work. | M9 idle intent continuation | `delete_intent.go`; `remove.go` `Cleaner.removePlanned` | `TestConsumeSnapshotDeleteIntent_Closure`, `TestDeleteIntentOfflineAndReplacementPreserved`, `TestDeleteIntentMarkConflictKeepsUnfinishedPage`, `TestLayoutSnapshotDeleteIntentResumesWithoutReceipt` | PageChain 246,251-253; offline authority refinement awaits model/code read | DORMANT | -| `INV-SNAPSHOT-DELETE-ADOPT-001` | Publication adopts every intent page with a fresh CAS-base tag and checks it is present, this attempt's and unmarked; stale cleaners/adopters cannot remove or retag a published page, and staging never restores old tags. | M9 delete intent publication | `delete_intent.go` `adoptDeleteIntentPage`, `RunDeleteSnapshotWithIntent`, `StageSnapshotDeletePage` | `TestDeleteIntentRefreshedBaseFencesDelayedCleanerMark`, `TestDeleteIntentRefreshedBaseFencesDelayedCleanerDelete`, `TestDeleteIntentAdoptionCannotRestoreStaleTags`, `TestDeleteIntentStagingNeverRevertsPublishedTags`, `TestDeleteIntentPublicationChecksAdoptedPageMetadata` | StaleClean 159-161; exact-head refinement read required | DORMANT | +| `INV-SNAPSHOT-DELETE-ADOPT-001` | Publication adopts every intent page with a fresh CAS-base tag and checks it is present, this attempt's and unmarked; stale cleaners/adopters cannot remove or retag a published page, and staging never restores old tags. | M9 delete intent publication | `delete_intent.go` `adoptDeleteIntentPage`, `RunDeleteSnapshotWithIntent`, `StageSnapshotDeletePage` | `TestDeleteIntentRefreshedBaseFencesDelayedCleanerMark`, `TestDeleteIntentRefreshedBaseFencesDelayedCleanerDelete`, `TestDeleteIntentAdoptionCannotRestoreStaleTags`, `TestDeleteIntentStagingNeverRevertsPublishedTags`, `TestDeleteIntentPublicationChecksAdoptedPageMetadata`, `TestGenericIntentStagingCannotUndoRefreshedPublication` | StaleClean 159-161; exact-head refinement read required | DORMANT | The routine full-sweep scope of `INV-SNAPK-REMOVE-MARK-001` is explicit here: its holder/session guard and all existing controls remain unchanged. The new From 10cbe8a5b025c14b3c805047221f98ffabaa2e25 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 16:40:45 -0800 Subject: [PATCH 13/20] storage: a pre-copy rate sample survives an upload below the clock's tick samplePrecopy recorded a rate only when the round's payload time was nonzero, so a round whose upload ended below the clock's resolution gave no rate, and three such rounds left the estimate "samples_unknown". The payload time is now floored at the coarsest clock resolution (1 ms): the rate of a fast round is a lower bound, never missing or infinite. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_precopy.go | 12 ++++++-- .../storage/chunk_precopy_rate_floor_test.go | 29 +++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_precopy_rate_floor_test.go diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 61a746c4cd..5d9a1d037c 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -448,6 +448,11 @@ func precopyFixedPartsFromSample(s precopySample) PrecopyFixedParts { return p } +// precopyPayloadClockFloor is the least payload time a rate sample divides +// by: the coarsest clock resolution a host may have (Windows ticks about +// every 0.5 ms). It lowers the rate of an upload measured faster than that. +const precopyPayloadClockFloor = time.Millisecond + func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats, fixedNs int64) { // A no-op root read is not a measurement of final CAS + confirmation. if st.CASNs <= 0 { @@ -460,8 +465,11 @@ func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats, fixedNs int64) { } s := precopySample{at: time.Now(), fixed: time.Duration(max(int64(1), fixedNs))} s.parts = precopyFixedParts(st, s.fixed) - if st.UploadedBytes > 0 && st.PayloadNs > 0 { - s.rate = float64(st.UploadedBytes) / time.Duration(st.PayloadNs).Seconds() + if st.UploadedBytes > 0 { + // An upload can also end below the clock's resolution (its payload + // time reads zero): its rate is taken at the resolution, a lower + // bound, so a fast round is never a missing or an infinite sample. + s.rate = float64(st.UploadedBytes) / max(time.Duration(st.PayloadNs), precopyPayloadClockFloor).Seconds() } l.precopySamples = append(l.precopySamples, s) if len(l.precopySamples) > 32 { diff --git a/seaweed-block/core/storage/chunk_precopy_rate_floor_test.go b/seaweed-block/core/storage/chunk_precopy_rate_floor_test.go new file mode 100644 index 0000000000..0367b129a7 --- /dev/null +++ b/seaweed-block/core/storage/chunk_precopy_rate_floor_test.go @@ -0,0 +1,29 @@ +package storage + +import ( + "testing" + "time" +) + +// A round that uploaded bytes in less time than the clock resolves (its +// payload time reads zero) is still a rate sample: its rate is taken at the +// clock's resolution, a lower bound, never missing and never infinite. A +// round that uploaded nothing gives no rate, as before. +func TestPrecopyRateSampleAtTheClocksResolution(t *testing.T) { + l := &chunkLayerImpl{} + l.samplePrecopy(chunkCutStats{CASNs: 5, CASResult: "ok", UploadedBytes: 16384, PayloadNs: 0}, 1000) + if len(l.precopySamples) != 1 { + t.Fatalf("%d samples, want 1", len(l.precopySamples)) + } + rate := l.precopySamples[0].rate + if most := 16384 / precopyPayloadClockFloor.Seconds(); rate <= 0 || rate > most { + t.Fatalf("a sub-resolution upload's rate is %.0f B/s, want above 0 and at most %.0f (its bytes over the clock's resolution)", rate, most) + } + l.samplePrecopy(chunkCutStats{CASNs: 5, CASResult: "ok", UploadedBytes: 0, PayloadNs: 0}, 1000) + if r := l.precopySamples[1].rate; r != 0 { + t.Fatalf("a round that uploaded nothing gave rate %.0f, want none", r) + } + if precopyPayloadClockFloor < time.Microsecond || precopyPayloadClockFloor > 10*time.Millisecond { + t.Fatalf("the clock floor %s is outside any clock's resolution", precopyPayloadClockFloor) + } +} From 67f770d650a3c8c2033eb23fadc703e2c9639f0f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 16:53:21 -0800 Subject: [PATCH 14/20] storage: floor each pre-copy payload interval, not their sum The payload time sums several intervals (staging, the copy, the upload); three that each ended below the clock's tick read zero although together they took up to three ticks, so one floor on the sum overstated the rate. Each interval now adds at least one tick to an unexported floored sum that the rate divides by; the reported payload time is unchanged. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 6 ++-- seaweed-block/core/storage/chunk_precopy.go | 17 ++++++++--- .../storage/chunk_precopy_rate_floor_test.go | 29 +++++++++++++++++++ seaweed-block/core/storage/chunk_seam.go | 5 ++++ 4 files changed, 50 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 580ffddaec..a67bc42dbd 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1150,7 +1150,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if !guestFrozen { staged, err = l.stage(ctx, &st, spill.bytes) } - st.PayloadNs += time.Since(stageStart).Nanoseconds() + st.addPayload(time.Since(stageStart).Nanoseconds()) if err != nil { return chunkCutResult{}, err } @@ -1334,7 +1334,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.CopyNs = time.Since(copyStart).Nanoseconds() if st.UploadedBytes > bytesBeforeCopy { - st.PayloadNs += st.CopyNs + st.addPayload(st.CopyNs) } else { st.NonPayloadCopyNs += st.CopyNs } @@ -1417,7 +1417,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err)) } if len(uploads) > 0 { - st.PayloadNs += time.Since(payloadStart).Nanoseconds() + st.addPayload(time.Since(payloadStart).Nanoseconds()) } prepareStart = time.Now() for _, u := range uploads { diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 5d9a1d037c..c3f03d9a1d 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -453,6 +453,13 @@ func precopyFixedPartsFromSample(s precopySample) PrecopyFixedParts { // every 0.5 ms). It lowers the rate of an upload measured faster than that. const precopyPayloadClockFloor = time.Millisecond +// addPayload adds one payload interval (d nanoseconds as measured) to the +// cut's payload time, and to its tick-floored sum. +func (st *chunkCutStats) addPayload(d int64) { + st.PayloadNs += d + st.payloadFloorNs += max(d, int64(precopyPayloadClockFloor)) +} + func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats, fixedNs int64) { // A no-op root read is not a measurement of final CAS + confirmation. if st.CASNs <= 0 { @@ -466,10 +473,12 @@ func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats, fixedNs int64) { s := precopySample{at: time.Now(), fixed: time.Duration(max(int64(1), fixedNs))} s.parts = precopyFixedParts(st, s.fixed) if st.UploadedBytes > 0 { - // An upload can also end below the clock's resolution (its payload - // time reads zero): its rate is taken at the resolution, a lower - // bound, so a fast round is never a missing or an infinite sample. - s.rate = float64(st.UploadedBytes) / max(time.Duration(st.PayloadNs), precopyPayloadClockFloor).Seconds() + // Each payload interval can end below the clock's resolution (and + // read zero): the rate divides by the intervals each counted at least + // one tick, a lower bound, so a fast round is never a missing or an + // overstated sample. + div := max(time.Duration(st.payloadFloorNs), time.Duration(st.PayloadNs), precopyPayloadClockFloor) + s.rate = float64(st.UploadedBytes) / div.Seconds() } l.precopySamples = append(l.precopySamples, s) if len(l.precopySamples) > 32 { diff --git a/seaweed-block/core/storage/chunk_precopy_rate_floor_test.go b/seaweed-block/core/storage/chunk_precopy_rate_floor_test.go index 0367b129a7..cd73bb31bc 100644 --- a/seaweed-block/core/storage/chunk_precopy_rate_floor_test.go +++ b/seaweed-block/core/storage/chunk_precopy_rate_floor_test.go @@ -27,3 +27,32 @@ func TestPrecopyRateSampleAtTheClocksResolution(t *testing.T) { t.Fatalf("the clock floor %s is outside any clock's resolution", precopyPayloadClockFloor) } } + +// The payload time sums several intervals (staging, the copy, the upload). +// Three intervals that each ended below the clock's resolution read zero +// although together they took up to three ticks: the rate divides by three +// ticks, never one, so it stays a lower bound. An interval longer than a +// tick counts as measured. +func TestPrecopyRateFloorsEachPayloadInterval(t *testing.T) { + const bytes = 1 << 20 + var st chunkCutStats + st.CASNs, st.CASResult, st.UploadedBytes = 5, "ok", bytes + for i := 0; i < 3; i++ { + st.addPayload(0) // a sub-tick interval, read as zero + } + l := &chunkLayerImpl{} + l.samplePrecopy(st, 1000) + if most := bytes / (3 * precopyPayloadClockFloor).Seconds(); l.precopySamples[0].rate > most+1 { + t.Fatalf("three sub-tick intervals gave rate %.0f B/s, want at most %.0f (bytes over three ticks)", l.precopySamples[0].rate, most) + } + var measured chunkCutStats + measured.CASNs, measured.CASResult, measured.UploadedBytes = 5, "ok", bytes + measured.addPayload(int64(5 * time.Millisecond)) + l.samplePrecopy(measured, 1000) + if want := bytes / (5 * time.Millisecond).Seconds(); l.precopySamples[1].rate < want-1 || l.precopySamples[1].rate > want+1 { + t.Fatalf("a measured 5 ms interval gave rate %.0f B/s, want %.0f", l.precopySamples[1].rate, want) + } + if measured.PayloadNs != int64(5*time.Millisecond) || st.PayloadNs != 0 { + t.Fatalf("the reported payload time changed: %d and %d", measured.PayloadNs, st.PayloadNs) + } +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index dc02640da8..ba12327c37 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -422,6 +422,11 @@ type chunkCutStats struct { NonPayloadCopyNs int64 PayloadNs int64 // disjoint streaming/copy/upload wall intervals + // payloadFloorNs is PayloadNs with each interval counted at least one + // clock tick (precopyPayloadClockFloor): an interval that ended below + // the clock's resolution reads zero, so the rate a sample takes from + // PayloadNs would be too high. Only the pre-copy rate reads it. + payloadFloorNs int64 // Local validated WAL attempts and local copy duration, including savers. COWWALReadAttempts uint64 From a6d1f4d93bd198602511ef0926d5eb94f643bc56 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 18:06:22 -0800 Subject: [PATCH 15/20] storage: keep the floored payload sum out of the cut statistics The tick-floored payload sum was an unexported field of ChunkCutStats, so the layer statistics grew a field the cut body does not mirror (the mirror test counts every field). The cut now keeps the sum locally and hands it to samplePrecopy; ChunkCutStats is unchanged from main. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 15 +++++++++++---- seaweed-block/core/storage/chunk_precopy.go | 17 +++++++++-------- .../chunk_precopy_cold_estimator_test.go | 6 +++--- .../storage/chunk_precopy_fixed_commit_test.go | 6 +++--- .../storage/chunk_precopy_rate_floor_test.go | 13 +++++++------ .../storage/chunk_precopy_sample_bound_test.go | 2 +- seaweed-block/core/storage/chunk_seam.go | 5 ----- 7 files changed, 34 insertions(+), 30 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index fe23c15049..cb1cf4ed23 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1133,6 +1133,13 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch start := time.Now() recoveredPublication := l.pending != nil var st chunkCutStats + // payloadFloor is the cut's payload intervals each floored at a clock + // tick, for the pre-copy rate only (st.PayloadNs stays as measured). + var payloadFloor int64 + addPayload := func(d int64) { + st.PayloadNs += d + payloadFloor += flooredPayload(d) + } work := &cutAttemptObservation{} ctx = context.WithValue(ctx, cutObservationKey{}, work) persistCapturedMap := func(versions map[uint64]uint64) { @@ -1179,7 +1186,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch res.Stats = st if !pauseStart.IsZero() { fixed := time.Since(pauseStart).Nanoseconds() - st.PayloadNs + payloadBeforeBarrier - l.samplePrecopy(st, fixed) + l.samplePrecopy(st, fixed, payloadFloor) } res.CandidateTail = l.estimateCandidateTail(tailBytes) } @@ -1266,7 +1273,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if !guestFrozen { staged, err = l.stage(ctx, &st, spill.bytes) } - st.addPayload(time.Since(stageStart).Nanoseconds()) + addPayload(time.Since(stageStart).Nanoseconds()) if err != nil { return chunkCutResult{}, err } @@ -1450,7 +1457,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.CopyNs = time.Since(copyStart).Nanoseconds() if st.UploadedBytes > bytesBeforeCopy { - st.addPayload(st.CopyNs) + addPayload(st.CopyNs) } else { st.NonPayloadCopyNs += st.CopyNs } @@ -1533,7 +1540,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err)) } if len(uploads) > 0 { - st.addPayload(time.Since(payloadStart).Nanoseconds()) + addPayload(time.Since(payloadStart).Nanoseconds()) } prepareStart = time.Now() for _, u := range uploads { diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index c3f03d9a1d..a55ffda7f9 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -453,14 +453,15 @@ func precopyFixedPartsFromSample(s precopySample) PrecopyFixedParts { // every 0.5 ms). It lowers the rate of an upload measured faster than that. const precopyPayloadClockFloor = time.Millisecond -// addPayload adds one payload interval (d nanoseconds as measured) to the -// cut's payload time, and to its tick-floored sum. -func (st *chunkCutStats) addPayload(d int64) { - st.PayloadNs += d - st.payloadFloorNs += max(d, int64(precopyPayloadClockFloor)) -} +// flooredPayload is one payload interval (d nanoseconds as measured) counted +// at least one clock tick: an interval that ended below the clock's +// resolution reads zero, so a rate taken from the raw sum would be too high. +func flooredPayload(d int64) int64 { return max(d, int64(precopyPayloadClockFloor)) } -func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats, fixedNs int64) { +// samplePrecopy records one cut's pre-copy sample. payloadFloorNs is the +// cut's payload intervals each floored (flooredPayload), which the rate +// divides by; st.PayloadNs stays the measured sum the cut reports. +func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats, fixedNs, payloadFloorNs int64) { // A no-op root read is not a measurement of final CAS + confirmation. if st.CASNs <= 0 { if st.CASNs != 0 || (st.CASResult != "ok" && st.CASResult != "resolved-by-reread") { @@ -477,7 +478,7 @@ func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats, fixedNs int64) { // read zero): the rate divides by the intervals each counted at least // one tick, a lower bound, so a fast round is never a missing or an // overstated sample. - div := max(time.Duration(st.payloadFloorNs), time.Duration(st.PayloadNs), precopyPayloadClockFloor) + div := max(time.Duration(payloadFloorNs), time.Duration(st.PayloadNs), precopyPayloadClockFloor) s.rate = float64(st.UploadedBytes) / div.Seconds() } l.precopySamples = append(l.precopySamples, s) diff --git a/seaweed-block/core/storage/chunk_precopy_cold_estimator_test.go b/seaweed-block/core/storage/chunk_precopy_cold_estimator_test.go index 6dfa04fcf0..894bab1150 100644 --- a/seaweed-block/core/storage/chunk_precopy_cold_estimator_test.go +++ b/seaweed-block/core/storage/chunk_precopy_cold_estimator_test.go @@ -70,12 +70,12 @@ func TestPrecopyColdNonemptyTailUsesFirstMeasuredRound(t *testing.T) { func TestPrecopySuccessfulCASBelowClockResolutionIsMeasured(t *testing.T) { layer := &chunkLayerImpl{} st := chunkCutStats{CASResult: "ok", CASNs: 0, UploadedBytes: ctChunkBytes, PayloadNs: int64(10 * time.Millisecond)} - layer.samplePrecopy(st, int64(20*time.Millisecond)) + layer.samplePrecopy(st, int64(20*time.Millisecond), 0) if len(layer.precopySamples) != 1 || layer.precopySamples[0].rate <= 0 { t.Fatalf("successful zero-ns CAS lost its measured upload: %+v", layer.precopySamples) } - layer.samplePrecopy(chunkCutStats{CASNs: 0, UploadedBytes: ctChunkBytes, PayloadNs: st.PayloadNs}, st.PayloadNs) - layer.samplePrecopy(chunkCutStats{CASResult: "precondition", CASNs: 0, UploadedBytes: ctChunkBytes, PayloadNs: st.PayloadNs}, st.PayloadNs) + layer.samplePrecopy(chunkCutStats{CASNs: 0, UploadedBytes: ctChunkBytes, PayloadNs: st.PayloadNs}, st.PayloadNs, 0) + layer.samplePrecopy(chunkCutStats{CASResult: "precondition", CASNs: 0, UploadedBytes: ctChunkBytes, PayloadNs: st.PayloadNs}, st.PayloadNs, 0) if len(layer.precopySamples) != 1 { t.Fatalf("no-op or refused CAS became a sample: %+v", layer.precopySamples) } diff --git a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go index 53d4b89ac8..2b692cf1e2 100644 --- a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go +++ b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go @@ -112,11 +112,11 @@ func TestPrecopyFixedPartsStayWithLargestObservation(t *testing.T) { _, _, l, _ := precopyLayer(t, 1024, 0) l.precopySamples = nil for i := 0; i < 3; i++ { - l.samplePrecopy(chunkCutStats{CASNs: 1}, int64(time.Millisecond)) + l.samplePrecopy(chunkCutStats{CASNs: 1}, int64(time.Millisecond), 0) } st := chunkCutStats{CASNs: 1, DrainNs: int64(10 * time.Millisecond), LockWaitNs: int64(30 * time.Millisecond), SyncNs: int64(40 * time.Millisecond), CASWriteNs: int64(50 * time.Millisecond), HeadReadbackNs: int64(60 * time.Millisecond), MapPersistNs: int64(10 * time.Millisecond)} - l.samplePrecopy(st, int64(200*time.Millisecond)) - l.samplePrecopy(chunkCutStats{CASNs: 1, SyncNs: int64(100 * time.Millisecond)}, int64(150*time.Millisecond)) + l.samplePrecopy(st, int64(200*time.Millisecond), 0) + l.samplePrecopy(chunkCutStats{CASNs: 1, SyncNs: int64(100 * time.Millisecond)}, int64(150*time.Millisecond), 0) r := l.precopyEstimate(0, 0) p := r.FixedParts if r.Fixed != 200*time.Millisecond || p.Drain != 10*time.Millisecond || p.StoreLock != 20*time.Millisecond || p.DataSync != 40*time.Millisecond || p.HeadCAS != 50*time.Millisecond || p.HeadReadback != 60*time.Millisecond || p.MapPersist != 10*time.Millisecond || p.Other != 10*time.Millisecond { diff --git a/seaweed-block/core/storage/chunk_precopy_rate_floor_test.go b/seaweed-block/core/storage/chunk_precopy_rate_floor_test.go index cd73bb31bc..09b386b4d3 100644 --- a/seaweed-block/core/storage/chunk_precopy_rate_floor_test.go +++ b/seaweed-block/core/storage/chunk_precopy_rate_floor_test.go @@ -11,7 +11,7 @@ import ( // round that uploaded nothing gives no rate, as before. func TestPrecopyRateSampleAtTheClocksResolution(t *testing.T) { l := &chunkLayerImpl{} - l.samplePrecopy(chunkCutStats{CASNs: 5, CASResult: "ok", UploadedBytes: 16384, PayloadNs: 0}, 1000) + l.samplePrecopy(chunkCutStats{CASNs: 5, CASResult: "ok", UploadedBytes: 16384, PayloadNs: 0}, 1000, 0) if len(l.precopySamples) != 1 { t.Fatalf("%d samples, want 1", len(l.precopySamples)) } @@ -19,7 +19,7 @@ func TestPrecopyRateSampleAtTheClocksResolution(t *testing.T) { if most := 16384 / precopyPayloadClockFloor.Seconds(); rate <= 0 || rate > most { t.Fatalf("a sub-resolution upload's rate is %.0f B/s, want above 0 and at most %.0f (its bytes over the clock's resolution)", rate, most) } - l.samplePrecopy(chunkCutStats{CASNs: 5, CASResult: "ok", UploadedBytes: 0, PayloadNs: 0}, 1000) + l.samplePrecopy(chunkCutStats{CASNs: 5, CASResult: "ok", UploadedBytes: 0, PayloadNs: 0}, 1000, 0) if r := l.precopySamples[1].rate; r != 0 { t.Fatalf("a round that uploaded nothing gave rate %.0f, want none", r) } @@ -37,18 +37,19 @@ func TestPrecopyRateFloorsEachPayloadInterval(t *testing.T) { const bytes = 1 << 20 var st chunkCutStats st.CASNs, st.CASResult, st.UploadedBytes = 5, "ok", bytes + var floor int64 for i := 0; i < 3; i++ { - st.addPayload(0) // a sub-tick interval, read as zero + floor += flooredPayload(0) // a sub-tick interval, read as zero } l := &chunkLayerImpl{} - l.samplePrecopy(st, 1000) + l.samplePrecopy(st, 1000, floor) if most := bytes / (3 * precopyPayloadClockFloor).Seconds(); l.precopySamples[0].rate > most+1 { t.Fatalf("three sub-tick intervals gave rate %.0f B/s, want at most %.0f (bytes over three ticks)", l.precopySamples[0].rate, most) } var measured chunkCutStats measured.CASNs, measured.CASResult, measured.UploadedBytes = 5, "ok", bytes - measured.addPayload(int64(5 * time.Millisecond)) - l.samplePrecopy(measured, 1000) + measured.PayloadNs = int64(5 * time.Millisecond) + l.samplePrecopy(measured, 1000, flooredPayload(measured.PayloadNs)) if want := bytes / (5 * time.Millisecond).Seconds(); l.precopySamples[1].rate < want-1 || l.precopySamples[1].rate > want+1 { t.Fatalf("a measured 5 ms interval gave rate %.0f B/s, want %.0f", l.precopySamples[1].rate, want) } diff --git a/seaweed-block/core/storage/chunk_precopy_sample_bound_test.go b/seaweed-block/core/storage/chunk_precopy_sample_bound_test.go index 5be9c0093f..bd87e33ae4 100644 --- a/seaweed-block/core/storage/chunk_precopy_sample_bound_test.go +++ b/seaweed-block/core/storage/chunk_precopy_sample_bound_test.go @@ -12,7 +12,7 @@ func TestPrecopySampleHistoryKeepsNewest32(t *testing.T) { const taken = 40 for i := 1; i <= taken; i++ { // The fixed cost carries the sample's order. - l.samplePrecopy(chunkCutStats{CASNs: 1}, int64(i)) + l.samplePrecopy(chunkCutStats{CASNs: 1}, int64(i), 0) } if len(l.precopySamples) != 32 { t.Fatalf("sample history holds %d entries, want 32", len(l.precopySamples)) diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index ba12327c37..dc02640da8 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -422,11 +422,6 @@ type chunkCutStats struct { NonPayloadCopyNs int64 PayloadNs int64 // disjoint streaming/copy/upload wall intervals - // payloadFloorNs is PayloadNs with each interval counted at least one - // clock tick (precopyPayloadClockFloor): an interval that ended below - // the clock's resolution reads zero, so the rate a sample takes from - // PayloadNs would be too high. Only the pre-copy rate reads it. - payloadFloorNs int64 // Local validated WAL attempts and local copy duration, including savers. COWWALReadAttempts uint64 From bf9cec70ec54e81f76024c502e1ac8c5af02e108 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 18:23:14 -0800 Subject: [PATCH 16/20] hostlimit: test, a hand-off's idle bound is the skip window TestOneStalledTicketCostsOneSkipNotEveryHandoff bounded each hand-off's idle gap at a fixed 200 ms, which a loaded runner exceeded (295 ms). A hand-off that paid the stalled ticket's skip idles at least the skip window, so that is the bound now; the failure prints every gap. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/hostlimit/tickets_test.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/hostlimit/tickets_test.go b/seaweed-block/core/hostlimit/tickets_test.go index 17dc571926..c73647c4bc 100644 --- a/seaweed-block/core/hostlimit/tickets_test.go +++ b/seaweed-block/core/hostlimit/tickets_test.go @@ -510,12 +510,20 @@ func TestOneStalledTicketCostsOneSkipNotEveryHandoff(t *testing.T) { if len(log) < 6 { t.Fatalf("only %d admissions in 10 s", len(log)) } + // A hand-off that paid the stalled ticket's skip idles at least the skip + // window after the release; scheduling and the workers' poll idle far less, + // even on a loaded host. So the bound is the skip window itself, not a + // fixed fraction of it. + gaps := make([]time.Duration, 0, len(log)) + for i := 1; i < len(log); i++ { + gaps = append(gaps, log[i].at.Sub(log[i-1].done).Round(time.Millisecond)) + } for i := 1; i < len(log); i++ { if log[i].due <= log[i-1].due { t.Fatalf("admissions out of due order at %d", i) } - if gap := log[i].at.Sub(log[i-1].done); gap > 200*time.Millisecond { - t.Fatalf("hand-off %d idled %s after the release; one stalled ticket must not cost every hand-off a skip (%s)", i, gap.Round(time.Millisecond), skip) + if gap := log[i].at.Sub(log[i-1].done); gap >= skip { + t.Fatalf("hand-off %d idled %s after the release, at least the skip window (%s): one stalled ticket must not cost every hand-off a skip (hand-off gaps %v)", i, gap.Round(time.Millisecond), skip, gaps) } } } From 7f26eded1be58552d4576663889c8ea52ab38613 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 18:56:06 -0800 Subject: [PATCH 17/20] hostlimit: test, two more ticket waits bounded by their property - TestStalledEarlierTicketIsSkipped: instead of passing within 700 ms of the start, no attempt passes before the skip time and the first attempt begun after it passes (a 50 ms allowance for the skip judge's clock); the attempts' start times are printed. A loaded host's late polls no longer fail it (1.155 s seen on CI). - TestUrgentProceedsPastAStalledProbe: the admission runs with an outer bound of ten hold waits (a block behind the probe would never return) and must take at least its hold wait, instead of at most hold wait + 300 ms (1.153 s seen on CI). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/hostlimit/tickets_test.go | 53 ++++++++++++++++---- 1 file changed, 42 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/hostlimit/tickets_test.go b/seaweed-block/core/hostlimit/tickets_test.go index c73647c4bc..1aac20bffe 100644 --- a/seaweed-block/core/hostlimit/tickets_test.go +++ b/seaweed-block/core/hostlimit/tickets_test.go @@ -106,7 +106,8 @@ func TestDeadEarlierTicketIsRemoved(t *testing.T) { func TestStalledEarlierTicketIsSkipped(t *testing.T) { c := testConfig(t) a, b := newTest(t, c), newTest(t, c) - b.testSkipAfter = 300 * time.Millisecond + const skip = 300 * time.Millisecond + b.testSkipAfter = skip now := HostNow() stalled, _ := a.TakeTicket(now - 2e9) defer stalled.Close() @@ -115,22 +116,34 @@ func TestStalledEarlierTicketIsSkipped(t *testing.T) { start := time.Now() var id uint64 var err error + var refused []time.Duration // when each refused attempt began, from the first + var passedAt time.Duration for { + at := time.Since(start) if id, err = admitWith(b, late); err == nil { + passedAt = at break } if !errors.Is(err, ErrNotHead) { t.Fatalf("refusal: %v", err) } + refused = append(refused, at.Round(time.Millisecond)) if time.Since(start) > 3*time.Second { t.Fatal("never passed the stalled ticket") } time.Sleep(20 * time.Millisecond) } - el := time.Since(start) b.Release(id) - if el < 300*time.Millisecond || el > 700*time.Millisecond { - t.Fatalf("passed the stalled ticket after %s; want the skip time plus a poll", el) + // The property, independent of how late a loaded host runs the polls: + // no attempt passes before the skip time, and the first attempt that + // begins after it passes (a small allowance for the skip judge's own + // clock); the attempts' start times are printed on failure. + const judge = 50 * time.Millisecond + if passedAt < skip { + t.Fatalf("passed the stalled ticket at %s, before the skip time %s (refused at %v)", passedAt.Round(time.Millisecond), skip, refused) + } + if n := len(refused); n > 0 && refused[n-1] >= skip+judge { + t.Fatalf("an attempt begun at %s, after the skip time %s, was refused (refused at %v, passed at %s)", refused[n-1], skip, refused, passedAt.Round(time.Millisecond)) } if late.Skipped() != 1 { t.Fatalf("skipped %d tickets", late.Skipped()) @@ -211,14 +224,32 @@ func TestUrgentProceedsPastAStalledProbe(t *testing.T) { t.Fatal(err) } start := time.Now() - id, err := l.Acquire(context.Background(), Urgent, nil) - if err != nil { - t.Fatalf("urgent admission behind a stalled probe: %v", err) + type admitted struct { + id uint64 + err error + el time.Duration } - el := time.Since(start) - l.Release(id) - if el < urgentHoldWait || el > urgentHoldWait+300*time.Millisecond { - t.Fatalf("urgent admission took %s; want about %s", el, urgentHoldWait) + got := make(chan admitted, 1) + go func() { + id, err := l.Acquire(context.Background(), Urgent, nil) + got <- admitted{id, err, time.Since(start)} + }() + // Blocked behind the stalled probe, the admission would not return while + // the probe is held; bounded by its hold wait, it returns after about + // urgentHoldWait. The outer bound is ten hold waits, so a loaded host's + // scheduling does not fail it, while a block still does. + var a admitted + select { + case a = <-got: + case <-time.After(10 * urgentHoldWait): + t.Fatalf("urgent admission still waiting %s behind a stalled probe; want about %s", 10*urgentHoldWait, urgentHoldWait) + } + if a.err != nil { + t.Fatalf("urgent admission behind a stalled probe: %v", a.err) + } + l.Release(a.id) + if a.el < urgentHoldWait { + t.Fatalf("urgent admission took %s, less than its hold wait %s", a.el, urgentHoldWait) } if st := l.Snapshot().(Stats); st.UrgentPendingUnheld != 1 { t.Fatalf("UrgentPendingUnheld = %d", st.UrgentPendingUnheld) From 5ac568bc791bcb8d5aa587f6cb605783b6222714 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 19:28:56 -0800 Subject: [PATCH 18/20] test: retry transient NVMe completions within host budget --- .../nvme_host_retry_integration_test.go | 56 ++++++++++++++ .../cmd/blockvolume/nvme_retry_test.go | 12 ++- .../planned_handoff_integration_test.go | 74 ++++--------------- .../procedure_crash_io_integration_test.go | 2 +- 4 files changed, 84 insertions(+), 60 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/nvme_host_retry_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/nvme_host_retry_integration_test.go b/seaweed-block/cmd/blockvolume/nvme_host_retry_integration_test.go new file mode 100644 index 0000000000..53b23ccefc --- /dev/null +++ b/seaweed-block/cmd/blockvolume/nvme_host_retry_integration_test.go @@ -0,0 +1,56 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "fmt" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "net" + "testing" + "time" +) + +func TestInitiatorFlushRetriesTransientCompletion(t *testing.T) { + client, server := net.Pipe() + defer client.Close() + defer server.Close() + _ = server.SetDeadline(time.Now().Add(5 * time.Second)) + c := &nvmeInitiator{io: client, r: nvme.NewReader(client), w: nvme.NewWriter(client)} + done := make(chan error, 1) + go func() { + r, w := nvme.NewReader(server), nvme.NewWriter(server) + for i := 0; i < 6; i++ { + h, err := r.Dequeue() + if err != nil { + done <- err + return + } + if h.Type != 4 { + done <- fmt.Errorf("command type %d", h.Type) + return + } + var cmd nvme.CapsuleCommand + if err = r.Receive(&cmd); err != nil { + done <- err + return + } + if cmd.OpCode != 0 || cmd.CID != uint16(i+1) { + done <- fmt.Errorf("retry command %+v", cmd) + return + } + resp := nvme.CapsuleResponse{CID: cmd.CID} + if i < 5 { + resp.Status = 0x0104 + } + if err = w.SendHeaderOnly(5, &resp, 16); err != nil { + done <- err + return + } + } + done <- nil + }() + c.flush(t) + if err := <-done; err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/cmd/blockvolume/nvme_retry_test.go b/seaweed-block/cmd/blockvolume/nvme_retry_test.go index a69ef9dae7..42660e4d20 100644 --- a/seaweed-block/cmd/blockvolume/nvme_retry_test.go +++ b/seaweed-block/cmd/blockvolume/nvme_retry_test.go @@ -3,7 +3,9 @@ package main_test import ( "errors" "fmt" + "strings" "testing" + "time" ) // nvmeHostMaxRetries is the Linux NVMe host's default retry count for a @@ -28,6 +30,7 @@ func (e *nvmeStatusError) retryable() bool { return e.status&0x8000 == 0 } // Retry set, or any other error (transport, lost or unexpected bytes), is // returned at once. func retryLikeHost(max int, op func() error) (refused int, err error) { + started := time.Now() for { err = op() var se *nvmeStatusError @@ -36,7 +39,7 @@ func retryLikeHost(max int, op func() error) (refused int, err error) { } refused++ if refused > max { - return refused, fmt.Errorf("%w: refused %d times, %d retries used up", err, refused, max) + return refused, fmt.Errorf("%w: refused %d times, %d retries used up, elapsed=%s", err, refused, max, time.Since(started)) } } } @@ -85,3 +88,10 @@ func TestRetryLikeHostRetriesOnlyDNRClearStatusFiveTimes(t *testing.T) { }) } } + +func TestRetryLikeHostReportsExhaustedDuration(t *testing.T) { + _, err := retryLikeHost(nvmeHostMaxRetries, func() error { return &nvmeStatusError{op: "Write", status: 0x0104} }) + if err == nil || !strings.Contains(err.Error(), "elapsed=") { + t.Fatalf("missing exhaustion duration: %v", err) + } +} diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index e1c6614ed2..7c8c036345 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -867,75 +867,33 @@ func (c *nvmeInitiator) ioCmd(op uint8, lba uint64, blocks int) nvme.CapsuleComm return cmd } +// hostCommand keeps the raw try methods single-attempt for fault probes. +func hostCommand(t *testing.T, op func() error) { + t.Helper() + started := time.Now() + refused, err := retryLikeHost(nvmeHostMaxRetries, op) + if refused > 0 { + t.Logf("NVMe retryable completions=%d elapsed=%s exhausted=%t", refused, time.Since(started), refused > nvmeHostMaxRetries) + } + if err != nil { + t.Fatal(err) + } +} + func (c *nvmeInitiator) write(t *testing.T, lba uint64, data []byte) { t.Helper() - cmd := c.ioCmd(0x01, lba, len(data)/4096) - if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil { - t.Fatalf("nvme Write: %v", err) - } - ch, err := c.r.Dequeue() - if err != nil || ch.Type != 0x9 { - t.Fatalf("nvme Write: want R2T, got type %v err %v", ch, err) - } - var r2t nvme.R2THeader - if err := c.r.Receive(&r2t); err != nil { - t.Fatalf("nvme R2T: %v", err) - } - h2c := nvme.H2CDataHeader{CCCID: cmd.CID, TAG: r2t.TAG, DATAL: uint32(len(data))} - if err := c.w.SendWithData(0x6, 0, &h2c, 16, data); err != nil { - t.Fatalf("nvme H2CData: %v", err) - } - if resp := nvmeResponse(t, c.r); resp.Status != 0 { - t.Fatalf("nvme Write status 0x%04x", resp.Status) - } + hostCommand(t, func() error { return c.tryWrite(lba, data) }) } func (c *nvmeInitiator) flush(t *testing.T) { t.Helper() - cmd := c.ioCmd(0x00, 0, 0) - if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil { - t.Fatalf("nvme Flush: %v", err) - } - if resp := nvmeResponse(t, c.r); resp.Status != 0 { - t.Fatalf("nvme Flush status 0x%04x", resp.Status) - } + hostCommand(t, c.tryFlush) } func (c *nvmeInitiator) read(t *testing.T, lba uint64, n int) []byte { t.Helper() - cmd := c.ioCmd(0x02, lba, n/4096) - if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil { - t.Fatalf("nvme Read: %v", err) - } var data []byte - for { - ch, err := c.r.Dequeue() - if err != nil { - t.Fatalf("nvme Read: %v", err) - } - if ch.Type == 0x5 { - var resp nvme.CapsuleResponse - if err := c.r.Receive(&resp); err != nil || resp.Status != 0 { - t.Fatalf("nvme Read status 0x%04x err %v", resp.Status, err) - } - break - } - if ch.Type != 0x7 { - t.Fatalf("nvme Read: unexpected PDU type 0x%x", ch.Type) - } - var dh nvme.C2HDataHeader - if err := c.r.Receive(&dh); err != nil { - t.Fatalf("nvme C2HData: %v", err) - } - part := make([]byte, c.r.Length()) - if err := c.r.ReceiveData(part); err != nil { - t.Fatalf("nvme C2HData payload: %v", err) - } - data = append(data, part...) - } - if len(data) != n { - t.Fatalf("nvme Read returned %d bytes; want %d", len(data), n) - } + hostCommand(t, func() (err error) { data, err = c.tryRead(lba, n); return err }) return data } diff --git a/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go index 059ea0146d..8155c33928 100644 --- a/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go @@ -301,7 +301,7 @@ func (c *nvmeInitiator) tryRead(lba uint64, n int) ([]byte, error) { return nil, fmt.Errorf("nvme Read response: %w", err) } if resp.Status != 0 { - return nil, fmt.Errorf("nvme Read status 0x%04x", resp.Status) + return nil, &nvmeStatusError{op: "Read", status: resp.Status} } break } From 935b7c46cb1e1a21e43969ee45844c430a5bfcdc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 19:32:12 -0800 Subject: [PATCH 19/20] test: print each retryable completion and retry decision --- .../nvme_host_retry_integration_test.go | 3 ++- .../cmd/blockvolume/nvme_retry_test.go | 25 +++++++++++++++++++ .../planned_handoff_integration_test.go | 4 ++- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/nvme_host_retry_integration_test.go b/seaweed-block/cmd/blockvolume/nvme_host_retry_integration_test.go index 53b23ccefc..13392f161b 100644 --- a/seaweed-block/cmd/blockvolume/nvme_host_retry_integration_test.go +++ b/seaweed-block/cmd/blockvolume/nvme_host_retry_integration_test.go @@ -4,10 +4,11 @@ package main_test import ( "fmt" - "github.com/seaweedfs/seaweed-block/core/frontend/nvme" "net" "testing" "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" ) func TestInitiatorFlushRetriesTransientCompletion(t *testing.T) { diff --git a/seaweed-block/cmd/blockvolume/nvme_retry_test.go b/seaweed-block/cmd/blockvolume/nvme_retry_test.go index 42660e4d20..eaaf8b4717 100644 --- a/seaweed-block/cmd/blockvolume/nvme_retry_test.go +++ b/seaweed-block/cmd/blockvolume/nvme_retry_test.go @@ -30,6 +30,10 @@ func (e *nvmeStatusError) retryable() bool { return e.status&0x8000 == 0 } // Retry set, or any other error (transport, lost or unexpected bytes), is // returned at once. func retryLikeHost(max int, op func() error) (refused int, err error) { + return retryLikeHostReporting(max, op, nil) +} + +func retryLikeHostReporting(max int, op func() error, report func(int, uint16)) (refused int, err error) { started := time.Now() for { err = op() @@ -38,6 +42,9 @@ func retryLikeHost(max int, op func() error) (refused int, err error) { return refused, err } refused++ + if report != nil { + report(refused, se.status) + } if refused > max { return refused, fmt.Errorf("%w: refused %d times, %d retries used up, elapsed=%s", err, refused, max, time.Since(started)) } @@ -95,3 +102,21 @@ func TestRetryLikeHostReportsExhaustedDuration(t *testing.T) { t.Fatalf("missing exhaustion duration: %v", err) } } + +func TestRetryLikeHostReportsEveryRetryableStatus(t *testing.T) { + var statuses []uint16 + _, err := retryLikeHostReporting(5, func() error { return &nvmeStatusError{op: "Write", status: 0x0104} }, func(attempt int, status uint16) { + if attempt != len(statuses)+1 { + t.Fatalf("attempt %d", attempt) + } + statuses = append(statuses, status) + }) + if err == nil || len(statuses) != 6 { + t.Fatalf("statuses=%v err=%v", statuses, err) + } + for _, status := range statuses { + if status != 0x0104 { + t.Fatalf("status 0x%04x", status) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index 7c8c036345..d52e19f41f 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -871,7 +871,9 @@ func (c *nvmeInitiator) ioCmd(op uint8, lba uint64, blocks int) nvme.CapsuleComm func hostCommand(t *testing.T, op func() error) { t.Helper() started := time.Now() - refused, err := retryLikeHost(nvmeHostMaxRetries, op) + refused, err := retryLikeHostReporting(nvmeHostMaxRetries, op, func(attempt int, status uint16) { + t.Logf("NVMe retryable completion attempt=%d status=0x%04x retry=%t elapsed=%s", attempt, status, attempt <= nvmeHostMaxRetries, time.Since(started)) + }) if refused > 0 { t.Logf("NVMe retryable completions=%d elapsed=%s exhausted=%t", refused, time.Since(started), refused > nvmeHostMaxRetries) } From f9cca837b0f2098ee9a884ea8f312784cbf8d75d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 19:37:14 -0800 Subject: [PATCH 20/20] ci: named tests can be non-gating with an open issue; the preview fencing round is (#920) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/.github/process-level-tests.txt | 7 +- .../scripts/required-tests-check-test.py | 10 +++ .../.github/scripts/required-tests-check.py | 66 +++++++++++++++---- 3 files changed, 67 insertions(+), 16 deletions(-) diff --git a/seaweed-block/.github/process-level-tests.txt b/seaweed-block/.github/process-level-tests.txt index aeec6737dd..56e6775162 100644 --- a/seaweed-block/.github/process-level-tests.txt +++ b/seaweed-block/.github/process-level-tests.txt @@ -32,8 +32,11 @@ TestStandaloneCleanMoveWithoutTheACKIsRefused # Failover and the fencing round. TestDoubleFailoverReadsBackEveryAckedWrite -TestFencingRoundHealContinuesThePrimary -TestFencingRoundSurvivorRejoins +# The replicated preview's fencing round runs and is reported on every job but +# does not gate it (#920: a sync-quorum flush under shared-runner load); it +# gates the nightly run on a quiet lab box. +TestFencingRoundHealContinuesThePrimary # nongating=#920 +TestFencingRoundSurvivorRejoins # nongating=#920 TestAVolumeThatServedBeforeItsFirstGateTickFailsOver # Many volumes on one host (F1_RUN=1). diff --git a/seaweed-block/.github/scripts/required-tests-check-test.py b/seaweed-block/.github/scripts/required-tests-check-test.py index 7b6fa7086f..94385dc8ba 100644 --- a/seaweed-block/.github/scripts/required-tests-check-test.py +++ b/seaweed-block/.github/scripts/required-tests-check-test.py @@ -45,8 +45,18 @@ def run(names, *streams, status=None): return r.returncode, r.stdout + r.stderr +NG = 'TestA\nTestB # nongating=#920\n' + CASES = [ # (name, want exit, names file, streams) + ('a non-gating test that passed', 0, NG, [ran('TestA') + ran('TestB')]), + ('a non-gating test that failed does not fail the run', 0, NG, [ran('TestA') + ran('TestB', 'fail')]), + ('a non-gating failure, then its process failed: still its own', 0, NG, + [ran('TestA'), ran('TestB', 'fail') + [ev('fail')]]), + ('a gating test still fails the run beside a non-gating one', 1, NG, [ran('TestA', 'fail') + ran('TestB')]), + ('a process failure after a gating test still fails the run', 1, NG, [ran('TestA') + [ev('fail')], ran('TestB')]), + ('a non-gating test that never ran fails (not run is not reported)', 1, NG, [ran('TestA')]), + ('nongating without an issue is refused', 2, 'TestA\nTestB # nongating\n', [ran('TestA') + ran('TestB')]), ('every named test passed', 0, 'TestA\nTestB # a comment\n', [ran('TestA') + ran('TestB')]), ('passes spread over two streams', 0, 'TestA\nTestB\n', [ran('TestA'), ran('TestB')]), ('an unnamed test may fail', 0, 'TestA\n', [ran('TestA') + ran('TestOther', 'fail')]), diff --git a/seaweed-block/.github/scripts/required-tests-check.py b/seaweed-block/.github/scripts/required-tests-check.py index 9a82bfad33..59569ea1ef 100644 --- a/seaweed-block/.github/scripts/required-tests-check.py +++ b/seaweed-block/.github/scripts/required-tests-check.py @@ -2,7 +2,12 @@ Usage: required-tests-check.py [--status STATUS_FILE] NAMES_FILE EVENTS_FILE... -NAMES_FILE holds one top-level test name per line (# starts a comment). +NAMES_FILE holds one top-level test name per line (# starts a comment). A +name whose comment says `nongating=#N` (an open issue) is non-gating: it runs +and is reported like every other, but its failure does not fail the run; its +line says NON-GATING and names the issue, and a failure-process exit after it +is its own, not the binary's. A non-gating test that never ran still fails: +a test that is not run is not reported. EVENTS_FILE is `go test -json` (or `go tool test2json`) output. A named test that skipped, failed, never started or never ended is a failure: a test that cannot start proves nothing, so it is not allowed to read as a pass. A name @@ -57,13 +62,23 @@ def own_messages(text): return [[head] + cont[-CONT:] for head, cont in msgs] +NONGATING = re.compile(r'\bnongating=(#\d+)') + + def names_of(path): - names, seen = [], set() + """The named tests, in order, and the non-gating ones with their issue.""" + names, seen, nongating = [], set(), {} with open(path, encoding='utf-8') as f: for n, raw in enumerate(f, 1): - line = raw.split('#', 1)[0].strip() + line, _, comment = raw.partition('#') + line = line.strip() if not line: continue + m = NONGATING.search('#' + comment) + if m: + nongating[line] = m.group(1) + elif 'nongating' in comment: + raise ValueError('%s:%d: %r: nongating needs an issue, nongating=#N' % (path, n, raw.strip())) if not line.startswith('Test') or '/' in line or ' ' in line: raise ValueError('%s:%d: %r is not a top-level test name' % (path, n, line)) if line in seen: @@ -72,7 +87,7 @@ def names_of(path): names.append(line) if not names: raise ValueError('%s: no test names' % path) - return names + return names, nongating def statuses_of(path): @@ -91,10 +106,12 @@ def statuses_of(path): def outcomes(paths): """Test name -> list of (action, elapsed) for its terminal events, the - names that started (action run), and the number of package-level - failure events.""" - ends, started, pkg_fail, output = {}, set(), 0, {} + names that started (action run), the package-level failure events (each + with the test last started in its stream before it, or None), and each + test's output.""" + ends, started, pkg_fail, output = {}, set(), [], {} for path in paths: + last = None with open(path, encoding='utf-8', errors='replace') as f: for raw in f: raw = raw.strip() @@ -107,7 +124,7 @@ def outcomes(paths): test = ev.get('Test') if not test: if ev.get('Action') == 'fail': - pkg_fail += 1 # the binary failed outside any test (or after one) + pkg_fail.append(last) # the binary failed outside any test (or after one) continue # other package events; a subtest's name never matches a top-level one action = ev.get('Action') if action == 'output': @@ -115,6 +132,8 @@ def outcomes(paths): continue if action == 'run': started.add(test) + if '/' not in test: + last = test elif action in ('pass', 'fail', 'skip'): ends.setdefault(test, []).append((action, ev.get('Elapsed'))) return ends, started, pkg_fail, output @@ -132,24 +151,36 @@ def main(argv): print(__doc__.strip().splitlines()[2], file=sys.stderr) return 2 try: - names = names_of(args[0]) + names, nongating = names_of(args[0]) ends, started, pkg_fail, output = outcomes(args[1:]) statuses = statuses_of(status_file) if status_file else None except (OSError, ValueError) as e: print('required-tests: %s' % e, file=sys.stderr) return 2 - bad, total, failed = 0, 0.0, [] + # A package-level failure right after a non-gating test is that test's + # (each named test runs in its own process); any other fails the run. + pkg_own = {} + for after in pkg_fail: + if after in nongating: + pkg_own[after] = pkg_own.get(after, 0) + 1 + pkg_fail = [a for a in pkg_fail if a not in nongating] + bad, total, failed, ng_failed = 0, 0.0, [], 0 for name in names: got = ends.get(name, []) actions = {a for a, _ in got} secs = sum(e for _, e in got if isinstance(e, (int, float))) total += secs rcs = statuses.get(name, []) if statuses is not None else [0] - if actions == {'pass'} and len(got) == 1 and rcs == [0]: + if actions == {'pass'} and len(got) == 1 and rcs == [0] and not pkg_own.get(name): print('PASS %-70s %7.1fs' % (name, secs)) continue - bad += 1 failed.append(name) + issue = nongating.get(name) + ran_at_all = bool(got) or name in started + if issue and ran_at_all: + ng_failed += 1 + else: + bad += 1 if actions == {'pass'} and len(got) == 1: why = ('NO EXIT STATUS' if not rcs else 'PASSED, THEN EXIT %s' % ','.join(str(r) for r in rcs)) @@ -159,7 +190,12 @@ def main(argv): why = 'RAN %d TIMES (%s)' % (len(got), ', '.join(a for a, _ in got)) else: why = got[0][0].upper() - print('%-8s %-70s %7.1fs' % ('FAIL', name, secs) + ' ' + why) + if pkg_own.get(name): + why += ', THEN THE PROCESS FAILED' + if issue and ran_at_all: + print('%-8s %-70s %7.1fs' % ('FAIL', name, secs) + ' ' + why + ' NON-GATING (%s): reported, does not fail the run' % issue) + else: + print('%-8s %-70s %7.1fs' % ('FAIL', name, secs) + ' ' + why) for name in failed: text = ''.join(output.get(name, [])).splitlines() own = own_messages(text)[-OWN:] @@ -167,8 +203,10 @@ def main(argv): for line in [l for m in own for l in m] + [' ...'] + text[-TAIL:]: print(' ' + line[:300]) if pkg_fail: - print('FAIL the test binary reported %d package-level failure(s)' % pkg_fail) + print('FAIL the test binary reported %d package-level failure(s)' % len(pkg_fail)) print('required-tests: %d named, %d not passed, %.1fs in named tests' % (len(names), bad, total)) + if nongating: + print('required-tests: %d non-gating (%s), %d of them failed' % (len(nongating), ', '.join('%s %s' % (n, nongating[n]) for n in names if n in nongating), ng_failed)) return 1 if bad or pkg_fail else 0