From e44aba0ed613ecf607a69f5fafddbf72c8ef04e3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 12:37:54 -0800 Subject: [PATCH] storage: a v1.1 cut copies HEAD's chunks for its candidates only On the v1.1 format a cut's base is HEAD's identity and its candidates' references (cutBaseLocked), the commit sends identity plus the change set, and a landed commit is applied to HEAD in place (applyCommitLocked): O(C) where the base, the proposal and the install each copied every chunk. A no-op cut compares its captured chunks with the by-change rule less the generation. The cut's result still reports the whole installed HEAD (one copy after the settlement, until the flat map goes). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 166 +++++++++++++++--- .../core/storage/chunk_proposal_by_change.go | 9 +- .../storage/chunk_proposal_by_change_test.go | 55 ++++++ 3 files changed, 202 insertions(+), 28 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 718bc4d0c5..c53ca663a9 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1102,9 +1102,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.HeadReadbackNs += time.Since(start).Nanoseconds() return head, ok, err } - finishCapturedCut := func(head chunkHead, h uint64, changed []uint64, keys map[uint64]string) { + finishCapturedCut := func(head chunkHead, h uint64, changed []uint64, keys map[uint64]string, inPlace bool) { start := time.Now() - l.finishCut(head, h, changed, keys) + l.finishCut(head, h, changed, keys, inPlace) st.CommitStateNs += time.Since(start).Nanoseconds() } var pauseStart time.Time @@ -1329,7 +1329,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.dirty = map[uint64]bool{} l.allDirty = false l.cutLSN = h - baseHead := copyHead(l.head) + baseHead := l.cutBaseLocked(candidates) l.stMu.Unlock() l.cutPhase("compare") // Candidates, mutation versions and the copy-order hint belong to the same barrier. @@ -1490,7 +1490,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 := noopCutHead(baseHead, readCapturedRoot, readCapturedHead) + cur, fromBase, 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) @@ -1499,14 +1499,22 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // the CAS path does. Its generation alone may move without either // (a settlement that aborts this holder's session rewrites HEAD as // it was): the cut then completes on the newer generation. - if !sameProposal(cur, baseHead) { + // On the v1.1 format the image compared is the cut's: its captured + // chunks, every one equal to its base (the proposal by change). + byChange := l.commitByChange() + same := sameProposal(cur, baseHead) + if byChange { + same = sameByChange(cur, baseHead, headLookup(cur), nil, commitMarks(baseHead, captured, capturedVersions, map[uint64]*chunkRef{})) + } + if !same { l.requeueCut(all) l.fencePublication(cur) return chunkCutResult{}, errChunkLayerFenced } - finishCapturedCut(cur, h, nil, nil) // nothing new: no CAS + inPlace := byChange && fromBase // cur is the cut's base: its candidates only + finishCapturedCut(cur, h, nil, nil, inPlace) // nothing new: no CAS persistCapturedMap(capturedVersions) - return chunkCutResult{H: h, Head: copyHead(cur), Noop: true, FullHash: all}, nil + return chunkCutResult{H: h, Head: l.cutResultHead(cur, inPlace), Noop: true, FullHash: all}, nil } expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch} // On the v1.1 format the commit goes by change: one owned change set, @@ -1520,7 +1528,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // runs outside every other measured part, while a HEAD re-read (a // settlement) reads the manifest inside HeadReadbackNs. manifestBefore := work.spans[CutManifestRead].Load() + work.spans[CutSegmentWrites].Load() - checkErr := l.checkCommitFirstBy(ctx, expected, next, changes) + checkErr := l.checkCommitFirstBy(ctx, expected, proposalOf(next, changes), changes) st.ManifestNs += work.spans[CutManifestRead].Load() + work.spans[CutSegmentWrites].Load() - manifestBefore if err := checkErr; err != nil { l.requeueCut(all) @@ -1540,7 +1548,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } l.cutPhase("commit") casStart := time.Now() - gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, expected, next, changes, &st) + gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, expected, proposalOf(next, changes), changes, &st) st.CASNs = time.Since(casStart).Nanoseconds() st.CASResult = "ok" if errors.Is(casErr, errChunkHeadPrecondition) { @@ -1551,10 +1559,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if casErr == nil { l.cutPhase("settle") next.Gen = gen - finishCapturedCut(next, h, changed, newKeys) + finishCapturedCut(next, h, changed, newKeys, changes != nil) l.shadowCommit(captured, capturedVersions) persistCapturedMap(capturedVersions) - return l.cutDone(chunkCutResult{H: h, Head: copyHead(next), FullHash: all}, detach), nil + return l.cutDone(chunkCutResult{H: h, Head: l.cutResultHead(next, changes != nil), FullHash: all}, detach), nil } // Precondition or unknown outcome: resolve by re-reading HEAD, never by // a blind retry. @@ -1595,7 +1603,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } if landedNext { st.CASResult = "resolved-by-reread" - finishCapturedCut(cur, h, changed, newKeys) + finishCapturedCut(cur, h, changed, newKeys, false) // cur is HEAD as read: whole l.shadowCommit(captured, capturedVersions) persistCapturedMap(capturedVersions) return l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil @@ -1786,17 +1794,19 @@ func (l *chunkLayerImpl) supersededBy(cur chunkHead) bool { // 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 noopCutHead(baseHead chunkHead, rootRead func() (chunkHead, bool, error), full func() (chunkHead, error)) (chunkHead, error) { +// its chunks, and no manifest is read (fromBase). Otherwise it is the whole +// HEAD (full). +func noopCutHead(baseHead chunkHead, rootRead func() (chunkHead, bool, error), full func() (chunkHead, error)) (head chunkHead, fromBase bool, err error) { root, ok, err := rootRead() if err != nil { - return chunkHead{}, err + return chunkHead{}, false, 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 copyHead(baseHead), true, nil } - return full() + head, err = full() + return head, false, err } func sameProposal(cur, next chunkHead) bool { @@ -1919,7 +1929,97 @@ func proposalLanded(cur, next chunkHead, baseGen uint64, changes, marked map[uin if changes == nil { return sameProposal(cur, next) } - return sameProposalByChange(cur, next, baseGen, func(i uint64) (chunkRef, bool) { r, ok := cur.Chunks[i]; return r, ok }, changes, marked) + return sameProposalByChange(cur, next, baseGen, headLookup(cur), changes, marked) +} + +// cutBaseLocked is a cut's base: HEAD's identity, and its chunks: on the +// v1.1 format only the candidates' references (O(C): the commit by change, +// its marks and the COW window read no other chunk), else a copy of all. +// Caller holds stMu. +func (l *chunkLayerImpl) cutBaseLocked(candidates map[uint64]bool) chunkHead { + if !l.commitByChange() { + return copyHead(l.head) + } + b := l.head + b.Chunks, b.Segments = nil, nil + b = copyHead(b) + b.Segments = l.head.Segments // shared, never written: every install replaces the map + for idx := range candidates { + if r, ok := l.headRef(idx); ok { + b.Chunks[idx] = r + } + } + return b +} + +// proposalOf is the HEAD a commit sends: by change (changes not nil) its +// identity alone, the remote applying the changes to its own chunks; else +// next whole. +func proposalOf(next chunkHead, changes map[uint64]*chunkRef) chunkHead { + if changes != nil { + next.Chunks = nil + } + return next +} + +// cutResultHead is the HEAD a cut reports, whole: h, or, when h names only +// the cut's chunks (byChange), the HEAD the commit installed (one copy, +// after the settlement, outside the barrier; it goes with the flat map in +// V4-B PR 4 commit 4). +func (l *chunkLayerImpl) cutResultHead(h chunkHead, byChange bool) chunkHead { + if !byChange { + return copyHead(h) + } + l.stMu.Lock() + defer l.stMu.Unlock() + return copyHead(l.head) +} + +// changedIndices is a change set's indices. +func changedIndices(changes map[uint64]*chunkRef) []uint64 { + out := make([]uint64, 0, len(changes)) + for idx := range changes { + out = append(out, idx) + } + return out +} + +// headLookup reads h's chunks as sameProposalByChange's ref. +func headLookup(h chunkHead) func(uint64) (chunkRef, bool) { + return func(i uint64) (chunkRef, bool) { r, ok := h.Chunks[i]; return r, ok } +} + +// applyCommitLocked installs a landed commit by change onto HEAD in place +// (O(C)): id's identity (generation, epoch, holder, position, state, who +// detached, chunk size and count) and each changed chunk's reference from +// id (none: zeros); every other chunk is HEAD's already, as the commit left +// it. The publication report, when one is wanted, gets whole HEADs. Caller +// holds stMu. +func (l *chunkLayerImpl) applyCommitLocked(id chunkHead, changed []uint64) { + prev := l.head + if l.cfg.OnPublishSettled != nil { + prev = copyHead(l.head) + } + h := l.head + h.Gen, h.Epoch, h.Holder, h.RemoteLSN, h.State = id.Gen, id.Epoch, id.Holder, id.RemoteLSN, id.State + h.ChunkBytes, h.ManifestChunkCount = id.ChunkBytes, id.ManifestChunkCount + h.DetachedBy = nil + if id.DetachedBy != nil { + d := *id.DetachedBy + h.DetachedBy = &d + } + if h.Chunks == nil { + h.Chunks = map[uint64]chunkRef{} + } + for _, idx := range changed { + if r, ok := id.Chunks[idx]; ok { + h.Chunks[idx] = r + } else { + delete(h.Chunks, idx) + } + } + l.setHeadChangedLocked(h, changed) + l.noteSettled(prev, l.head) } func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { @@ -1935,6 +2035,9 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { if pending == nil { return nil } + // reproposed: cur is the re-proposal this settlement landed, not HEAD + // as read; by change it names the cut's chunks only. + reproposed := false cur, err := readChunkHead(ctx, l.remote) if err != nil { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved: %w: %w", errChunkCASOutcomeUnknown, err) @@ -1950,13 +2053,14 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { if err := l.admit(); err != nil { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%w); re-proposal refused: %w", errChunkCASOutcomeUnknown, err) } - if err := l.checkCommitFirstBy(ctx, base, *pending, changes); err != nil { + if err := l.checkCommitFirstBy(ctx, base, proposalOf(*pending, changes), changes); err != nil { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%w); re-proposal check failed: %w", errChunkCASOutcomeUnknown, err) } - gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, base, copyHead(*pending), changes, nil) + gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, base, proposalOf(copyHead(*pending), changes), changes, nil) if casErr == nil { cur = copyHead(*pending) cur.Gen = gen + reproposed = true } else if errors.Is(casErr, errChunkLayerFenced) { l.fencePublication(chunkHead{}) return errChunkLayerFenced @@ -1984,12 +2088,20 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { l.pendingCaptured, l.pendingChanges, l.pendingMarked = nil, nil, nil switch { case proposalLanded(cur, *pending, base.Gen, changes, marked): - l.noteSettled(l.head, cur) - l.setHeadLocked(copyHead(cur)) + inPlace := reproposed && changes != nil + if inPlace { + l.applyCommitLocked(cur, changedIndices(changes)) + } else { + l.noteSettled(l.head, cur) + l.setHeadLocked(copyHead(cur)) + } l.remoteLSN = cur.RemoteLSN l.shadowCommitCaptured(landed, true) if wasDetach { cut.Head = copyHead(cur) + if inPlace { + cut.Head = copyHead(l.head) // cur names the cut's chunks only + } l.detached = &cut return errChunkLayerDetached } @@ -2321,11 +2433,15 @@ func (l *chunkLayerImpl) requeueCut(all bool) { // finishCut installs HEAD in memory and rolls the bitmap over: only chunks // dirtied after the cut (and WAL entries above it) stay set. -func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, newKeys map[uint64]string) { +func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, newKeys map[uint64]string, inPlace bool) { l.stMu.Lock() defer l.stMu.Unlock() - l.noteSettled(l.head, head) - l.setHeadChangedLocked(copyHead(head), changed) + if inPlace { + l.applyCommitLocked(head, changed) + } else { + l.noteSettled(l.head, head) + l.setHeadChangedLocked(copyHead(head), changed) + } l.remoteLSN, l.pending = h, nil l.pendingCaptured, l.pendingChanges, l.pendingMarked = nil, nil, nil l.reusable = nil diff --git a/seaweed-block/core/storage/chunk_proposal_by_change.go b/seaweed-block/core/storage/chunk_proposal_by_change.go index 464d343174..24fe53f649 100644 --- a/seaweed-block/core/storage/chunk_proposal_by_change.go +++ b/seaweed-block/core/storage/chunk_proposal_by_change.go @@ -22,9 +22,12 @@ package storage // in whatever representation the caller has: a map, the ref table). func sameProposalByChange(cur, ident chunkHead, baseGen uint64, ref func(idx uint64) (chunkRef, bool), changes, marked map[uint64]*chunkRef) bool { - if cur.Gen <= baseGen { - return false - } + return cur.Gen > baseGen && sameByChange(cur, ident, ref, changes, marked) +} + +// sameByChange is sameProposalByChange without the generation (conditions +// 2-4): a no-op cut, which commits nothing, compares HEAD with its base so. +func sameByChange(cur, ident chunkHead, ref func(idx uint64) (chunkRef, bool), changes, marked map[uint64]*chunkRef) bool { if cur.Epoch != ident.Epoch || cur.Holder != ident.Holder || cur.RemoteLSN != ident.RemoteLSN || cur.ChunkBytes != ident.ChunkBytes || cur.ManifestChunkCount != ident.ManifestChunkCount { return false diff --git a/seaweed-block/core/storage/chunk_proposal_by_change_test.go b/seaweed-block/core/storage/chunk_proposal_by_change_test.go index c6f8d40000..077c1f50cd 100644 --- a/seaweed-block/core/storage/chunk_proposal_by_change_test.go +++ b/seaweed-block/core/storage/chunk_proposal_by_change_test.go @@ -3,6 +3,7 @@ package storage import ( "crypto/sha256" "fmt" + "reflect" "testing" ) @@ -110,3 +111,57 @@ func TestV11LostCommitReplySettlesByChange(t *testing.T) { t.Fatal("the settled HEAD is not the one read back") } } + +// On the v1.1 format a cut copies HEAD's chunks for its candidates only: its +// base names those (at S and at S/16 chunks alike), and a landed commit +// changes HEAD in place (the same map, the changed chunk replaced), where +// the full form copied every chunk at the barrier, for the proposal and at +// the install. +func TestV11CutCopiesOnlyItsCandidates(t *testing.T) { + withV11Format(t) + s, _ := v11Store(t) + f := newFakeChunkRemote() + l := v11Attach(t, s, f) + w := newWriteLog() + for c := uint32(0); c < 4; c++ { + w.write(t, s, c*ctChunkBlocks, byte(0x40+c)) + } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + l.stMu.Lock() + before := reflect.ValueOf(l.head.Chunks).Pointer() + l.stMu.Unlock() + w.write(t, s, 2*ctChunkBlocks, 0x77) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + l.stMu.Lock() + after, n, ref2 := reflect.ValueOf(l.head.Chunks).Pointer(), len(l.head.Chunks), l.head.Chunks[2] + l.stMu.Unlock() + if after != before { + t.Fatal("a landed commit by change copied HEAD's chunk map instead of changing it in place") + } + remote, err := f.GetHead(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if got := remote.Chunks; n != len(got) || ref2 != got[2] { + t.Fatalf("HEAD changed in place is not the remote's: %d chunks, chunk 2 %+v; remote %d, %+v", n, ref2, len(got), got[2]) + } + for _, s := range []uint64{16384, 16384 / 16} { + h := chunkHead{Gen: 5, Epoch: 1, Holder: "h", Chunks: make(map[uint64]chunkRef, s)} + for i := uint64(0); i < s; i++ { + h.Chunks[i] = chunkRef{Key: fmt.Sprintf("k%d", i), Encoding: "full"} + } + l.stMu.Lock() + saved := l.head + l.setHeadLocked(h) + base := l.cutBaseLocked(map[uint64]bool{3: true, 9: true, s + 1: true}) // s+1: a candidate HEAD names nothing at + l.setHeadLocked(saved) + l.stMu.Unlock() + if len(base.Chunks) != 2 || base.Chunks[3] != h.Chunks[3] || base.Chunks[9] != h.Chunks[9] || base.Gen != 5 || base.Holder != "h" { + t.Fatalf("S=%d: the cut's base holds %d chunks (want its 2 named candidates) and identity gen %d holder %q", s, len(base.Chunks), base.Gen, base.Holder) + } + } +}