storage: read only HEAD where a HEAD read compares identity; bound a whole-manifest read per fetch

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-29 08:38:32 -08:00
1 parent 30b5177b17
commit 34636c5f4d
8 files changed
+241 -21

No files matched your search

@@ -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))
}
@@ -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
@@ -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)
}
}
@@ -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
@@ -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 {
@@ -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)
}
}
+18 -1
View File
@@ -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
+1
View File
@@ -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 |