From c9f4ad4bf537aba8f36c62718eac43c4f31cb079 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 02:48:06 -0800 Subject: [PATCH 1/4] fix: check a commit's objects with the cut's budget, before the HEAD update The commit's object check (every new chunk, segment and root written by the session, unmarked) ran inside the one HEAD update, which the chunk layer bounds at 2 s; the work grows with the changed chunks, so it capped the volume size. The chunk layer now asks the remote to run that check with the cut's context, just before the CAS; the CAS then skips the lookups only for exactly the session and root that passed. Any other CAS (another root, another session, the snapshot commit) runs them inside as before. The session stays open between the two, so no cleaning can begin. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/fake_test.go | 19 +- .../frontend/chunkstore/head_readers_test.go | 4 + .../core/frontend/chunkstore/layout/commit.go | 114 +++++---- .../head_generation_source_guard_test.go | 2 +- .../frontend/chunkstore/layout/stale_test.go | 20 +- .../layout_commit_check_budget_test.go | 223 ++++++++++++++++++ .../core/frontend/chunkstore/layout_remote.go | 72 +++++- .../frontend/chunkstore/layout_remote_test.go | 6 +- .../chunkstore/layout_stop_session_test.go | 7 +- seaweed-block/core/storage/chunk_layer.go | 13 +- seaweed-block/core/storage/chunk_public.go | 31 +-- seaweed-block/core/storage/chunk_seam.go | 8 + seaweed-block/docs/design/invariants.md | 2 +- 13 files changed, 439 insertions(+), 82 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go diff --git a/seaweed-block/core/frontend/chunkstore/fake_test.go b/seaweed-block/core/frontend/chunkstore/fake_test.go index 93dfc985b5..273ae134c2 100644 --- a/seaweed-block/core/frontend/chunkstore/fake_test.go +++ b/seaweed-block/core/frontend/chunkstore/fake_test.go @@ -9,6 +9,7 @@ import ( "sort" "strings" "sync" + "time" "google.golang.org/protobuf/proto" @@ -58,16 +59,28 @@ type fakeFiler struct { stallCreate func(p string) bool // afterLookup, if set, runs under the lock after a lookup of p has read // its result: a change it makes is seen by the next read only. - afterLookup func(p string) + afterLookup func(p string) + // slowLookup, if set, gives a lookup of p a latency, outside the lock + // (lookups overlap) and bounded by ctx, as a remote filer's. + slowLookup func(p string) time.Duration deferredCreates []deferredCreate } func newFakeFiler() *fakeFiler { return &fakeFiler{entries: map[string]*filerpb.Entry{}} } -func (f *fakeFiler) LookupEntry(_ context.Context, dir, name string) (*filerpb.Entry, error) { +func (f *fakeFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + p := path.Join(dir, name) + if slow := f.slowLookup; slow != nil { + if d := slow(p); d > 0 { + select { + case <-time.After(d): + case <-ctx.Done(): + return nil, ctx.Err() + } + } + } f.mu.Lock() defer f.mu.Unlock() - p := path.Join(dir, name) if f.failLookup != nil { if err := f.failLookup(p); err != nil { return nil, err diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 665ee0b7fc..42f20c1487 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -48,6 +48,7 @@ var headReaders = map[string]string{ "core/frontend/chunkstore/layout_remote.go AbortOpenSession -> ReadHead": "refuses ErrHeadAbsent, aborts nothing (probe LayoutRemote)", "core/frontend/chunkstore/layout_remote.go CommitPendingSnapshot -> ReadHead": "refuses ErrHeadAbsent, commits nothing (probe LayoutRemote)", "core/frontend/durable/provider_layout_snapshot.go SnapshotVolume -> ReadHead": "the layout remote's HEAD read: refuses ErrHeadAbsent, names nothing (probe LayoutRemote)", + "core/frontend/chunkstore/layout_remote.go prepareCommitLocked -> ReadHead": "refuses ErrHeadAbsent, writes nothing (probe LayoutRemote: CASHead, CheckCommit)", "core/frontend/chunkstore/layout_remote.go CASHead -> ReadHead": "refuses ErrHeadAbsent, writes nothing (probe LayoutRemote)", "core/frontend/chunkstore/layout_remote.go ReadHead -> ReadHead": "refuses ErrHeadAbsent (probe LayoutRemote)", "core/frontend/chunkstore/layout_remote.go rollBackLocked -> ReadHead": "refuses ErrHeadAbsent before any Begin or upload (probe LayoutRemote)", @@ -217,6 +218,9 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 0, Epoch: 1}, storage.ChunkHead{Epoch: 1}); !errors.Is(err, layout.ErrHeadAbsent) || len(f.written) != 0 { t.Fatalf("engine commit over an absent HEAD: %v (%d writes); want ErrHeadAbsent and none", err, len(f.written)) } + if err := r.CheckCommit(ctx, storage.ChunkHeadVersion{Gen: 0, Epoch: 1}, storage.ChunkHead{Epoch: 1}); !errors.Is(err, layout.ErrHeadAbsent) || len(f.written) != 0 { + t.Fatalf("engine commit check over an absent HEAD: %v (%d writes); want ErrHeadAbsent and none", err, len(f.written)) + } }) t.Run("LayoutCreate", func(t *testing.T) { st := &existsButAbsent{} diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit.go b/seaweed-block/core/frontend/chunkstore/layout/commit.go index 3b267db421..29ebbadd61 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit.go @@ -47,6 +47,16 @@ type CommitRequest struct { Snapshot string // "" = no named snapshot Meta SnapshotMeta // the new snapshot's retention facts State string // StateLive, or StateDetached for the final synced image + // ObjectsChecked says CheckCommitObjects passed for this request's + // session and root, in the same open session: RunCommit then skips the + // object lookups. The caller keys it to exactly (session, root). + ObjectsChecked bool +} + +// CommitRoot is the root a commit of next names. +func CommitRoot(next map[uint64]Ref) (RootName, error) { + root, _, err := rootOf(next) + return root, err } // rootOf names the root of a manifest. @@ -168,53 +178,75 @@ func RunCommit(ctx context.Context, st HeadStore, os ObjectStore, vol string, me 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, req.Meta, req.State); err != nil || !changed { - return next, changed, err // refused, or already applied: no lookups + return commitChecked(ctx, h, os, vol, me, req, root, segs, !req.ObjectsChecked) + }) +} + +// CheckCommitObjects runs RunCommit's checks of req against h, the object +// lookups included, without the update. It is run in the open session after +// its last upload, with the caller's budget rather than the HEAD update's: +// no cleaning can begin while the session is open, so what it found holds +// until that session's commit. A commit already applied passes. +func CheckCommitObjects(ctx context.Context, h Head, os ObjectStore, vol string, me HolderID, req CommitRequest) error { + root, segs, err := rootOf(req.Next) + if err != nil { + return err + } + _, _, err = commitChecked(ctx, h, os, vol, me, req, root, segs, true) + return err +} + +// commitChecked is the commit of req against h after its checks; lookups +// says whether the object lookups run. +func commitChecked(ctx context.Context, h Head, os ObjectStore, vol string, me HolderID, req CommitRequest, root RootName, segs map[SegName][]byte, lookups bool) (Head, bool, error) { + if next, changed, err := h.Commit(me, req.Session, root, req.Position, req.Snapshot, req.Meta, req.State); err != nil || !changed { + return next, changed, err // refused, or already applied: no lookups + } + // 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 } - // 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 - } - if base != *h.Current { - return Head{}, false, ErrStaleBase - } + } else { + base, _, err := rootOf(req.Prev) + if err != nil { + return Head{}, false, err } - if i, ok := addedForeign(vol, h.VolumeID, req.Prev, req.Next); ok { - return Head{}, false, fmt.Errorf("%w: index %d names %s's chunk", ErrForeignRefAdded, i, req.Next[i].Owner) + if base != *h.Current { + return Head{}, false, ErrStaleBase } - var rels []string - chunks := newOwn(vol, req.Prev, req.Next) - idx := make([]uint64, 0, len(chunks)) - for i := range chunks { - idx = append(idx, i) - } - sort.Slice(idx, func(a, b int) bool { return idx[a] < idx[b] }) - for _, i := range idx { - rels = append(rels, chunks[i].Chunk.Path()) - } - 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 { - rels = append(rels, n.Path()) - } - rels = append(rels, root.Path()) + } + if i, ok := addedForeign(vol, h.VolumeID, req.Prev, req.Next); ok { + return Head{}, false, fmt.Errorf("%w: index %d names %s's chunk", ErrForeignRefAdded, i, req.Next[i].Owner) + } + var rels []string + chunks := newOwn(vol, req.Prev, req.Next) + idx := make([]uint64, 0, len(chunks)) + for i := range chunks { + idx = append(idx, i) + } + sort.Slice(idx, func(a, b int) bool { return idx[a] < idx[b] }) + for _, i := range idx { + rels = append(rels, chunks[i].Chunk.Path()) + } + 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 { + rels = append(rels, n.Path()) + } + rels = append(rels, root.Path()) + if lookups { if err := allOwnedBySession(ctx, os, rels, req.Session); err != nil { return Head{}, false, err } - return h.Commit(me, req.Session, root, req.Position, req.Snapshot, req.Meta, req.State) - }) + } + return h.Commit(me, req.Session, root, req.Position, req.Snapshot, req.Meta, req.State) } // commitVerifyParallel bounds the object lookups one commit runs at once. diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_generation_source_guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_generation_source_guard_test.go index 25181344bc..d0cd99704b 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_generation_source_guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_generation_source_guard_test.go @@ -36,7 +36,7 @@ func headGenerationComparisons(name string, src []byte) ([]generationSite, error if name == "core/frontend/chunkstore/layout_store.go" && fn.Name.Name == "UpdateHead" { continue } - if name == "core/frontend/chunkstore/layout_remote.go" && fn.Name.Name == "CASHead" { + if name == "core/frontend/chunkstore/layout_remote.go" && (fn.Name.Name == "CASHead" || fn.Name.Name == "prepareCommitLocked") { continue } aliases := map[*ast.Object]bool{} diff --git a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go index 271488fe14..333c6c5ec1 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go @@ -20,9 +20,12 @@ import ( func TestTransitions_RefuseAStaleHolder(t *testing.T) { rn := RootName{Hash: Sum([]byte("r"))} steps := map[string]func(Head, HolderID) error{ - "Begin": func(h Head, c HolderID) error { _, _, err := h.Begin(c, "s"); return err }, - "Abort": func(h Head, c HolderID) error { _, _, err := h.Abort(c, "s"); return err }, - "Commit": func(h Head, c HolderID) error { _, _, err := h.Commit(c, "s", rn, 1, "", SnapshotMeta{}, StateLive); return err }, + "Begin": func(h Head, c HolderID) error { _, _, err := h.Begin(c, "s"); return err }, + "Abort": func(h Head, c HolderID) error { _, _, err := h.Abort(c, "s"); return err }, + "Commit": func(h Head, c HolderID) error { + _, _, err := h.Commit(c, "s", rn, 1, "", SnapshotMeta{}, StateLive) + return err + }, "BeginClean": func(h Head, c HolderID) error { _, _, err := h.BeginClean(c, "c"); return err }, "EndClean": func(h Head, c HolderID) error { _, _, err := h.EndClean(c, "c"); return err }, "Claim": func(h Head, c HolderID) error { _, _, err := h.Claim(c); return err }, @@ -97,7 +100,16 @@ func TestHolderFunctions_RefuseAStaleHolder(t *testing.T) { t.Errorf("DetachedBy accepted %s", who) } } - covered := map[string]bool{"RemoveUnreachable": true, "Start": true, "startCheck": true, "DetachedBy": true} + // CheckCommitObjects runs commitChecked (RunCommit's body): Head.Commit + // refuses a stale caller before any lookup (no object store is given). + for who, c := range callers { + h := Head{Gen: 2, State: StateLive, Epoch: me.Epoch, Holder: me.Holder, ClaimID: me.ClaimID} + h.Activity = Activity{Kind: ActSnap, Session: "s"} + if err := CheckCommitObjects(context.Background(), h, nil, "v1", c, CommitRequest{Session: "s", Next: map[uint64]Ref{}, State: StateLive}); err == nil { + t.Errorf("CheckCommitObjects by %s over a snap(s) HEAD held by %s passed", who, me.Holder) + } + } + covered := map[string]bool{"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_commit_check_budget_test.go b/seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go new file mode 100644 index 0000000000..cd0690ec47 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go @@ -0,0 +1,223 @@ +package chunkstore + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A cut whose commit checks more objects than the filer can look up within +// one HEAD update (2 s) still commits: the check that every new chunk is +// this session's runs with the cut's budget, before the update. Here every +// chunk lookup takes 2.5 s, as a slow or remote filer's. +func TestCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate(t *testing.T) { + if testing.Short() { + t.Skip("lookups take 2.5 s each") + } + lh := newLayoutHost(t) + s, l, _ := lh.attach("a", true, true) + t.Cleanup(func() { _ = l.Close(); _ = s.Close() }) + w := map[uint32][]byte{} + for c := uint32(0); c < lrBlocks/lrChunkBlocks; c++ { + w[c*lrChunkBlocks] = block(byte(c + 1)) + } + writeSync(t, s, w) + lh.ff.slowLookup = func(p string) time.Duration { + if strings.Contains(p, "/pool/") { + return 2500 * time.Millisecond + } + return 0 + } + before := lh.head() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + if _, err := l.Cut(ctx); err != nil { + t.Fatalf("cut whose object check outlasts one HEAD update: %v", err) + } + after := lh.head() + if after.Current == nil || before.Current != nil && *after.Current == *before.Current { + t.Fatalf("HEAD's root did not move: before %v, after %v", before.Current, after.Current) + } +} + +// c1Remote wraps the holder's LayoutRemote under the chunk layer: check +// replaces CheckCommit (nil: the real one), and pool lookups made inside +// CASHead are counted. +type c1Remote struct { + *LayoutRemote + check func(ctx context.Context, e storage.ChunkHeadVersion, n storage.ChunkHead) error + inCAS atomic.Bool + casGot atomic.Int64 +} + +func (w *c1Remote) CheckCommit(ctx context.Context, e storage.ChunkHeadVersion, n storage.ChunkHead) error { + if w.check != nil { + return w.check(ctx, e, n) + } + return w.LayoutRemote.CheckCommit(ctx, e, n) +} + +func (w *c1Remote) CASHead(ctx context.Context, e storage.ChunkHeadVersion, n storage.ChunkHead) (uint64, error) { + w.inCAS.Store(true) + defer w.inCAS.Store(false) + return w.LayoutRemote.CASHead(ctx, e, n) +} + +// c1Cut writes one block in every chunk of a fresh volume and cuts it once +// through the chunk layer over a c1Remote with check. +func c1Cut(t *testing.T, check func(w *c1Remote) func(context.Context, storage.ChunkHeadVersion, storage.ChunkHead) error) (*layoutHost, *c1Remote, error) { + t.Helper() + lh := newLayoutHost(t) + s, err := storage.CreateWALStoreWithOptions(filepath.Join(lh.dir, "a"), lrBlocks, 4096, storage.WALStoreOptions{ChunkBlocks: lrChunkBlocks}) + if err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + r, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + w := &c1Remote{LayoutRemote: r} + if check != nil { + w.check = check(w) + } + l, err := storage.AttachChunkLayer(s, w, storage.ChunkLayerConfig{ChunkBlocks: lrChunkBlocks, Epoch: lh.me.Epoch, Holder: lh.me.Holder, FreshFromHead: true}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = l.Close(); _ = s.Close() }) + blocks := map[uint32][]byte{} + for c := uint32(0); c < lrBlocks/lrChunkBlocks; c++ { + blocks[c*lrChunkBlocks] = block(byte(c + 1)) + } + writeSync(t, s, blocks) + lh.ff.afterLookup = func(p string) { + if strings.Contains(p, "/pool/") && w.inCAS.Load() { + w.casGot.Add(1) + } + } + _, err = l.Cut(context.Background()) + return lh, w, err +} + +// With the pre-check passed for its (session, root), the CAS looks up no +// chunk; the commit lands. +func TestCASSkipsTheLookupsCheckedForItsSessionAndRoot(t *testing.T) { + _, w, err := c1Cut(t, nil) + if err != nil { + t.Fatal(err) + } + if n := w.casGot.Load(); n != 0 { + t.Fatalf("CAS looked up %d chunks after a passed pre-check of its own root", n) + } +} + +// A CAS with no passed pre-check for its (session, root) runs the lookups +// itself, as before the change: here the pre-check is not run at all. +func TestCASWithNoPassedCheckDoesTheLookups(t *testing.T) { + _, w, err := c1Cut(t, func(*c1Remote) func(context.Context, storage.ChunkHeadVersion, storage.ChunkHead) error { + return func(context.Context, storage.ChunkHeadVersion, storage.ChunkHead) error { return nil } + }) + if err != nil { + t.Fatal(err) + } + if n := w.casGot.Load(); n == 0 { + t.Fatal("CAS with no passed pre-check looked up no chunk") + } +} + +// A pre-check of another root (here the image without its last chunk) is +// not a check of the CAS's root: the CAS does the lookups. +func TestCASAfterACheckOfAnotherRootDoesTheLookups(t *testing.T) { + _, w, err := c1Cut(t, func(w *c1Remote) func(context.Context, storage.ChunkHeadVersion, storage.ChunkHead) error { + return func(ctx context.Context, e storage.ChunkHeadVersion, n storage.ChunkHead) error { + other := n + other.Chunks = map[uint64]storage.ChunkRef{} + last := uint64(0) + for i := range n.Chunks { + last = max(last, i) + } + for i, ref := range n.Chunks { + if i != last { + other.Chunks[i] = ref + } + } + return w.LayoutRemote.CheckCommit(ctx, e, other) + } + }) + if err != nil { + t.Fatal(err) + } + if n := w.casGot.Load(); n == 0 { + t.Fatal("CAS after a pre-check of another root looked up no chunk") + } +} + +// Between the pre-check and the update the session stays open, so a +// cleaning cannot begin (ErrBusy): nothing can remove what was checked. +func TestBeginCleanBetweenTheCheckAndTheUpdateIsBusy(t *testing.T) { + var cleanErr error + lh, _, err := c1Cut(t, func(w *c1Remote) func(context.Context, storage.ChunkHeadVersion, storage.ChunkHead) error { + return func(ctx context.Context, e storage.ChunkHeadVersion, n storage.ChunkHead) error { + if err := w.LayoutRemote.CheckCommit(ctx, e, n); err != nil { + return err + } + s, _ := lhStore(w) + _, cleanErr = layout.RunBeginClean(ctx, s, w.LayoutRemote.me, "c-between") + return nil + } + }) + if err != nil { + t.Fatal(err) + } + if !errors.Is(cleanErr, layout.ErrBusy) { + t.Fatalf("BeginClean between the check and the update: %v, want ErrBusy", cleanErr) + } + if h := lh.head(); h.Activity.Kind != layout.ActIdle || h.Current == nil { + t.Fatalf("after the commit: HEAD %+v", h.Activity) + } +} + +// lhStore is the HEAD store w's remote commits through. +func lhStore(w *c1Remote) (layout.HeadStore, error) { return w.LayoutRemote.st, nil } + +// Only LayoutRemote.CASHead may tell RunCommit that the objects were +// checked, and only for the (session, root) CheckCommit passed: a new site +// that sets ObjectsChecked fails here until it is reviewed and listed. +func TestObjectsCheckedIsSetOnlyByCASHead(t *testing.T) { + var sites []string + for _, dir := range []string{".", "layout"} { + files, err := filepath.Glob(filepath.Join(dir, "*.go")) + if err != nil { + t.Fatal(err) + } + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + b, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + for i, line := range strings.Split(string(b), "\n") { + if strings.Contains(line, "ObjectsChecked =") || strings.Contains(line, "ObjectsChecked:") { + sites = append(sites, fmt.Sprintf("%s:%d", filepath.ToSlash(f), i+1)) + } + } + } + } + if len(sites) != 1 || !strings.HasPrefix(sites[0], "layout_remote.go:") { + t.Fatalf("ObjectsChecked is set at %v; want exactly one site, in LayoutRemote.CASHead", sites) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go index c7e94f7dc8..2f4a742ea5 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -58,7 +58,14 @@ type LayoutRemote struct { // abandoned is set by the engine when a cut ends without a commit // (Abort): the next call drops the session and the pending name. abandoned atomic.Bool - pending *pendingSnapshot + // checked is the (session, root) whose commit's object check passed + // (CheckCommit), in that open session: CASHead skips the lookups only for + // exactly that pair. A new session has a new id, so it never matches. + checked struct { + session string + root layout.RootName + } + pending *pendingSnapshot // snapErr is why the last commit could not name its snapshot (the cut // itself committed unnamed); TakeSnapshotErr hands it to the request. snapErr error @@ -297,38 +304,81 @@ func (l *LayoutRemote) manifest(ctx context.Context, rn layout.RootName) (map[ui // snapshot name. It uses the engine view from before this session's Begin. // A concurrent operator-only HEAD update is rebased with a bounded retry; // a foreign claim or detached/deleted state remains a final refusal. -func (l *LayoutRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { - l.mu.Lock() - defer l.mu.Unlock() +// prepareCommitLocked reads HEAD and builds next's commit request in the +// open session, its root and segments written (CASHead and CheckCommit). +func (l *LayoutRemote) prepareCommitLocked(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (layout.Head, layout.CommitRequest, error) { l.takeAbandonLocked() if expected.Epoch != l.me.Epoch || next.Epoch != l.me.Epoch { - return 0, storage.ErrChunkHeadPrecondition + return layout.Head{}, layout.CommitRequest{}, storage.ErrChunkHeadPrecondition } h, found, err := l.st.ReadHead(ctx) if err != nil { - return 0, err + return layout.Head{}, layout.CommitRequest{}, err } if !found { - return 0, layout.ErrHeadAbsent + return layout.Head{}, layout.CommitRequest{}, layout.ErrHeadAbsent } l.viewLocked(h) if expected.Gen != l.visible { - return 0, storage.ErrChunkHeadPrecondition + return layout.Head{}, layout.CommitRequest{}, storage.ErrChunkHeadPrecondition } prev, nextM, err := l.manifests(ctx, h, next) if err != nil { - return 0, err + return layout.Head{}, layout.CommitRequest{}, err } if err := l.openSessionLocked(ctx); err != nil { - return 0, err + return layout.Head{}, layout.CommitRequest{}, err } if err := l.writeRootLocked(ctx, nextM); err != nil { - return 0, err + return layout.Head{}, layout.CommitRequest{}, err } req := layout.CommitRequest{Session: l.session, Prev: prev, Next: nextM, Position: next.RemoteLSN, State: layout.StateLive} if next.State == "detached" { req.State = layout.StateDetached } + return h, req, nil +} + +// CheckCommit runs the object check of next's commit (every new chunk, +// segment and root written by this session and unmarked) with ctx, the +// cut's budget, before the bounded HEAD update. It runs after the cut's +// last upload, in the same open session; it writes no HEAD. On success +// CASHead skips those lookups for this (session, root). A failed check +// leaves the session open for a retry. +func (l *LayoutRemote) CheckCommit(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) error { + l.mu.Lock() + defer l.mu.Unlock() + l.checked.session, l.checked.root = "", layout.RootName{} + h, req, err := l.prepareCommitLocked(ctx, expected, next) + if err != nil { + return err + } + root, err := layout.CommitRoot(req.Next) + if err != nil { + return err + } + if err := layout.CheckCommitObjects(ctx, h, l.st, l.vol.Name, l.me, req); err != nil { + if errors.Is(err, layout.ErrNotPrepared) { + l.forceView = true // as CASHead: the re-read drops what the ended session staged + return fmt.Errorf("%w: %w", storage.ErrChunkHeadPrecondition, err) + } + return layoutRemoteErr(err) + } + l.checked.session, l.checked.root = req.Session, root + return nil +} + +func (l *LayoutRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + l.mu.Lock() + defer l.mu.Unlock() + h, req, err := l.prepareCommitLocked(ctx, expected, next) + if err != nil { + return 0, err + } + if root, rerr := layout.CommitRoot(req.Next); rerr == nil && l.checked.session != "" && l.checked.session == req.Session && l.checked.root == root { + req.ObjectsChecked = true + } + l.checked.session, l.checked.root = "", layout.RootName{} if l.pending != nil { if err := layout.CheckSnapshot(l.pending.name, l.pending.meta); err != nil { // A name or facts the commit would refuse: the cut commits diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote_test.go b/seaweed-block/core/frontend/chunkstore/layout_remote_test.go index 32c989fae6..b0a6971e1d 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote_test.go @@ -24,12 +24,14 @@ type layoutHost struct { v VolumeRef me layout.HolderID dir string + ff *fakeFiler } func newLayoutHost(t *testing.T) *layoutHost { t.Helper() ctx := context.Background() - cat, err := NewBCatalog(newFakeFiler(), newFakeBlobs(), "/blocks") + ff := newFakeFiler() + cat, err := NewBCatalog(ff, newFakeBlobs(), "/blocks") if err != nil { t.Fatal(err) } @@ -42,7 +44,7 @@ func newLayoutHost(t *testing.T) *layoutHost { if _, err := layout.Start(ctx, s, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "a"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 8 * 4096}, ClaimID: "k-a", Fresh: true, CanStartFrom: anyStart}); err != nil { t.Fatal(err) } - return &layoutHost{t: t, cat: cat, v: v, me: me, dir: t.TempDir()} + return &layoutHost{t: t, cat: cat, v: v, me: me, dir: t.TempDir(), ff: ff} } // attach opens (create: a new local store) the store named name over a new diff --git a/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go b/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go index 5a5262365a..1610fc3921 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go @@ -27,9 +27,10 @@ func TestLayoutRemoteSessionFieldSites(t *testing.T) { return true }) } - // Begin returns the session it opened; CASHead's third read checks that - // it survived a concurrent operator HEAD write before retrying. - if !reflect.DeepEqual(fields, map[string]int{"openSessionLocked": 2, "rollBackLocked": 1, "Begin": 1, "PutPaced": 1, "CASHead": 3, "CommitPendingSnapshot": 2, "writeRootLocked": 1, "Clean": 1, "syncSessionLocked": 3, "takeAbandonLocked": 1}) { + // Begin returns the session it opened; CASHead checks that it survived + // a concurrent operator HEAD write before retrying, and keys its skip of + // the object check to the session CheckCommit checked (checked.session). + if !reflect.DeepEqual(fields, map[string]int{"openSessionLocked": 2, "rollBackLocked": 1, "Begin": 1, "PutPaced": 1, "CASHead": 5, "CheckCommit": 2, "prepareCommitLocked": 1, "CommitPendingSnapshot": 2, "writeRootLocked": 1, "Clean": 1, "syncSessionLocked": 3, "takeAbandonLocked": 1}) { t.Fatal("session field sites changed; enumerate and probe them", fields) } } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 87f42feb59..277becf626 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1111,6 +1111,18 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch persistCapturedMap(capturedVersions) return chunkCutResult{H: h, Head: copyHead(cur), Noop: true, FullHash: all}, nil } + expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch} + // The commit's object check runs here, with the cut's budget: inside the + // CAS it would share the 2 s HEAD update. A lookup failure writes nothing + // and leaves the session open; the dirty set returns for the next cut. A + // precondition or fence goes on to the CAS, which answers it from HEAD + // (before any lookup) and resolves it as without the check. + if c, ok := l.remote.(chunkCommitChecker); ok { + if err := c.CheckCommit(ctx, expected, next); err != nil && !errors.Is(err, errChunkHeadPrecondition) && !errors.Is(err, errChunkLayerFenced) { + l.requeueCut(all) + return chunkCutResult{}, fmt.Errorf("storage: commit check: %w: %w", errChunkRemoteUnavailable, err) + } + } if err := l.admit(); err != nil { // admission re-checked right before the CAS l.requeueCut(all) return chunkCutResult{}, err @@ -1123,7 +1135,6 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.abortCOW(errChunkLayerFenced) return chunkCutResult{}, errChunkLayerFenced } - expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch} casStart := time.Now() gen, casErr := casAndConfirmChunkHeadMeasured(ctx, l.remote, expected, next, &st) st.CASNs = time.Since(casStart).Nanoseconds() diff --git a/seaweed-block/core/storage/chunk_public.go b/seaweed-block/core/storage/chunk_public.go index c182ceb9b0..139f59501a 100644 --- a/seaweed-block/core/storage/chunk_public.go +++ b/seaweed-block/core/storage/chunk_public.go @@ -5,21 +5,22 @@ package storage // contract types single-sourced in chunk_seam.go. type ( - ChunkRemote = chunkRemote - ChunkHead = chunkHead - ChunkHeadVersion = chunkHeadVersion - ChunkRef = chunkRef - ChunkBitmapStore = chunkBitmapStore - ChunkBitmapHeader = chunkBitmapHeader - ChunkBaseState = chunkBaseState - ChunkDelta = chunkDelta - ChunkLayerConfig = chunkLayerConfig - ChunkLayer = chunkLayer - ChunkCutResult = chunkCutResult - ChunkCutStats = chunkCutStats - ChunkLayerStats = chunkLayerStats - ChunkDetachedBy = chunkDetachedBy - DetachSettlement = detachSettlement + ChunkRemote = chunkRemote + ChunkCommitChecker = chunkCommitChecker + ChunkHead = chunkHead + ChunkHeadVersion = chunkHeadVersion + ChunkRef = chunkRef + ChunkBitmapStore = chunkBitmapStore + ChunkBitmapHeader = chunkBitmapHeader + ChunkBaseState = chunkBaseState + ChunkDelta = chunkDelta + ChunkLayerConfig = chunkLayerConfig + ChunkLayer = chunkLayer + ChunkCutResult = chunkCutResult + ChunkCutStats = chunkCutStats + ChunkLayerStats = chunkLayerStats + ChunkDetachedBy = chunkDetachedBy + DetachSettlement = detachSettlement ) // How a failed Detach ended (ChunkLayer.SettleDetach). diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index d453bd0c78..54f15338c5 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -244,6 +244,14 @@ type chunkRemote interface { Abort() } +// chunkCommitChecker is a chunkRemote that checks a commit's objects (every +// new chunk, segment and root written by this holder's session) before the +// bounded HEAD update: CheckCommit with the cut's budget, then CASHead for +// the same next skips that check. +type chunkCommitChecker interface { + CheckCommit(ctx context.Context, expected chunkHeadVersion, next chunkHead) error +} + // validChunkKey is the chunk key domain: a non-empty, valid UTF-8 string. // Every remote refuses any other key at Put, before it persists anything (an // encoding that replaced invalid bytes would store another key than the diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d404ca0235..5b2442d60e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1078,7 +1078,7 @@ 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`; `core/frontend/durable/provider_layout.go` `settleLayoutStop` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestLayoutRemote_AbortOpenSessionDoesNotWaitForAHeldCommit`, `TestLayoutRemote_AbortOpenSessionFencesAForeignHead`, `TestLayoutRemoteSessionFieldSites`, `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`; its verification is bounded parallel and stays all-or-nothing: `TestCommitVerifiesManyNewChunksWithinTheBudget`, `TestADetachingCommitOfManyNewChunksCompletesWithinTheBudget`, `TestCommitRefusesWhenOneOfManyNewChunksIsNotPrepared`, `TestCommitLookupsNeverExceedTheCap`, `TestACancelledCommitStopsJoinsAndWritesNothing`, `TestTheEarliestFailureByPositionDecidesTheError` (`commit_verify_scale_test.go`, `commit_verify_controls_test.go`) | — (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`, `CheckCommitObjects`, `Head.Commit`; the lookups run with the cut's budget before the bounded HEAD update (`layout_remote.go` `LayoutRemote.CheckCommit`, called by `core/storage/chunk_layer.go`), and the CAS skips them only for the (session, root) checked | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep`; its verification is bounded parallel and stays all-or-nothing: `TestCommitVerifiesManyNewChunksWithinTheBudget`, `TestADetachingCommitOfManyNewChunksCompletesWithinTheBudget`, `TestCommitRefusesWhenOneOfManyNewChunksIsNotPrepared`, `TestCommitLookupsNeverExceedTheCap`, `TestACancelledCommitStopsJoinsAndWritesNothing`, `TestTheEarliestFailureByPositionDecidesTheError` (`commit_verify_scale_test.go`, `commit_verify_controls_test.go`); outside the 2 s update: `TestCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestCASSkipsTheLookupsCheckedForItsSessionAndRoot`, `TestCASWithNoPassedCheckDoesTheLookups`, `TestCASAfterACheckOfAnotherRootDoesTheLookups`, `TestBeginCleanBetweenTheCheckAndTheUpdateIsBusy`, `TestObjectsCheckedIsSetOnlyByCASHead` (`core/frontend/chunkstore/layout_commit_check_budget_test.go`) | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-SNAPSHOT-META-001` | Snapshot retention metadata (creation time, class, expiry and at most four bounded labels) is written by the commit that creates the snapshot name and never changed by a replay. | M9 snap -> idle (named Commit) | `core/frontend/chunkstore/layout/head.go` `SnapshotMeta`, codec; `commit.go` `Head.Commit`, `RunCommit`; host `chunkControl.Snapshot`, `ListSnapshots` | `TestSnapshotMeta_WrittenOnceByTheCommit`, `TestHead_BoundsRefused`, `TestGuard_SafetyIgnoresSnapshotMeta`; `TestChunkControlPassesRetentionFactsToTheNamedCommit`, `TestChunkControlUsesTheBoundLayoutIdentity` | Retention facts affect policy only; the safety guard forbids their use in reachability/removal. Actual provider and scheduled capture integration remain cutover work; no live-path claim. | ACTIVE | | `INV-SNAPK-DETACHED-001` | A detached HEAD remains closed to its same-epoch holder; only a higher-epoch Claim returns it to live. | M9 snap → detached → higher-epoch idle | `core/frontend/chunkstore/layout` `commit.go`, `head.go`, `claim.go`, `start.go` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestWorkspaceLayoutDetachedProof`, `TestCommitDetached_ProofAndLostReply`, `TestDetachedHEAD_RefusesEveryHolderTransition`, `TestDetachedHEAD_NewGrantStillWaitsForTheOldLease` | Caller write-barrier and synced-position join, master clean-proof reader and composed model review remain cutover gates. | 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 | From 3051e8f42c13667191b09d16652662a19f84b537 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 03:03:01 -0800 Subject: [PATCH 2/4] fix: forward the commit check through the provider's wrapped remote blockvolume's chunk layer holds the LayoutRemote inside closeBoundRemote and layoutBoundRemote, so its assertion for the commit check failed and the lookups stayed inside the 2 s HEAD update. closeBoundRemote now forwards CheckCommit with the same binding as CASHead; a remote without it passes, and its CAS checks inside. Tests go through the provider's attach, check every optional interface the chunk layer asserts against the wrapped remote, and cover a pre-check that finds a chunk missing. Co-Authored-By: Claude Opus 5.5 --- .../layout_commit_check_budget_test.go | 36 ++++- .../durable/commit_check_budget_test.go | 147 ++++++++++++++++++ .../core/frontend/durable/provider_chunk.go | 12 ++ seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 195 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/commit_check_budget_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go b/seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go index cd0690ec47..e5e5f59ddf 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go @@ -57,6 +57,7 @@ type c1Remote struct { check func(ctx context.Context, e storage.ChunkHeadVersion, n storage.ChunkHead) error inCAS atomic.Bool casGot atomic.Int64 + ff *fakeFiler } func (w *c1Remote) CheckCommit(ctx context.Context, e storage.ChunkHeadVersion, n storage.ChunkHead) error { @@ -88,7 +89,7 @@ func c1Cut(t *testing.T, check func(w *c1Remote) func(context.Context, storage.C if err != nil { t.Fatal(err) } - w := &c1Remote{LayoutRemote: r} + w := &c1Remote{LayoutRemote: r, ff: lh.ff} if check != nil { w.check = check(w) } @@ -221,3 +222,36 @@ func TestObjectsCheckedIsSetOnlyByCASHead(t *testing.T) { t.Fatalf("ObjectsChecked is set at %v; want exactly one site, in LayoutRemote.CASHead", sites) } } + +// A pre-check that finds a chunk missing (here one uploaded chunk is gone +// from the filer) ends the cut as a refusal: the CAS that follows answers it +// from HEAD and looks up no chunk, and HEAD keeps its root. +func TestAPreCheckThatFindsAChunkMissingEndsWithNoLookupInTheCAS(t *testing.T) { + var lost string + lh, w, err := c1Cut(t, func(w *c1Remote) func(context.Context, storage.ChunkHeadVersion, storage.ChunkHead) error { + return func(ctx context.Context, e storage.ChunkHeadVersion, n storage.ChunkHead) error { + w.ff.mu.Lock() + for p := range w.ff.entries { + if strings.Contains(p, "/pool/") { + lost = p + delete(w.ff.entries, p) + break + } + } + w.ff.mu.Unlock() + return w.LayoutRemote.CheckCommit(ctx, e, n) + } + }) + if lost == "" { + t.Fatal("no uploaded chunk to remove") + } + if err == nil { + t.Fatalf("cut committed with %s missing", lost) + } + if n := w.casGot.Load(); n != 0 { + t.Fatalf("CAS after a failed pre-check looked up %d chunks", n) + } + if h := lh.head(); h.Current != nil { + t.Fatalf("HEAD moved to %v after a refused commit", h.Current) + } +} diff --git a/seaweed-block/core/frontend/durable/commit_check_budget_test.go b/seaweed-block/core/frontend/durable/commit_check_budget_test.go new file mode 100644 index 0000000000..c629bda77c --- /dev/null +++ b/seaweed-block/core/frontend/durable/commit_check_budget_test.go @@ -0,0 +1,147 @@ +package durable + +import ( + "bytes" + "context" + "os" + "path" + "path/filepath" + "regexp" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// slowPoolFiler gives every lookup of a chunk object (pool/) a latency, +// bounded by its ctx as a remote filer's is. +type slowPoolFiler struct { + *chunkstore.MemFiler + delay atomic.Int64 // nanoseconds; 0 = none +} + +func (f *slowPoolFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if d := time.Duration(f.delay.Load()); d > 0 && strings.Contains(path.Join(dir, name), "/pool/") { + select { + case <-time.After(d): + case <-ctx.Done(): + return nil, ctx.Err() + } + } + return f.MemFiler.LookupEntry(ctx, dir, name) +} + +// Through the provider's own attach (the remote wrapped as blockvolume wraps +// it), a cut whose commit checks objects slower than one HEAD update (2 s) +// still publishes: the check runs with the cut's budget, before the update. +func TestProviderCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate(t *testing.T) { + if testing.Short() { + t.Skip("lookups take 2.5 s each") + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + filer := &slowPoolFiler{MemFiler: chunkstore.NewMemFiler()} + b := &kzLayoutBlobs{b: map[string][]byte{}} + cat, err := chunkstore.NewBCatalog(filer, b, "/c1") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 256 * 4096, BlockSize: 4096, ChunkBytes: 16 * 4096}); err != nil { + t.Fatal(err) + } + remote := &kzLayout{cat: cat, ref: ref, blobs: b} + p := kzProvider(t, t.TempDir(), remote) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + for c := 0; c < 16; c++ { + if _, err := p.Backend("v1").Write(ctx, int64(c)*16*4096, bytes.Repeat([]byte{byte(c + 1)}, 4096)); err != nil { + t.Fatal(err) + } + } + if err := p.Backend("v1").Sync(ctx); err != nil { + t.Fatal(err) + } + before, _, err := cat.ReadHead(ctx, ref) + if err != nil { + t.Fatal(err) + } + filer.delay.Store(int64(2500 * time.Millisecond)) + if _, err := p.CaptureVolume(ctx, "v1"); err != nil { + t.Fatalf("capture whose object check outlasts one HEAD update: %v", err) + } + after, _, err := cat.ReadHead(ctx, ref) + if err != nil { + t.Fatal(err) + } + if after.Current == nil || before.Current != nil && *after.Current == *before.Current { + t.Fatalf("HEAD's root did not move: before %v, after %v", before.Current, after.Current) + } +} + +// Every optional interface the chunk layer asserts on its remote, and the +// holder's LayoutRemote implements, is still implemented by the remote as +// the provider wraps it. The list is checked against the chunk layer's +// assertions in storage, read from its source: a new assertion fails here +// until it is listed. +func TestProviderWrappedRemoteKeepsTheLayoutRemotesOptionalInterfaces(t *testing.T) { + remote := newKZLayout(t) + lr, err := chunkstore.NewLayoutRemote(remote.cat, remote.ref, layout.HolderID{Epoch: 1, Holder: "a", ClaimID: "k"}) + if err != nil { + t.Fatal(err) + } + wrapped := storage.ChunkRemote(&layoutBoundRemote{closeBoundRemote: &closeBoundRemote{ChunkRemote: lr, done: context.Background()}, keyer: lr}) + checks := map[string]func(storage.ChunkRemote) bool{ + "ChunkHeadRootReader": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkHeadRootReader); return ok }, + "ChunkCommitChecker": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkCommitChecker); return ok }, + "ChunkKeyer": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkKeyer); return ok }, + "ChunkPutRounds": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkPutRounds); return ok }, + } + for name, has := range checks { + if has(lr) && !has(wrapped) { + t.Errorf("the provider's wrapped remote drops %s, which its LayoutRemote implements", name) + } + } + asserted := map[string]bool{} + files, err := filepath.Glob("../../storage/*.go") + if err != nil || len(files) == 0 { + t.Fatalf("storage sources: %v (%d files)", err, len(files)) + } + re := regexp.MustCompile(`remote\.\((\w+)\)`) + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + src, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + for _, m := range re.FindAllStringSubmatch(string(src), -1) { + asserted[strings.ToUpper(m[1][:1])+m[1][1:]] = true + } + } + for name := range asserted { + if checks[name] == nil { + t.Errorf("storage asserts %s on its remote; list it here", name) + } + } + if len(asserted) == 0 { + t.Fatal("found no remote assertion in storage: the scan is broken") + } + if _, ok := storage.ChunkRemote(lr).(storage.ChunkCommitChecker); !ok { + t.Fatal("LayoutRemote no longer implements ChunkCommitChecker") + } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 316eda9439..e275e2ac4e 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -663,6 +663,18 @@ func (r *closeBoundRemote) CASHead(ctx context.Context, expected storage.ChunkHe return r.ChunkRemote.CASHead(c, expected, next) } +// CheckCommit forwards the commit's object check (storage.ChunkCommitChecker) +// with the same binding as CASHead. A remote without it passes: its CAS then +// runs the check itself. +func (r *closeBoundRemote) CheckCommit(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) error { + c, end := r.bind(ctx) + defer end() + if checker, ok := r.ChunkRemote.(storage.ChunkCommitChecker); ok { + return checker.CheckCommit(c, expected, next) + } + return nil +} + func (r *closeBoundRemote) Delete(ctx context.Context, key string) error { c, end := r.bind(ctx) defer end() diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5b2442d60e..fcf01f7bd5 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1078,7 +1078,7 @@ 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`; `core/frontend/durable/provider_layout.go` `settleLayoutStop` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestLayoutRemote_AbortOpenSessionDoesNotWaitForAHeldCommit`, `TestLayoutRemote_AbortOpenSessionFencesAForeignHead`, `TestLayoutRemoteSessionFieldSites`, `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`, `CheckCommitObjects`, `Head.Commit`; the lookups run with the cut's budget before the bounded HEAD update (`layout_remote.go` `LayoutRemote.CheckCommit`, called by `core/storage/chunk_layer.go`), and the CAS skips them only for the (session, root) checked | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep`; its verification is bounded parallel and stays all-or-nothing: `TestCommitVerifiesManyNewChunksWithinTheBudget`, `TestADetachingCommitOfManyNewChunksCompletesWithinTheBudget`, `TestCommitRefusesWhenOneOfManyNewChunksIsNotPrepared`, `TestCommitLookupsNeverExceedTheCap`, `TestACancelledCommitStopsJoinsAndWritesNothing`, `TestTheEarliestFailureByPositionDecidesTheError` (`commit_verify_scale_test.go`, `commit_verify_controls_test.go`); outside the 2 s update: `TestCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestCASSkipsTheLookupsCheckedForItsSessionAndRoot`, `TestCASWithNoPassedCheckDoesTheLookups`, `TestCASAfterACheckOfAnotherRootDoesTheLookups`, `TestBeginCleanBetweenTheCheckAndTheUpdateIsBusy`, `TestObjectsCheckedIsSetOnlyByCASHead` (`core/frontend/chunkstore/layout_commit_check_budget_test.go`) | — (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`, `CheckCommitObjects`, `Head.Commit`; the lookups run with the cut's budget before the bounded HEAD update (`layout_remote.go` `LayoutRemote.CheckCommit`, called by `core/storage/chunk_layer.go`), and the CAS skips them only for the (session, root) checked | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep`; its verification is bounded parallel and stays all-or-nothing: `TestCommitVerifiesManyNewChunksWithinTheBudget`, `TestADetachingCommitOfManyNewChunksCompletesWithinTheBudget`, `TestCommitRefusesWhenOneOfManyNewChunksIsNotPrepared`, `TestCommitLookupsNeverExceedTheCap`, `TestACancelledCommitStopsJoinsAndWritesNothing`, `TestTheEarliestFailureByPositionDecidesTheError` (`commit_verify_scale_test.go`, `commit_verify_controls_test.go`); outside the 2 s update: `TestCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestCASSkipsTheLookupsCheckedForItsSessionAndRoot`, `TestCASWithNoPassedCheckDoesTheLookups`, `TestCASAfterACheckOfAnotherRootDoesTheLookups`, `TestBeginCleanBetweenTheCheckAndTheUpdateIsBusy`, `TestObjectsCheckedIsSetOnlyByCASHead`, `TestAPreCheckThatFindsAChunkMissingEndsWithNoLookupInTheCAS` (`core/frontend/chunkstore/layout_commit_check_budget_test.go`); through the provider's wrapped remote: `TestProviderCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestProviderWrappedRemoteKeepsTheLayoutRemotesOptionalInterfaces` (`core/frontend/durable/commit_check_budget_test.go`) | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-SNAPSHOT-META-001` | Snapshot retention metadata (creation time, class, expiry and at most four bounded labels) is written by the commit that creates the snapshot name and never changed by a replay. | M9 snap -> idle (named Commit) | `core/frontend/chunkstore/layout/head.go` `SnapshotMeta`, codec; `commit.go` `Head.Commit`, `RunCommit`; host `chunkControl.Snapshot`, `ListSnapshots` | `TestSnapshotMeta_WrittenOnceByTheCommit`, `TestHead_BoundsRefused`, `TestGuard_SafetyIgnoresSnapshotMeta`; `TestChunkControlPassesRetentionFactsToTheNamedCommit`, `TestChunkControlUsesTheBoundLayoutIdentity` | Retention facts affect policy only; the safety guard forbids their use in reachability/removal. Actual provider and scheduled capture integration remain cutover work; no live-path claim. | ACTIVE | | `INV-SNAPK-DETACHED-001` | A detached HEAD remains closed to its same-epoch holder; only a higher-epoch Claim returns it to live. | M9 snap → detached → higher-epoch idle | `core/frontend/chunkstore/layout` `commit.go`, `head.go`, `claim.go`, `start.go` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestWorkspaceLayoutDetachedProof`, `TestCommitDetached_ProofAndLostReply`, `TestDetachedHEAD_RefusesEveryHolderTransition`, `TestDetachedHEAD_NewGrantStillWaitsForTheOldLease` | Caller write-barrier and synced-position join, master clean-proof reader and composed model review remain cutover gates. | 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 | From 263a1ffa9b6993cb63ffba0e49169c328fc1f74e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 06:15:15 -0800 Subject: [PATCH 3/4] test: syntax-aware ObjectsChecked census; session, snapshot and retry guards The writer census parses every production file and attributes each write of ObjectsChecked to its receiver and method (only CASHead), with controls for another method, a keyed literal and a multiple assignment. New guards: a check passed in one session is not reused after an abort and a new session at the same root; CommitPendingSnapshot looks up the root and segments; the metadata-conflict retry looks up again without a passed check and may reuse a passed check of the same pair. Co-Authored-By: Claude Opus 5.5 --- .../layout_commit_check_budget_test.go | 32 --- .../layout_commit_check_guards_test.go | 228 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 229 insertions(+), 33 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout_commit_check_guards_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go b/seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go index e5e5f59ddf..2b1c049a75 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go @@ -3,8 +3,6 @@ package chunkstore import ( "context" "errors" - "fmt" - "os" "path/filepath" "strings" "sync/atomic" @@ -193,36 +191,6 @@ func TestBeginCleanBetweenTheCheckAndTheUpdateIsBusy(t *testing.T) { // lhStore is the HEAD store w's remote commits through. func lhStore(w *c1Remote) (layout.HeadStore, error) { return w.LayoutRemote.st, nil } -// Only LayoutRemote.CASHead may tell RunCommit that the objects were -// checked, and only for the (session, root) CheckCommit passed: a new site -// that sets ObjectsChecked fails here until it is reviewed and listed. -func TestObjectsCheckedIsSetOnlyByCASHead(t *testing.T) { - var sites []string - for _, dir := range []string{".", "layout"} { - files, err := filepath.Glob(filepath.Join(dir, "*.go")) - if err != nil { - t.Fatal(err) - } - for _, f := range files { - if strings.HasSuffix(f, "_test.go") { - continue - } - b, err := os.ReadFile(f) - if err != nil { - t.Fatal(err) - } - for i, line := range strings.Split(string(b), "\n") { - if strings.Contains(line, "ObjectsChecked =") || strings.Contains(line, "ObjectsChecked:") { - sites = append(sites, fmt.Sprintf("%s:%d", filepath.ToSlash(f), i+1)) - } - } - } - } - if len(sites) != 1 || !strings.HasPrefix(sites[0], "layout_remote.go:") { - t.Fatalf("ObjectsChecked is set at %v; want exactly one site, in LayoutRemote.CASHead", sites) - } -} - // A pre-check that finds a chunk missing (here one uploaded chunk is gone // from the filer) ends the cut as a refusal: the CAS that follows answers it // from HEAD and looks up no chunk, and HEAD keeps its root. diff --git a/seaweed-block/core/frontend/chunkstore/layout_commit_check_guards_test.go b/seaweed-block/core/frontend/chunkstore/layout_commit_check_guards_test.go new file mode 100644 index 0000000000..601402ecbd --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_commit_check_guards_test.go @@ -0,0 +1,228 @@ +package chunkstore + +import ( + "context" + "fmt" + "go/ast" + "go/parser" + "go/token" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "sync/atomic" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// objectsCheckedWriters returns every place in src that writes +// ObjectsChecked (an assignment to a field of that name, or a keyed +// composite-literal element), as "file (Receiver).Method" or "file func". +func objectsCheckedWriters(t *testing.T, file, src string) []string { + t.Helper() + f, err := parser.ParseFile(token.NewFileSet(), file, src, 0) + if err != nil { + t.Fatalf("parse %s: %v", file, err) + } + var sites []string + for _, d := range f.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + owner := fn.Name.Name + if fn.Recv != nil && len(fn.Recv.List) == 1 { + typ := fn.Recv.List[0].Type + if star, ok := typ.(*ast.StarExpr); ok { + typ = star.X + } + if id, ok := typ.(*ast.Ident); ok { + owner = "(" + id.Name + ")." + fn.Name.Name + } + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.AssignStmt: + for _, lhs := range x.Lhs { + if sel, ok := lhs.(*ast.SelectorExpr); ok && sel.Sel.Name == "ObjectsChecked" { + sites = append(sites, file+" "+owner) + } + } + case *ast.KeyValueExpr: + if id, ok := x.Key.(*ast.Ident); ok && id.Name == "ObjectsChecked" { + sites = append(sites, file+" "+owner) + } + } + return true + }) + } + return sites +} + +// Only LayoutRemote.CASHead may tell RunCommit that the objects were +// checked (and only for the session and root CheckCommit passed). The +// census parses every production Go file of the module and attributes each +// write to its receiver and method; the controls show it finds a write in +// another method, a keyed literal and a multiple assignment. +func TestObjectsCheckedIsWrittenOnlyByCASHead(t *testing.T) { + root, err := filepath.Abs(filepath.Join("..", "..", "..")) + if err != nil { + t.Fatal(err) + } + var sites []string + err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if name := d.Name(); name == ".git" || name == "testdata" || name == "vendor" { + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { + return nil + } + b, err := os.ReadFile(p) + if err != nil { + return err + } + if !strings.Contains(string(b), "ObjectsChecked") { + return nil + } + rel, _ := filepath.Rel(root, p) + sites = append(sites, objectsCheckedWriters(t, filepath.ToSlash(rel), string(b))...) + return nil + }) + if err != nil { + t.Fatal(err) + } + sort.Strings(sites) + want := []string{"core/frontend/chunkstore/layout_remote.go (LayoutRemote).CASHead"} + if fmt.Sprint(sites) != fmt.Sprint(want) { + t.Fatalf("ObjectsChecked is written at %v; want only %v", sites, want) + } + + for name, c := range map[string]struct { + src string + want string + }{ + "another LayoutRemote method": { + "package chunkstore\nfunc (l *LayoutRemote) Other(req *CommitRequest) { req.ObjectsChecked = true }\n", + "x.go (LayoutRemote).Other", + }, + "a keyed literal in another package": { + "package other\nfunc build() { _ = layout.CommitRequest{Session: \"s\", ObjectsChecked: true} }\n", + "x.go build", + }, + "a multiple assignment": { + "package chunkstore\nfunc (l *LayoutRemote) CASHead2(req *CommitRequest) { var n int; req.ObjectsChecked, n = true, 1; _ = n }\n", + "x.go (LayoutRemote).CASHead2", + }, + } { + if got := objectsCheckedWriters(t, "x.go", c.src); len(got) != 1 || got[0] != c.want { + t.Errorf("control %q: census found %v, want [%s]", name, got, c.want) + } + } +} + +// A check passed in one session does not cover the same root in another: +// after an abort and a new session, the CAS of the same image does the +// lookups. +func TestCASAfterAnAbortAndANewSessionAtTheSameRootDoesTheLookups(t *testing.T) { + var checkedIn string + _, w, _ := c1Cut(t, func(w *c1Remote) func(context.Context, storage.ChunkHeadVersion, storage.ChunkHead) error { + return func(ctx context.Context, e storage.ChunkHeadVersion, n storage.ChunkHead) error { + if err := w.LayoutRemote.CheckCommit(ctx, e, n); err != nil { + return err + } + w.LayoutRemote.mu.Lock() + checkedIn = w.LayoutRemote.checked.session + w.LayoutRemote.mu.Unlock() + w.LayoutRemote.Abort() // the next call drops the session; CASHead opens another + return nil + } + }) + if checkedIn == "" { + t.Fatal("the pre-check recorded no session") + } + if n := w.casGot.Load(); n == 0 { + t.Fatal("CAS in a new session looked up no chunk: a check of another session was reused") + } +} + +// CommitPendingSnapshot never has a passed check: naming the current image +// (no new chunks) still looks up its segments and its root. +func TestCommitPendingSnapshotLooksUpTheRootAndSegments(t *testing.T) { + lh, w, err := c1Cut(t, nil) + if err != nil { + t.Fatal(err) + } + var segRoot atomic.Int64 + lh.ff.afterLookup = func(p string) { + if strings.Contains(p, "/seg/") || strings.Contains(p, "/root/") { + segRoot.Add(1) + } + } + w.LayoutRemote.SetSnapshot("s1", layout.SnapshotMeta{}) + if err := w.LayoutRemote.CommitPendingSnapshot(context.Background()); err != nil { + t.Fatal(err) + } + if segRoot.Load() == 0 { + t.Fatal("CommitPendingSnapshot looked up no segment or root") + } + if _, ok := lh.head().Snapshots["s1"]; !ok { + t.Fatal("snapshot s1 not in HEAD") + } +} + +// The metadata-conflict retry inside CASHead (HEAD's generation moved with +// its image and session unchanged, as by an operator's snapshot-table +// write): without a passed check the retry looks up the chunks again; with +// one for the same pair it may reuse it. +func TestMetadataRetryLooksUpOnlyWithoutAPassedCheck(t *testing.T) { + for _, c := range []struct { + name string + check bool + lookups bool + }{ + {"no passed check", false, true}, + {"passed check of the same pair", true, false}, + } { + t.Run(c.name, func(t *testing.T) { + var retried atomic.Bool + var atRetry atomic.Int64 + var ff *fakeFiler + _, w, err := c1Cut(t, func(w *c1Remote) func(context.Context, storage.ChunkHeadVersion, storage.ChunkHead) error { + ff = w.ff + ff.failUpdate = func(p string) error { + if strings.HasSuffix(p, "/HEAD") && w.inCAS.Load() && !retried.Load() { + retried.Store(true) + atRetry.Store(w.casGot.Load()) + e := ff.entries[p] // under ff.mu: an operator write that moves only the generation + gen := string(e.Extended[layoutGen]) + e.Extended[layoutGen] = []byte(gen + "0") + } + return nil + } + if c.check { + return nil // the real pre-check + } + return func(context.Context, storage.ChunkHeadVersion, storage.ChunkHead) error { return nil } + }) + if err != nil { + t.Fatal(err) + } + if !retried.Load() { + t.Fatal("no metadata retry happened") + } + afterRetry := w.casGot.Load() - atRetry.Load() + if got := afterRetry > 0; got != c.lookups { + t.Fatalf("retry looked up %d chunks; want lookups=%v", afterRetry, c.lookups) + } + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index fcf01f7bd5..7ac18c11c3 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1078,7 +1078,7 @@ 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`; `core/frontend/durable/provider_layout.go` `settleLayoutStop` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestLayoutRemote_AbortOpenSessionDoesNotWaitForAHeldCommit`, `TestLayoutRemote_AbortOpenSessionFencesAForeignHead`, `TestLayoutRemoteSessionFieldSites`, `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`, `CheckCommitObjects`, `Head.Commit`; the lookups run with the cut's budget before the bounded HEAD update (`layout_remote.go` `LayoutRemote.CheckCommit`, called by `core/storage/chunk_layer.go`), and the CAS skips them only for the (session, root) checked | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep`; its verification is bounded parallel and stays all-or-nothing: `TestCommitVerifiesManyNewChunksWithinTheBudget`, `TestADetachingCommitOfManyNewChunksCompletesWithinTheBudget`, `TestCommitRefusesWhenOneOfManyNewChunksIsNotPrepared`, `TestCommitLookupsNeverExceedTheCap`, `TestACancelledCommitStopsJoinsAndWritesNothing`, `TestTheEarliestFailureByPositionDecidesTheError` (`commit_verify_scale_test.go`, `commit_verify_controls_test.go`); outside the 2 s update: `TestCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestCASSkipsTheLookupsCheckedForItsSessionAndRoot`, `TestCASWithNoPassedCheckDoesTheLookups`, `TestCASAfterACheckOfAnotherRootDoesTheLookups`, `TestBeginCleanBetweenTheCheckAndTheUpdateIsBusy`, `TestObjectsCheckedIsSetOnlyByCASHead`, `TestAPreCheckThatFindsAChunkMissingEndsWithNoLookupInTheCAS` (`core/frontend/chunkstore/layout_commit_check_budget_test.go`); through the provider's wrapped remote: `TestProviderCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestProviderWrappedRemoteKeepsTheLayoutRemotesOptionalInterfaces` (`core/frontend/durable/commit_check_budget_test.go`) | — (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`, `CheckCommitObjects`, `Head.Commit`; the lookups run with the cut's budget before the bounded HEAD update (`layout_remote.go` `LayoutRemote.CheckCommit`, called by `core/storage/chunk_layer.go`), and the CAS skips them only for the (session, root) checked | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep`; its verification is bounded parallel and stays all-or-nothing: `TestCommitVerifiesManyNewChunksWithinTheBudget`, `TestADetachingCommitOfManyNewChunksCompletesWithinTheBudget`, `TestCommitRefusesWhenOneOfManyNewChunksIsNotPrepared`, `TestCommitLookupsNeverExceedTheCap`, `TestACancelledCommitStopsJoinsAndWritesNothing`, `TestTheEarliestFailureByPositionDecidesTheError` (`commit_verify_scale_test.go`, `commit_verify_controls_test.go`); outside the 2 s update: `TestCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestCASSkipsTheLookupsCheckedForItsSessionAndRoot`, `TestCASWithNoPassedCheckDoesTheLookups`, `TestCASAfterACheckOfAnotherRootDoesTheLookups`, `TestBeginCleanBetweenTheCheckAndTheUpdateIsBusy`, `TestAPreCheckThatFindsAChunkMissingEndsWithNoLookupInTheCAS` (`core/frontend/chunkstore/layout_commit_check_budget_test.go`); `TestObjectsCheckedIsWrittenOnlyByCASHead`, `TestCASAfterAnAbortAndANewSessionAtTheSameRootDoesTheLookups`, `TestCommitPendingSnapshotLooksUpTheRootAndSegments`, `TestMetadataRetryLooksUpOnlyWithoutAPassedCheck` (`core/frontend/chunkstore/layout_commit_check_guards_test.go`); through the provider's wrapped remote: `TestProviderCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestProviderWrappedRemoteKeepsTheLayoutRemotesOptionalInterfaces` (`core/frontend/durable/commit_check_budget_test.go`) | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-SNAPSHOT-META-001` | Snapshot retention metadata (creation time, class, expiry and at most four bounded labels) is written by the commit that creates the snapshot name and never changed by a replay. | M9 snap -> idle (named Commit) | `core/frontend/chunkstore/layout/head.go` `SnapshotMeta`, codec; `commit.go` `Head.Commit`, `RunCommit`; host `chunkControl.Snapshot`, `ListSnapshots` | `TestSnapshotMeta_WrittenOnceByTheCommit`, `TestHead_BoundsRefused`, `TestGuard_SafetyIgnoresSnapshotMeta`; `TestChunkControlPassesRetentionFactsToTheNamedCommit`, `TestChunkControlUsesTheBoundLayoutIdentity` | Retention facts affect policy only; the safety guard forbids their use in reachability/removal. Actual provider and scheduled capture integration remain cutover work; no live-path claim. | ACTIVE | | `INV-SNAPK-DETACHED-001` | A detached HEAD remains closed to its same-epoch holder; only a higher-epoch Claim returns it to live. | M9 snap → detached → higher-epoch idle | `core/frontend/chunkstore/layout` `commit.go`, `head.go`, `claim.go`, `start.go` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestWorkspaceLayoutDetachedProof`, `TestCommitDetached_ProofAndLostReply`, `TestDetachedHEAD_RefusesEveryHolderTransition`, `TestDetachedHEAD_NewGrantStillWaitsForTheOldLease` | Caller write-barrier and synced-position join, master clean-proof reader and composed model review remain cutover gates. | 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 | From a9a24880e723a0766f8e6d1f2a79f953d330d0ee Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 06:26:48 -0800 Subject: [PATCH 4/4] test: census package-level ObjectsChecked writes; separate root and segment checks Co-Authored-By: Claude Opus 5.5 --- .../layout_commit_check_guards_test.go | 74 +++++++++++++------ 1 file changed, 53 insertions(+), 21 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout_commit_check_guards_test.go b/seaweed-block/core/frontend/chunkstore/layout_commit_check_guards_test.go index 601402ecbd..a08dde9fde 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_commit_check_guards_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_commit_check_guards_test.go @@ -28,22 +28,8 @@ func objectsCheckedWriters(t *testing.T, file, src string) []string { t.Fatalf("parse %s: %v", file, err) } var sites []string - for _, d := range f.Decls { - fn, ok := d.(*ast.FuncDecl) - if !ok || fn.Body == nil { - continue - } - owner := fn.Name.Name - if fn.Recv != nil && len(fn.Recv.List) == 1 { - typ := fn.Recv.List[0].Type - if star, ok := typ.(*ast.StarExpr); ok { - typ = star.X - } - if id, ok := typ.(*ast.Ident); ok { - owner = "(" + id.Name + ")." + fn.Name.Name - } - } - ast.Inspect(fn.Body, func(n ast.Node) bool { + writes := func(owner string, n ast.Node) { + ast.Inspect(n, func(n ast.Node) bool { switch x := n.(type) { case *ast.AssignStmt: for _, lhs := range x.Lhs { @@ -59,6 +45,27 @@ func objectsCheckedWriters(t *testing.T, file, src string) []string { return true }) } + for _, d := range f.Decls { + if gen, ok := d.(*ast.GenDecl); ok { + writes("package", gen) // var and const initializers outside any function + continue + } + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + owner := fn.Name.Name + if fn.Recv != nil && len(fn.Recv.List) == 1 { + typ := fn.Recv.List[0].Type + if star, ok := typ.(*ast.StarExpr); ok { + typ = star.X + } + if id, ok := typ.(*ast.Ident); ok { + owner = "(" + id.Name + ")." + fn.Name.Name + } + } + writes(owner, fn.Body) + } return sites } @@ -118,6 +125,10 @@ func TestObjectsCheckedIsWrittenOnlyByCASHead(t *testing.T) { "package other\nfunc build() { _ = layout.CommitRequest{Session: \"s\", ObjectsChecked: true} }\n", "x.go build", }, + "a package-level literal": { + "package chunkstore\nvar unchecked = layout.CommitRequest{ObjectsChecked: true}\n", + "x.go package", + }, "a multiple assignment": { "package chunkstore\nfunc (l *LayoutRemote) CASHead2(req *CommitRequest) { var n int; req.ObjectsChecked, n = true, 1; _ = n }\n", "x.go (LayoutRemote).CASHead2", @@ -161,18 +172,25 @@ func TestCommitPendingSnapshotLooksUpTheRootAndSegments(t *testing.T) { if err != nil { t.Fatal(err) } - var segRoot atomic.Int64 + var segs, roots atomic.Int64 lh.ff.afterLookup = func(p string) { - if strings.Contains(p, "/seg/") || strings.Contains(p, "/root/") { - segRoot.Add(1) + switch { + case strings.Contains(p, "/seg/"): + segs.Add(1) + case strings.Contains(p, "/root/"): + roots.Add(1) } } w.LayoutRemote.SetSnapshot("s1", layout.SnapshotMeta{}) if err := w.LayoutRemote.CommitPendingSnapshot(context.Background()); err != nil { t.Fatal(err) } - if segRoot.Load() == 0 { - t.Fatal("CommitPendingSnapshot looked up no segment or root") + if err := requireRootAndSegments(segs.Load(), roots.Load()); err != nil { + t.Fatalf("CommitPendingSnapshot: %v", err) + } + // Controls: the check fails when either kind of lookup is missing. + if requireRootAndSegments(0, roots.Load()) == nil || requireRootAndSegments(segs.Load(), 0) == nil { + t.Fatal("requireRootAndSegments passes with one kind of lookup missing") } if _, ok := lh.head().Snapshots["s1"]; !ok { t.Fatal("snapshot s1 not in HEAD") @@ -226,3 +244,17 @@ func TestMetadataRetryLooksUpOnlyWithoutAPassedCheck(t *testing.T) { }) } } + +// requireRootAndSegments refuses a commit check that looked up no segment +// or no root. +func requireRootAndSegments(segs, roots int64) error { + switch { + case segs == 0 && roots == 0: + return fmt.Errorf("looked up no segment and no root") + case segs == 0: + return fmt.Errorf("looked up %d roots but no segment", roots) + case roots == 0: + return fmt.Errorf("looked up %d segments but no root", segs) + } + return nil +}