From 99c6a50749eb719e7c02cbc32b43eac127650d8b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 12:34:28 -0800 Subject: [PATCH 1/4] layout: the Commit transition Commit ends a snapshot session: for the holder at HEAD's epoch with snap(session) open, one conditional update sets the current root, the position and an optional named snapshot and returns activity to idle. Before it, every object the new root reaches must be written: the chunks of this volume that are new against HEAD's current root, every segment, and the root. The previous manifest must rebuild to HEAD's current root, so what is new is checked, not trusted; unchanged and foreign chunks are not looked up. A HEAD that already shows the commit is a replay and nothing is written or looked up. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/commit.go | 160 ++++++++++++++ .../frontend/chunkstore/layout/commit_test.go | 202 ++++++++++++++++++ 2 files changed, 362 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/commit.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/commit_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit.go b/seaweed-block/core/frontend/chunkstore/layout/commit.go new file mode 100644 index 0000000000..4b83d48f97 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/commit.go @@ -0,0 +1,160 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "sort" +) + +// Commit refusals. +var ( + // ErrNotPrepared: an object the new root reaches is not in the store + // yet (a chunk of this volume, a segment or the root itself). + ErrNotPrepared = errors.New("layout: commit names an object not written yet") + // ErrStaleBase: the previous manifest given is not HEAD's current + // root, so what is new cannot be told. + ErrStaleBase = errors.New("layout: previous manifest is not HEAD's current root") + // ErrSnapshotExists: the snapshot name is taken by another root. + ErrSnapshotExists = errors.New("layout: snapshot name taken") + // ErrTooManySnapshots: HEAD already holds MaxSnapshots. + ErrTooManySnapshots = errors.New("layout: snapshot limit reached") +) + +// CommitRequest is what a snapshot session commits: the image at +// Position, as a manifest, and optionally a snapshot name for it. Prev is +// the manifest of HEAD's current root (empty if none) that the session +// computed what is new against. +type CommitRequest struct { + Session string + Prev map[uint64]Ref + Next map[uint64]Ref + Position uint64 + Snapshot string // "" = no named snapshot +} + +// rootOf names the root of a manifest. +func rootOf(m map[uint64]Ref) (RootName, map[SegName][]byte, error) { + root, segs, err := Build(m) + if err != nil { + return RootName{}, nil, err + } + rn, _, err := NameRoot(root) + return rn, segs, err +} + +// newOwn returns the entries of next held in vol's pool whose name is not +// at the same index of prev: the only chunks a commit must look up (every +// name prev's root names is already in its owner's pool). +func newOwn(vol string, prev, next map[uint64]Ref) map[uint64]Ref { + out := map[uint64]Ref{} + for i, r := range next { + if r.Owner == vol && prev[i] != r { + out[i] = r + } + } + return out +} + +// Commit is transition 4 as a pure step on HEAD: for the holder at HEAD's +// epoch with snap(session) open, current = root, position, the optional +// snapshot added, activity idle. A HEAD that already shows this commit +// applied (idle, current = root, position, the snapshot) is a replay: +// unchanged, changed=false. +func (h Head) Commit(me HolderID, session string, root RootName, position uint64, snapshot string) (next Head, changed bool, err error) { + if session == "" { + return Head{}, false, errors.New("layout: Commit needs a session id") + } + if !h.heldBy(me) { + return Head{}, false, fmt.Errorf("%w: HEAD epoch %d holder %q, caller epoch %d holder %q", ErrNotHolder, h.Epoch, h.Holder, me.Epoch, me.Holder) + } + if h.Activity.Kind == ActIdle && h.Current != nil && *h.Current == root && h.Position == position { + if s, ok := h.Snapshots[snapshot]; snapshot == "" || ok && s.Root == root { + return h, false, nil + } + } + if h.Activity != (Activity{Kind: ActSnap, Session: session}) { + return Head{}, false, fmt.Errorf("%w: HEAD has %s(%s), not snap(%s)", ErrNoSession, h.Activity.Kind, h.Activity.Session, session) + } + next = h.clone() + if snapshot != "" { + if s, ok := next.Snapshots[snapshot]; ok { + if s.Root != root { + return Head{}, false, fmt.Errorf("%w: %q", ErrSnapshotExists, snapshot) + } + } else { + if len(next.Snapshots) >= MaxSnapshots { + return Head{}, false, fmt.Errorf("%w: %d", ErrTooManySnapshots, MaxSnapshots) + } + if next.Snapshots == nil { + next.Snapshots = map[string]Snapshot{} + } + next.Snapshots[snapshot] = Snapshot{Root: root} + } + } + rn := root + next.Current = &rn + next.Position = position + next.Activity = Activity{Kind: ActIdle} + return next, true, nil +} + +// RunCommit checks that every object the new root reaches is written (the +// new chunks of this volume against HEAD's current root, every segment, +// the root), then commits by one conditional update. Prev must build to +// HEAD's current root; a re-run after a lost reply finds the commit +// applied and writes nothing. +func RunCommit(ctx context.Context, st HeadStore, look Lookup, volRoot, vol string, me HolderID, req CommitRequest) (Head, error) { + root, segs, err := rootOf(req.Next) + if err != nil { + return Head{}, err + } + return runTransition(ctx, st, func(h Head) (Head, bool, error) { + if next, changed, err := h.Commit(me, req.Session, root, req.Position, req.Snapshot); err != nil || !changed { + return next, changed, err // refused, or already applied: no lookups + } + var base *RootName + if len(req.Prev) > 0 { + rn, _, err := rootOf(req.Prev) + if err != nil { + return Head{}, false, err + } + base = &rn + } + if (base == nil) != (h.Current == nil) || base != nil && *base != *h.Current { + return Head{}, false, ErrStaleBase + } + missing, err := MissingOwn(ctx, look, volRoot, vol, newOwn(vol, req.Prev, req.Next)) + if err != nil { + return Head{}, false, err + } + if len(missing) > 0 { + return Head{}, false, fmt.Errorf("%w: %d chunks, first %s", ErrNotPrepared, len(missing), missing[0]) + } + names := make([]SegName, 0, len(segs)) + for n := range segs { + names = append(names, n) + } + sort.Slice(names, func(a, b int) bool { return names[a].Shard < names[b].Shard }) + for _, n := range names { + if err := present(ctx, look, volRoot, n.Path()); err != nil { + return Head{}, false, err + } + } + if err := present(ctx, look, volRoot, root.Path()); err != nil { + return Head{}, false, err + } + return h.Commit(me, req.Session, root, req.Position, req.Snapshot) + }) +} + +func present(ctx context.Context, look Lookup, volRoot, rel string) error { + ok, err := Present(ctx, look, volRoot, rel) + if err != nil { + return fmt.Errorf("layout: look up %s: %w", rel, err) + } + if !ok { + return fmt.Errorf("%w: %s", ErrNotPrepared, rel) + } + return nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit_test.go b/seaweed-block/core/frontend/chunkstore/layout/commit_test.go new file mode 100644 index 0000000000..be58e6d328 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/commit_test.go @@ -0,0 +1,202 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "path" + "strings" + "testing" +) + +const volRoot = "/swblock/chunks/v1" + +// prepared writes (in the fake store) every object a commit of next needs: +// next's own chunks, its segments and its root. +func prepared(t *testing.T, f *fakeStore, next map[uint64]Ref) RootName { + t.Helper() + root, segs, err := Build(next) + if err != nil { + t.Fatal(err) + } + for i, r := range next { + if r.Owner == "v1" { + f.have[path.Join(volRoot, next[i].Chunk.Path())] = true + } + } + for n := range segs { + f.have[path.Join(volRoot, n.Path())] = true + } + rn, _, err := NameRoot(root) + if err != nil { + t.Fatal(err) + } + f.have[path.Join(volRoot, rn.Path())] = true + return rn +} + +func manifest(entries ...Ref) map[uint64]Ref { + m := map[uint64]Ref{} + for _, r := range entries { + m[r.Chunk.Index] = r + } + return m +} + +func TestCommit_Closure(t *testing.T) { + rn := RootName{Hash: Sum([]byte("new"))} + h := snapHead("s1") + next, changed, err := h.Commit(me, "s1", rn, 50, "hourly") + if err != nil || !changed || next.Activity.Kind != ActIdle || *next.Current != rn || next.Position != 50 || next.Snapshots["hourly"].Root != rn { + t.Fatalf("Commit: %+v %t %v", next, changed, err) + } + if next.Snapshots["daily"].Dependents[0] != "t1" || len(next.Snapshots) != 2 { + t.Fatalf("Commit changed other snapshots: %+v", next.Snapshots) + } + if h.Activity.Kind != ActSnap || h.Snapshots["hourly"].Root == rn { + t.Fatal("Commit changed its receiver") + } + if again, changed, err := next.Commit(me, "s1", rn, 50, "hourly"); err != nil || changed || again.Gen != next.Gen { + t.Fatalf("Commit over its applied HEAD: %+v %t %v; want a replay", again, changed, err) + } + if n2, changed, err := h.Commit(me, "s1", rn, 50, ""); err != nil || !changed || len(n2.Snapshots) != 1 { + t.Fatalf("Commit without a snapshot name: %+v %t %v", n2, changed, err) + } + full := snapHead("s1") + for i := len(full.Snapshots); i < MaxSnapshots; i++ { + full.Snapshots[fmt.Sprintf("n%03d", i)] = Snapshot{Root: rn} + } + for name, tc := range map[string]struct { + h Head + me HolderID + snapshot string + want error + }{ + "idle": {idleHead(), me, "", ErrNoSession}, + "other session": {snapHead("s2"), me, "", ErrNoSession}, + "cleaning": {Head{Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActClean, Session: "s1"}}, me, "", ErrNoSession}, + "other epoch": {h, HolderID{Epoch: 2, Holder: "srv-a"}, "", ErrNotHolder}, + "other holder": {h, HolderID{Epoch: 3, Holder: "srv-b"}, "", ErrNotHolder}, + "name taken": {h, me, "daily", ErrSnapshotExists}, + "snapshot limit": {full, me, "one-more", ErrTooManySnapshots}, + } { + if _, _, err := tc.h.Commit(tc.me, "s1", rn, 50, tc.snapshot); !errors.Is(err, tc.want) { + t.Errorf("%s: %v; want %v", name, err, tc.want) + } + } +} + +// commitFixture: HEAD is snap(s1) at current root = prev's root; prev and +// next share chunk 0 (unchanged), next changes chunk 3, adds chunk 10004 +// and names chunk 7 of volume "src". +func commitFixture(t *testing.T) (*fakeStore, Head, CommitRequest) { + t.Helper() + f := &fakeStore{have: map[string]bool{}} + prev := manifest(ref("v1", 0, "a"), ref("v1", 3, "b")) + prevRoot := prepared(t, f, prev) + next := manifest(ref("v1", 0, "a"), ref("v1", 3, "b2"), ref("v1", 10004, "c"), ref("src", 7, "d")) + prepared(t, f, next) + h := Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s1"}, Current: &prevRoot, Position: 40} + return f, h, CommitRequest{Session: "s1", Prev: prev, Next: next, Position: 50, Snapshot: "hourly"} +} + +func runCommit(st HeadStore, f *fakeStore, req CommitRequest) (Head, error) { + return RunCommit(context.Background(), st, f.look, volRoot, "v1", me, req) +} + +func TestRunCommit_LooksUpOnlyWhatIsNew(t *testing.T) { + f, h, req := commitFixture(t) + st := &memHead{h: &h} + f.asked = nil + got, err := runCommit(st, f, req) + if err != nil || got.Activity.Kind != ActIdle || got.Position != 50 || st.h.Gen != 8 { + t.Fatalf("RunCommit: %+v %v", got, err) + } + wantRoot, _, _ := rootOf(req.Next) + if *st.h.Current != wantRoot || st.h.Snapshots["hourly"].Root != wantRoot { + t.Fatalf("HEAD current %v snapshot %v; want %v", st.h.Current, st.h.Snapshots["hourly"], wantRoot) + } + var pool []string + for _, p := range f.asked { + if strings.Contains(p, "/"+PoolDir+"/") { + pool = append(pool, path.Base(p)) + } + } + want := []string{req.Next[3].Chunk.String(), req.Next[10004].Chunk.String()} + if strings.Join(pool, ",") != strings.Join(want, ",") { + t.Fatalf("pool lookups %v; want only the new own chunks %v (not the unchanged chunk 0, not the foreign chunk 7)", pool, want) + } +} + +func TestRunCommit_RefusesUnwrittenObjects(t *testing.T) { + for _, what := range []string{"new chunk", "segment", "root"} { + t.Run(what, func(t *testing.T) { + f, h, req := commitFixture(t) + root, segs, _ := rootOf(req.Next) + var p string + switch what { + case "new chunk": + p = req.Next[10004].Chunk.Path() + case "segment": + for n := range segs { + if n.Shard == 1 { + p = n.Path() + } + } + case "root": + p = root.Path() + } + delete(f.have, path.Join(volRoot, p)) + st := &memHead{h: &h} + if _, err := runCommit(st, f, req); !errors.Is(err, ErrNotPrepared) { + t.Fatalf("commit with its %s missing: %v; want ErrNotPrepared", what, err) + } + if st.updates != 0 || st.h.Activity.Kind != ActSnap { + t.Fatalf("HEAD written by a refused commit: %+v", st.h) + } + }) + } +} + +func TestRunCommit_StaleBaseAndLookupFailure(t *testing.T) { + f, h, req := commitFixture(t) + stale := req + stale.Prev = manifest(ref("v1", 0, "a")) // not HEAD's current root + st := &memHead{h: &h} + if _, err := runCommit(st, f, stale); !errors.Is(err, ErrStaleBase) { + t.Fatalf("commit against another base: %v; want ErrStaleBase", err) + } + empty := req + empty.Prev = nil // HEAD has a current root, so "nothing before" is stale too + if _, err := runCommit(st, f, empty); !errors.Is(err, ErrStaleBase) { + t.Fatalf("commit with no base over a current root: %v; want ErrStaleBase", err) + } + f.fail = path.Join(volRoot, req.Next[3].Chunk.Path()) + if _, err := runCommit(st, f, req); err == nil || errors.Is(err, ErrNotPrepared) { + t.Fatalf("commit with a failing lookup: %v; want an error that is not a refusal", err) + } + if st.updates != 0 { + t.Fatal("HEAD written by a refused commit") + } + // The first commit of a volume: no current root, no previous manifest. + f2 := &fakeStore{have: map[string]bool{}} + next := manifest(ref("v1", 1, "x")) + prepared(t, f2, next) + h2 := Head{Gen: 1, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s1"}} + if got, err := runCommit(&memHead{h: &h2}, f2, CommitRequest{Session: "s1", Next: next, Position: 5}); err != nil || got.Current == nil { + t.Fatalf("first commit: %+v %v", got, err) + } +} + +func TestRunCommit_InterruptAtEveryStep(t *testing.T) { + f, h, req := commitFixture(t) + wantRoot, _, _ := rootOf(req.Next) + interruptHead(t, h, func(st HeadStore) error { + _, err := runCommit(st, f, req) + return err + }, func(t *testing.T, got Head) { + if got.Activity.Kind != ActIdle || got.Current == nil || *got.Current != wantRoot || got.Position != 50 || got.Snapshots["hourly"].Root != wantRoot { + t.Fatalf("HEAD after Commit: %+v", got) + } + }) +} From ec5af310d32b7d1311611c20e4aa1506a749aebf Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 12:43:10 -0800 Subject: [PATCH 2/4] test: kill a snapshot transaction at every write and restart it The whole transaction (Begin, every new chunk, segment and root, then Commit) is run once to enumerate its writes; for each it is killed before the write applies and after it applied with its reply lost. The restarted holder rolls back the session it finds open, begins a new one, recomputes what is new against HEAD's current root, reuses the objects already written by name and commits. Every run ends at the committed image with every object it reaches present. Co-Authored-By: Claude Opus 5.5 --- .../chunkstore/layout/session_test.go | 253 ++++++++++++++++++ 1 file changed, 253 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/session_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout/session_test.go b/seaweed-block/core/frontend/chunkstore/layout/session_test.go new file mode 100644 index 0000000000..13d18ced25 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/session_test.go @@ -0,0 +1,253 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "path" + "testing" +) + +// memVolume is one volume's store: HEAD (memHead) and its objects, with +// one kill point counted over every write of either kind. +type memVolume struct { + head *memHead + objects map[string][]byte + writes []string // every write, in order + killAt int + after bool + dead bool +} + +func (v *memVolume) write(what string) (apply, die bool, err error) { + if v.dead { + return false, false, errKilled + } + v.writes = append(v.writes, what) + if len(v.writes) == v.killAt { + v.dead = true + return v.after, true, nil + } + return true, false, nil +} + +func (v *memVolume) ReadHead(ctx context.Context) (Head, bool, error) { + if v.dead { + return Head{}, false, errKilled + } + return v.head.ReadHead(ctx) +} + +func (v *memVolume) UpdateHead(ctx context.Context, gen uint64, next Head) error { + apply, die, err := v.write("update HEAD") + if err != nil { + return err + } + if apply { + if err := v.head.UpdateHead(ctx, gen, next); err != nil { + return err + } + } + if die { + return errKilled + } + return nil +} + +func (v *memVolume) look(_ context.Context, dir, name string) (bool, error) { + if v.dead { + return false, errKilled + } + _, ok := v.objects[path.Join(dir, name)] + return ok, nil +} + +// put writes an object if absent (a content name that exists is complete, +// so a present one is skipped). +func (v *memVolume) put(rel string, b []byte) error { + p := path.Join(volRoot, rel) + if v.dead { + return errKilled + } + if _, ok := v.objects[p]; ok { + return nil + } + apply, die, err := v.write("create " + rel) + if err != nil { + return err + } + if apply { + v.objects[p] = append([]byte(nil), b...) + } + if die { + return errKilled + } + return nil +} + +// snapshotSession is the whole snapshot transaction as the holder runs it +// after a (re)start: an open session of its own at HEAD's epoch is rolled +// back first (memory is empty after a crash), then Begin, write every new +// object (chunks, segments, root; present ones skipped), and Commit. +func snapshotSession(v *memVolume, session string, data map[uint64][]byte, req CommitRequest) error { + ctx := context.Background() + h, found, err := v.ReadHead(ctx) + if err != nil { + return err + } + if !found { + return ErrHeadAbsent + } + if h.Activity.Kind == ActSnap && h.heldBy(me) { + if _, err := RunAbort(ctx, v, me, h.Activity.Session); err != nil { + return err + } + } + if _, err := RunBegin(ctx, v, me, session); err != nil { + return err + } + // What is new is recomputed against HEAD's current root, never kept + // from before the crash (a commit may have applied with its reply lost). + switch cur := h.Current; { + case cur != nil && *cur == mustRoot(req.Next): + req.Prev = req.Next + case cur != nil && *cur != mustRoot(req.Prev): + return fmt.Errorf("unexpected current root %s", cur) + } + for i, r := range newOwn("v1", req.Prev, req.Next) { + if err := v.put(r.Chunk.Path(), data[i]); err != nil { + return err + } + } + root, segs, err := Build(req.Next) + if err != nil { + return err + } + for n, b := range segs { + if err := v.put(n.Path(), b); err != nil { + return err + } + } + rn, rb, err := NameRoot(root) + if err != nil { + return err + } + if err := v.put(rn.Path(), rb); err != nil { + return err + } + req.Session = session + _, err = RunCommit(ctx, v, v.look, volRoot, "v1", me, req) + return err +} + +func mustRoot(m map[uint64]Ref) RootName { + rn, _, err := rootOf(m) + if err != nil { + panic(err) + } + return rn +} + +// sessionFixture: HEAD idle at the root of prev (chunks 0 and 3, written); +// the session commits next (chunk 3 changed, chunk 10004 added, a foreign +// chunk named). +func sessionFixture(t *testing.T) (func() *memVolume, map[uint64][]byte, CommitRequest) { + t.Helper() + data := map[uint64][]byte{0: []byte("a"), 3: []byte("b2"), 10004: []byte("c")} + prev := manifest(ref("v1", 0, "a"), ref("v1", 3, "b")) + next := manifest(ref("v1", 0, "a"), ref("v1", 3, "b2"), ref("v1", 10004, "c"), ref("src", 7, "d")) + fresh := func() *memVolume { + f := &fakeStore{have: map[string]bool{}} + prevRoot := prepared(t, f, prev) + objs := map[string][]byte{} + for p := range f.have { + objs[p] = []byte("x") + } + h := Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActIdle}, Current: &prevRoot, Position: 40} + return &memVolume{head: &memHead{h: &h}, objects: objs} + } + return fresh, data, CommitRequest{Prev: prev, Next: next, Position: 50, Snapshot: "hourly"} +} + +// requireCommitted: HEAD idle at next's root with the snapshot, and every +// object next's root reaches in this volume exists, its bytes as written. +func requireCommitted(t *testing.T, v *memVolume, data map[uint64][]byte, req CommitRequest) { + t.Helper() + h := v.head.h + root, segs, _ := Build(req.Next) + rn, _, _ := NameRoot(root) + if h.Activity.Kind != ActIdle || h.Current == nil || *h.Current != rn || h.Position != 50 || h.Snapshots["hourly"].Root != rn { + t.Fatalf("HEAD after the session: %+v", h) + } + for i, r := range req.Next { + if r.Owner != "v1" { + continue + } + b, ok := v.objects[path.Join(volRoot, r.Chunk.Path())] + if !ok { + t.Fatalf("chunk %d the committed root names is missing", i) + } + if _, changed := newOwn("v1", req.Prev, req.Next)[i]; changed && string(b) != string(data[i]) { + t.Fatalf("chunk %d holds %q; want %q", i, b, data[i]) + } + } + for n := range segs { + if _, ok := v.objects[path.Join(volRoot, n.Path())]; !ok { + t.Fatalf("segment %s the committed root names is missing", n) + } + } + if _, ok := v.objects[path.Join(volRoot, rn.Path())]; !ok { + t.Fatal("the committed root is missing") + } +} + +// Interrupt at every step of the snapshot transaction: killed at each of +// its writes (Begin's HEAD update, every object create, Commit's HEAD +// update), before the write applies and after it applied with its reply +// lost; the restarted holder rolls back what it finds open, begins a new +// session, reuses written objects by name and commits. The end state is +// the committed image with every object it reaches present; at no point +// does HEAD name an object that is missing. +func TestSnapshotSession_InterruptAtEveryStep(t *testing.T) { + fresh, data, req := sessionFixture(t) + count := fresh() + if err := snapshotSession(count, "s1", data, req); err != nil { + t.Fatal(err) + } + requireCommitted(t, count, data, req) + steps := append([]string(nil), count.writes...) + if len(steps) < 5 { + t.Fatalf("the session made %d writes: %v", len(steps), steps) + } + t.Logf("%d step boundaries: %v", len(steps), steps) + for k := range steps { + for _, after := range []bool{false, true} { + t.Run(fmt.Sprintf("step%d %s/after=%t", k+1, steps[k], after), func(t *testing.T) { + v := fresh() + v.killAt, v.after = k+1, after + if err := snapshotSession(v, "s1", data, req); !errors.Is(err, errKilled) { + t.Fatalf("killed run: %v", err) + } + requireReachablePresent(t, v) + v.dead, v.killAt = false, 0 + if err := snapshotSession(v, "s2", data, req); err != nil { + t.Fatalf("re-run after a kill at step %d: %v", k+1, err) + } + requireCommitted(t, v, data, req) + }) + } + } +} + +// requireReachablePresent: every own object HEAD's current root reaches +// exists (checked after a kill, before the restart). +func requireReachablePresent(t *testing.T, v *memVolume) { + t.Helper() + h := v.head.h + if h.Current == nil { + return + } + if _, ok := v.objects[path.Join(volRoot, h.Current.Path())]; !ok { + t.Fatalf("HEAD names root %s, which is missing", h.Current) + } +} From cfffb3fd7a8e235e658a28ccf611c810490ffd97 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 13:09:53 -0800 Subject: [PATCH 3/4] layout: commit on an empty published image; walk the reached graph An empty image is a real root: once it is HEAD's current root, a commit with an empty previous manifest builds on it instead of being refused as a stale base. Before any commit a previous manifest must be empty; after one it must build to HEAD's current root. The snapshot transaction's interrupt test now checks, right after each kill, every object any root in HEAD reaches (current and snapshot roots, their segments, this volume's chunks, bytes hashed against names), on a fixture that stores real objects. Controls delete a reachable chunk, a segment or a snapshot root, or tamper with a chunk, and each is reported. Abort after a commit leaves the commit in place. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/commit.go | 25 ++-- .../frontend/chunkstore/layout/commit_test.go | 66 +++++++++ .../chunkstore/layout/session_test.go | 135 ++++++++++++++++-- 3 files changed, 204 insertions(+), 22 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit.go b/seaweed-block/core/frontend/chunkstore/layout/commit.go index 4b83d48f97..3afbc378a1 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit.go @@ -23,8 +23,9 @@ var ( // CommitRequest is what a snapshot session commits: the image at // Position, as a manifest, and optionally a snapshot name for it. Prev is -// the manifest of HEAD's current root (empty if none) that the session -// computed what is new against. +// the manifest of HEAD's current root that the session computed what is +// new against: empty when HEAD has no current root, and empty also when +// the current root is that of an empty image. type CommitRequest struct { Session string Prev map[uint64]Ref @@ -113,16 +114,22 @@ func RunCommit(ctx context.Context, st HeadStore, look Lookup, volRoot, vol stri if next, changed, err := h.Commit(me, req.Session, root, req.Position, req.Snapshot); err != nil || !changed { return next, changed, err // refused, or already applied: no lookups } - var base *RootName - if len(req.Prev) > 0 { - rn, _, err := rootOf(req.Prev) + // The base is HEAD's current root. Before any commit there is none + // and the previous manifest must be empty; after one (even of an + // empty image, which is a real root) the previous manifest must + // build to it. + if h.Current == nil { + if len(req.Prev) > 0 { + return Head{}, false, ErrStaleBase + } + } else { + base, _, err := rootOf(req.Prev) if err != nil { return Head{}, false, err } - base = &rn - } - if (base == nil) != (h.Current == nil) || base != nil && *base != *h.Current { - return Head{}, false, ErrStaleBase + if base != *h.Current { + return Head{}, false, ErrStaleBase + } } missing, err := MissingOwn(ctx, look, volRoot, vol, newOwn(vol, req.Prev, req.Next)) if err != nil { diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit_test.go b/seaweed-block/core/frontend/chunkstore/layout/commit_test.go index be58e6d328..5a2119b002 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit_test.go @@ -200,3 +200,69 @@ func TestRunCommit_InterruptAtEveryStep(t *testing.T) { } }) } + +// An empty image is a real root: after it is published, a commit whose +// previous manifest is empty builds on it (empty -> written, and empty -> +// empty); a previous manifest that is not HEAD's current root is still +// refused. +func TestRunCommit_AfterAnEmptyPublishedRoot(t *testing.T) { + ctx := context.Background() + f := &fakeStore{have: map[string]bool{}} + prepared(t, f, nil) + h := idleHead() + st := &memHead{h: &h} + if _, err := RunBegin(ctx, st, me, "s0"); err != nil { + t.Fatal(err) + } + if _, err := runCommit(st, f, CommitRequest{Session: "s0", Snapshot: "empty"}); err != nil { + t.Fatal(err) + } + if st.h.Current == nil { + t.Fatal("the empty snapshot did not publish its root") + } + if _, err := RunBegin(ctx, st, me, "s1"); err != nil { + t.Fatal(err) + } + if _, err := runCommit(st, f, CommitRequest{Session: "s1", Prev: map[uint64]Ref{}, Position: 1}); err != nil { + t.Fatalf("empty -> empty: %v", err) + } + next := manifest(ref("v1", 1, "x")) + prepared(t, f, next) + if _, err := RunBegin(ctx, st, me, "s2"); err != nil { + t.Fatal(err) + } + stale := manifest(ref("v1", 9, "z")) + if _, err := runCommit(st, f, CommitRequest{Session: "s2", Prev: stale, Next: next, Position: 2}); !errors.Is(err, ErrStaleBase) { + t.Fatalf("a non-empty previous manifest over the empty root: %v; want ErrStaleBase", err) + } + if _, err := runCommit(st, f, CommitRequest{Session: "s2", Next: next, Position: 2, Snapshot: "written"}); err != nil { + t.Fatalf("empty -> written: %v", err) + } + if want, _, _ := rootOf(next); *st.h.Current != want { + t.Fatalf("HEAD current %s; want %s", st.h.Current, want) + } + // Before any commit there is no current root: a non-empty previous + // manifest is stale there too. + h0 := Head{Gen: 1, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s9"}} + if _, err := runCommit(&memHead{h: &h0}, f, CommitRequest{Session: "s9", Prev: next, Next: next, Position: 3}); !errors.Is(err, ErrStaleBase) { + t.Fatalf("a previous manifest before any commit: %v; want ErrStaleBase", err) + } +} + +// Abort after the session committed succeeds without a write and leaves +// the commit in place: its success says only that no activity remains. +func TestAbort_AfterCommitLeavesTheCommit(t *testing.T) { + f, h, req := commitFixture(t) + st := &memHead{h: &h} + if _, err := runCommit(st, f, req); err != nil { + t.Fatal(err) + } + committed := *st.h.Current + before := st.updates + if _, err := RunAbort(context.Background(), st, me, "s1"); err != nil { + t.Fatalf("Abort after the commit: %v", err) + } + if st.updates != before || *st.h.Current != committed || st.h.Snapshots["hourly"].Root != committed { + t.Fatalf("Abort after the commit wrote or changed HEAD: %+v", st.h) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/session_test.go b/seaweed-block/core/frontend/chunkstore/layout/session_test.go index 13d18ced25..c8e89926de 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/session_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/session_test.go @@ -156,14 +156,12 @@ func sessionFixture(t *testing.T) (func() *memVolume, map[uint64][]byte, CommitR data := map[uint64][]byte{0: []byte("a"), 3: []byte("b2"), 10004: []byte("c")} prev := manifest(ref("v1", 0, "a"), ref("v1", 3, "b")) next := manifest(ref("v1", 0, "a"), ref("v1", 3, "b2"), ref("v1", 10004, "c"), ref("src", 7, "d")) + prevData := map[uint64][]byte{0: []byte("a"), 3: []byte("b")} fresh := func() *memVolume { - f := &fakeStore{have: map[string]bool{}} - prevRoot := prepared(t, f, prev) objs := map[string][]byte{} - for p := range f.have { - objs[p] = []byte("x") - } - h := Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActIdle}, Current: &prevRoot, Position: 40} + prevRoot := writeImage(t, objs, prev, prevData) + h := Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActIdle}, Current: &prevRoot, Position: 40, + Snapshots: map[string]Snapshot{"daily": {Root: prevRoot}}} return &memVolume{head: &memHead{h: &h}, objects: objs} } return fresh, data, CommitRequest{Prev: prev, Next: next, Position: 50, Snapshot: "hourly"} @@ -199,6 +197,9 @@ func requireCommitted(t *testing.T, v *memVolume, data map[uint64][]byte, req Co if _, ok := v.objects[path.Join(volRoot, rn.Path())]; !ok { t.Fatal("the committed root is missing") } + if err := reachableMissing(h, v.objects); err != nil { + t.Fatalf("after the session HEAD reaches a missing object: %v", err) + } } // Interrupt at every step of the snapshot transaction: killed at each of @@ -239,15 +240,123 @@ func TestSnapshotSession_InterruptAtEveryStep(t *testing.T) { } } -// requireReachablePresent: every own object HEAD's current root reaches -// exists (checked after a kill, before the restart). +// writeImage stores a manifest's own chunks (with their bytes), its +// segments and its root, and returns the root's name. +func writeImage(t *testing.T, objs map[string][]byte, m map[uint64]Ref, data map[uint64][]byte) RootName { + t.Helper() + root, segs, err := Build(m) + if err != nil { + t.Fatal(err) + } + for i, r := range m { + if r.Owner == "v1" { + objs[path.Join(volRoot, r.Chunk.Path())] = data[i] + } + } + for n, b := range segs { + objs[path.Join(volRoot, n.Path())] = b + } + rn, rb, err := NameRoot(root) + if err != nil { + t.Fatal(err) + } + objs[path.Join(volRoot, rn.Path())] = rb + return rn +} + +// reachableMissing walks every root HEAD names (current and every +// snapshot) through its segments to this volume's chunks, reading the +// stored bytes, and reports the first object that is missing or does not +// hash to its name. +func reachableMissing(h *Head, objs map[string][]byte) error { + roots := map[RootName]bool{} + if h.Current != nil { + roots[*h.Current] = true + } + for _, s := range h.Snapshots { + roots[s.Root] = true + } + get := func(rel string, want Hash) ([]byte, error) { + b, ok := objs[path.Join(volRoot, rel)] + if !ok { + return nil, fmt.Errorf("%s is missing", rel) + } + if Sum(b) != want { + return nil, fmt.Errorf("%s does not hash to its name", rel) + } + return b, nil + } + for rn := range roots { + rb, err := get(rn.Path(), rn.Hash) + if err != nil { + return err + } + root, err := DecodeRoot(rb) + if err != nil { + return err + } + for _, sn := range root.Segments { + sb, err := get(sn.Path(), sn.Hash) + if err != nil { + return err + } + seg, err := DecodeSegment(sb) + if err != nil { + return err + } + for _, r := range seg.Chunks { + if r.Owner != "v1" { + continue // the source's pool holds it + } + if _, err := get(r.Chunk.Path(), r.Chunk.Hash); err != nil { + return err + } + } + } + } + return nil +} + +// requireReachablePresent: every object any root in HEAD reaches in this +// volume exists with its bytes (checked after a kill, before the restart). func requireReachablePresent(t *testing.T, v *memVolume) { t.Helper() - h := v.head.h - if h.Current == nil { - return + if err := reachableMissing(v.head.h, v.objects); err != nil { + t.Fatalf("after the kill HEAD reaches a missing object: %v", err) } - if _, ok := v.objects[path.Join(volRoot, h.Current.Path())]; !ok { - t.Fatalf("HEAD names root %s, which is missing", h.Current) +} + +// The reachability observer's negative controls: a reachable own chunk, +// segment or snapshot root deleted (the current root kept) is reported. +func TestReachableMissing_Controls(t *testing.T) { + fresh, _, req := sessionFixture(t) + if err := reachableMissing(fresh().head.h, fresh().objects); err != nil { + t.Fatalf("control: the fixture itself: %v", err) + } + _, segs, _ := Build(req.Prev) + var seg0 SegName + for n := range segs { + seg0 = n + } + for name, rel := range map[string]string{ + "own chunk": req.Prev[3].Chunk.Path(), + "segment": seg0.Path(), + } { + v := fresh() + delete(v.objects, path.Join(volRoot, rel)) + if err := reachableMissing(v.head.h, v.objects); err == nil { + t.Errorf("%s deleted: not reported", name) + } + } + v := fresh() + other := RootName{Hash: Sum([]byte("missing root"))} + v.head.h.Snapshots["weekly"] = Snapshot{Root: other} + if err := reachableMissing(v.head.h, v.objects); err == nil { + t.Error("a snapshot root that is missing: not reported") + } + v = fresh() + v.objects[path.Join(volRoot, req.Prev[0].Chunk.Path())] = []byte("tampered") + if err := reachableMissing(v.head.h, v.objects); err == nil { + t.Error("a chunk whose bytes do not match its name: not reported") } } From 02b4a476da64e4c1b52717fd27c70c9eeedb45d8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 13:15:32 -0800 Subject: [PATCH 4/4] docs: snapshot kernel ledger rows for this step Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index cd49cec125..910cbc639f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -505,16 +505,18 @@ stateDiagram-v2 [*] --> idle: HEAD created outside this package idle --> snap: Begin(s) snap --> idle: Abort(s) + snap --> idle: Commit(s, root) ``` | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | idle | snap(s) | caller is the holder at HEAD's epoch (epoch and server); 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; activity is snap(s); over idle it succeeds without a write and means only that no activity remains | head.go `Head.Abort` | `INV-SNAPK-ABORT-001` | +| snap(s) | idle, current = root | holder at HEAD's epoch; activity is snap(s); the previous manifest builds to HEAD's current root; the new own chunks, every segment and the root are present | commit.go `Head.Commit`, `RunCommit` | `INV-SNAPK-COMMIT-REACH-001`, `INV-SNAPK-TXN-INTERRUPT-001` | ## Part B. Invariant ledger -330 rows: 260 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 315 new. +332 rows: 262 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 317 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -1055,6 +1057,8 @@ Notes: | `INV-SNAPK-HEAD-CODEC-001` | HEAD is canonical JSON with at most 100 snapshots and sorted unique dependents; unknown fields, non-canonical bytes and names that are not valid UTF-8 are refused at encode and decode, and the next HEAD is checked before it is written. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `Head.check`, `Head.Encode`, `DecodeHead` | `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals`, `TestHead_RefusesInvalidUTF8` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-BEGIN-001` | Begin opens snap(s) only for the holder at HEAD's epoch and only from idle; a re-run of the open session writes nothing; killed at its write and re-run, it ends in snap(s) at one generation step. | M9 idle → snap | `core/frontend/chunkstore/layout` `head.go` `Head.Begin`, `RunBegin` | `TestBegin_Closure`, `TestRunBegin_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-ABORT-001` | Abort closes the holder's own snap(s) and changes nothing else; after its own crash a holder rolls the open session back before beginning another; over idle Abort writes nothing and its success never says whether the work was committed. | M9 snap → idle (Abort) | `core/frontend/chunkstore/layout` `head.go` `Head.Abort`, `RunAbort` | `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-COMMIT-REACH-001` | A commit never names an object that is not written: before its one HEAD update it finds present the own chunks new against HEAD's current root (that root rebuilt from the previous manifest, an empty image included), every segment and the root; unchanged and foreign chunks are not looked up. | M9 snap → idle (Commit) | `core/frontend/chunkstore/layout` `commit.go` `RunCommit`, `Head.Commit` | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-TXN-INTERRUPT-001` | A snapshot transaction killed at any of its writes (Begin, each object, Commit), before the write or after it applied with its reply lost, never leaves HEAD reaching a missing object, and the restarted holder (roll back, new session, base recomputed from HEAD) ends at the committed image. | M9 idle → snap → idle | `core/frontend/chunkstore/layout` `head.go`, `commit.go` (the transitions above) | `TestSnapshotSession_InterruptAtEveryStep`, `TestReachableMissing_Controls`, `TestAbort_AfterCommitLeavesTheCommit` | — (the snapshot kernel model is not in this repository) | ACTIVE | Notes: