From 34636c5f4da8ef41b40cd92a971fac92aa4ced07 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 29 Nov 2026 08:38:32 -0800 Subject: [PATCH 1/3] storage: read only HEAD where a HEAD read compares identity; bound a whole-manifest read per fetch Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/head_readers_test.go | 4 + .../head_generation_source_guard_test.go | 1 + .../chunkstore/layout_head_read_root_test.go | 108 ++++++++++++++++++ .../core/frontend/chunkstore/layout_remote.go | 62 ++++++---- seaweed-block/core/storage/chunk_head_belt.go | 21 ++++ .../storage/chunk_head_read_bound_test.go | 46 ++++++++ seaweed-block/core/storage/chunk_layer.go | 19 ++- seaweed-block/docs/design/invariants.md | 1 + 8 files changed, 241 insertions(+), 21 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go create mode 100644 seaweed-block/core/storage/chunk_head_read_bound_test.go diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 9ea1486c23..60c07d8e22 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -66,6 +66,7 @@ var headReaders = map[string]string{ "core/storage/chunk_head_belt.go confirmChunkHead -> GetHead": "ErrHeadAbsent from the layout remote: not confirmed (probe LayoutRemote)", "core/storage/chunk_head_belt.go confirmChunkHead -> GetHeadRoot": "ErrHeadAbsent from the layout remote: not confirmed (probe LayoutRemote)", "core/storage/chunk_head_belt.go readChunkHead -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", + "core/storage/chunk_head_belt.go readChunkHeadRoot -> GetHeadRoot": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", "core/storage/chunk_layer.go attachChunkLayerImpl -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", } @@ -217,6 +218,9 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { if _, err := r.GetHead(ctx); !errors.Is(err, layout.ErrHeadAbsent) { t.Fatalf("engine HEAD read of an absent HEAD: %v; want ErrHeadAbsent", err) } + if _, err := r.GetHeadRoot(ctx); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("engine HEAD identity read of an absent HEAD: %v; want ErrHeadAbsent", err) + } 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)) } 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 d0cd99704b..6fa8fc5547 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 @@ -185,6 +185,7 @@ func TestHeadGenerationComparedOnlyByConditionalUpdate(t *testing.T) { allowed := map[string]int{ "core/storage/chunk_head_belt.go confirmChunkHead got.Gen != want.Gen": 1, // publication confirmation "core/storage/chunk_layer.go captureLocked sc.headGen == l.head.Gen": 1, // staged image cache + "core/storage/chunk_layer.go noopCutHead root.Gen == baseHead.Gen": 1, // no-op cut keeps its base while HEAD's image token is unchanged "core/storage/chunk_layer.go captureLocked cur.Gen == expected.Gen": 1, // unresolved CAS base "core/storage/chunk_layer.go SettleDetach cur.Gen == base.Gen": 2, // pending and cancelled CAS base "core/storage/chunk_layer.go resolvePending cur.Gen == base.Gen": 2, // pending and cancelled CAS base diff --git a/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go b/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go new file mode 100644 index 0000000000..93ca45adef --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go @@ -0,0 +1,108 @@ +package chunkstore + +import ( + "context" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// afterCASRemote is the holder's layout remote, marking when a HEAD write +// has returned, so a test can count what the layer reads after it. +type afterCASRemote struct { + *LayoutRemote + after atomic.Bool + onAfter func() +} + +func (r *afterCASRemote) CASHead(ctx context.Context, e storage.ChunkHeadVersion, n storage.ChunkHead) (uint64, error) { + gen, err := r.LayoutRemote.CASHead(ctx, e, n) + r.after.Store(true) + if r.onAfter != nil { + r.onAfter() + } + return gen, err +} + +// manifestReads attaches a chunk layer over the holder's layout remote, one +// block written in every chunk, and counts every lookup of a root or a +// segment made while counting is on. +func manifestReads(t *testing.T) (*storage.WALStore, *afterCASRemote, storage.ChunkLayer, *atomic.Bool, *atomic.Int64) { + 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 := &afterCASRemote{LayoutRemote: r} + 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) + var counting atomic.Bool + var reads atomic.Int64 + lh.ff.afterLookup = func(p string) { + if counting.Load() && (strings.Contains(p, "/root/") || strings.Contains(p, "/seg/")) { + reads.Add(1) + } + } + return s, w, l, &counting, &reads +} + +// The confirmation after a HEAD write compares HEAD's generation, epoch and +// holder only, inside the HEAD step's fixed 2 s limit, so it reads HEAD and +// nothing else: no root and no segment, whose number grows with the volume. +func TestTheConfirmationAfterAHeadWriteReadsNoManifest(t *testing.T) { + _, w, l, counting, reads := manifestReads(t) + w.onAfter = func() { counting.Store(true) } // count what is read once the HEAD write returns + if _, err := l.Cut(context.Background()); err != nil { + t.Fatal(err) + } + if !w.after.Load() { + t.Fatal("setup: the cut wrote no HEAD") + } + if n := reads.Load(); n != 0 { + t.Fatalf("the confirmation after the HEAD write read %d roots or segments; want 0 (HEAD only)", n) + } +} + +// A cut with nothing new (a no-op cut, run each interval on an idle volume) +// still reads HEAD to observe authority. While HEAD is the image the layer +// already holds, it reads HEAD only and keeps its chunk list: no root and no +// segment. +func TestANoOpCutReadsNoManifestWhileHeadIsUnchanged(t *testing.T) { + _, _, l, counting, reads := manifestReads(t) + if _, err := l.Cut(context.Background()); err != nil { // publish the written chunks + t.Fatal(err) + } + counting.Store(true) + res, err := l.Cut(context.Background()) + if err != nil { + t.Fatal(err) + } + if !res.Noop { + t.Fatalf("setup: the second cut was not a no-op: %+v", res) + } + if n := reads.Load(); n != 0 { + t.Fatalf("a no-op cut over an unchanged HEAD read %d roots or segments; want 0", n) + } + if len(res.Head.Chunks) != lrBlocks/lrChunkBlocks { + t.Fatalf("the no-op cut's HEAD names %d chunks; want the %d it already held", len(res.Head.Chunks), lrBlocks/lrChunkBlocks) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go index cfc80ca47e..010d71da8e 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -299,26 +299,9 @@ func (l *LayoutRemote) Get(ctx context.Context, key string) ([]byte, error) { func (l *LayoutRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { l.mu.Lock() defer l.mu.Unlock() - l.takeAbandonLocked() - h, err := l.rollBackLocked(ctx) - if err != nil { - return storage.ChunkHead{}, err - } - if h.State == layout.StateDeleting || h.State == layout.StateDeleted { - return storage.ChunkHead{}, storage.ErrChunkHeadDeleted - } - // Another claim at this holder's own epoch is another owner of HEAD: the - // head the engine sees carries no claim id, so it must not read as its own. - if h.Epoch == l.me.Epoch && h.Holder == l.me.Holder && h.ClaimID != l.me.ClaimID { - return storage.ChunkHead{}, fmt.Errorf("%w: HEAD is held by %s at epoch %d (claim %q)", storage.ErrChunkLayerFenced, h.Holder, h.Epoch, h.ClaimID) - } - out := storage.ChunkHead{Gen: l.visible, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.Position, Chunks: map[uint64]storage.ChunkRef{}, State: "active"} - if h.State == layout.StateDetached { - out.State = "detached" - out.DetachedBy = &storage.ChunkDetachedBy{Holder: h.Holder, Epoch: h.Epoch, Gen: h.Gen} - } - if h.Current == nil { - return out, nil + h, out, err := l.headIdentityLocked(ctx) + if err != nil || h.Current == nil { + return out, err } m, err := l.manifest(ctx, *h.Current) if err != nil { @@ -342,6 +325,45 @@ func (l *LayoutRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { return out, nil } +// GetHeadRoot is GetHead without the manifest (storage.ChunkHeadRootReader): +// the same view of HEAD, its generation token, epoch, holder, position and +// state, after the same rollback and refusals, with no chunk listed. It reads +// HEAD only, never a root or a segment, so it does not grow with the volume. +// The token changes whenever HEAD's root does, so a caller that kept the +// chunks of a HEAD with the same token still has them. +func (l *LayoutRemote) GetHeadRoot(ctx context.Context) (storage.ChunkHead, error) { + l.mu.Lock() + defer l.mu.Unlock() + _, out, err := l.headIdentityLocked(ctx) + out.Chunks = nil + return out, err +} + +// headIdentityLocked reads HEAD as the engine's view, without its manifest: +// the rollback of a session this process does not hold, the deleted and +// other-claim refusals, and HEAD's identity (Chunks empty). +func (l *LayoutRemote) headIdentityLocked(ctx context.Context) (layout.Head, storage.ChunkHead, error) { + l.takeAbandonLocked() + h, err := l.rollBackLocked(ctx) + if err != nil { + return layout.Head{}, storage.ChunkHead{}, err + } + if h.State == layout.StateDeleting || h.State == layout.StateDeleted { + return layout.Head{}, storage.ChunkHead{}, storage.ErrChunkHeadDeleted + } + // Another claim at this holder's own epoch is another owner of HEAD: the + // head the engine sees carries no claim id, so it must not read as its own. + if h.Epoch == l.me.Epoch && h.Holder == l.me.Holder && h.ClaimID != l.me.ClaimID { + return layout.Head{}, storage.ChunkHead{}, fmt.Errorf("%w: HEAD is held by %s at epoch %d (claim %q)", storage.ErrChunkLayerFenced, h.Holder, h.Epoch, h.ClaimID) + } + out := storage.ChunkHead{Gen: l.visible, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.Position, Chunks: map[uint64]storage.ChunkRef{}, State: "active"} + if h.State == layout.StateDetached { + out.State = "detached" + out.DetachedBy = &storage.ChunkDetachedBy{Holder: h.Holder, Epoch: h.Epoch, Gen: h.Gen} + } + return h, out, nil +} + // manifest is the chunk map root names. Within an attach (ctx carries // storage.AttachFetch) it is read fetch by fetch: the root and each segment // under their own bound, each completed segment reported as progress, and diff --git a/seaweed-block/core/storage/chunk_head_belt.go b/seaweed-block/core/storage/chunk_head_belt.go index ea21ccdf81..0fca73811c 100644 --- a/seaweed-block/core/storage/chunk_head_belt.go +++ b/seaweed-block/core/storage/chunk_head_belt.go @@ -68,12 +68,33 @@ func casChunkHead(ctx context.Context, remote chunkRemote, expected chunkHeadVer return remote.CASHead(ctx, expected, next) } +// readChunkHead reads HEAD with its whole manifest. A remote that bounds +// its own HEAD step reads it fetch by fetch (the root, then each segment), +// each fetch bounded by chunkHeadOperationTimeout and the read as a whole by +// ctx only: the segment count grows with the volume. Any other remote's read +// is bounded as one call. func readChunkHead(ctx context.Context, remote chunkRemote) (chunkHead, error) { + if b, ok := remote.(chunkHeadStepBounder); ok && b.BoundsHeadStep() { + return remote.GetHead(WithAttachFetch(ctx, AttachFetch{Bound: chunkHeadOperationTimeout})) + } ctx, cancel := context.WithTimeout(ctx, chunkHeadOperationTimeout) defer cancel() return remote.GetHead(ctx) } +// readChunkHeadRoot reads HEAD's identity without its manifest when the +// remote can (ChunkHeadRootReader); ok is false otherwise. +func readChunkHeadRoot(ctx context.Context, remote chunkRemote) (head chunkHead, ok bool, err error) { + reader, ok := remote.(ChunkHeadRootReader) + if !ok { + return chunkHead{}, false, nil + } + ctx, cancel := context.WithTimeout(ctx, chunkHeadOperationTimeout) + defer cancel() + head, err = reader.GetHeadRoot(ctx) + return head, true, err +} + // ChunkHeadRootReader confirms publication identity without resolving every // immutable manifest. The returned Chunks need not be populated. type ChunkHeadRootReader interface { diff --git a/seaweed-block/core/storage/chunk_head_read_bound_test.go b/seaweed-block/core/storage/chunk_head_read_bound_test.go new file mode 100644 index 0000000000..b03f21c9cc --- /dev/null +++ b/seaweed-block/core/storage/chunk_head_read_bound_test.go @@ -0,0 +1,46 @@ +package storage + +import ( + "context" + "testing" +) + +// readRemote records the context its GetHead got; bounds says whether it +// declares that it bounds its own HEAD step. +type readRemote struct { + chunkRemote + bounds bool + deadline bool + fetch AttachFetch + perFetch bool +} + +func (r *readRemote) BoundsHeadStep() bool { return r.bounds } + +func (r *readRemote) GetHead(ctx context.Context) (chunkHead, error) { + _, r.deadline = ctx.Deadline() + r.fetch, r.perFetch = AttachFetchFrom(ctx) + return chunkHead{}, nil +} + +// A whole-manifest HEAD read from a remote that bounds its own step is read +// fetch by fetch: each fetch bounded by the HEAD operation limit, the read as +// a whole only by the caller (its segment count grows with the volume). Any +// other remote's read is bounded as one call, as before. +func TestAWholeHeadReadIsBoundedPerFetchWhenTheRemoteBoundsItsStep(t *testing.T) { + stepped := &readRemote{bounds: true} + if _, err := readChunkHead(context.Background(), stepped); err != nil { + t.Fatal(err) + } + if stepped.deadline || !stepped.perFetch || stepped.fetch.Bound != chunkHeadOperationTimeout { + t.Fatalf("a remote that bounds its step: deadline=%v per-fetch=%v bound=%v; want no deadline and a per-fetch bound of %v", + stepped.deadline, stepped.perFetch, stepped.fetch.Bound, chunkHeadOperationTimeout) + } + plain := &readRemote{bounds: false} + if _, err := readChunkHead(context.Background(), plain); err != nil { + t.Fatal(err) + } + if !plain.deadline || plain.perFetch { + t.Fatalf("a remote that does not bound its step: deadline=%v per-fetch=%v; want the whole read bounded", plain.deadline, plain.perFetch) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 6a890b43ee..b4775c96d5 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1176,7 +1176,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) { // A no-op cut still observes authority: a fresh host may have // claimed HEAD without uploading a single chunk since our last cut. - cur, err := readCapturedHead() + cur, err := l.noopCutHead(ctx, baseHead, readCapturedHead) if err != nil { l.requeueCut(all) return chunkCutResult{}, fmt.Errorf("storage: no-op cut authority read: %w: %w", errChunkRemoteUnavailable, err) @@ -1423,6 +1423,23 @@ func (l *chunkLayerImpl) supersededBy(cur chunkHead) bool { // and who detached; the segments; per chunk its key, content hash and // encoding. A value the store does not keep (a chunk's birth) or that it // owns (a generation) would make an applied commit look foreign. +// noopCutHead is a no-op cut's authority read. When the remote reads HEAD's +// identity alone (ChunkHeadRootReader) and HEAD is still the image baseHead +// names (the same generation token, epoch, holder, position and detach +// state; the token changes whenever HEAD's root does), it is baseHead with +// its chunks, and no manifest is read. Otherwise it is the whole HEAD (full). +func (l *chunkLayerImpl) noopCutHead(ctx context.Context, baseHead chunkHead, full func() (chunkHead, error)) (chunkHead, error) { + root, ok, err := readChunkHeadRoot(ctx, l.remote) + if err != nil { + return chunkHead{}, err + } + if ok && root.Gen == baseHead.Gen && root.Epoch == baseHead.Epoch && root.Holder == baseHead.Holder && + root.RemoteLSN == baseHead.RemoteLSN && chunkHeadIsDetached(root) == chunkHeadIsDetached(baseHead) { + return copyHead(baseHead), nil + } + return full() +} + func sameProposal(cur, next chunkHead) bool { if (cur.Segments == nil) != (next.Segments == nil) || cur.ChunkBytes != next.ChunkBytes || cur.ManifestChunkCount != next.ManifestChunkCount || len(cur.Segments) != len(next.Segments) { return false diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7d21261498..ea7351d744 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1204,6 +1204,7 @@ One row per fixed time limit on a volume's path that surrounds, or once surround |---|---|---|---|---|---| | `core/storage/chunk_head_belt.go` `casChunkHead`, applied by `LayoutRemote.commitStepLocked` | 2 s per attempt | one HEAD step: the HEAD read, the commit's decision from its plan, the conditional write | no | the commit's preparation (the previous manifest, the next root and segments, the plan) and its object lookups, under the cut's limit; a commit after a passed check reuses the preparation | `TestHolderCommitAtOneTiBKeepsItsPreparationOutOfTheHeadStep`, `TestCommitUpdateStepDoesNotRereadTheManifests` | | the same step, for a commit that was NOT checked first | 2 s per attempt | the step and the object lookups of every new chunk, and of a new root's segments and root even when no chunk is new | **yes** | nothing: no production caller commits without the check; a new caller must check first | none: a known gap, stated here so it is not claimed. Kept true by `TestEveryHeadCommitIsCheckedFirst`: every HEAD commit of the chunk layer (a cut's commit, a detach's cancellation, an unresolved cut's re-proposal) runs the object check before its CAS, and a new site fails until it does. `TestDetachCancellationAfterALostUpdateLooksUpNothingInTheHeadStep` measures the cancellation. The snapshot of an unchanged image commits under its caller's limit, not in this step | +| `core/storage/chunk_head_belt.go` the chunk layer's HEAD reads: `confirmChunkHead` after a HEAD write, a no-op cut's authority read (`noopCutHead`), and `readChunkHead` when a write's outcome is settled | 2 s per remote call | the confirmation and a no-op cut over an unchanged HEAD read HEAD only (`GetHeadRoot`), no root and no segment; a settlement reads the whole manifest, one root fetch and one fetch per segment, each bounded on its own | the confirmation and the no-op read: no; a settlement's fetch count: **yes** | a settlement's read as a whole, under the cut's limit; a no-op cut over a changed HEAD reads the whole manifest the same way | `TestTheConfirmationAfterAHeadWriteReadsNoManifest`, `TestANoOpCutReadsNoManifestWhileHeadIsUnchanged` (count 0 fetches whatever the size), `TestAWholeHeadReadIsBoundedPerFetchWhenTheRemoteBoundsItsStep` | | `DurableProvider.chunkCutContext` (`ChunkCutTimeout`) | 5 min per attempt | staging the changed chunks, the check, the commit | yes | uploads finished by an attempt are kept; the next attempt uploads only the rest (same process) | `TestACutAttemptThatRunsOutOfTimeLeavesUploadsTheNextAttemptKeeps` | | the cleaning pass (`boundedPass`) | the configured pass limit | listing and removing by page | yes | the pass resumes at its cursor; a session after a restart starts at the root page | the cleaning cursor's tests | | `core/host/volume/chunk_control.go` `chunkContext` (a chunk control operation: a cut, a snapshot or a detach, each of which takes a cut; the chunk status read also runs under it and reads one HEAD) | 5 min, or the request's shorter limit | the operation, including the cut it takes | yes | the cut's uploads, as the cut's row: an attempt that runs out of time keeps what it uploaded | STUB: no test at the control operation's level yet | From c38a049327e791083e0bd84459aee165a5c5ad56 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 29 Nov 2026 09:38:59 -0800 Subject: [PATCH 2/3] storage: a no-op cut's identity read is its settle phase and counts as HEAD read-back; controls for a foreign claim and the caller's deadline Co-Authored-By: Claude Opus 5.5 --- .../chunkstore/layout_head_read_root_test.go | 22 +++++ .../storage/chunk_head_read_bound_test.go | 84 ++++++++++++++++++- seaweed-block/core/storage/chunk_layer.go | 19 +++-- 3 files changed, 119 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go b/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go index 93ca45adef..5f1de99dce 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go @@ -2,11 +2,13 @@ package chunkstore import ( "context" + "errors" "path/filepath" "strings" "sync/atomic" "testing" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -106,3 +108,23 @@ func TestANoOpCutReadsNoManifestWhileHeadIsUnchanged(t *testing.T) { t.Fatalf("the no-op cut's HEAD names %d chunks; want the %d it already held", len(res.Head.Chunks), lrBlocks/lrChunkBlocks) } } + +// A no-op cut over a HEAD another holder has claimed since the last cut reads +// HEAD's identity through the root reader, finds it changed, and fences: it +// never keeps its base over a changed HEAD. +func TestANoOpCutOverAForeignClaimFences(t *testing.T) { + ctx := context.Background() + _, w, l, _, _ := manifestReads(t) + if _, err := l.Cut(ctx); err != nil { // publish the written chunks + t.Fatal(err) + } + if _, err := layout.RunClaim(ctx, w.st, okClaimLease{}, layout.HolderID{Epoch: w.me.Epoch + 1, Holder: "foreign", ClaimID: "foreign-claim"}); err != nil { + t.Fatal(err) + } + if _, err := l.Cut(ctx); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("a no-op cut over a foreign claim: %v; want ErrChunkLayerFenced", err) + } + if !l.Fenced() { + t.Fatal("the layer is not fenced after a no-op cut over a foreign claim") + } +} diff --git a/seaweed-block/core/storage/chunk_head_read_bound_test.go b/seaweed-block/core/storage/chunk_head_read_bound_test.go index b03f21c9cc..8de0241de3 100644 --- a/seaweed-block/core/storage/chunk_head_read_bound_test.go +++ b/seaweed-block/core/storage/chunk_head_read_bound_test.go @@ -2,7 +2,9 @@ package storage import ( "context" + "errors" "testing" + "time" ) // readRemote records the context its GetHead got; bounds says whether it @@ -11,6 +13,8 @@ type readRemote struct { chunkRemote bounds bool deadline bool + at time.Time + err error fetch AttachFetch perFetch bool } @@ -18,7 +22,8 @@ type readRemote struct { func (r *readRemote) BoundsHeadStep() bool { return r.bounds } func (r *readRemote) GetHead(ctx context.Context) (chunkHead, error) { - _, r.deadline = ctx.Deadline() + r.at, r.deadline = ctx.Deadline() + r.err = ctx.Err() r.fetch, r.perFetch = AttachFetchFrom(ctx) return chunkHead{}, nil } @@ -44,3 +49,80 @@ func TestAWholeHeadReadIsBoundedPerFetchWhenTheRemoteBoundsItsStep(t *testing.T) t.Fatalf("a remote that does not bound its step: deadline=%v per-fetch=%v; want the whole read bounded", plain.deadline, plain.perFetch) } } + +// A caller's deadline and cancellation reach a stepped whole read: the +// per-fetch bound is added, the caller's context is kept. +func TestAWholeHeadReadKeepsTheCallersDeadlineAndCancellation(t *testing.T) { + want := time.Now().Add(time.Hour) + ctx, cancel := context.WithDeadline(context.Background(), want) + defer cancel() + stepped := &readRemote{bounds: true} + if _, err := readChunkHead(ctx, stepped); err != nil { + t.Fatal(err) + } + if !stepped.deadline || !stepped.at.Equal(want) || !stepped.perFetch { + t.Fatalf("caller deadline: got deadline=%v at=%v per-fetch=%v; want the caller's %v with the per-fetch bound", stepped.deadline, stepped.at, stepped.perFetch, want) + } + gone, stop := context.WithCancel(context.Background()) + stop() + if _, err := readChunkHead(gone, stepped); err != nil { + t.Fatal(err) + } + if !errors.Is(stepped.err, context.Canceled) { + t.Fatalf("caller cancellation: the read's context reports %v; want context.Canceled", stepped.err) + } +} + +// gatedRootRemote reads HEAD's whole identity alone and runs during while it +// does, so a test can observe the cut while the read is in progress. +type gatedRootRemote struct { + *fakeChunkRemote + during func() +} + +func (r *gatedRootRemote) GetHeadRoot(ctx context.Context) (ChunkHead, error) { + if r.during != nil { + r.during() + } + r.mu.Lock() + defer r.mu.Unlock() + h := r.head + return ChunkHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: h.State, DetachedBy: h.DetachedBy}, nil +} + +// A no-op cut's identity read is the cut's settle phase and its time counts +// as HEAD read-back, as the whole read it replaces did. +func TestANoOpCutsRootReadIsTheSettlePhaseAndCountsItsTime(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &gatedRootRemote{fakeChunkRemote: f} + layer := mustAttach(t, s, r, ctConfig(1)) + if _, err := s.Write(0, makeBlock(4096, 0x42)); err != nil { + t.Fatal(err) + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + impl := layer.(*chunkLayerImpl) + const pause = 20 * time.Millisecond + phase := "" + r.during = func() { + if c := impl.Stats().CurrentCut; c != nil { + phase = c.Phase + } + time.Sleep(pause) + } + res, err := layer.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if !res.Noop { + t.Fatalf("setup: the second cut was not a no-op: %+v", res) + } + if phase != "settle" { + t.Fatalf("phase during the no-op cut's identity read: %q; want settle", phase) + } + if got := time.Duration(res.Stats.HeadReadbackNs); got < pause { + t.Fatalf("HEAD read-back time %v; want at least the %v the identity read took", got, pause) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index b4775c96d5..a6a7c20143 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -798,6 +798,15 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.HeadReadbackNs += time.Since(start).Nanoseconds() return head, err } + // readCapturedRoot is the same read of HEAD's identity alone, when the + // remote can; each read counts only its own time. + readCapturedRoot := func() (chunkHead, bool, error) { + l.cutPhase("settle") + start := time.Now() + head, ok, err := readChunkHeadRoot(ctx, l.remote) + st.HeadReadbackNs += time.Since(start).Nanoseconds() + return head, ok, err + } finishCapturedCut := func(head chunkHead, h uint64, changed []uint64, keys map[uint64]string) { start := time.Now() l.finishCut(head, h, changed, keys) @@ -1176,7 +1185,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) { // A no-op cut still observes authority: a fresh host may have // claimed HEAD without uploading a single chunk since our last cut. - cur, err := l.noopCutHead(ctx, baseHead, readCapturedHead) + cur, err := noopCutHead(baseHead, readCapturedRoot, readCapturedHead) if err != nil { l.requeueCut(all) return chunkCutResult{}, fmt.Errorf("storage: no-op cut authority read: %w: %w", errChunkRemoteUnavailable, err) @@ -1423,13 +1432,13 @@ func (l *chunkLayerImpl) supersededBy(cur chunkHead) bool { // and who detached; the segments; per chunk its key, content hash and // encoding. A value the store does not keep (a chunk's birth) or that it // owns (a generation) would make an applied commit look foreign. -// noopCutHead is a no-op cut's authority read. When the remote reads HEAD's -// identity alone (ChunkHeadRootReader) and HEAD is still the image baseHead +// noopCutHead is a no-op cut's authority read. When rootRead reads HEAD's +// identity alone (a ChunkHeadRootReader remote) and HEAD is still the image baseHead // names (the same generation token, epoch, holder, position and detach // state; the token changes whenever HEAD's root does), it is baseHead with // its chunks, and no manifest is read. Otherwise it is the whole HEAD (full). -func (l *chunkLayerImpl) noopCutHead(ctx context.Context, baseHead chunkHead, full func() (chunkHead, error)) (chunkHead, error) { - root, ok, err := readChunkHeadRoot(ctx, l.remote) +func noopCutHead(baseHead chunkHead, rootRead func() (chunkHead, bool, error), full func() (chunkHead, error)) (chunkHead, error) { + root, ok, err := rootRead() if err != nil { return chunkHead{}, err } From 28e4a54fe4da4f153e5fafc93877b645f289f0f7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 29 Nov 2026 10:41:49 -0800 Subject: [PATCH 3/3] chunkstore: a no-op cut after the token moved under the holder's own identity reads the whole HEAD Co-Authored-By: Claude Opus 5.5 --- .../chunkstore/layout_head_read_root_test.go | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go b/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go index 5f1de99dce..3f79bbbedc 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go @@ -128,3 +128,60 @@ func TestANoOpCutOverAForeignClaimFences(t *testing.T) { t.Fatal("the layer is not fenced after a no-op cut over a foreign claim") } } + +// The generation token can move while HEAD keeps this holder's own identity +// and image: a session ended without its commit (a stop's abort), seen by a +// HEAD read before the abandonment notice, forces the view. A no-op cut then reads the whole HEAD and completes on the newer +// generation; keeping the base because epoch and holder still match would +// leave the layer on a generation HEAD no longer has. +func TestANoOpCutAfterTheTokenMovedUnderTheHoldersOwnIdentityReadsTheWholeHead(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + defer s.Close() + writeSync(t, s, map[uint32][]byte{2: block(2)}) + first, err := l.Cut(ctx) + if err != nil { + t.Fatal(err) + } + session, err := r.Begin(ctx) + if err != nil { + t.Fatal(err) + } + st, err := lh.cat.Store(lh.v) + if err != nil { + t.Fatal(err) + } + if _, err := layout.RunAbort(ctx, st, lh.me, session, layout.CauseSessionRollback); err != nil { + t.Fatal(err) + } + // An adapter HEAD read in progress observes the ended session before the + // abandonment notice and forces the view: the token moves, identity and + // image stay. + if _, err := r.GetHead(ctx); err != nil { + t.Fatal(err) + } + r.Abort() + var reads atomic.Int64 + lh.ff.afterLookup = func(p string) { + if strings.Contains(p, "/root/") || strings.Contains(p, "/seg/") { + reads.Add(1) + } + } + second, err := l.Cut(ctx) + if err != nil { + t.Fatalf("no-op cut after the token moved: %v", err) + } + if !second.Noop { + t.Fatalf("setup: the cut after the abort was not a no-op: %+v", second) + } + if second.Head.Gen == first.Head.Gen { + t.Fatalf("the no-op cut kept generation %d; HEAD's token moved, so it must complete on the newer one", first.Head.Gen) + } + if reads.Load() == 0 { + t.Fatal("the no-op cut read no root or segment although HEAD's token moved; want the whole HEAD") + } + if e, h := second.Head.Epoch, second.Head.Holder; e != first.Head.Epoch || h != first.Head.Holder { + t.Fatalf("setup: the holder's identity changed: %d/%s, was %d/%s", e, h, first.Head.Epoch, first.Head.Holder) + } +}