From 69cd920b13280ccd97f380eeaeee776a7de86981 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 12:57:02 -0800 Subject: [PATCH 01/27] 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/27] 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/27] 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 ad9ee63491d1ef1e8660a71f32963f3c2c86700b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:15:33 -0800 Subject: [PATCH 04/27] authority: a heartbeat that changes nothing wakes no observation rebuild The observation store wakes a rebuild only when an ingest changes what a snapshot build reads: a new server, a server's facts or freshness, a slot added, removed or changed but for its timestamps, a slot's expiry state, a volume two servers report, or a passed deadline. What changes with time is a deadline: each server's next expiry in a heap, the pending grace's end; the host wakes at the earliest. A published line wakes the build through the publisher's line-change hook. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/authority.go | 17 ++ .../core/authority/observation_changes.go | 174 +++++++++++++ .../authority/observation_changes_test.go | 238 ++++++++++++++++++ .../core/authority/observation_host.go | 31 +++ .../core/authority/observation_store.go | 28 ++- seaweed-block/core/host/master/host.go | 3 + 6 files changed, 490 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/authority/observation_changes.go create mode 100644 seaweed-block/core/authority/observation_changes_test.go diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 30cafb9342..1e9ba83378 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -124,6 +124,9 @@ type Publisher struct { // (SetIncarnationSource); its own lock, never taken under mu. incarnationMu sync.RWMutex incarnationOf func(volumeID, replicaID, dataAddr, ctrlAddr string) string + // lineChanged is told the volume of every published line (the + // observation build reads lines, and no heartbeat carries them). + lineChanged func(volumeID string) mu sync.Mutex state map[subKey]assignmentState @@ -480,6 +483,14 @@ func (p *Publisher) SetIncarnationSource(of func(volumeID, replicaID, dataAddr, p.incarnationMu.Unlock() } +// SetLineChangeHook registers fn, told the volume of every published line +// after the publication (outside the publisher's lock). nil removes it. +func (p *Publisher) SetLineChangeHook(fn func(volumeID string)) { + p.incarnationMu.Lock() + p.lineChanged = fn + p.incarnationMu.Unlock() +} + func (p *Publisher) apply(ask AssignmentAsk) error { if p.publicationAdmission != nil { return p.publicationAdmission(ask, func() error { return p.applyWithWorkspaceMove(ask, nil) }) @@ -751,6 +762,12 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr if p.observer != nil { safeInvokePublishObserver(p.observer, PublishEvent{Info: next, Ask: ask}) } + p.incarnationMu.RLock() + changed := p.lineChanged + p.incarnationMu.RUnlock() + if changed != nil { + changed(ask.VolumeID) + } return nil } diff --git a/seaweed-block/core/authority/observation_changes.go b/seaweed-block/core/authority/observation_changes.go new file mode 100644 index 0000000000..0c499335ee --- /dev/null +++ b/seaweed-block/core/authority/observation_changes.go @@ -0,0 +1,174 @@ +package authority + +import ( + "container/heap" + "reflect" + "time" +) + +// What a snapshot build reads changes only by a heartbeat that changes it, +// by time (a server's or a slot's expiry, the pending grace's end), by a +// published line, or by the topology. A heartbeat that refreshes only +// timestamps changes none of these, so it wakes no rebuild; the time each +// such fact changes is kept as a deadline, and the host wakes then. + +// buildReadsChangedLocked says whether storing next for its server (prev the +// observation it replaces) can change a snapshot build at now: a new server; +// a change of the server's facts or freshness; a slot added, removed, or +// changed in anything but its timestamps; a slot whose expiry state flips; +// or any slot of a volume that another server also reports (a build orders +// such slots by their timestamps, so a refresh can change it). s.mu held. +func (s *ObservationStore) buildReadsChangedLocked(prev Observation, hadPrev bool, next Observation, now time.Time) bool { + if !hadPrev || prev.Server != next.Server || now.After(prev.ExpiresAt) != now.After(next.ExpiresAt) || len(prev.Slots) != len(next.Slots) { + return true + } + before := make(map[string]SlotFact, len(prev.Slots)) + for _, sl := range prev.Slots { + before[slotKey(sl)] = sl + } + for _, sl := range next.Slots { + p, ok := before[slotKey(sl)] + if !ok || !sameSlotContent(p, sl) || slotExpired(p, prev, now) != slotExpired(sl, next, now) { + return true + } + if len(s.volServers[sl.VolumeID]) > 1 { + return true + } + } + return false +} + +// sameSlotContent compares two slot facts but for their timestamps. +func sameSlotContent(a, b SlotFact) bool { + a.ObservedAt, a.ExpiresAt, b.ObservedAt, b.ExpiresAt = time.Time{}, time.Time{}, time.Time{}, time.Time{} + return reflect.DeepEqual(a, b) +} + +// indexServerLocked records which volumes server id reports (prev's slots +// out, next's in). s.mu held. +func (s *ObservationStore) indexServerLocked(id string, prev []SlotFact, next []SlotFact) { + if s.volServers == nil { + s.volServers = map[string]map[string]struct{}{} + } + for _, sl := range prev { + if m := s.volServers[sl.VolumeID]; m != nil { + delete(m, id) + if len(m) == 0 { + delete(s.volServers, sl.VolumeID) + } + } + } + for _, sl := range next { + m := s.volServers[sl.VolumeID] + if m == nil { + m = map[string]struct{}{} + s.volServers[sl.VolumeID] = m + } + m[id] = struct{}{} + } +} + +// nextExpiry is the earliest expiry of obs (its own, or a slot's) not yet +// passed at now; zero when none is ahead. A fact expires once now is after +// its expiry (observation_store.go), so an expiry equal to now is still +// ahead. +func nextExpiry(obs Observation, now time.Time) time.Time { + var at time.Time + consider := func(t time.Time) { + if !t.IsZero() && !now.After(t) && (at.IsZero() || t.Before(at)) { + at = t + } + } + consider(obs.ExpiresAt) + for _, sl := range obs.Slots { + consider(sl.ExpiresAt) + } + return at +} + +// deadlineEntry is one server's next expiry; seq tells a current entry from +// one a later heartbeat replaced (lazy deletion). +type deadlineEntry struct { + at time.Time + server string + seq uint64 +} + +type deadlineHeap []deadlineEntry + +func (h deadlineHeap) Len() int { return len(h) } +func (h deadlineHeap) Less(i, j int) bool { return h[i].at.Before(h[j].at) } +func (h deadlineHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *deadlineHeap) Push(x any) { *h = append(*h, x.(deadlineEntry)) } +func (h *deadlineHeap) Pop() any { + old := *h + e := old[len(old)-1] + *h = old[:len(old)-1] + return e +} + +// scheduleLocked records server id's next expiry after now. s.mu held. +func (s *ObservationStore) scheduleLocked(id string, obs Observation, now time.Time) { + if s.deadlineSeq == nil { + s.deadlineSeq = map[string]uint64{} + } + s.deadlineSeq[id]++ + if at := nextExpiry(obs, now); !at.IsZero() { + heap.Push(&s.deadlines, deadlineEntry{at: at, server: id, seq: s.deadlineSeq[id]}) + } +} + +// NextDeadline is the earliest time a build's input changes with no +// heartbeat: a server's or slot's expiry, or the pending grace's end; zero +// when none is ahead. +func (s *ObservationStore) NextDeadline() time.Time { + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + for s.deadlines.Len() > 0 { + e := s.deadlines[0] + if e.seq == s.deadlineSeq[e.server] { + break + } + heap.Pop(&s.deadlines) // replaced by a later heartbeat + } + var at time.Time + if s.deadlines.Len() > 0 { + at = s.deadlines[0].at + } + if g := s.startedAt.Add(s.config.PendingGrace); g.After(now) && (at.IsZero() || g.Before(at)) { + at = g + } + return at +} + +// ExpireDue reports whether a deadline has passed since the last call (an +// expiry or the pending grace's end: a build's input changed), and moves +// each such server to its next deadline. +func (s *ObservationStore) ExpireDue() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.expireDueLocked(s.now()) +} + +// expireDueLocked is ExpireDue with s.mu held. +func (s *ObservationStore) expireDueLocked(now time.Time) bool { + due := false + for s.deadlines.Len() > 0 && now.After(s.deadlines[0].at) { + e := heap.Pop(&s.deadlines).(deadlineEntry) + if e.seq != s.deadlineSeq[e.server] { + continue + } + due = true + if obs, ok := s.observations[e.server]; ok { + s.scheduleLocked(e.server, obs, now) + } + } + if !s.graceSeen { + if g := s.startedAt.Add(s.config.PendingGrace); !g.After(now) { + s.graceSeen = true + due = true + } + } + return due +} diff --git a/seaweed-block/core/authority/observation_changes_test.go b/seaweed-block/core/authority/observation_changes_test.go new file mode 100644 index 0000000000..29e1b77dc0 --- /dev/null +++ b/seaweed-block/core/authority/observation_changes_test.go @@ -0,0 +1,238 @@ +package authority + +import ( + "context" + "fmt" + "math/rand" + "reflect" + "sync/atomic" + "testing" + "time" +) + +func countingStore(t *testing.T, clk *fakeClock, window time.Duration) (*ObservationStore, *atomic.Int64) { + t.Helper() + s := NewObservationStore(FreshnessConfig{FreshnessWindow: window}, clk.Now) + var wakes atomic.Int64 + s.SetOnMutation(func() { wakes.Add(1) }) + return s, &wakes +} + +func oneSlotObs(server string, at time.Time, slots ...SlotFact) Observation { + return Observation{ServerID: server, ObservedAt: at, Server: ServerFact{Reachable: true, Eligible: true}, Slots: slots} +} + +// A heartbeat that refreshes only timestamps (every volume process sends one +// every 2 s) wakes no rebuild; a changed slot, a new server, or a refresh of +// a volume two servers report does. On main every heartbeat woke a full +// rebuild. +func TestObservationStoreTimestampOnlyRefreshWakesNothing(t *testing.T) { + start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + s, wakes := countingStore(t, clk, 30*time.Second) + const servers = 200 + for i := 0; i < servers; i++ { + if err := s.Ingest(oneSlotObs(fmt.Sprintf("s%03d", i), start, healthySlot(fmt.Sprintf("v%03d", i), "r1"))); err != nil { + t.Fatal(err) + } + } + if wakes.Load() != servers { + t.Fatalf("%d wakes for %d new servers", wakes.Load(), servers) + } + wakes.Store(0) + clk.Advance(2 * time.Second) + for round := 0; round < 3; round++ { + for i := 0; i < 100; i++ { + if err := s.Ingest(oneSlotObs(fmt.Sprintf("s%03d", i), clk.Now(), healthySlot(fmt.Sprintf("v%03d", i), "r1"))); err != nil { + t.Fatal(err) + } + } + clk.Advance(2 * time.Second) + } + if n := wakes.Load(); n != 0 { + t.Fatalf("300 timestamp-only heartbeats woke %d rebuilds, want 0", n) + } + changed := healthySlot("v007", "r1") + changed.ReadyForPrimary = false + if err := s.Ingest(oneSlotObs("s007", clk.Now(), changed)); err != nil { + t.Fatal(err) + } + if n := wakes.Load(); n != 1 { + t.Fatalf("a changed slot woke %d rebuilds, want 1", n) + } + // A volume two servers report: a refresh of either wakes. + if err := s.Ingest(oneSlotObs("s900", clk.Now(), healthySlot("v008", "r2"))); err != nil { + t.Fatal(err) + } + wakes.Store(0) + if err := s.Ingest(oneSlotObs("s008", clk.Now(), healthySlot("v008", "r1"))); err != nil { + t.Fatal(err) + } + if n := wakes.Load(); n != 1 { + t.Fatalf("a refresh of a volume two servers report woke %d rebuilds, want 1", n) + } +} + +// What changes with time wakes the host at its deadline, with no heartbeat: +// a server whose heartbeats stop is seen expired once its freshness window +// passes. +func TestObservationHostRebuildsAtAnExpiryWithNoHeartbeat(t *testing.T) { + start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: 100 * time.Millisecond}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Now: clk.Now, + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host.Start(ctx) + defer host.Stop() + _ = host.IngestHeartbeat(serverObs("s1", start, healthySlot("v1", "r1"))) + waitFor := func(what string, ok func(BuildResult) bool) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + if b, have := host.LastBuild(); have && ok(b) { + return + } + time.Sleep(10 * time.Millisecond) + } + b, _ := host.LastBuild() + t.Fatalf("%s: last build at %v with %d servers", what, b.BuiltAt, len(b.Snapshot.Servers)) + } + waitFor("the heartbeat's build", func(b BuildResult) bool { return len(b.Snapshot.Servers) == 1 }) + clk.Advance(time.Second) // past s1's freshness; no heartbeat follows + waitFor("the expiry's build", func(b BuildResult) bool { return len(b.Snapshot.Servers) == 0 && b.BuiltAt.Equal(clk.Now()) }) +} + +// normalizedBuild is a build with its stamps cleared: when it was built, the +// store revision, and the timestamps the evidence carries. +func normalizedBuild(b BuildResult) BuildResult { + b.BuiltAt, b.InputRev = time.Time{}, 0 + b.Snapshot.CollectedAt, b.Snapshot.CollectedRevision = time.Time{}, 0 + vols := make([]VolumeTopologySnapshot, len(b.Snapshot.Volumes)) + for i, v := range b.Snapshot.Volumes { + v.Slots = append([]ReplicaCandidate(nil), v.Slots...) + for j := range v.Slots { + v.Slots[j].ObservedAt = time.Time{} + } + vols[i] = v + } + b.Snapshot.Volumes = vols + pend := map[string]VolumePendingStatus{} + for k, v := range b.Report.Pending { + v.EvaluatedAt = time.Time{} + pend[k] = v + } + b.Report.Pending = pend + uns := map[string]VolumeUnsupportedEvidence{} + for k, v := range b.Report.Unsupported { + v.EvaluatedAt, v.SnapshotRevision = time.Time{}, 0 + facts := make([]Observation, len(v.OffendingFacts)) + for i, o := range v.OffendingFacts { + o.ObservedAt, o.ExpiresAt = time.Time{}, time.Time{} + o.Slots = append([]SlotFact(nil), o.Slots...) + for j := range o.Slots { + o.Slots[j].ObservedAt, o.Slots[j].ExpiresAt = time.Time{}, time.Time{} + } + facts[i] = o + } + v.OffendingFacts = facts + uns[k] = v + } + b.Report.Unsupported = uns + return b +} + +// Whenever the store reports no change (no wake, no passed deadline), a +// build now equals the last build, but for its stamps: random heartbeats +// (new, changed, timestamp-only, of a shared volume), time steps past +// freshness windows and the pending grace, and GC. +func TestObservationStoreNoWakeMeansTheSameBuild(t *testing.T) { + topo := AcceptedTopology{Volumes: []VolumeExpected{ + {VolumeID: "va", Slots: []ExpectedSlot{{ReplicaID: "r1", ServerID: "s1"}}}, + {VolumeID: "vb", Slots: []ExpectedSlot{{ReplicaID: "r1", ServerID: "s2"}}}, + threeSlotVolume("vc"), + }} + for seed := int64(1); seed <= 300; seed++ { + rng := rand.New(rand.NewSource(seed)) + start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + s := NewObservationStore(FreshnessConfig{FreshnessWindow: 5 * time.Second, PendingGrace: 7 * time.Second}, clk.Now) + var woke bool + s.SetOnMutation(func() { woke = true }) + last := BuildSnapshot(s.Snapshot(), topo, nil) + s.ExpireDue() + reports := map[string][]SlotFact{ + "s1": {healthySlot("va", "r1"), healthySlot("vc", "r1")}, + "s2": {healthySlot("vb", "r1"), healthySlot("vc", "r2")}, + "s3": {healthySlot("vc", "r3")}, + "s4": {healthySlot("vx", "r1")}, + } + names := []string{"s1", "s2", "s3", "s4"} + for step := 0; step < 300; step++ { + woke = false + switch rng.Intn(7) { + case 0, 1, 2: // a heartbeat, maybe with a change + srv := names[rng.Intn(len(names))] + slots := append([]SlotFact(nil), reports[srv]...) + if rng.Intn(4) == 0 { + i := rng.Intn(len(slots)) + slots[i].ReadyForPrimary = !slots[i].ReadyForPrimary + reports[srv] = slots + } + obs := oneSlotObs(srv, clk.Now(), slots...) + if rng.Intn(8) == 0 { + obs.Server.Eligible = false + } + _ = s.Ingest(obs) + case 3: // time passes + clk.Advance(time.Duration(rng.Intn(4000)) * time.Millisecond) + case 4: // the host's timer + if s.ExpireDue() { + woke = true + } + case 5: + s.GC(time.Duration(rng.Intn(20)) * time.Second) + case 6: // exactly at the next deadline, or just past it + if at := s.NextDeadline(); !at.IsZero() { + clk.Set(at.Add(time.Duration(rng.Intn(2)))) + } + } + if s.ExpireDue() { // a deadline passed: the host's timer would wake + woke = true + } + now := BuildSnapshot(s.Snapshot(), topo, nil) + if woke { + last = now + continue + } + if !reflect.DeepEqual(normalizedBuild(now), normalizedBuild(last)) { + t.Fatalf("seed %d step %d: the store reported no change, but the build changed:\nlast %+v\nnow %+v", seed, step, normalizedBuild(last), normalizedBuild(now)) + } + } + } +} + +// A published line wakes the observation build (no heartbeat carries it): +// the publisher tells its line-change hook the volume of every publication, +// and only of a publication. +func TestPublisherTellsItsLineChangeHook(t *testing.T) { + var told []string + pub := NewPublisher(NewStaticDirective(nil)) + pub.SetLineChangeHook(func(v string) { told = append(told, v) }) + ask := AssignmentAsk{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind} + if err := pub.apply(ask); err != nil { + t.Fatal(err) + } + if len(told) != 1 || told[0] != "v1" { + t.Fatalf("hook told %v after one publication, want [v1]", told) + } + if err := pub.apply(ask); err == nil { + t.Fatal("a second bind was accepted") + } + if len(told) != 1 { + t.Fatalf("hook told %v after a refused ask", told) + } +} diff --git a/seaweed-block/core/authority/observation_host.go b/seaweed-block/core/authority/observation_host.go index 8748df39f0..1d1850f6df 100644 --- a/seaweed-block/core/authority/observation_host.go +++ b/seaweed-block/core/authority/observation_host.go @@ -116,6 +116,11 @@ func NewObservationHost(cfg ObservationHostConfig) *ObservationHost { return h } +// Wake asks for a rebuild: a change a build reads that no heartbeat +// carries (a published authority line, a topology change). Non-blocking; +// wakes coalesce. +func (h *ObservationHost) Wake() { h.signalRebuild() } + // Store returns the underlying store. Exposed for tests and for // downstream diagnosis; the host does not expect external code // to manipulate it beyond Ingest. @@ -221,14 +226,40 @@ func (h *ObservationHost) run(ctx context.Context) { h.rebuildOnce() for { + // A heartbeat that refreshes only timestamps wakes nothing; what + // changes with time (an expiry, the pending grace's end) wakes the + // loop at its deadline. + var deadlineC <-chan time.Time + var timer *time.Timer + if at := h.store.NextDeadline(); !at.IsZero() { + d := at.Sub(h.store.now()) + if d < 10*time.Millisecond { + d = 10 * time.Millisecond + } + timer = time.NewTimer(d) + deadlineC = timer.C + } + stopTimer := func() { + if timer != nil { + timer.Stop() + } + } select { case <-ctx.Done(): + stopTimer() return case <-h.stop: + stopTimer() return case <-h.wake: + stopTimer() h.rebuildOnce() + case <-deadlineC: + if h.store.ExpireDue() { + h.rebuildOnce() + } case <-gcC: + stopTimer() h.store.GC(h.gcRetain) // GC may have set the mutation flag; that is OK — the // next iteration will pick up the wake. diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index 4283ff4f82..12f26fb460 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -36,6 +36,15 @@ type ObservationStore struct { revision uint64 onMutation func() + // volServers: the servers reporting a slot of each volume (a volume + // two servers report is ordered by timestamps in a build). + volServers map[string]map[string]struct{} + // deadlines: each server's next expiry (lazily replaced: deadlineSeq); + // graceSeen: the pending grace's end was reported (observation_changes.go). + deadlines deadlineHeap + deadlineSeq map[string]uint64 + graceSeen bool + // supersededCount counts slot reports that were dropped because a // newer ObservedAt was stored for that server/volume/replica slot. // Diagnostic only — PCDD-DELAYED-HB-001 evidence @@ -377,9 +386,22 @@ func (s *ObservationStore) ingest(obs Observation) ([]SlotHealthTransition, erro obs.ObservedAt, obs.ExpiresAt, obs.Server = prev.ObservedAt, prev.ExpiresAt, prev.Server } } + now := s.now() + // A deadline passed since the last build is a change too (the build a + // heartbeat wakes then sees the expiry, as before). + changed := s.expireDueLocked(now) + if s.buildReadsChangedLocked(prev, hadPrev, obs, now) { + changed = true + } + s.indexServerLocked(obs.ServerID, prev.Slots, obs.Slots) + s.scheduleLocked(obs.ServerID, obs, now) s.observations[obs.ServerID] = obs s.revision++ - fn = s.onMutation + if changed { + // A heartbeat that refreshes only timestamps wakes no rebuild: its + // expiry is a deadline (NextDeadline) the host wakes at. + fn = s.onMutation + } s.mu.Unlock() if fn != nil { @@ -561,6 +583,10 @@ func (s *ObservationStore) GC(retain time.Duration) int { for id, obs := range s.observations { if now.Sub(obs.ObservedAt) > retain { delete(s.observations, id) + s.indexServerLocked(id, obs.Slots, nil) + if s.deadlineSeq != nil { + s.deadlineSeq[id]++ // its pending deadline is void + } removed++ } } diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index ef00e39956..743de83b35 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -298,6 +298,9 @@ func New(cfg Config) (*Host, error) { Sink: sink, Reader: boot.Publisher, }) + // A published line changes what the observation build reads, and no + // heartbeat carries it: it wakes the build. + boot.Publisher.SetLineChangeHook(func(string) { obs.Wake() }) // An ask built outside the controller (a heal, a planned or workspace // move, an operator's request) is issued for the process its target // reports now. From 75bb94c46dc06bd53bf22557d012819d8c7606d0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:31:26 -0800 Subject: [PATCH 05/27] authority: the grace's end stays a deadline until consumed; the master's line wake is pinned NextDeadline keeps the pending grace's end until ExpireDue reports it, even once past, so a build taken just before it and submitted just after it is rebuilt with no heartbeat. The property test now fires the host's timer only at NextDeadline, so a dropped deadline shows. A master test pins the line-change wiring: a volume reported once is bound by the controller and the next build carries the line. Comments that promised a wake on every ingest now say what wakes. Co-Authored-By: Claude Opus 5.5 --- .../core/authority/observation_changes.go | 11 ++-- .../authority/observation_changes_test.go | 64 +++++++++++++++++-- .../core/authority/observation_host.go | 8 ++- .../core/authority/observation_store.go | 4 +- .../core/host/master/line_change_wake_test.go | 58 +++++++++++++++++ 5 files changed, 133 insertions(+), 12 deletions(-) create mode 100644 seaweed-block/core/host/master/line_change_wake_test.go diff --git a/seaweed-block/core/authority/observation_changes.go b/seaweed-block/core/authority/observation_changes.go index 0c499335ee..94e6f1a901 100644 --- a/seaweed-block/core/authority/observation_changes.go +++ b/seaweed-block/core/authority/observation_changes.go @@ -119,12 +119,12 @@ func (s *ObservationStore) scheduleLocked(id string, obs Observation, now time.T } // NextDeadline is the earliest time a build's input changes with no -// heartbeat: a server's or slot's expiry, or the pending grace's end; zero -// when none is ahead. +// heartbeat and ExpireDue has not reported yet: a server's or slot's expiry, +// or the pending grace's end (possibly already past); zero when none is +// left. func (s *ObservationStore) NextDeadline() time.Time { s.mu.Lock() defer s.mu.Unlock() - now := s.now() for s.deadlines.Len() > 0 { e := s.deadlines[0] if e.seq == s.deadlineSeq[e.server] { @@ -136,7 +136,10 @@ func (s *ObservationStore) NextDeadline() time.Time { if s.deadlines.Len() > 0 { at = s.deadlines[0].at } - if g := s.startedAt.Add(s.config.PendingGrace); g.After(now) && (at.IsZero() || g.Before(at)) { + // The grace's end stays a deadline until ExpireDue reports it, even once + // past: a build taken just before it, with the host's next look just + // after it, must still be rebuilt. + if g := s.startedAt.Add(s.config.PendingGrace); !s.graceSeen && (at.IsZero() || g.Before(at)) { at = g } return at diff --git a/seaweed-block/core/authority/observation_changes_test.go b/seaweed-block/core/authority/observation_changes_test.go index 29e1b77dc0..c48b97e55c 100644 --- a/seaweed-block/core/authority/observation_changes_test.go +++ b/seaweed-block/core/authority/observation_changes_test.go @@ -189,9 +189,9 @@ func TestObservationStoreNoWakeMeansTheSameBuild(t *testing.T) { _ = s.Ingest(obs) case 3: // time passes clk.Advance(time.Duration(rng.Intn(4000)) * time.Millisecond) - case 4: // the host's timer - if s.ExpireDue() { - woke = true + case 4: // time passes to the next deadline the host would wake at + if at := s.NextDeadline(); !at.IsZero() { + clk.Set(at.Add(time.Millisecond)) } case 5: s.GC(time.Duration(rng.Intn(20)) * time.Second) @@ -200,7 +200,9 @@ func TestObservationStoreNoWakeMeansTheSameBuild(t *testing.T) { clk.Set(at.Add(time.Duration(rng.Intn(2)))) } } - if s.ExpireDue() { // a deadline passed: the host's timer would wake + // The host's timer: it fires at NextDeadline (a deadline NextDeadline + // leaves out never fires). + if at := s.NextDeadline(); !at.IsZero() && !at.After(clk.Now()) && s.ExpireDue() { woke = true } now := BuildSnapshot(s.Snapshot(), topo, nil) @@ -236,3 +238,57 @@ func TestPublisherTellsItsLineChangeHook(t *testing.T) { t.Fatalf("hook told %v after a refused ask", told) } } + +// submitHook is a sink that runs a function at each submission (the +// submission is where a real build can cross a deadline). +type submitHook struct { + recordingSink + on func(n int) + n int +} + +func (s *submitHook) SubmitObservedState(snap ClusterSnapshot, report SupportabilityReport) error { + s.n++ + if s.on != nil { + s.on(s.n) + } + return s.recordingSink.SubmitObservedState(snap, report) +} + +// The pending grace's end is rebuilt even when a build taken just before it +// is submitted just after it, with no heartbeat ever arriving: the deadline +// stays until it is consumed. +func TestObservationHostRebuildsAfterTheGraceCrossedDuringASubmission(t *testing.T) { + start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + grace := 100 * time.Millisecond + sink := &submitHook{} + sink.on = func(n int) { + if n == 1 { + clk.Set(start.Add(grace + time.Millisecond)) // the first build crosses the grace's end + } + } + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: time.Hour, PendingGrace: grace}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Sink: sink, + Now: clk.Now, + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host.Start(ctx) + defer host.Stop() + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + if b, ok := host.LastBuild(); ok { + if _, pending := b.Report.Pending["v1"]; !pending { + if _, unsupported := b.Report.Unsupported["v1"]; unsupported { + return + } + } + } + time.Sleep(10 * time.Millisecond) + } + b, _ := host.LastBuild() + t.Fatalf("v1 is still pending past the grace with no heartbeat: pending %v, unsupported %v", b.Report.Pending, b.Report.Unsupported) +} diff --git a/seaweed-block/core/authority/observation_host.go b/seaweed-block/core/authority/observation_host.go index 1d1850f6df..3dbbc81085 100644 --- a/seaweed-block/core/authority/observation_host.go +++ b/seaweed-block/core/authority/observation_host.go @@ -16,9 +16,11 @@ import ( // Institution logic lives here, not in cmd/sparrow. The cmd // layer is only allowed to construct, start, and stop the host. // -// Default operation is build-on-change (sketch §11): every -// successful Ingest fires a non-blocking signal that wakes the -// rebuild goroutine. The goroutine drains the signal, takes one +// Default operation is build-on-change (sketch §11): an Ingest +// that changes what a build reads (observation_changes.go), a +// deadline passing (an expiry, the pending grace's end) or Wake (a +// published line) wakes the rebuild goroutine; a heartbeat that +// refreshes only timestamps does not. The goroutine drains the signal, takes one // store snapshot, runs BuildSnapshot, and hands the // ClusterSnapshot to the controller's SubmitClusterSnapshot. // Pending / Unsupported volumes are surfaced via the last diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index 12f26fb460..0081267ef4 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -246,7 +246,9 @@ func NewObservationStore(config FreshnessConfig, now func() time.Time) *Observat } // SetOnMutation registers a callback that fires whenever a -// successful ingest changes store contents. The callback must +// successful ingest changes what a snapshot build reads (not on a +// heartbeat that refreshes only timestamps; GC removing an entry fires it +// too). The callback must // NOT block; typical use is a non-blocking signal into the host's // rebuild goroutine. // diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go new file mode 100644 index 0000000000..5929ddadfb --- /dev/null +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -0,0 +1,58 @@ +package master + +import ( + "runtime" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" +) + +// A published line wakes the observation build, through the master's +// wiring of the publisher's line-change hook: a volume reported once (no +// heartbeat follows) is bound by the controller, and the next build carries +// that line. Timestamp-only heartbeats wake nothing, so without the wiring +// the build would keep the unbound basis until some unrelated change. +func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the lifecycle stores need directory fsync") + } + h, err := New(Config{ + AuthorityStoreDir: t.TempDir(), + LifecycleStoreDir: t.TempDir(), + Listen: "127.0.0.1:0", + // No expiry and no GC wake within the test. + Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour}, + Topology: authority.AcceptedTopology{Volumes: []authority.VolumeExpected{{ + VolumeID: "v1", + Slots: []authority.ExpectedSlot{{ReplicaID: "r1", ServerID: "node-a"}}, + }}}, + }) + if err != nil { + t.Fatal(err) + } + h.Start() + defer closeTestMaster(t, h) + if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ + ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, + Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, + }); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { + if b, have := h.obs.LastBuild(); have { + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { + return + } + } + } + } + time.Sleep(20 * time.Millisecond) + } + line, ok := h.Publisher().VolumeAuthorityLine("v1") + b, _ := h.obs.LastBuild() + t.Fatalf("published line %+v (%v), but the last build's volumes are %+v", line, ok, b.Snapshot.Volumes) +} From 1cb5e0e124fbcef3a3c6df84d691f1ec941983c7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:36:48 -0800 Subject: [PATCH 06/27] master: the line-wake test orders its builds so only the hook can wake the last The test now drains the initial build and the grace's rebuild before the one heartbeat, whose single wake is consumed by the build showing v1 supported; the controller binds after it, and with no heartbeat, expiry or GC tick left, the build carrying the line can only come from the hook. Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/line_change_wake_test.go | 64 +++++++++++++------ 1 file changed, 44 insertions(+), 20 deletions(-) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 5929ddadfb..6f07a6bb50 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -9,10 +9,16 @@ import ( ) // A published line wakes the observation build, through the master's -// wiring of the publisher's line-change hook: a volume reported once (no -// heartbeat follows) is bound by the controller, and the next build carries -// that line. Timestamp-only heartbeats wake nothing, so without the wiring -// the build would keep the unbound basis until some unrelated change. +// wiring of the publisher's line-change hook. The order is made +// deterministic so no other wake can stand in for the hook: +// - the master starts with nothing ingested; its initial build runs, and +// the 1 ms pending grace's deadline is consumed (its rebuild runs too); +// - after the builds drain, one heartbeat is ingested: its single wake is +// consumed by one build whose snapshot already holds it (the snapshot is +// taken after the wake is received), showing v1 supported and unbound; +// - the controller binds v1 after that build. No heartbeat follows, no +// expiry is due (a one-hour window), and there is no GC tick: a later +// build carrying the line can only come from the hook. func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("the lifecycle stores need directory fsync") @@ -21,8 +27,7 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", - // No expiry and no GC wake within the test. - Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour}, + Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour, PendingGrace: time.Millisecond}, Topology: authority.AcceptedTopology{Volumes: []authority.VolumeExpected{{ VolumeID: "v1", Slots: []authority.ExpectedSlot{{ReplicaID: "r1", ServerID: "node-a"}}, @@ -33,26 +38,45 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } h.Start() defer closeTestMaster(t, h) + waitBuild := func(what string, ok func(authority.BuildResult) bool) authority.BuildResult { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if b, have := h.obs.LastBuild(); have && ok(b) { + return b + } + time.Sleep(10 * time.Millisecond) + } + b, _ := h.obs.LastBuild() + t.Fatalf("%s: last build %+v", what, b.Snapshot.Volumes) + return authority.BuildResult{} + } + waitBuild("the initial build", func(authority.BuildResult) bool { return true }) + time.Sleep(300 * time.Millisecond) // the grace's deadline fires and its rebuild drains if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, }); err != nil { t.Fatal(err) } - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { - if b, have := h.obs.LastBuild(); have { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { - return - } - } + waitBuild("the heartbeat's build (v1 supported)", func(b authority.BuildResult) bool { + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" { + return true } } - time.Sleep(20 * time.Millisecond) - } - line, ok := h.Publisher().VolumeAuthorityLine("v1") - b, _ := h.obs.LastBuild() - t.Fatalf("published line %+v (%v), but the last build's volumes are %+v", line, ok, b.Snapshot.Volumes) + return false + }) + waitBuild("the build after the controller's publication", func(b authority.BuildResult) bool { + line, ok := h.Publisher().VolumeAuthorityLine("v1") + if !ok || !line.Assigned { + return false + } + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { + return true + } + } + return false + }) } From 2caed63f04d05b3b20927e0c19858e5d5ec01bea Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:41:47 -0800 Subject: [PATCH 07/27] master: the line-wake test waits on a settled observation host, not a sleep ObservationHost.BuildsForTest reports the builds completed and whether a wake is buffered or a build is running. The test settles the host before the heartbeat, requires the heartbeat's build to be a new one, settles again after the controller's publication, and then requires the line in a build after that point (or in the settled last build, which can only have come after the publication). Co-Authored-By: Claude Opus 5.5 --- .../core/authority/observation_host.go | 21 ++++++- .../core/host/master/line_change_wake_test.go | 61 +++++++++++++++---- 2 files changed, 68 insertions(+), 14 deletions(-) diff --git a/seaweed-block/core/authority/observation_host.go b/seaweed-block/core/authority/observation_host.go index 3dbbc81085..301a271be4 100644 --- a/seaweed-block/core/authority/observation_host.go +++ b/seaweed-block/core/authority/observation_host.go @@ -3,6 +3,7 @@ package authority import ( "context" "sync" + "sync/atomic" "time" ) @@ -57,8 +58,12 @@ type ObservationHost struct { sink ControllerSink reader AuthorityBasisReader - mu sync.Mutex - lastBuild *BuildResult + mu sync.Mutex + lastBuild *BuildResult + // builds counts completed rebuilds and building is set while one runs + // (BuildsForTest). + builds atomic.Uint64 + building atomic.Bool sinkErrors []error wake chan struct{} @@ -118,6 +123,13 @@ func NewObservationHost(cfg ObservationHostConfig) *ObservationHost { return h } +// BuildsForTest reports the rebuilds completed and whether the host is +// settled (no wake buffered, no rebuild running), so a test can order a +// change after every earlier build. Production code MUST NOT call this. +func (h *ObservationHost) BuildsForTest() (builds uint64, settled bool) { + return h.builds.Load(), len(h.wake) == 0 && !h.building.Load() +} + // Wake asks for a rebuild: a change a build reads that no heartbeat // carries (a published authority line, a topology change). Non-blocking; // wakes coalesce. @@ -281,6 +293,11 @@ func (h *ObservationHost) run(ctx context.Context) { // AND no report entries is a genuine no-op (e.g. start-up // before any ingest) and is skipped. func (h *ObservationHost) rebuildOnce() { + h.building.Store(true) + defer func() { + h.builds.Add(1) + h.building.Store(false) + }() snap := h.store.Snapshot() result := BuildSnapshot(snap, h.topology, h.reader) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 6f07a6bb50..347f75b417 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -38,28 +38,47 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } h.Start() defer closeTestMaster(t, h) - waitBuild := func(what string, ok func(authority.BuildResult) bool) authority.BuildResult { + // settle waits until no wake is buffered and no rebuild runs, twice in a + // row with the same count (a deadline timer could fire in between), and + // returns the count. + settle := func(what string) uint64 { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { - if b, have := h.obs.LastBuild(); have && ok(b) { - return b + n1, ok1 := h.obs.BuildsForTest() + time.Sleep(50 * time.Millisecond) + n2, ok2 := h.obs.BuildsForTest() + if ok1 && ok2 && n1 == n2 && n1 > 0 { + return n2 + } + } + t.Fatalf("%s: the observation host did not settle", what) + return 0 + } + waitAfter := func(what string, after uint64, ok func(authority.BuildResult) bool) uint64 { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + n, _ := h.obs.BuildsForTest() + if b, have := h.obs.LastBuild(); have && n > after && ok(b) { + return n } time.Sleep(10 * time.Millisecond) } b, _ := h.obs.LastBuild() - t.Fatalf("%s: last build %+v", what, b.Snapshot.Volumes) - return authority.BuildResult{} + t.Fatalf("%s: no build after #%d satisfied it; last build %+v", what, after, b.Snapshot.Volumes) + return 0 } - waitBuild("the initial build", func(authority.BuildResult) bool { return true }) - time.Sleep(300 * time.Millisecond) // the grace's deadline fires and its rebuild drains + // The initial build and the 1 ms grace's rebuild, drained. + before := settle("startup") if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, }); err != nil { t.Fatal(err) } - waitBuild("the heartbeat's build (v1 supported)", func(b authority.BuildResult) bool { + // The heartbeat's build: a new build, v1 supported. + waitAfter("the heartbeat's build", before, func(b authority.BuildResult) bool { for _, v := range b.Snapshot.Volumes { if v.VolumeID == "v1" { return true @@ -67,11 +86,29 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } return false }) - waitBuild("the build after the controller's publication", func(b authority.BuildResult) bool { - line, ok := h.Publisher().VolumeAuthorityLine("v1") - if !ok || !line.Assigned { - return false + // The controller binds v1; its publication is the only wake left. + for wait := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) { + if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { + break } + if time.Now().After(wait) { + t.Fatal("the controller did not bind v1") + } + } + line, _ := h.Publisher().VolumeAuthorityLine("v1") + // Settled again: any build the heartbeat's wake caused has run. If the + // last build already carries the line, it came after the publication, + // so from the hook (the heartbeat's single wake was consumed by a build + // that saw no line); otherwise a later build must bring it. + settled := settle("after the publication") + if b, have := h.obs.LastBuild(); have { + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { + return + } + } + } + waitAfter("the build after the publication", settled, func(b authority.BuildResult) bool { for _, v := range b.Snapshot.Volumes { if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { return true From db7f6530a3c43322e8451ef8d84218d68e6da960 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:48:58 -0800 Subject: [PATCH 08/27] authority: a counter handshake orders the master's line-wake test The observation host counts the rebuilds it takes (in the step that takes the wake) and the rebuilds it finishes, and records when its armed deadline timer fires, all under its lock; BuildsForTest returns them with whether a wake is buffered. The master test settles on started == done with no buffered wake and no timer due, records N, ingests one heartbeat (build N+1, v1 supported and unbound), and after the controller's publication requires build N+2 to carry the line: only the hook can take it. Co-Authored-By: Claude Opus 5.5 --- .../core/authority/observation_host.go | 49 +++++++++---- .../core/host/master/line_change_wake_test.go | 70 ++++++++----------- 2 files changed, 66 insertions(+), 53 deletions(-) diff --git a/seaweed-block/core/authority/observation_host.go b/seaweed-block/core/authority/observation_host.go index 301a271be4..d1d851bbe7 100644 --- a/seaweed-block/core/authority/observation_host.go +++ b/seaweed-block/core/authority/observation_host.go @@ -3,7 +3,6 @@ package authority import ( "context" "sync" - "sync/atomic" "time" ) @@ -60,11 +59,12 @@ type ObservationHost struct { mu sync.Mutex lastBuild *BuildResult - // builds counts completed rebuilds and building is set while one runs - // (BuildsForTest). - builds atomic.Uint64 - building atomic.Bool - sinkErrors []error + // buildsStarted counts rebuilds the loop took (in the step that takes + // their wake), buildsDone the rebuilds finished, timerAt when the armed deadline + // timer fires (zero: none); all under mu (BuildsForTest). + buildsStarted, buildsDone uint64 + timerAt time.Time + sinkErrors []error wake chan struct{} stop chan struct{} @@ -123,11 +123,22 @@ func NewObservationHost(cfg ObservationHostConfig) *ObservationHost { return h } -// BuildsForTest reports the rebuilds completed and whether the host is -// settled (no wake buffered, no rebuild running), so a test can order a -// change after every earlier build. Production code MUST NOT call this. -func (h *ObservationHost) BuildsForTest() (builds uint64, settled bool) { - return h.builds.Load(), len(h.wake) == 0 && !h.building.Load() +// BuildsForTest reports, under one lock, the rebuilds the loop took and +// finished, whether a wake is buffered, and when the armed deadline timer +// fires (zero: none), so a test can order a change after every earlier +// build. Production code MUST NOT call this. +func (h *ObservationHost) BuildsForTest() (started, done uint64, wakeBuffered bool, timerAt time.Time) { + h.mu.Lock() + defer h.mu.Unlock() + return h.buildsStarted, h.buildsDone, len(h.wake) > 0, h.timerAt +} + +// takeBuild counts a rebuild the loop takes, in the step that takes it. +func (h *ObservationHost) takeBuild() { + h.mu.Lock() + h.buildsStarted++ + h.timerAt = time.Time{} + h.mu.Unlock() } // Wake asks for a rebuild: a change a build reads that no heartbeat @@ -237,6 +248,7 @@ func (h *ObservationHost) run(ctx context.Context) { // First build on start — so consumers see an initial empty // snapshot rather than waiting for the first ingest. + h.takeBuild() h.rebuildOnce() for { @@ -252,6 +264,9 @@ func (h *ObservationHost) run(ctx context.Context) { } timer = time.NewTimer(d) deadlineC = timer.C + h.mu.Lock() + h.timerAt = time.Now().Add(d) + h.mu.Unlock() } stopTimer := func() { if timer != nil { @@ -267,10 +282,16 @@ func (h *ObservationHost) run(ctx context.Context) { return case <-h.wake: stopTimer() + h.takeBuild() h.rebuildOnce() case <-deadlineC: if h.store.ExpireDue() { + h.takeBuild() h.rebuildOnce() + } else { + h.mu.Lock() + h.timerAt = time.Time{} + h.mu.Unlock() } case <-gcC: stopTimer() @@ -293,10 +314,10 @@ func (h *ObservationHost) run(ctx context.Context) { // AND no report entries is a genuine no-op (e.g. start-up // before any ingest) and is skipped. func (h *ObservationHost) rebuildOnce() { - h.building.Store(true) defer func() { - h.builds.Add(1) - h.building.Store(false) + h.mu.Lock() + h.buildsDone++ + h.mu.Unlock() }() snap := h.store.Snapshot() result := BuildSnapshot(snap, h.topology, h.reader) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 347f75b417..3e9d47fef5 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -38,47 +38,57 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } h.Start() defer closeTestMaster(t, h) - // settle waits until no wake is buffered and no rebuild runs, twice in a - // row with the same count (a deadline timer could fire in between), and - // returns the count. + // settle waits until every build the loop took has finished, no wake is + // buffered and no deadline timer fires within the test (the one-hour + // expiry timer stays armed), all read under the host's lock; it returns + // the builds done. settle := func(what string) uint64 { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { - n1, ok1 := h.obs.BuildsForTest() - time.Sleep(50 * time.Millisecond) - n2, ok2 := h.obs.BuildsForTest() - if ok1 && ok2 && n1 == n2 && n1 > 0 { - return n2 + started, done, buffered, timerAt := h.obs.BuildsForTest() + if started == done && done > 0 && !buffered && (timerAt.IsZero() || timerAt.After(time.Now().Add(time.Minute))) { + return done } + time.Sleep(10 * time.Millisecond) } t.Fatalf("%s: the observation host did not settle", what) return 0 } - waitAfter := func(what string, after uint64, ok func(authority.BuildResult) bool) uint64 { + waitDone := func(what string, n uint64, ok func(authority.BuildResult) bool) { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { - n, _ := h.obs.BuildsForTest() - if b, have := h.obs.LastBuild(); have && n > after && ok(b) { - return n + _, done, _, _ := h.obs.BuildsForTest() + if b, have := h.obs.LastBuild(); have && done >= n && ok(b) { + return } time.Sleep(10 * time.Millisecond) } b, _ := h.obs.LastBuild() - t.Fatalf("%s: no build after #%d satisfied it; last build %+v", what, after, b.Snapshot.Volumes) - return 0 + t.Fatalf("%s: no build #%d satisfied it; last build %+v", what, n, b.Snapshot.Volumes) } - // The initial build and the 1 ms grace's rebuild, drained. - before := settle("startup") + carriesLine := func(epoch uint64) func(authority.BuildResult) bool { + return func(b authority.BuildResult) bool { + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == epoch { + return true + } + } + return false + } + } + // The initial build and the 1 ms grace's rebuild, finished. + n := settle("startup") if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, }); err != nil { t.Fatal(err) } - // The heartbeat's build: a new build, v1 supported. - waitAfter("the heartbeat's build", before, func(b authority.BuildResult) bool { + // The heartbeat's one build (#n+1) shows v1 supported and unbound: the + // controller binds only after it. + waitDone("the heartbeat's build", n+1, func(b authority.BuildResult) bool { for _, v := range b.Snapshot.Volumes { if v.VolumeID == "v1" { return true @@ -86,7 +96,6 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } return false }) - // The controller binds v1; its publication is the only wake left. for wait := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) { if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { break @@ -96,24 +105,7 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } } line, _ := h.Publisher().VolumeAuthorityLine("v1") - // Settled again: any build the heartbeat's wake caused has run. If the - // last build already carries the line, it came after the publication, - // so from the hook (the heartbeat's single wake was consumed by a build - // that saw no line); otherwise a later build must bring it. - settled := settle("after the publication") - if b, have := h.obs.LastBuild(); have { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { - return - } - } - } - waitAfter("the build after the publication", settled, func(b authority.BuildResult) bool { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { - return true - } - } - return false - }) + // Every build after the heartbeat's was taken after the publication (no + // other wake was left): the hook's. One must come and carry the line. + waitDone("the hook's build", n+2, carriesLine(line.Epoch)) } From d17696d1ea4e45604a35d892ebb6e8a31b76a088 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:52:35 -0800 Subject: [PATCH 09/27] master: the line-wake test waits for the grace's rebuild (build 2) before the heartbeat Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/line_change_wake_test.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 3e9d47fef5..44fbc9c9f4 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -42,12 +42,12 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { // buffered and no deadline timer fires within the test (the one-hour // expiry timer stays armed), all read under the host's lock; it returns // the builds done. - settle := func(what string) uint64 { + settle := func(what string, atLeast uint64) uint64 { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { started, done, buffered, timerAt := h.obs.BuildsForTest() - if started == done && done > 0 && !buffered && (timerAt.IsZero() || timerAt.After(time.Now().Add(time.Minute))) { + if started == done && done >= atLeast && !buffered && (timerAt.IsZero() || timerAt.After(time.Now().Add(time.Minute))) { return done } time.Sleep(10 * time.Millisecond) @@ -78,8 +78,10 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { return false } } - // The initial build and the 1 ms grace's rebuild, finished. - n := settle("startup") + // The initial build (#1) and the 1 ms grace's rebuild (#2, with nothing + // ingested yet) both finished: the grace's deadline is consumed, so no + // timer can arm after this point and see the heartbeat. + n := settle("startup", 2) if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, From 9f823870477a73a2809069392ad659f29e975436 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 14:23:58 -0800 Subject: [PATCH 10/27] master: the line-wake test publishes by the product tick it runs itself The controller never bound a once-reported static volume on Linux, so the test now creates and places a volume through the lifecycle, ingests its holder's heartbeat, settles the observation host (started == done, no buffered wake, no timer due), runs the product tick (the master runs none by itself), which binds the volume, and requires a build after that point: only the line-change hook can take it. Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/line_change_wake_test.go | 133 ++++++++---------- 1 file changed, 58 insertions(+), 75 deletions(-) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 44fbc9c9f4..fb79d0c2b1 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -1,47 +1,61 @@ package master import ( + "context" "runtime" "testing" "time" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" ) // A published line wakes the observation build, through the master's -// wiring of the publisher's line-change hook. The order is made -// deterministic so no other wake can stand in for the hook: -// - the master starts with nothing ingested; its initial build runs, and -// the 1 ms pending grace's deadline is consumed (its rebuild runs too); -// - after the builds drain, one heartbeat is ingested: its single wake is -// consumed by one build whose snapshot already holds it (the snapshot is -// taken after the wake is received), showing v1 supported and unbound; -// - the controller binds v1 after that build. No heartbeat follows, no -// expiry is due (a one-hour window), and there is no GC tick: a later -// build carrying the line can only come from the hook. +// wiring of the publisher's line-change hook. The publication is the +// product tick's bind of a created and placed volume, run by the test (the +// master runs no tick by itself), and the order leaves nothing else to wake +// the build: +// - the master starts; its initial build (#1) and the 1 ms grace's +// rebuild (#2) finish; the volume is created and placed and its holder's +// heartbeat ingested; the observation host settles (every build taken +// has finished, no wake is buffered, no deadline is due within the test: +// a one-hour freshness window, no GC tick), all read under its lock: N +// builds done; +// - the test runs the product tick, which binds the volume; +// - a build N+1 must follow: nothing but the hook can take it. func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("the lifecycle stores need directory fsync") } h, err := New(Config{ - AuthorityStoreDir: t.TempDir(), - LifecycleStoreDir: t.TempDir(), - Listen: "127.0.0.1:0", - Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour, PendingGrace: time.Millisecond}, - Topology: authority.AcceptedTopology{Volumes: []authority.VolumeExpected{{ - VolumeID: "v1", - Slots: []authority.ExpectedSlot{{ReplicaID: "r1", ServerID: "node-a"}}, - }}}, + Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), + WorkspaceRPC: true, LifecycleProductLoop: true, LayoutCreateVolume: testLayoutCreateVolume, + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{}, nil + }, + Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour, PendingGrace: time.Millisecond}, }) if err != nil { t.Fatal(err) } h.Start() - defer closeTestMaster(t, h) - // settle waits until every build the loop took has finished, no wake is - // buffered and no deadline timer fires within the test (the one-hour - // expiry timer stays armed), all read under the host's lock; it returns - // the builds done. + t.Cleanup(func() { closeTestMaster(t, h) }) + c, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + t.Cleanup(cancel) + if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-a", DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + // settle waits, under the host's lock, until every build taken has + // finished, no wake is buffered and no deadline timer fires within a + // minute, with at least atLeast builds done; it returns the builds done. settle := func(what string, atLeast uint64) uint64 { t.Helper() deadline := time.Now().Add(5 * time.Second) @@ -55,59 +69,28 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { t.Fatalf("%s: the observation host did not settle", what) return 0 } - waitDone := func(what string, n uint64, ok func(authority.BuildResult) bool) { - t.Helper() - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - _, done, _, _ := h.obs.BuildsForTest() - if b, have := h.obs.LastBuild(); have && done >= n && ok(b) { - return - } - time.Sleep(10 * time.Millisecond) - } - b, _ := h.obs.LastBuild() - t.Fatalf("%s: no build #%d satisfied it; last build %+v", what, n, b.Snapshot.Volumes) - } - carriesLine := func(epoch uint64) func(authority.BuildResult) bool { - return func(b authority.BuildResult) bool { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == epoch { - return true - } - } - return false - } - } - // The initial build (#1) and the 1 ms grace's rebuild (#2, with nothing - // ingested yet) both finished: the grace's deadline is consumed, so no - // timer can arm after this point and see the heartbeat. - n := settle("startup", 2) - if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ - ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, - Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, - }); err != nil { + settle("startup", 2) + reviewCreate(t, c, ctx, "v1") + if _, err := h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "v1", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: "v1", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { t.Fatal(err) } - // The heartbeat's one build (#n+1) shows v1 supported and unbound: the - // controller binds only after it. - waitDone("the heartbeat's build", n+1, func(b authority.BuildResult) bool { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" { - return true - } - } - return false - }) - for wait := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) { - if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { - break - } - if time.Now().After(wait) { - t.Fatal("the controller did not bind v1") - } + reviewHeartbeat(t, c, ctx, "v1", "node-a", "127.0.0.1:10000", "127.0.0.1:10001") + n := settle("after the heartbeat", 3) + if _, ok := h.Publisher().VolumeAuthorityLine("v1"); ok { + t.Fatal("v1 was bound before the product tick: the publication under test is not the test's") } - line, _ := h.Publisher().VolumeAuthorityLine("v1") - // Every build after the heartbeat's was taken after the publication (no - // other wake was left): the hook's. One must come and carry the line. - waitDone("the hook's build", n+2, carriesLine(line.Epoch)) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + if line := waitAuthorityLine(t, h.Publisher(), "v1"); line.Epoch != 1 { + t.Fatalf("the product tick bound %+v", line) + } + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if _, done, _, _ := h.obs.BuildsForTest(); done > n { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("no observation build followed the publication (still %d builds): the line-change hook did not wake it", n) } From ad9663bfe0b93ee64f0b421e867139708c4e4b45 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:11:19 -0800 Subject: [PATCH 11/27] 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 12/27] 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 13/27] 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 14/27] 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 15/27] 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 16/27] 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 aa512ab6d46f5b6f1dff035e71b2c139f3e19b42 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:41:31 -0800 Subject: [PATCH 17/27] blockvolume, volume: red tests, an underivable cgroup limit starts on the default - A holder whose cgroup v2 limit cannot be derived (its membership is outside the cgroup2 mount of its mount namespace, or memory.max is unreadable), with neither --memory-limit-mib nor GOMEMLIMIT, must start on the 256 MiB default and record why (fails: exit 2 on the derivation error). An explicit but invalid flag still refuses. - Applying that limit must log exactly one WARN naming the reason and the two ways to choose a limit, and status must report the reason; a derived limit logs nothing (fails: no WARN, status empty). - Seams: flags.memoryLimitFallback, applyMemoryLimit (now called after logging is configured), ProcessMemoryStatus.SoftLimitFallback, volume.SetSoftLimitFallback / SoftLimitFallback. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/main.go | 10 +- .../cmd/blockvolume/memory_fallback_test.go | 110 ++++++++++++++++++ seaweed-block/cmd/blockvolume/memory_limit.go | 11 ++ .../core/host/volume/memory_fallback.go | 8 ++ .../core/host/volume/memory_fallback_test.go | 18 +++ .../core/host/volume/memory_status.go | 3 + 6 files changed, 156 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/memory_fallback_test.go create mode 100644 seaweed-block/cmd/blockvolume/memory_limit.go create mode 100644 seaweed-block/core/host/volume/memory_fallback.go create mode 100644 seaweed-block/core/host/volume/memory_fallback_test.go diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index ea483d87ef..9e94b6a39e 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -9,12 +9,12 @@ import ( "errors" "flag" "fmt" + "log" "math" "net" "os" "os/exec" "path/filepath" - "runtime/debug" "strconv" "strings" "time" @@ -163,6 +163,10 @@ type flags struct { // gating through the durable WriteObserver seam. replicationAck string version bool + + // memoryLimitFallback says why the default soft memory limit is in + // force instead of a cgroup-derived one (seam). + memoryLimitFallback string } // volumeLockDirTestOnlyFlag is hidden from --help (printVisibleUsage). @@ -592,13 +596,11 @@ func main() { fmt.Println(buildinfo.Version("blockvolume")) return } - if f.memoryLimitMiB > 0 { - debug.SetMemoryLimit(f.memoryLimitMiB << 20) - } if err := logging.Configure(f.logLevel); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } + applyMemoryLimit(f, log.Printf) os.Exit(run(f)) } diff --git a/seaweed-block/cmd/blockvolume/memory_fallback_test.go b/seaweed-block/cmd/blockvolume/memory_fallback_test.go new file mode 100644 index 0000000000..7d9c924460 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/memory_fallback_test.go @@ -0,0 +1,110 @@ +package main + +import ( + "fmt" + "os" + "runtime/debug" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/host/volume" +) + +var fallbackBase = []string{"--master", "127.0.0.1:1", "--server-id", "h1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:2", "--ctrl-addr", "127.0.0.1:3"} + +// cgroupFiles serves fixture /proc and cgroup files; anything else is absent. +func cgroupFiles(files map[string]string) func(string) ([]byte, error) { + return func(name string) ([]byte, error) { + if s, ok := files[name]; ok { + return []byte(s), nil + } + return nil, os.ErrNotExist + } +} + +// A holder whose cgroup v2 limit cannot be derived, with neither +// --memory-limit-mib nor GOMEMLIMIT given, starts on the 256 MiB default and +// says why: it is the no-limit case, never a refusal. The first case is a +// mount namespace whose cgroup2 mount does not cover the process's +// membership (what the process sees in /proc/self/mountinfo and cgroup). +func TestMemoryLimitFallsBackWhenTheCgroupLimitCannotBeDerived(t *testing.T) { + t.Setenv("GOMEMLIMIT", "") + for _, tc := range []struct { + name, reason string + files map[string]string + }{ + {"membership outside the namespace's cgroup2 mount", `no cgroup2 mount resolves membership "/user.slice/user-1000.slice/session-7.scope"`, map[string]string{ + "/proc/self/mountinfo": "29 23 0:26 /system.slice/runner.service /sys/fs/cgroup rw - cgroup2 cgroup rw\n", + "/proc/self/cgroup": "0::/user.slice/user-1000.slice/session-7.scope\n", + }}, + {"unreadable memory.max", "invalid /sys/fs/cgroup/holder/memory.max value", map[string]string{ + "/proc/self/mountinfo": "29 23 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup rw\n", + "/proc/self/cgroup": "0::/holder\n", + "/sys/fs/cgroup/holder/memory.max": "garbage\n", + }}, + } { + t.Run(tc.name, func(t *testing.T) { + f, err := parseFlagsWithCgroup(fallbackBase, cgroupFiles(tc.files)) + if err != nil { + t.Fatalf("refused to start: %v", err) + } + if f.memoryLimitMiB != 256 { + t.Fatalf("limit %d MiB, want the 256 MiB default", f.memoryLimitMiB) + } + if !strings.Contains(f.memoryLimitFallback, tc.reason) { + t.Fatalf("fallback reason %q does not name %q", f.memoryLimitFallback, tc.reason) + } + }) + } + // An explicit but invalid limit still refuses. + if _, err := parseFlagsWithCgroup(append(append([]string{}, fallbackBase...), "--memory-limit-mib", "-1"), cgroupFiles(nil)); err == nil { + t.Fatal("an invalid --memory-limit-mib was accepted") + } +} + +// Applying a fallback limit logs exactly one WARN naming why and the two ways +// to choose a limit, and status reports the reason; a derived limit logs +// nothing and reports no reason. +func TestMemoryLimitFallbackWarnsOnceAndShowsInStatus(t *testing.T) { + t.Setenv("GOMEMLIMIT", "") + old := debug.SetMemoryLimit(-1) + t.Cleanup(func() { debug.SetMemoryLimit(old); volume.SetSoftLimitFallback("") }) + f, err := parseFlagsWithCgroup(fallbackBase, cgroupFiles(map[string]string{ + "/proc/self/mountinfo": "29 23 0:26 /system.slice/runner.service /sys/fs/cgroup rw - cgroup2 cgroup rw\n", + "/proc/self/cgroup": "0::/user.slice/user-1000.slice/session-7.scope\n", + })) + if err != nil { + t.Fatalf("refused to start: %v", err) + } + var lines []string + logf := func(format string, args ...any) { lines = append(lines, fmt.Sprintf(format, args...)) } + applyMemoryLimit(f, logf) + if len(lines) != 1 { + t.Fatalf("%d log lines, want exactly one WARN: %q", len(lines), lines) + } + for _, want := range []string{"level=WARN", "no cgroup2 mount resolves membership", "256 MiB", "--memory-limit-mib", "GOMEMLIMIT"} { + if !strings.Contains(lines[0], want) { + t.Fatalf("the WARN does not name %q: %s", want, lines[0]) + } + } + if got := debug.SetMemoryLimit(-1); got != 256<<20 { + t.Fatalf("soft limit in force %d, want 256 MiB", got) + } + if got := volume.SoftLimitFallback(); !strings.Contains(got, "no cgroup2 mount resolves membership") { + t.Fatalf("status reports the fallback as %q", got) + } + + lines = nil + f, err = parseFlagsWithCgroup(fallbackBase, cgroupFiles(map[string]string{ + "/proc/self/mountinfo": "29 23 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup rw\n", + "/proc/self/cgroup": "0::/system.slice/volume.service\n", + "/sys/fs/cgroup/system.slice/volume.service/memory.max": "2147483648\n", + })) + if err != nil { + t.Fatal(err) + } + applyMemoryLimit(f, logf) + if len(lines) != 0 || volume.SoftLimitFallback() != "" { + t.Fatalf("a derived limit logged %q and reports fallback %q", lines, volume.SoftLimitFallback()) + } +} diff --git a/seaweed-block/cmd/blockvolume/memory_limit.go b/seaweed-block/cmd/blockvolume/memory_limit.go new file mode 100644 index 0000000000..8ce7f76eb1 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/memory_limit.go @@ -0,0 +1,11 @@ +package main + +import "runtime/debug" + +// applyMemoryLimit sets the process's Go soft memory limit from the parsed +// flags (seam: no fallback report yet). +func applyMemoryLimit(f flags, logf func(string, ...any)) { + if f.memoryLimitMiB > 0 { + debug.SetMemoryLimit(f.memoryLimitMiB << 20) + } +} diff --git a/seaweed-block/core/host/volume/memory_fallback.go b/seaweed-block/core/host/volume/memory_fallback.go new file mode 100644 index 0000000000..78adf6b52f --- /dev/null +++ b/seaweed-block/core/host/volume/memory_fallback.go @@ -0,0 +1,8 @@ +package volume + +// SetSoftLimitFallback records why the process runs on the default soft +// memory limit (seam: not reported yet). +func SetSoftLimitFallback(reason string) {} + +// SoftLimitFallback is the reason SetSoftLimitFallback recorded (seam). +func SoftLimitFallback() string { return "" } diff --git a/seaweed-block/core/host/volume/memory_fallback_test.go b/seaweed-block/core/host/volume/memory_fallback_test.go new file mode 100644 index 0000000000..d5c6cc4b31 --- /dev/null +++ b/seaweed-block/core/host/volume/memory_fallback_test.go @@ -0,0 +1,18 @@ +package volume + +import "testing" + +// The status projection reports why the process runs on the default soft +// memory limit, and reports nothing once there is no such reason. +func TestStatusProjectionReportsTheSoftLimitFallback(t *testing.T) { + t.Cleanup(func() { SetSoftLimitFallback("") }) + s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil)) + SetSoftLimitFallback("no cgroup2 mount resolves membership \"/user.slice/x.scope\"") + if got := s.statusProjection().Memory.SoftLimitFallback; got != "no cgroup2 mount resolves membership \"/user.slice/x.scope\"" { + t.Fatalf("status reports the fallback as %q", got) + } + SetSoftLimitFallback("") + if got := s.statusProjection().Memory.SoftLimitFallback; got != "" { + t.Fatalf("status still reports a cleared fallback: %q", got) + } +} diff --git a/seaweed-block/core/host/volume/memory_status.go b/seaweed-block/core/host/volume/memory_status.go index 1ad9e5573e..1c952f7f75 100644 --- a/seaweed-block/core/host/volume/memory_status.go +++ b/seaweed-block/core/host/volume/memory_status.go @@ -16,6 +16,9 @@ type ProcessMemoryStatus struct { HeapSysBytes uint64 // Go heap bytes obtained from the OS (HeapSys) HeapReleasedBytes uint64 // Go heap bytes returned to the OS (HeapReleased) SoftLimitBytes int64 // the Go soft memory limit in force (flag, GOMEMLIMIT or cgroup-derived default) + // SoftLimitFallback says why SoftLimitBytes is the default instead of a + // cgroup-derived limit (seam). + SoftLimitFallback string `json:",omitempty"` RSSBytes uint64 // resident set size from /proc/self/status (VmRSS); 0 off Linux AnonymousRSSBytes uint64 // anonymous resident memory (RssAnon); 0 off Linux } From d3a0975aef9866d50eb6573181cf9270823ad168 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:43:16 -0800 Subject: [PATCH 18/27] 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 7a70a7a1ca41a1fb72ecc2d74ab8051cf515ba62 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:46:02 -0800 Subject: [PATCH 19/27] blockvolume: an underivable cgroup memory limit starts on the default With neither --memory-limit-mib nor GOMEMLIMIT, a cgroup v2 limit that cannot be derived (a membership outside the cgroup2 mount of the holder's mount namespace, an unreadable or malformed memory.max) is the no-limit case: the holder keeps the 256 MiB default and starts, instead of exiting 2. applyMemoryLimit, run once logging is configured, logs one level=WARN line naming the derivation's error and the two ways to choose a limit, and status reports the reason in Memory.SoftLimitFallback (empty otherwise). Only an explicit but invalid limit still refuses. Docs: the flag's help, the operator guide's memory section, the status schema and the v1.1 notes. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/main.go | 13 +++++++---- .../cmd/blockvolume/memory_cgroup.go | 3 ++- seaweed-block/cmd/blockvolume/memory_limit.go | 14 +++++++++-- .../core/host/volume/memory_fallback.go | 23 +++++++++++++++---- .../core/host/volume/memory_status.go | 6 ++--- seaweed-block/docs/operator-guide.md | 10 +++++--- seaweed-block/docs/releases/v1.1.md | 4 ++++ seaweed-block/docs/status-schema.md | 1 + 8 files changed, 54 insertions(+), 20 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 9e94b6a39e..dcf572881f 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -165,7 +165,8 @@ type flags struct { version bool // memoryLimitFallback says why the default soft memory limit is in - // force instead of a cgroup-derived one (seam). + // force instead of a cgroup-derived one: the derivation's error. Empty + // when a limit was derived, given, or not needed. memoryLimitFallback string } @@ -193,7 +194,7 @@ func parseFlagsWithCgroup(args []string, readFile func(string) ([]byte, error)) var f flags fs := flag.NewFlagSet("blockvolume", flag.ContinueOnError) fs.StringVar(&f.logLevel, "log-level", "info", "log verbosity: info or debug; timestamps are UTC with microseconds") - fs.Int64Var(&f.memoryLimitMiB, "memory-limit-mib", 4*storage.DefaultCutPayloadMemoryBudget/(1<<20), "process Go soft memory limit in MiB; unset: 90% of the effective cgroup v2 memory.max, or 256 MiB without a limit; 0 preserves GOMEMLIMIT; explicit GOMEMLIMIT is preserved unless this flag is set") + fs.Int64Var(&f.memoryLimitMiB, "memory-limit-mib", 4*storage.DefaultCutPayloadMemoryBudget/(1<<20), "process Go soft memory limit in MiB; unset: 90% of the effective cgroup v2 memory.max, or 256 MiB without a limit or when it cannot be derived (one WARN says why); 0 preserves GOMEMLIMIT; explicit GOMEMLIMIT is preserved unless this flag is set") fs.StringVar(&f.masterAddr, "master", "", "master gRPC address (required)") fs.StringVar(&f.serverID, "server-id", "", "this server identity (required)") fs.StringVar(&f.masterTLS.Cert, "master-tls-cert", "", "this node's certificate (PEM) for mutual TLS to blockmaster; its CN must equal --server-id") @@ -297,11 +298,13 @@ func parseFlagsWithCgroup(args []string, readFile func(string) ([]byte, error)) if !memoryFlagSet && os.Getenv("GOMEMLIMIT") != "" { f.memoryLimitMiB = 0 } else if !memoryFlagSet && !f.version { + // An underivable cgroup limit is the no-limit case: the default stays + // in force and applyMemoryLimit warns why. Only an explicit limit + // (the flag, or GOMEMLIMIT read by the runtime) may refuse. limit, err := cgroupMemoryLimitMiB(readFile) if err != nil { - return flags{}, fmt.Errorf("derive memory limit: %w", err) - } - if limit != 0 { + f.memoryLimitFallback = err.Error() + } else if limit != 0 { f.memoryLimitMiB = limit } } diff --git a/seaweed-block/cmd/blockvolume/memory_cgroup.go b/seaweed-block/cmd/blockvolume/memory_cgroup.go index 7bab4193f8..ca6854f88d 100644 --- a/seaweed-block/cmd/blockvolume/memory_cgroup.go +++ b/seaweed-block/cmd/blockvolume/memory_cgroup.go @@ -75,7 +75,8 @@ func cgroupMemoryLimitMiB(readFile func(string) ([]byte, error)) (int64, error) // mountinfo names both the filesystem subtree root and its visible mountpoint. // A membership path must resolve inside that view; an unresolved v2 hierarchy -// is a configuration error, not evidence of unlimited memory. +// is an error here, not evidence of unlimited memory: the caller keeps the +// default limit and warns why. func cgroupMemoryDirectory(group string, readFile func(string) ([]byte, error)) (string, string, error) { data, err := readFile("/proc/self/mountinfo") if err != nil { diff --git a/seaweed-block/cmd/blockvolume/memory_limit.go b/seaweed-block/cmd/blockvolume/memory_limit.go index 8ce7f76eb1..c4f2d17c99 100644 --- a/seaweed-block/cmd/blockvolume/memory_limit.go +++ b/seaweed-block/cmd/blockvolume/memory_limit.go @@ -1,11 +1,21 @@ package main -import "runtime/debug" +import ( + "runtime/debug" + + "github.com/seaweedfs/seaweed-block/core/host/volume" +) // applyMemoryLimit sets the process's Go soft memory limit from the parsed -// flags (seam: no fallback report yet). +// flags. When the default is in force because the cgroup v2 limit could not +// be derived, it logs one WARN naming why and how to choose a limit, and +// status reports the reason (Memory.SoftLimitFallback). func applyMemoryLimit(f flags, logf func(string, ...any)) { if f.memoryLimitMiB > 0 { debug.SetMemoryLimit(f.memoryLimitMiB << 20) } + volume.SetSoftLimitFallback(f.memoryLimitFallback) + if f.memoryLimitFallback != "" { + logf("blockvolume: level=WARN memory limit: the cgroup v2 limit could not be derived (%s); running with the %d MiB default soft limit; set --memory-limit-mib or GOMEMLIMIT to choose a limit", f.memoryLimitFallback, f.memoryLimitMiB) + } } diff --git a/seaweed-block/core/host/volume/memory_fallback.go b/seaweed-block/core/host/volume/memory_fallback.go index 78adf6b52f..adb2b1aeb5 100644 --- a/seaweed-block/core/host/volume/memory_fallback.go +++ b/seaweed-block/core/host/volume/memory_fallback.go @@ -1,8 +1,21 @@ package volume -// SetSoftLimitFallback records why the process runs on the default soft -// memory limit (seam: not reported yet). -func SetSoftLimitFallback(reason string) {} +import "sync/atomic" -// SoftLimitFallback is the reason SetSoftLimitFallback recorded (seam). -func SoftLimitFallback() string { return "" } +// softLimitFallback is why the process runs on the default soft memory limit +// instead of a cgroup-derived one; the limit itself is process-wide too. +var softLimitFallback atomic.Pointer[string] + +// SetSoftLimitFallback records why the process runs on the default soft +// memory limit; empty clears it. +func SetSoftLimitFallback(reason string) { + softLimitFallback.Store(&reason) +} + +// SoftLimitFallback is the reason SetSoftLimitFallback recorded, or empty. +func SoftLimitFallback() string { + if p := softLimitFallback.Load(); p != nil { + return *p + } + return "" +} diff --git a/seaweed-block/core/host/volume/memory_status.go b/seaweed-block/core/host/volume/memory_status.go index 1c952f7f75..b77a4fad11 100644 --- a/seaweed-block/core/host/volume/memory_status.go +++ b/seaweed-block/core/host/volume/memory_status.go @@ -16,9 +16,7 @@ type ProcessMemoryStatus struct { HeapSysBytes uint64 // Go heap bytes obtained from the OS (HeapSys) HeapReleasedBytes uint64 // Go heap bytes returned to the OS (HeapReleased) SoftLimitBytes int64 // the Go soft memory limit in force (flag, GOMEMLIMIT or cgroup-derived default) - // SoftLimitFallback says why SoftLimitBytes is the default instead of a - // cgroup-derived limit (seam). - SoftLimitFallback string `json:",omitempty"` + SoftLimitFallback string `json:",omitempty"` // why SoftLimitBytes is the 256 MiB default instead of a cgroup-derived limit (the derivation's error) RSSBytes uint64 // resident set size from /proc/self/status (VmRSS); 0 off Linux AnonymousRSSBytes uint64 // anonymous resident memory (RssAnon); 0 off Linux } @@ -26,7 +24,7 @@ type ProcessMemoryStatus struct { func processMemoryStatus() ProcessMemoryStatus { var m runtime.MemStats runtime.ReadMemStats(&m) - out := ProcessMemoryStatus{HeapAllocBytes: m.HeapAlloc, HeapInuseBytes: m.HeapInuse, HeapSysBytes: m.HeapSys, HeapReleasedBytes: m.HeapReleased, SoftLimitBytes: debug.SetMemoryLimit(-1)} + out := ProcessMemoryStatus{HeapAllocBytes: m.HeapAlloc, HeapInuseBytes: m.HeapInuse, HeapSysBytes: m.HeapSys, HeapReleasedBytes: m.HeapReleased, SoftLimitBytes: debug.SetMemoryLimit(-1), SoftLimitFallback: SoftLimitFallback()} b, err := os.ReadFile("/proc/self/status") if err != nil { return out diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index 711b03dc45..18aa423eba 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -271,9 +271,13 @@ are its only SeaweedFS flags. Run SeaweedFS on a trusted network; mTLS covers th Automatic sizing requires the cgroup v2 memory controller. On cgroup v1, or a hybrid hierarchy without v2 `memory.max`, set `--memory-limit-mib` explicitly for a large volume; otherwise it receives the 256 MiB fallback. - An unreadable or malformed cgroup limit refuses startup with a diagnostic; - an explicit memory flag or `GOMEMLIMIT` bypasses this detection. - Inspect `Memory.SoftLimitBytes` on the holder's status for the value in force. + A cgroup limit that cannot be derived (unreadable or malformed, or a + membership outside the cgroup2 mount visible in the holder's mount namespace) + does not stop the holder: it starts on the 256 MiB default and logs one + `level=WARN` line naming why. An explicit memory flag or `GOMEMLIMIT` bypasses + this detection; only an explicit but invalid one refuses startup. + Inspect `Memory.SoftLimitBytes` on the holder's status for the value in force, + and `Memory.SoftLimitFallback` for why the default is in force. - **Measured throughput on one host** (three runs; 16 cores, 23.2 GiB RAM, one consumer NVMe drive, fsync on every volume): diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md index 13c0502601..2deb89237d 100644 --- a/seaweed-block/docs/releases/v1.1.md +++ b/seaweed-block/docs/releases/v1.1.md @@ -20,6 +20,10 @@ These notes collect v1.1's changes as they land; v1.1 is not released. - A normal cut that has held its host slot for `--host-limit-yield-after` (default 5 min) gives the slot to a waiting cut at its next staging batch, keeping what it staged; its next attempt queues behind the waiters. A lone cut never yields, and status counts yields apart from failures (`CutYields`). +- A `blockvolume` whose cgroup v2 memory limit cannot be derived (for example, its cgroup membership lies outside + the cgroup2 mount visible in its mount namespace) now starts on the 256 MiB default soft limit and logs one + `level=WARN` line naming why, instead of exiting 2; status reports the reason in `Memory.SoftLimitFallback`. An + explicit but invalid `--memory-limit-mib` or `GOMEMLIMIT` still refuses. ## Upgrade - With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 36c0315fe7..41533450f0 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -26,6 +26,7 @@ The volume's authority and health projection. Go type `volume.StatusProjection`. | `Memory.HeapSysBytes` | uint64 | Go heap bytes obtained from the OS (HeapSys) | | `Memory.HeapReleasedBytes` | uint64 | Go heap bytes returned to the OS (HeapReleased) | | `Memory.SoftLimitBytes` | int64 | the Go soft memory limit in force (flag, GOMEMLIMIT or cgroup-derived default) | +| `Memory.SoftLimitFallback` | string | why SoftLimitBytes is the 256 MiB default instead of a cgroup-derived limit (the derivation's error) (omitted when empty) | | `Memory.RSSBytes` | uint64 | resident set size from /proc/self/status (VmRSS); 0 off Linux | | `Memory.AnonymousRSSBytes` | uint64 | anonymous resident memory (RssAnon); 0 off Linux | | `FrontendPrimaryReady` | bool | FrontendPrimaryReady: this replica is the healthy, non-superseded primary, its local durable backend admits I/O, and it may serve guest I/O (INV-FE-PRIMARY-READY-OPERATIONAL-001). | From 848effb9aa290c084360ec825db08f9cbc828d18 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:55:01 -0800 Subject: [PATCH 20/27] 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 21/27] 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 22/27] 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 07b3d31697228842434adfe10c246c857a21b2eb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 16:44:01 -0800 Subject: [PATCH 23/27] blockvolume tests: adopt waits for the holder's frontend to admit I/O, not only a healthy primary Fixes #905. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/procedure_gate_integration_test.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go index 6fb6024f8d..4bc555fce0 100644 --- a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go @@ -403,13 +403,19 @@ func (env *handoffEnv) start(t *testing.T, name, id string) *daemon { return env.h.start(t, name, env.h.volume, env.volArgs(id)...) } -// adopt waits for the process to adopt v1 as primary and its host to report -// it healthy, and returns the epoch. +// adopt waits for the process to adopt v1 as primary, its host to report it +// a healthy primary, and its frontend to admit guest I/O +// (FrontendPrimaryReady), and returns the epoch. Healthy alone is not +// enough: until the frontend admits I/O, a write is answered "namespace not +// ready" (retryable), which the test's initiator does not retry. func (env *handoffEnv) adopt(t *testing.T, d *daemon, id string) uint64 { t.Helper() _, mustU := fatalOn(t) e := mustU(adoptedEpoch(d.waitLog(t, 60*time.Second, "blockvolume: volume v1 adopted as PRIMARY at r1@"))) env.h.waitPrimaryAt(t, env.hosts[id].status, e) + poll(t, 60*time.Second, fmt.Sprintf("%s: the holder adopted epoch %d but never reported its frontend ready", id, e), func() bool { + return env.frontendReadyAt(id) + }) return e } From 67f770d650a3c8c2033eb23fadc703e2c9639f0f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 16:53:21 -0800 Subject: [PATCH 24/27] 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 25/27] 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 26/27] 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 27/27] 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)