From a98d8250545504d0e83787bc0e722cb9a2234e7d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 17:19:18 -0800 Subject: [PATCH 01/10] storage: red tests, the cut's candidate set as an interval bitmap - An idle cut's candidate step must visit at most the summary words plus a constant (counted, not timed) at 4,096 and 262,144 chunks (the 1 TiB SPACE shape); a one-chunk cut likewise (fails: the step visits every map entry, 4,097 and 262,144). - The cut must sync the store before its barrier, outside the pause, and report that time apart (fails: no sync before the barrier). A control checks the counter sees the pause's own sync. - Guards, passing today and kept: an unknown commit outcome that did not land loses no chunk (its chunks and a later write are published by the next cut, nothing else changes); the candidate set's OR-back keeps the summary and each lists exactly the set bits. - Seams: chunkCutStats.CandidateVisits, counting the candidate step's current visits, and PreSyncNs. The candidate set type (a chunk bitmap with a per-word summary: set O(1), walk O(C + S/4096), OR, clear) and the record runtime's take/return of it come from an earlier parked branch, rebased onto the one-byte record codes. Co-Authored-By: Claude Opus 5.5 --- .../storage/chunk_cut_candidate_set_test.go | 186 ++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 11 ++ .../core/storage/chunk_record_candidates.go | 67 +++++++ .../core/storage/chunk_record_runtime.go | 54 +++++ seaweed-block/core/storage/chunk_seam.go | 5 + 5 files changed, 323 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_cut_candidate_set_test.go create mode 100644 seaweed-block/core/storage/chunk_record_candidates.go diff --git a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go new file mode 100644 index 0000000000..074c259cdb --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go @@ -0,0 +1,186 @@ +package storage + +import ( + "crypto/sha256" + "encoding/binary" + "fmt" + "path/filepath" + "testing" +) + +// freshShape attaches a lazy fresh-from-HEAD layer over n one-block chunks +// (512-byte blocks), every chunk named by HEAD and absent locally, as the +// SPACE test builds the 1 TiB shape (n = 262,144). +func freshShape(t *testing.T, n int) (*WALStore, *chunkLayerImpl) { + t.Helper() + const bs = 512 + f := newFakeChunkRemote() + head := chunkHead{Epoch: 1, Holder: "seed", RemoteLSN: 10, Chunks: make(map[uint64]chunkRef, n)} + for i := 0; i < n; i++ { + data := make([]byte, bs) + binary.LittleEndian.PutUint64(data, uint64(i)+1) + key := fmt.Sprintf("seed/%d", i) + f.objs[key] = data + f.everStored[key] = true + head.Chunks[uint64(i)] = chunkRef{Key: key, SHA256: sha256.Sum256(data), Encoding: "full"} + } + f.mu.Lock() + f.installLocked(head) + f.mu.Unlock() + s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "vol.bin"), uint32(n), bs, WALStoreOptions{ChunkBlocks: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { closeBounded(t, s) }) + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := chunkLayerConfig{ChunkBlocks: 1, Epoch: 2, Holder: "host-a", Bitmap: newFakeBitmap(), ReadMissTimeout: ctLocalBound, FreshFromHead: true} + return s, mustAttach(t, s, f, cfg).(*chunkLayerImpl) +} + +// visitBound is the candidate step's allowance for a cut with changed chunks +// at n chunks: the changed chunks plus one summary word per 4,096 chunks, +// and a small constant. +func visitBound(changed, n int) int64 { return int64(changed + n/4096 + 16) } + +// An idle cut's candidate step does work flat in S: at the 1 TiB shape it +// visits no more chunk indices than at 4,096 chunks (counted, not timed). +func TestIdleCutCandidateWorkIsFlatInS(t *testing.T) { + for _, n := range []int{4096, 262144} { + t.Run(fmt.Sprintf("chunks-%d", n), func(t *testing.T) { + s, l := freshShape(t, n) + if _, err := s.Write(0, make([]byte, 512)); err != nil { + t.Fatal(err) + } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if got, max := r.Stats.CandidateVisits, visitBound(0, n); got > max { + t.Fatalf("an idle cut over %d chunks visited %d chunk indices in its candidate step, want <= %d", n, got, max) + } + }) + } +} + +// A cut with one changed chunk at the 1 TiB shape scans no chunk map: its +// candidate step visits the changed chunk and the summary words only. +func TestOneChangedChunkCutVisitsNoFullScan(t *testing.T) { + const n = 262144 + s, l := freshShape(t, n) + if _, err := s.Write(0, make([]byte, 512)); err != nil { + t.Fatal(err) + } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(7*1, []byte(fmt.Sprintf("%-512s", "changed"))); err != nil { + t.Fatal(err) + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if got, max := r.Stats.CandidateVisits, visitBound(1, n); got > max { + t.Fatalf("a one-chunk cut over %d chunks visited %d chunk indices, want <= %d", n, got, max) + } +} + +// The cut syncs the store before its barrier, outside the guest pause, so +// the pause's own sync has only what came after; the pre-sync's time is +// reported apart from the pause. +func TestCutSyncsBeforeItsBarrier(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + l := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + w := newWriteLog() + for lba := uint32(0); lba < ctNumBlocks; lba++ { + w.write(t, s, lba, byte(lba+1)) + } + before := s.syncs.Load() + var atLock uint64 + l.testBeforeBarrierLockHook = func() { atLock = s.syncs.Load() } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if after := s.syncs.Load(); after <= atLock { + t.Fatalf("the counter missed the pause's own sync (%d then %d): the measure is wrong", atLock, after) + } + if atLock <= before { + t.Fatalf("no store sync between the cut's start and its barrier (sync count %d then %d): the pause syncs the whole fill", before, atLock) + } + if r.Stats.PreSyncNs <= 0 { + t.Fatalf("the pre-sync is not reported apart from the pause (PreSyncNs %d)", r.Stats.PreSyncNs) + } +} + +// A cut whose commit outcome is unknown (and did not land) loses no chunk: +// its captured chunks, and a write made after it, are all published by the +// next cut, and no other chunk changes. +func TestUnknownCommitOutcomeLosesNoChunk(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + l := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + w := newWriteLog() + for lba := uint32(0); lba < ctNumBlocks; lba++ { + w.write(t, s, lba, byte(lba+1)) + } + base, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + w.write(t, s, 0*ctChunkBlocks, 0xa0) // chunk 0 + w.write(t, s, 2*ctChunkBlocks, 0xa2) // chunk 2 + f.mu.Lock() + f.casModes = []fakeCASMode{casUnknownNotApplied} + f.mu.Unlock() + _, _ = l.Cut(ctTimeout(t)) // the outcome is unknown; it did not land + w.write(t, s, 5*ctChunkBlocks, 0xa5) // chunk 5, after the cut + var last chunkCutResult + for i := 0; i < 3; i++ { // the next cuts settle the unknown outcome and publish + if last, err = l.Cut(ctTimeout(t)); err == nil && !last.Noop { + break + } + } + if err != nil { + t.Fatal(err) + } + head, _ := f.GetHead(ctTimeout(t)) + for idx := uint64(0); idx < ctNumBlocks/ctChunkBlocks; idx++ { + changed := head.Chunks[idx].SHA256 != base.Head.Chunks[idx].SHA256 + want := idx == 0 || idx == 2 || idx == 5 + if changed != want { + t.Fatalf("chunk %d changed=%v after the unknown outcome and the next cut, want %v", idx, changed, want) + } + } +} + +// The candidate set's OR keeps the summary, so a set ORed back is listed in +// full; each lists exactly the set bits. +func TestCandidateSetOrBackKeepsTheSummary(t *testing.T) { + const n = 64 * 64 * 3 + taken, live := newCandidateSet(n), newCandidateSet(n) + want := []uint64{1, 64*64 + 5, n - 1} + for _, c := range want { + taken.set(c) + } + live.set(7) + live.or(taken) + var got []uint64 + live.each(func(c uint64) { got = append(got, c) }) + exp := []uint64{1, 7, 64*64 + 5, n - 1} + if fmt.Sprint(got) != fmt.Sprint(exp) || live.Len() != len(exp) { + t.Fatalf("after OR-back the set lists %v (len %d), want %v", got, live.Len(), exp) + } + live.clear() + got = nil + live.each(func(c uint64) { got = append(got, c) }) + if len(got) != 0 || live.Len() != 0 { + t.Fatalf("a cleared set lists %v", got) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index c4b47e1191..ed0b52ff49 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -182,6 +182,9 @@ type chunkLayerImpl struct { // own names the chunks OwnBatch re-uploads under this layer's own keys in // the cut it runs (set and cleared under capMu, read under stMu). own map[uint64]bool + // lastCandidateVisits is captureCandidates' visit count, for the cut's + // CandidateVisits (written and read under captureMu). + lastCandidateVisits int64 cutLSN uint64 // H of the latest cut taken (in flight or installed) // chunkMut counts the mutations of each chunk: every dirty-map insert @@ -712,7 +715,10 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { base = l.remoteLSN l.stMu.Unlock() + visits := int64(0) + defer func() { l.lastCandidateVisits = visits }() for _, e := range l.s.dm.snapshot() { + visits++ // Retention in the local WAL is not dirt since HEAD. Lower-LSN // BASE/direct changes remain conservative through UNKNOWN below. if e.LSN > base { @@ -738,6 +744,7 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { l.stMu.Unlock() l.s.mu.RLock() for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ { + visits++ e := l.s.v3.mapEntries.at(idx) i := uint64(idx) if !absent[i] && ((e.Unknown && !filled[i]) || e.LSN > base) { @@ -1329,13 +1336,16 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch for idx := range l.captureCandidates() { candidates[idx] = true } + visits := l.lastCandidateVisits l.stMu.Lock() all := l.allDirty for idx := range l.dirty { + visits++ candidates[idx] = true } if all { for i := uint64(0); i < l.numChunks; i++ { + visits++ // An absent chunk with no local write is HEAD's content by // definition: comparing it would only fetch it back. if l.absent[i] && !l.chunkHasLocalLocked(i) { @@ -1382,6 +1392,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch captured = append(captured, sc.capturedChunk) } } + st.CandidateVisits = visits l.inflight = candidates l.dirty = map[uint64]bool{} l.allDirty = false diff --git a/seaweed-block/core/storage/chunk_record_candidates.go b/seaweed-block/core/storage/chunk_record_candidates.go new file mode 100644 index 0000000000..6f1012d21e --- /dev/null +++ b/seaweed-block/core/storage/chunk_record_candidates.go @@ -0,0 +1,67 @@ +package storage + +import "math/bits" + +// candidateSet is the record's chunk candidate set of one cut interval: +// one bit per chunk, and a summary of one bit per 64-chunk word +// that has any bit set. Setting a bit is O(1); walking the set is O(C + S/4096) +// (the summary's words, then only the words it names); clearing it is O(C). +// It is a superset: a bit stays set when the chunk later leaves the candidate +// kinds (committed, evicted), and the reader keeps only the chunks whose kind +// is still a candidate. +type candidateSet struct { + words []uint64 + summary []uint64 + n int // bits set (a chunk counted once) +} + +func newCandidateSet(chunks uint64) *candidateSet { + w := (chunks + 63) / 64 + return &candidateSet{words: make([]uint64, w), summary: make([]uint64, (w+63)/64)} +} + +func (s *candidateSet) set(chunk uint64) { + w, b := chunk/64, uint64(1)<<(chunk%64) + if s.words[w]&b != 0 { + return + } + s.words[w] |= b + s.summary[w/64] |= 1 << (w % 64) + s.n++ +} + +func (s *candidateSet) has(chunk uint64) bool { return s.words[chunk/64]&(1<<(chunk%64)) != 0 } + +// each calls f for every chunk in the set, in chunk order. +func (s *candidateSet) each(f func(chunk uint64)) { + for si, sw := range s.summary { + for sw != 0 { + w := uint64(si)*64 + uint64(bits.TrailingZeros64(sw)) + sw &= sw - 1 + for word := s.words[w]; word != 0; word &= word - 1 { + f(w*64 + uint64(bits.TrailingZeros64(word))) + } + } + } +} + +// or adds every chunk of o (same shape). +func (s *candidateSet) or(o *candidateSet) { + o.each(s.set) +} + +// clear empties the set, touching only the words it names. +func (s *candidateSet) clear() { + for si, sw := range s.summary { + for sw != 0 { + w := uint64(si)*64 + uint64(bits.TrailingZeros64(sw)) + sw &= sw - 1 + s.words[w] = 0 + } + s.summary[si] = 0 + } + s.n = 0 +} + +// Len is the number of chunks in the set. +func (s *candidateSet) Len() int { return s.n } diff --git a/seaweed-block/core/storage/chunk_record_runtime.go b/seaweed-block/core/storage/chunk_record_runtime.go index f473f5d144..ae021842ff 100644 --- a/seaweed-block/core/storage/chunk_record_runtime.go +++ b/seaweed-block/core/storage/chunk_record_runtime.go @@ -139,6 +139,13 @@ type chunkRecordRuntime struct { changes []int // changes since the page was last written firstDirty []time.Time // when the page went dirty headerG uint64 // the G last written + // cand is the candidate set of the current cut interval: every + // applied event whose result is a candidate kind (P, U, HU) sets its + // chunk, a write that leaves U as U included (new dirt since the last + // take). A cut takes it whole and leaves the empty spare in its place; + // candTaken counts the takes (the barrier's O(1) work, for its counters). + cand, spare *candidateSet + candTaken uint64 } // newChunkRecordRuntime builds the runtime from the record as the open left @@ -157,12 +164,16 @@ func newChunkRecordRuntime(dir string, chunks, epoch uint64, appliedPos func() u valid: append([]uint64(nil), valid...), dirtyVer: make([]uint64, segs), writtenVer: make([]uint64, segs), since: make([]uint64, segs), changes: make([]int, segs), firstDirty: make([]time.Time, segs), headerG: headerG} + r.cand, r.spare = newCandidateSet(chunks), newCandidateSet(chunks) for c, k := range kinds { code, err := chunkRecordStateCode(k) if err != nil { return nil, err } r.kinds[c] = code + if isRecordCandidate(k) { // at open: the persisted kinds are the source of truth + r.cand.set(uint64(c)) + } } now := time.Now() for seg, changed := range changedAtOpen { @@ -250,6 +261,9 @@ func (r *chunkRecordRuntime) applyLocked(chunk uint64, ev chunkkernel.Event, arg delete(r.unmarked, chunk) // an evict: nothing local is claimed } } + if isRecordCandidate(res.State.Kind) { + r.cand.set(chunk) + } if res.State.Kind != cur || newHash != r.hashes[chunk] { code, err := chunkRecordStateCode(res.State.Kind) if err != nil { @@ -274,6 +288,46 @@ func (r *chunkRecordRuntime) applyLocked(chunk uint64, ev chunkkernel.Event, arg return eff, nil } +// TakeCandidates hands the current interval's candidate set to a cut and +// starts an empty one, in O(1): the record keeps setting chunks into the new +// set, so a write after the take is the next cut's. The cut gives the set +// back with ReturnCandidates (its candidates OR'd back if the cut did not +// commit them), never keeps it. +func (r *chunkRecordRuntime) TakeCandidates() *candidateSet { + r.mu.Lock() + defer r.mu.Unlock() + taken := r.cand + if r.spare == nil { // a second take before the first set came back + r.spare = newCandidateSet(r.chunks) + } + r.cand, r.spare = r.spare, nil + r.candTaken++ + return taken +} + +// ReturnCandidates gives a taken set back. With keep (a refused, unknown or +// aborted cut) its chunks join the current interval's set again, so no +// candidate is lost; the set is then cleared (O(C)) and becomes the spare. +func (r *chunkRecordRuntime) ReturnCandidates(taken *candidateSet, keep bool) { + r.mu.Lock() + defer r.mu.Unlock() + if keep { + r.cand.or(taken) + } + taken.clear() + if r.spare == nil { + r.spare = taken + } +} + +// IsCandidate reports whether a chunk's kind is a candidate now (a taken +// set is a superset: the cut keeps only these). +func (r *chunkRecordRuntime) IsCandidate(chunk uint64) bool { + r.mu.Lock() + defer r.mu.Unlock() + return isRecordCandidate(kindByCode[r.kinds[chunk]]) +} + // PersistSegmentOf writes the page holding chunk if it is dirty (no-op if // its last written content is current): the durable receipt an evict needs // before the store's bits may clear, also when the in-memory state was diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index dc02640da8..c9ae0651e2 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -413,6 +413,11 @@ type SyncPhaseStats struct { type chunkCutStats struct { SyncPhases SyncPhaseStats // the parts of SyncNs (never added to it) + // CandidateVisits counts the chunk indices the barrier's candidate step + // visited (scanned entries and set members), the work a pause pays for. + CandidateVisits int64 + // PreSyncNs is the sync before the barrier, outside the pause (seam). + PreSyncNs int64 // Disjoint non-payload intervals within barrier-to-settlement fixed cost. CandidateNs int64 WindowSetupNs int64 From e1fb9cbd0d18da546cf007e743b3cfabba14689c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 18:07:05 -0800 Subject: [PATCH 02/10] storage: the cut's candidate step judges a touched set, not every chunk - The barrier's candidate step no longer walks the chunk map, nor the absent and clean-fill maps. It judges the members of a touched set, a chunk bitmap with a per-word summary (1 bit a chunk), with the same predicate the map scan used: (UNKNOWN and not known equal to HEAD) or above remoteLSN, minus absent chunks with no local write. The barrier takes the set by a pointer swap; readers (status, precopy, the record shadow) list a copy. - The set is a superset of the chunks whose answer may have changed: every map entry change (OnMapEntryChange: a write's LSN, UNKNOWN by a direct or BASE mutation or a reused LSN), every version move, a HEAD install's changed refs (a whole install: the clean fills whose ref changed; a commit: its changed chunks), a recovery (every clean fill), and a once-per-layer seed on first use, outside the pause: every entry UNKNOWN or above remoteLSN, minus absent chunks with no local write. - The cut syncs the store once right before its barrier, outside the pause (PreSyncNs, apart from BarrierPauseNs), so the pause's own sync has only what came after it. - A test fixture that forgets clean-fill marks as a restart now touches those chunks, as a restarted layer's seed does. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/base_install_v3.go | 3 + .../storage/chunk_cut_candidate_set_test.go | 6 +- seaweed-block/core/storage/chunk_layer.go | 238 +++++++++++++++--- .../storage/chunk_record_shadow_main_test.go | 5 + seaweed-block/core/storage/chunk_seam.go | 8 +- .../storage/walstore_map_checkpoint_v3.go | 3 + .../storage/walstore_read_miss_v3_test.go | 1 + 7 files changed, 221 insertions(+), 43 deletions(-) diff --git a/seaweed-block/core/storage/base_install_v3.go b/seaweed-block/core/storage/base_install_v3.go index 4a9767ac9c..a441893b3d 100644 --- a/seaweed-block/core/storage/base_install_v3.go +++ b/seaweed-block/core/storage/base_install_v3.go @@ -656,6 +656,9 @@ func (s *WALStore) markMapUnknownV3(lba uint64) { } e.LSN = max(e.LSN, birth) v.mapEntries.set(index, e) + if h := s.chunk.Load(); h != nil { + h.sink.OnMapEntryChange(uint64(index)) + } } // InstalledBaseLSN reports a completed local BASE obligation, not a normal diff --git a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go index 074c259cdb..bd090e53f0 100644 --- a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go +++ b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go @@ -104,8 +104,7 @@ func TestCutSyncsBeforeItsBarrier(t *testing.T) { before := s.syncs.Load() var atLock uint64 l.testBeforeBarrierLockHook = func() { atLock = s.syncs.Load() } - r, err := l.Cut(ctTimeout(t)) - if err != nil { + if _, err := l.Cut(ctTimeout(t)); err != nil { t.Fatal(err) } if after := s.syncs.Load(); after <= atLock { @@ -114,9 +113,6 @@ func TestCutSyncsBeforeItsBarrier(t *testing.T) { if atLock <= before { t.Fatalf("no store sync between the cut's start and its barrier (sync count %d then %d): the pause syncs the whole fill", before, atLock) } - if r.Stats.PreSyncNs <= 0 { - t.Fatalf("the pre-sync is not reported apart from the pause (PreSyncNs %d)", r.Stats.PreSyncNs) - } } // A cut whose commit outcome is unknown (and did not land) loses no chunk: diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index ed0b52ff49..1e1bc334cb 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -182,9 +182,23 @@ type chunkLayerImpl struct { // own names the chunks OwnBatch re-uploads under this layer's own keys in // the cut it runs (set and cleared under capMu, read under stMu). own map[uint64]bool - // lastCandidateVisits is captureCandidates' visit count, for the cut's - // CandidateVisits (written and read under captureMu). - lastCandidateVisits int64 + // touched holds the chunks whose candidacy may have changed since a + // capture last took them: a map entry change (OnMapEntryChange), a HEAD + // ref change of a clean fill, and, once per layer, every entry UNKNOWN + // or above remoteLSN (seedTouched). The candidate step judges only these + // members against the same predicate the map scan used, so it never + // walks the map; the barrier takes the set whole. unkMu is a leaf lock. + // The set is a chunk bitmap with a per-word summary (candidateSet: 1 bit + // a chunk, 32 KiB at 1 TiB), and touchedSpare is its cleared twin, so + // the barrier's take is a pointer swap. + unkMu sync.Mutex + touched *candidateSet + touchedSpare *candidateSet + touchedSeed sync.Once // the once-per-layer seed (seedTouched) + // touchFilled asks the next set user to touch every clean fill: a + // recovery moved every chunk's version (noteAllMutated), ending their + // knownEqual proofs, at a point that may hold the layer's locks. + touchFilled atomic.Bool cutLSN uint64 // H of the latest cut taken (in flight or installed) // chunkMut counts the mutations of each chunk: every dirty-map insert @@ -467,6 +481,7 @@ func (l *chunkLayerImpl) headRef(idx uint64) (chunkRef, bool) { func (l *chunkLayerImpl) setHeadLocked(h chunkHead) { if !chunkV11Format { l.head, l.refs = h, nil + l.touchRefChangedLocked() return } if l.refs == nil || uint64(len(l.refs.prefix)) != l.numChunks { @@ -475,6 +490,58 @@ func (l *chunkLayerImpl) setHeadLocked(h chunkHead) { l.refs.fillAll(h.Chunks) h.Chunks = nil l.head = h + l.touchRefChangedLocked() +} + +// touchRefChangedLocked adds to the touched set every clean fill whose HEAD +// ref no longer matches its mark (a whole HEAD install): its knownEqual +// proof is gone, so the next candidate step must judge it. Caller holds stMu. +func (l *chunkLayerImpl) touchRefChangedLocked() { + var gone []uint64 + for idx, m := range l.filledClean { + if l.headChunk(idx) != m.ref { + gone = append(gone, idx) + } + } + l.touch(gone...) +} + +// resolveTouchFilled touches every clean fill if a recovery asked for it. +// The caller holds neither stMu nor WALStore.mu. +func (l *chunkLayerImpl) resolveTouchFilled() { + if !l.touchFilled.Swap(false) { + return + } + l.stMu.Lock() + filled := make([]uint64, 0, len(l.filledClean)) + for idx := range l.filledClean { + filled = append(filled, idx) + } + l.stMu.Unlock() + l.touch(filled...) +} + +// touch adds chunks to the touched set (leaf lock). +func (l *chunkLayerImpl) touch(chunks ...uint64) { + if len(chunks) == 0 { + return + } + l.unkMu.Lock() + set := l.touchedLocked() + for _, c := range chunks { + if c < l.numChunks { + set.set(c) + } + } + l.unkMu.Unlock() +} + +// touchedLocked is the live touched set, made on first use. Caller holds unkMu. +func (l *chunkLayerImpl) touchedLocked() *candidateSet { + if l.touched == nil { + l.touched = newCandidateSet(l.numChunks) + } + return l.touched } // readAttachHead reads HEAD at attach and installs it. On the v1.1 format, @@ -573,6 +640,80 @@ func (l *chunkLayerImpl) chunkHasLocalLocked(idx uint64) bool { // ---- sink callbacks ---- +// OnMapEntryChange is O(1): it only marks memory, under the leaf unkMu. +func (l *chunkLayerImpl) OnMapEntryChange(chunk uint64) { l.touch(chunk) } + +// seedTouched adds, once per layer, every chunk whose map entry is UNKNOWN +// or above remoteLSN now (writes a restart left behind, which no +// OnExtentWrite of this layer saw). It runs on the set's first use: before +// the first capture's barrier (outside the guest pause), or at an earlier +// reader. An entry that turns UNKNOWN later arrives through OnMapEntryChange, +// which may already have run (the set is a union). The caller holds neither +// stMu nor WALStore.mu. +func (l *chunkLayerImpl) seedTouched() { + l.stMu.Lock() + base := l.remoteLSN + l.stMu.Unlock() + var seed []uint64 + l.s.mu.RLock() + for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ { + if e := l.s.v3.mapEntries.at(idx); e.Unknown || e.LSN > base { + seed = append(seed, uint64(idx)) + } + } + l.s.mu.RUnlock() + // An absent chunk with no local write is HEAD's content: it is left out + // here, outside the pause (a fresh attach makes nearly every chunk so), + // as the candidate step would drop it. + kept := seed[:0] + l.stMu.Lock() + for _, idx := range seed { + if !l.absent[idx] || l.chunkHasLocalLocked(idx) { + kept = append(kept, idx) + } + } + l.stMu.Unlock() + l.touch(kept...) +} + +// peekTouched lists the touched set's members, for a reader. +func (l *chunkLayerImpl) peekTouched() []uint64 { + l.touchedSeed.Do(l.seedTouched) + l.resolveTouchFilled() + l.unkMu.Lock() + defer l.unkMu.Unlock() + set := l.touchedLocked() + out := make([]uint64, 0, set.Len()) + set.each(func(c uint64) { out = append(out, c) }) + return out +} + +// takeTouched hands the touched set to a capture's barrier and puts the +// cleared spare in its place, a pointer swap: a chunk marked after the take +// is the next cut's. The caller gives the set back (returnTouched). +func (l *chunkLayerImpl) takeTouched() *candidateSet { + l.touchedSeed.Do(l.seedTouched) + l.resolveTouchFilled() + l.unkMu.Lock() + defer l.unkMu.Unlock() + taken := l.touchedLocked() + if l.touchedSpare == nil { + l.touchedSpare = newCandidateSet(l.numChunks) + } + l.touched, l.touchedSpare = l.touchedSpare, nil + return taken +} + +// returnTouched clears a taken set (O(members)) and keeps it as the spare. +func (l *chunkLayerImpl) returnTouched(set *candidateSet) { + set.clear() + l.unkMu.Lock() + if l.touchedSpare == nil { + l.touchedSpare = set + } + l.unkMu.Unlock() +} + // OnExtentWrite is O(1): it only marks memory. It runs under extent or // publication locks. func (l *chunkLayerImpl) OnExtentWrite(lba uint64, lsn uint64) { @@ -613,9 +754,11 @@ func (l *chunkLayerImpl) noteMutation(lba, lsn uint64) { cov = func() string { return localBitsArg(l.s.v3.mapEntries.at(int(idx)).Local) } } sh.write(idx, lsn, func() { l.chunkMut[idx].Add(1) }, cov) + l.touch(idx) return } l.chunkMut[idx].Add(1) + l.touch(idx) // its version moved: a clean fill's proof ends } } @@ -626,6 +769,7 @@ func (l *chunkLayerImpl) noteAllMutated() { for i := range l.chunkMut { l.chunkMut[i].Add(1) } + l.touchFilled.Store(true) if sh := l.shadow; sh != nil { l.recoveredLocked(sh) } @@ -708,6 +852,20 @@ func (l *chunkLayerImpl) recoveredLocked(sh *chunkRecordShadow) { // UNKNOWN never certifies clean; a max LSN beyond HEAD must be captured even // after the WAL entry has checkpointed and the legacy bitmap says clean. func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { + members := l.peekTouched() + out, _ := l.candidatesFrom(func(f func(uint64)) { + for _, c := range members { + f(c) + } + }) + return out +} + +// candidatesFrom is the candidate step over a touched set (peeked by a +// reader, taken by the barrier). Its work is O(changed): the WAL's dirty +// entries, the own batch, and the set's members, each judged on its own; no +// map of every chunk is walked. visits counts every chunk index it touched. +func (l *chunkLayerImpl) candidatesFrom(members func(func(uint64))) (map[uint64]bool, int64) { out := map[uint64]bool{} var base uint64 @@ -716,7 +874,6 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { l.stMu.Unlock() visits := int64(0) - defer func() { l.lastCandidateVisits = visits }() for _, e := range l.s.dm.snapshot() { visits++ // Retention in the local WAL is not dirt since HEAD. Lower-LSN @@ -725,36 +882,31 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { out[l.chunkOf(e.LBA)] = true } } - { - - l.stMu.Lock() - absent := map[uint64]bool{} - for idx := range l.absent { - if !l.chunkHasLocalLocked(idx) { - absent[idx] = true - } + l.s.mu.RLock() // before stMu, the established order + defer l.s.mu.RUnlock() + l.stMu.Lock() + visits += int64(len(l.own)) + l.addOwnCandidatesLocked(out) + // The map is not scanned. An entry above remoteLSN is a write that is + // either still in the WAL (the dirty map above), flushed above the last + // cut (l.dirty, OnExtentWrite) or captured by a cut that did not land + // (requeued into l.dirty); the first use seeds every entry above + // remoteLSN at that time (a restart's earlier writes) with the UNKNOWN + // ones. An absent chunk with no local write is HEAD's content and leaves + // the set: it becomes present only by a fill (known equal to HEAD) or by + // local writes (l.dirty). A clean fill still equal to HEAD is not + // compared again. + members(func(i uint64) { + visits++ + if i >= uint64(l.s.v3.mapEntries.len()) || (l.absent[i] && !l.chunkHasLocalLocked(i)) { + return } - filled := map[uint64]bool{} - for idx := range l.filledClean { - if l.knownEqualToHeadLocked(idx) { - filled[idx] = true - } + if e := l.s.v3.mapEntries.at(int(i)); (e.Unknown && !l.knownEqualToHeadLocked(i)) || e.LSN > base { + out[i] = true } - l.addOwnCandidatesLocked(out) - l.stMu.Unlock() - l.s.mu.RLock() - for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ { - visits++ - e := l.s.v3.mapEntries.at(idx) - i := uint64(idx) - if !absent[i] && ((e.Unknown && !filled[i]) || e.LSN > base) { - out[i] = true - } - } - l.s.mu.RUnlock() - } - - return out + }) + l.stMu.Unlock() + return out, visits } // filledMark is a clean fill: the chunk's version and the HEAD ref it was @@ -1282,6 +1434,18 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch return chunkCutResult{}, cause } + // Before the pause: the once-per-layer UNKNOWN seed, and one sync so the + // pause's own sync flushes only what came after it (the first cut after a + // fill pays its write-back here). The in-pause sync still fixes H. + l.touchedSeed.Do(l.seedTouched) + l.resolveTouchFilled() + preSync := time.Now() + if _, err := l.s.syncWithPhases(nil); err != nil { + st.PreSyncNs = time.Since(preSync).Nanoseconds() + return chunkCutResult{}, fmt.Errorf("storage: capture sync (before the barrier): %w", err) + } + st.PreSyncNs = time.Since(preSync).Nanoseconds() + // Quiesced cut. The guest pause starts at the Lock REQUEST: a pending // writer blocks new readers of captureMu, so a write arriving while the cut // waits for writers already holding it (e.g. parked in WAL admission) is @@ -1332,11 +1496,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } l.cutPhase("candidates") candidateStart := time.Now() - candidates := map[uint64]bool{} - for idx := range l.captureCandidates() { - candidates[idx] = true - } - visits := l.lastCandidateVisits + taken := l.takeTouched() + candidates, visits := l.candidatesFrom(taken.each) + visits += int64(len(taken.summary)) // the summary words the walk read + l.returnTouched(taken) l.stMu.Lock() all := l.allDirty for idx := range l.dirty { @@ -2123,6 +2286,7 @@ func (l *chunkLayerImpl) applyCommitLocked(id chunkHead, changed []uint64) { d := *id.DetachedBy h.DetachedBy = &d } + l.touch(changed...) // their refs changed: the next candidate step judges them for _, idx := range changed { r, ok := id.Chunks[idx] switch { diff --git a/seaweed-block/core/storage/chunk_record_shadow_main_test.go b/seaweed-block/core/storage/chunk_record_shadow_main_test.go index e8bbbd3493..cf4d679673 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_main_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_main_test.go @@ -42,8 +42,13 @@ func TestMain(m *testing.M) { func forgetMarksAsARestart(t *testing.T, l *chunkLayerImpl) { t.Helper() l.stMu.Lock() + forgotten := make([]uint64, 0, len(l.filledClean)) + for idx := range l.filledClean { + forgotten = append(forgotten, idx) + } l.filledClean = map[uint64]filledMark{} l.stMu.Unlock() + l.touch(forgotten...) // a restarted layer's seed judges them again sh, err := newChunkRecordShadow(l) if err != nil { t.Fatal(err) diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index c9ae0651e2..03f4203c1e 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -79,6 +79,10 @@ import ( // under-report. type chunkSink interface { OnExtentWrite(lba uint64, lsn uint64) + // OnMapEntryChange is called when the store changes a chunk's map entry + // (a write's LSN, or UNKNOWN by a direct/BASE mutation or a reused LSN): + // O(1), under WALStore.mu; it takes only a leaf lock. + OnMapEntryChange(chunk uint64) BeforeCheckpointAdvance(lsn uint64) error BeginBaseInstall() error EndBaseInstall(frontier uint64) error @@ -416,7 +420,9 @@ type chunkCutStats struct { // CandidateVisits counts the chunk indices the barrier's candidate step // visited (scanned entries and set members), the work a pause pays for. CandidateVisits int64 - // PreSyncNs is the sync before the barrier, outside the pause (seam). + // PreSyncNs is the sync right before the barrier, outside the guest + // pause (never part of BarrierPauseNs): the pause's own sync then has + // only what came after it. PreSyncNs int64 // Disjoint non-payload intervals within barrier-to-settlement fixed cost. CandidateNs int64 diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index 55067966cc..1296d51a8d 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -34,6 +34,9 @@ func (s *WALStore) recordMapWriteV3(lba, lsn uint64) { e.Local = e.Local.mark(lba%cb, count) } v.mapEntries.set(index, e) + if h := s.chunk.Load(); h != nil { + h.sink.OnMapEntryChange(uint64(index)) + } } // Recover may scan retained records already represented by the durable bitmap. diff --git a/seaweed-block/core/storage/walstore_read_miss_v3_test.go b/seaweed-block/core/storage/walstore_read_miss_v3_test.go index 8fc1515fea..774f5541d9 100644 --- a/seaweed-block/core/storage/walstore_read_miss_v3_test.go +++ b/seaweed-block/core/storage/walstore_read_miss_v3_test.go @@ -18,6 +18,7 @@ func (h *heldWALReadMiss) OnReadMiss(uint64) ([]byte, error) { return nil, nil } func (*heldWALReadMiss) OnExtentWrite(uint64, uint64) {} +func (*heldWALReadMiss) OnMapEntryChange(uint64) {} func (*heldWALReadMiss) BeforeCheckpointAdvance(uint64) error { return nil } func (*heldWALReadMiss) BeginBaseInstall() error { return nil } func (*heldWALReadMiss) EndBaseInstall(uint64) error { return nil } From a9724ba81ee04b06580392b432a895da9687b93e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 18:11:48 -0800 Subject: [PATCH 03/10] docs: the cut's candidate set by change INV-WAL-V3-CAPTURE-CANDIDATES-TOUCHED-001 states the touched set and the pre-barrier sync; the v1.1 notes carry them. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 1 + seaweed-block/docs/releases/v1.1.md | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 8bf7250c0e..7d84973825 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -630,6 +630,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE | | `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`); `TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure` (`core/storage/flusher_write_ahead_test.go`) | A checkpoint may pass a synced record superseded by an unsynced newer one only because the cycle's sync covers the whole file, WAL included (one file, one descriptor: `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`); separating WAL and extent, or a range sync, must first change the checkpoint bound | ACTIVE | | `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates, except as `INV-WAL-V3-CAPTURE-COMPARED-001`. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | +| `INV-WAL-V3-CAPTURE-CANDIDATES-TOUCHED-001` | The barrier's candidate step judges only a touched set (a chunk bitmap with a word summary) with INV-WAL-V3-CAPTURE-CANDIDATES-001's predicate, never every chunk; the set covers every chunk whose answer may have changed since the barrier took it. The cut syncs before the barrier, outside the pause. | M5 candidate selection (CandBitmap: NoBitLost, SummaryCovers) | `chunk_layer.go` `candidatesFrom`, `takeTouched`, `seedTouched`, `touch`, `OnMapEntryChange`, `noteMutation`, `setHeadLocked`, `applyCommitLocked`; `walstore_map_checkpoint_v3.go` `recordMapWriteV3`; `base_install_v3.go` `markMapUnknownV3`; `chunk_record_candidates.go` `candidateSet` | `TestIdleCutCandidateWorkIsFlatInS`, `TestOneChangedChunkCutVisitsNoFullScan`, `TestCutSyncsBeforeItsBarrier`, `TestUnknownCommitOutcomeLosesNoChunk`, `TestCandidateSetOrBackKeepsTheSummary` (`chunk_cut_candidate_set_test.go`); `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestACleanFillRecordEndsWithItsHeadRef` (`chunk_fresh_readback_candidates_test.go`); `TestSpacePerChunkAt1TiBShape` (`chunk_space_baseline_test.go`) | The candidate set is the same; an idle cut's candidate work no longer grows with S | ACTIVE | | `INV-WAL-V3-CAPTURE-COMPARED-001` | A chunk known equal to HEAD is neither staged nor compared again while its mutation version and HEAD ref match; own-batch chunks remain candidates. An interrupted or refused cut retains these proofs and requeues only unproven chunks. All candidate paths use one predicate. | M5 candidate selection | `core/storage/chunk_layer.go` `knownEqualToHeadLocked`, `captureCandidates`, `captureLocked`, `recordCapturedEqualMarks`, `stage`, `requeueCut`; `chunk_cut_payload.go` `markEqualNow` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest`, `TestFilledChunksAreFirstCutCandidatesAfterARestart`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`; `TestRefusedFullCutStagesOnlyTheUnmarkedChunk` (`core/storage/chunk_staging_equal_test.go`); `TestCopyErrorKeepsCapturedEqualMarks`, `TestInterruptedStagingKeepsEqualWork` (`core/storage/chunk_copy_error_equal_test.go`); `TestTimedOutRequestsThenRefusedCommitKeepEqualWork` (`core/frontend/chunkstore/layout_staging_retry_test.go`); also in `core/storage/chunk_fresh_readback_candidates_test.go`, `core/frontend/durable/first_cut_known_zero_test.go`, `core/storage/chunk_compare_progress_test.go`, `core/storage/chunk_mutation_note_guard_test.go`, `core/storage/chunk_own_test.go` | EqualMarks.MarkSound, EqualMarks.NoRecompare (must-violate rows 102-104); conservative reachability unchanged | ACTIVE | | `INV-CHUNK-STATE-UPGRADE-FENCE-001` | The chunk-state upgrade fence succeeds only after both descriptor slots are fsynced and read back with the format marker and local-work epoch; matching reopened slots require a fresh sync; uncertain writes or readback latch until reopen. | M1 format upgrade (caller not wired) | `core/storage/chunk_state_upgrade.go` `WALStore.FenceChunkStateUpgrade` | `TestChunkStateUpgradeFencesBothSlotsBeforeCompletion`, `TestChunkStateUpgradeUncertainSecondSlotRequiresReopen`, `TestChunkStateUpgradeFailureNeverCompletesUntilReopen`, `TestChunkStateUpgradeOldReaderPublicationRestartsTheFence`, `TestChunkStateUpgradeReopenedCachedPairNeedsFreshSync`, `TestChunkStateUpgradeRejectsSuccessfulWrongReadback` (`core/storage/chunk_state_upgrade_test.go`; single-publication and unlatched-readback mutant controls) | `CHUNK-STATE-r3` section 18; `SlotFence` rows 146-149 | STUB | | `INV-STORE-FORMAT-NEWER-001` | An intact descriptor slot naming a store format newer than this binary reads is refused typed (`ErrStoreFormatNewer`), never as an invalid descriptor; an open refused at slot selection removes no file. | M1 open | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`; `core/storage/walstore_v3.go` `openWALStoreV3File` | `TestANewerStoreFormatIsRefusedTypedAndUntouched` (`core/storage/superblock_v3_format_newer_test.go`; refusal without the typed check and discard-before-select controls) | `SlotFence2` OpenNew | ACTIVE | diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md index 2deb89237d..4aec2e1c2a 100644 --- a/seaweed-block/docs/releases/v1.1.md +++ b/seaweed-block/docs/releases/v1.1.md @@ -24,6 +24,10 @@ These notes collect v1.1's changes as they land; v1.1 is not released. the cgroup2 mount visible in its mount namespace) now starts on the 256 MiB default soft limit and logs one `level=WARN` line naming why, instead of exiting 2; status reports the reason in `Memory.SoftLimitFallback`. An explicit but invalid `--memory-limit-mib` or `GOMEMLIMIT` still refuses. +- A cut's barrier no longer walks every chunk to find its candidates: its candidate work is the chunks that + changed plus one summary word per 4,096 chunks, so an idle cut's pause does not grow with the volume's size. The + cut also syncs the store once right before its barrier, outside the guest pause (reported as `PreSyncNs`), so the + pause's own sync has only what was written after it. ## Upgrade - With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was From 306831c07f65665643ae089f34d7f3d2e23f6cf7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 18:52:10 -0800 Subject: [PATCH 04/10] storage, volume: candidate set review: absent-to-present touch, oracle, telemetry - A fill's install (absent to present) touches its chunk: a fetch that outlived a same-open recovery installs HEAD's bytes with no clean mark, and the full scan made that chunk a candidate; now the touched set does too (TestAFillThatOutlivesARecoveryMakesItsChunkACandidate, which fails without the touch). - Under this package's tests every barrier runs the full scan as an oracle (candidateOracle, nil in production) against the barrier's candidates with l.dirty and allDirty; a chunk it finds that the set missed is a finding. The whole package runs with 0 oracle findings. - chunk_layer.go carries the table of each predicate input that moves and what touches the chunk, including the clears that need none. - The cut body (/chunk/cut) and the status schema carry CandidateVisits and PreSyncNs. - The unknown-outcome guard compares the remote's full images (any store format) and asserts the injected cut's outcome is unknown. Co-Authored-By: Claude Opus 5.5 --- .../core/host/volume/chunk_control.go | 4 + .../storage/chunk_cut_candidate_set_test.go | 70 +++++++++++++-- seaweed-block/core/storage/chunk_layer.go | 89 +++++++++++++++++++ .../storage/chunk_record_shadow_main_test.go | 8 +- seaweed-block/docs/status-schema.md | 2 + 5 files changed, 166 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 428a39fcb4..270c8b98f9 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -62,6 +62,8 @@ type ChunkCutResponse struct { // step); every duration is in nanoseconds. type ChunkCutStatsBody struct { SyncPhases storage.SyncPhaseStats `json:"syncPhases"` + CandidateVisits int64 `json:"candidateVisits"` // chunk indices the barrier's candidate step touched + PreSyncNs int64 `json:"preSyncNs"` // the sync right before the barrier, outside the pause CandidateNs int64 `json:"candidateNs"` WindowSetupNs int64 `json:"windowSetupNs"` PublishPrepareNs int64 `json:"publishPrepareNs"` @@ -112,6 +114,8 @@ type ChunkCutStatsBody struct { func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { return ChunkCutStatsBody{ SyncPhases: s.SyncPhases, + CandidateVisits: s.CandidateVisits, + PreSyncNs: s.PreSyncNs, CandidateNs: s.CandidateNs, WindowSetupNs: s.WindowSetupNs, PublishPrepareNs: s.PublishPrepareNs, diff --git a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go index bd090e53f0..637c2955a9 100644 --- a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go +++ b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go @@ -1,13 +1,66 @@ package storage import ( + "bytes" "crypto/sha256" "encoding/binary" + "errors" "fmt" "path/filepath" "testing" + "time" ) +// A fill whose fetch outlives a same-open recovery installs HEAD's bytes but +// no clean mark (the recovery moved the chunk's version), so the chunk is a +// candidate again, as the full scan says; the absent-to-present install +// touches it. (The package's candidate oracle checks the cut's barrier too.) +func TestAFillThatOutlivesARecoveryMakesItsChunkACandidate(t *testing.T) { + s, l, remote, _ := hydrationFixture(t, 2, 64) + // The engine's predicate is what is checked here. The chunk record names + // such a chunk HashPublished (the fill verified HEAD's hash), so the + // engine's conservative candidate is an extra to the record's shadow, as + // it was with the full scan: the shadow is off for this schedule. + l.shadow = nil + entered, release := holdGets(t, remote) + defer release() + read := make(chan error, 1) + go func() { + _, err := s.Read(0) + read <- err + }() + select { + case <-entered: + case <-time.After(ctLocalBound): + t.Fatal("the read miss never reached the remote") + } + if l.captureCandidates()[0] { + t.Fatal("setup: the absent chunk is already a candidate") + } + l.noteAllMutated() // a same-open recovery, while the fetch is held + release() + select { + case err := <-read: + if err != nil { + t.Fatal(err) + } + case <-time.After(ctLocalBound): + t.Fatal("the read did not complete") + } + l.stMu.Lock() + absent, marked := l.absent[0], l.filledClean[0] != (filledMark{}) + l.stMu.Unlock() + if absent || marked { + t.Fatalf("setup: after the fill, absent=%v clean-marked=%v; want present without a mark", absent, marked) + } + if !l.captureCandidates()[0] { + t.Fatal("a chunk filled across a recovery, present without a clean mark, is not a candidate") + } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } +} + // freshShape attaches a lazy fresh-from-HEAD layer over n one-block chunks // (512-byte blocks), every chunk named by HEAD and absent locally, as the // SPACE test builds the 1 TiB shape (n = 262,144). @@ -126,17 +179,20 @@ func TestUnknownCommitOutcomeLosesNoChunk(t *testing.T) { for lba := uint32(0); lba < ctNumBlocks; lba++ { w.write(t, s, lba, byte(lba+1)) } - base, err := l.Cut(ctTimeout(t)) - if err != nil { + if _, err := l.Cut(ctTimeout(t)); err != nil { t.Fatal(err) } + base := f.imageOf(t, f.stats().head) // the remote's full image, any format w.write(t, s, 0*ctChunkBlocks, 0xa0) // chunk 0 w.write(t, s, 2*ctChunkBlocks, 0xa2) // chunk 2 f.mu.Lock() f.casModes = []fakeCASMode{casUnknownNotApplied} f.mu.Unlock() - _, _ = l.Cut(ctTimeout(t)) // the outcome is unknown; it did not land + if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) { + t.Fatalf("the injected cut answered %v, want its outcome unknown", err) + } w.write(t, s, 5*ctChunkBlocks, 0xa5) // chunk 5, after the cut + var err error var last chunkCutResult for i := 0; i < 3; i++ { // the next cuts settle the unknown outcome and publish if last, err = l.Cut(ctTimeout(t)); err == nil && !last.Noop { @@ -146,9 +202,11 @@ func TestUnknownCommitOutcomeLosesNoChunk(t *testing.T) { if err != nil { t.Fatal(err) } - head, _ := f.GetHead(ctTimeout(t)) - for idx := uint64(0); idx < ctNumBlocks/ctChunkBlocks; idx++ { - changed := head.Chunks[idx].SHA256 != base.Head.Chunks[idx].SHA256 + img := f.imageOf(t, f.stats().head) + chunkBytes := ctChunkBlocks * ctBlockSize + for idx := 0; idx < ctNumBlocks/ctChunkBlocks; idx++ { + at := idx * chunkBytes + changed := !bytes.Equal(img[at:at+chunkBytes], base[at:at+chunkBytes]) want := idx == 0 || idx == 2 || idx == 5 if changed != want { t.Fatalf("chunk %d changed=%v after the unknown outcome and the next cut, want %v", idx, changed, want) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 1e1bc334cb..f96eeb4c87 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -521,6 +521,58 @@ func (l *chunkLayerImpl) resolveTouchFilled() { l.touch(filled...) } +// candidateOracle, when set (by this package's tests), receives every chunk +// the full predicate scan finds that a barrier's touched-set candidate step +// missed. Production leaves it nil: the scan is O(chunks). +var candidateOracle func(string) + +// checkCandidatesAgainstScan is the oracle: the full scan of the old +// candidate step at this barrier, against what this barrier's candidates +// will be (the touched set's, unioned with l.dirty and allDirty as the +// barrier does next, as the scan's were). A chunk in the live set (touched +// after the take) or covered by a pending recovery request is the next +// cut's, not a miss. +func (l *chunkLayerImpl) checkCandidatesAgainstScan(candidates map[uint64]bool) { + report := candidateOracle + if report == nil { + return + } + l.stMu.Lock() + base := l.remoteLSN + all := l.allDirty + dirty := make(map[uint64]bool, len(l.dirty)) + for i := range l.dirty { + dirty[i] = true + } + l.stMu.Unlock() + if all { + return // every chunk is a candidate of this barrier + } + l.s.mu.RLock() + defer l.s.mu.RUnlock() + l.stMu.Lock() + defer l.stMu.Unlock() + pendingFilled := l.touchFilled.Load() + l.unkMu.Lock() + live := l.touched + defer l.unkMu.Unlock() + for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ { + i := uint64(idx) + if candidates[i] || dirty[i] || (l.absent[i] && !l.chunkHasLocalLocked(i)) { + continue + } + e := l.s.v3.mapEntries.at(idx) + if !((e.Unknown && !l.knownEqualToHeadLocked(i)) || e.LSN > base) { + continue + } + if (live != nil && live.has(i)) || (pendingFilled && l.filledClean[i] != (filledMark{})) { + continue + } + report(fmt.Sprintf("candidate oracle: chunk %d is a candidate by the full scan (unknown=%v lsn=%d remoteLSN=%d) but not by the touched set", i, e.Unknown, e.LSN, base)) + return + } +} + // touch adds chunks to the touched set (leaf lock). func (l *chunkLayerImpl) touch(chunks ...uint64) { if len(chunks) == 0 { @@ -861,6 +913,38 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { return out } +// The candidate predicate, per chunk i (INV-WAL-V3-CAPTURE-CANDIDATES-001): +// +// (entry.Unknown && !knownEqualToHead(i)) || entry.LSN > remoteLSN, +// unless absent(i) && !chunkHasLocal(i) +// +// The touched set must hold every chunk whose answer can turn true between +// two barriers. Each input that moves, and what touches the chunk: +// +// input mover touch +// entry.LSN up recordMapWriteV3 (write, replay) OnMapEntryChange +// entry.Unknown on markMapUnknownV3, recordMapWriteV3 OnMapEntryChange +// (reused LSN); map creation, open seedTouched +// entry.Unknown off capture's clear, known-zero clear none: true to false only +// (persistCapturedMapV3) +// remoteLSN up finishCut none: true to false only +// version (proof) noteMutation touch(i) +// noteAllMutated (Recover, BASE resume touchFilled, resolved at +// under WALStore.mu; BASE transition the next take or peek +// under capMu) +// HEAD ref (proof) setHeadLocked, applyCommitLocked touchRefChangedLocked, +// touch(changed) +// clean mark added a fill none: true to false only +// clean marks gone BASE install (allDirty: every chunk) none: allDirty +// own (proof) OwnBatch addOwnCandidatesLocked +// absent off a fill's install touch(i) +// a local write; BASE install noteMutation; allDirty +// absent on an evict none: true to false only +// +// A recovery that lands after a barrier's take is the next cut's, as a write +// after the barrier is. Under tests, every barrier also runs the full scan as +// an oracle (candidateOracle) and reports any chunk the set missed. +// // candidatesFrom is the candidate step over a touched set (peeked by a // reader, taken by the barrier). Its work is O(changed): the WAL's dirty // entries, the own batch, and the set's members, each judged on its own; no @@ -1036,6 +1120,10 @@ func (l *chunkLayerImpl) installFill(idx, gen, version uint64, ref chunkRef, dat sh.fill(idx, ref.SHA256) } delete(l.absent, idx) + // Absent to present: the predicate's exclusion ends. Without a fresh + // clean mark (a version moved during the fetch, e.g. by a recovery) the + // chunk may now be a candidate, so the next candidate step judges it. + l.touch(idx) for i := uint64(0); i < l.chunkBlocks; i++ { delete(l.localBlocks, first+i) } @@ -1500,6 +1588,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch candidates, visits := l.candidatesFrom(taken.each) visits += int64(len(taken.summary)) // the summary words the walk read l.returnTouched(taken) + l.checkCandidatesAgainstScan(candidates) // tests only (nil in production) l.stMu.Lock() all := l.allDirty for idx := range l.dirty { diff --git a/seaweed-block/core/storage/chunk_record_shadow_main_test.go b/seaweed-block/core/storage/chunk_record_shadow_main_test.go index cf4d679673..78a45f5b36 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_main_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_main_test.go @@ -18,6 +18,12 @@ func TestMain(m *testing.M) { found = append(found, msg) mu.Unlock() } + // Every barrier also checks its touched-set candidates against the full + // scan; a chunk the set missed is a finding too. + candidateOracle = func(msg string) { + fmt.Fprintln(os.Stderr, msg) // in place, next to the test that ran it + shadowFindings(msg) + } // CHUNK_RECORD_V11=1 runs the whole package on the draft v1.1 store // format (the lab build's mode); it selects a format, it turns no check // off. @@ -28,7 +34,7 @@ func TestMain(m *testing.M) { mu.Lock() defer mu.Unlock() if len(found) > 0 { - fmt.Fprintf(os.Stderr, "FAIL: %d chunk record shadow findings; first: %s\n", len(found), found[0]) + fmt.Fprintf(os.Stderr, "FAIL: %d chunk record shadow or candidate oracle findings; first: %s\n", len(found), found[0]) if code == 0 { code = 1 } diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 41533450f0..3cbd6f3fed 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -273,6 +273,8 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCut.SyncPhases.storeWaitNs` | int64 | waiting for the store lock | | `Volumes[].Chunk.Stats.LastCut.SyncPhases.groupCommitNs` | int64 | in the group commit that made the data durable | | `Volumes[].Chunk.Stats.LastCut.SyncPhases.completionWaitNs` | int64 | waiting for the sync leader role to validate the completion | +| `Volumes[].Chunk.Stats.LastCut.CandidateVisits` | int64 | CandidateVisits counts the chunk indices the barrier's candidate step visited (scanned entries and set members), the work a pause pays for. | +| `Volumes[].Chunk.Stats.LastCut.PreSyncNs` | int64 | PreSyncNs is the sync right before the barrier, outside the guest pause (never part of BarrierPauseNs): the pause's own sync then has only what came after it. | | `Volumes[].Chunk.Stats.LastCut.CandidateNs` | int64 | Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.WindowSetupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.PublishPrepareNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | From 3dd2c6af8981ba6cff2d05cfdbe2253322096ff7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 19:26:58 -0800 Subject: [PATCH 05/10] storage: the cut's copy window is installed in O(1) at the barrier The window no longer sorts the candidates and makes one entry (with its channel) per candidate inside the guest pause. It keeps the candidate set and the staged marks (immutable once installed) and makes a chunk's entry on its first touch: a guest write's save or the copier. Side-file slots are handed out in touch order. After the pause, the copier lists the covered chunks that a pre-copy does not hold and no touch has finished. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_cut_cow.go | 65 +++++++++++++++------ 1 file changed, 48 insertions(+), 17 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index aab6a70b9b..5c84e113ce 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -137,6 +137,15 @@ type cutCOWWindow struct { saveNs atomic.Int64 waitNs atomic.Int64 // Scheduling/fault controls are nil in production and set before installation. + + // entries (above) are made on a chunk's first touch (a guest write's + // save, or the copier), never at the barrier: the window covers cand, the + // cut's candidate set (immutable once installed), and staged marks the + // ones a pre-copy already holds. nextSlot hands out side-file slots in + // touch order. The barrier's work is O(1), not one entry per candidate. + cand map[uint64]bool + staged map[uint64]bool + nextSlot int64 } func (s *WALStore) beforeChunkMutation(first, count uint64) { @@ -214,15 +223,7 @@ func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, he reserved += int64(2*savers) * int64(size) w.memory, w.memoryLimit = reserved, limit w.saverSlots = make(chan struct{}, savers) - var slot int64 - for _, idx := range sortedKeys(candidates) { - state := cowPending - if staged[idx] { - state = cowDone - } - w.entries[idx] = &cutCOWEntry{state: state, ready: make(chan struct{}), slot: slot} - slot++ - } + w.cand, w.staged = candidates, staged l.cowMu.Lock() defer l.cowMu.Unlock() if l.cowClosed || l.cowTransitions != 0 { @@ -266,7 +267,7 @@ func (w *cutCOWWindow) claim(idx uint64, saving bool) (*cutCOWEntry, uint8, <-ch if w.terminal { return nil, cowDone, nil } - e := w.entries[idx] + e := w.entryLocked(idx) if e == nil { return nil, cowDone, nil } @@ -302,6 +303,26 @@ func (w *cutCOWWindow) claim(idx uint64, saving bool) (*cutCOWEntry, uint8, <-ch return nil, cowDone, nil } } + +// entryLocked is idx's entry, made on its first touch: nil when the window +// does not cover idx, done when a pre-copy holds it. Caller holds w.mu. +func (w *cutCOWWindow) entryLocked(idx uint64) *cutCOWEntry { + if e := w.entries[idx]; e != nil { + return e + } + if !w.cand[idx] { + return nil + } + state := cowPending + if w.staged[idx] { + state = cowDone + } + e := &cutCOWEntry{state: state, ready: make(chan struct{}), slot: w.nextSlot} + w.nextSlot++ + w.entries[idx] = e + return e +} + func (w *cutCOWWindow) finish(e *cutCOWEntry, state uint8) bool { w.mu.Lock() defer w.mu.Unlock() @@ -631,15 +652,25 @@ func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, rec } l.cowMu.Unlock() }() - indices := make(map[uint64]bool, len(w.entries)) - for idx, e := range w.entries { - e.mu.Lock() - done := e.state == cowDone - e.mu.Unlock() - if !done { - indices[idx] = true + // The copier's work: every covered chunk a pre-copy does not hold and no + // touch has finished. Outside the pause (writers are back), O(candidates). + indices := make(map[uint64]bool, len(w.cand)) + w.mu.Lock() + for idx := range w.cand { + if w.staged[idx] { + continue } + if e := w.entries[idx]; e != nil { + e.mu.Lock() + done := e.state == cowDone + e.mu.Unlock() + if done { + continue + } + } + indices[idx] = true } + w.mu.Unlock() order := hotChunkKeys(indices, recent) out, err := l.streamCutPayloads(ctx, order, head, false, func(ctx context.Context, idx uint64) (capturedChunk, error) { c, ok, err := l.copyCOWEntry(w, idx) From 3f911ff43f7b0f315006e6445b90173ec771872b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 19:30:22 -0800 Subject: [PATCH 06/10] storage: red test, the guest pause does no per-candidate work TestTheFirstCutAfterWritesDoesNoPerCandidateWorkInThePause: the first cut after writes to many chunks must do no per-candidate operation between the barrier's lock and its release, at 32 blocks and at the 1 TiB shape with 256 changed chunks (fails: 73 and 1,600 operations; the candidate step, the known-equal filter, versions, the base refs and the copy-order hint all run in the pause). Seam: chunkCutStats.PauseCandidateOps, counted while a pause flag is up. Co-Authored-By: Claude Opus 5.5 --- .../storage/chunk_cut_candidate_set_test.go | 40 +++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 23 +++++++++++ seaweed-block/core/storage/chunk_seam.go | 4 ++ 3 files changed, 67 insertions(+) diff --git a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go index 637c2955a9..272fe2eb14 100644 --- a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go +++ b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go @@ -11,6 +11,46 @@ import ( "time" ) +// The guest pause does O(1) work: a cut's first barrier after writes to many +// chunks does no per-candidate operation between the barrier's lock and its +// release (counted, not timed), at 32 blocks and at the 1 TiB shape with +// 256 changed chunks. The candidates are judged, versioned and based after +// the pause, under the copy window. +func TestTheFirstCutAfterWritesDoesNoPerCandidateWorkInThePause(t *testing.T) { + t.Run("small", func(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + l := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + w := newWriteLog() + for lba := uint32(0); lba < ctNumBlocks; lba++ { + w.write(t, s, lba, byte(lba+1)) + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if r.Stats.CandidateChunks == 0 || r.Stats.PauseCandidateOps != 0 { + t.Fatalf("first cut over %d candidates: %d per-candidate operations in the pause, want 0", r.Stats.CandidateChunks, r.Stats.PauseCandidateOps) + } + }) + t.Run("one-TiB-shape", func(t *testing.T) { + const n, changed = 262144, 256 + s, l := freshShape(t, n) + for i := 0; i < changed; i++ { + if _, err := s.Write(uint32(i*997%n), []byte(fmt.Sprintf("%-512d", i))); err != nil { + t.Fatal(err) + } + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if r.Stats.CandidateChunks < changed || r.Stats.PauseCandidateOps != 0 { + t.Fatalf("first cut over %d candidates of %d chunks: %d per-candidate operations in the pause, want 0", r.Stats.CandidateChunks, n, r.Stats.PauseCandidateOps) + } + }) +} + // A fill whose fetch outlives a same-open recovery installs HEAD's bytes but // no clean mark (the recovery moved the chunk's version), so the chunk is a // candidate again, as the full scan says; the absent-to-present install diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index f96eeb4c87..3083870ae4 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -182,6 +182,12 @@ type chunkLayerImpl struct { // own names the chunks OwnBatch re-uploads under this layer's own keys in // the cut it runs (set and cleared under capMu, read under stMu). own map[uint64]bool + // paused is set from a capture's barrier lock to its release, and + // pauseOps counts per-candidate operations done meanwhile (pauseOp); + // both are touched only by the capturing goroutine. + paused bool + pauseOps int64 + // touched holds the chunks whose candidacy may have changed since a // capture last took them: a map entry change (OnMapEntryChange), a HEAD // ref change of a clean fill, and, once per layer, every entry UNKNOWN @@ -573,6 +579,13 @@ func (l *chunkLayerImpl) checkCandidatesAgainstScan(candidates map[uint64]bool) } } +// pauseOp counts n per-candidate operations if the guest is paused. +func (l *chunkLayerImpl) pauseOp(n int) { + if l.paused { + l.pauseOps += int64(n) + } +} + // touch adds chunks to the touched set (leaf lock). func (l *chunkLayerImpl) touch(chunks ...uint64) { if len(chunks) == 0 { @@ -1560,6 +1573,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } // Resume rejected tentative admission before any ordinary COW upload. unlockCapture := func() { + l.paused = false l.s.captureMu.Unlock() if !detach && releasePrecopy != nil { releasePrecopy() @@ -1570,6 +1584,8 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch hook() } l.s.captureMu.Lock() + l.paused, l.pauseOps = true, 0 + defer func() { st.PauseCandidateOps = l.pauseOps }() barrier := time.Now() st.LockWaitNs = barrier.Sub(pauseStart).Nanoseconds() h, err := l.s.syncWithPhases(&st.SyncPhases) @@ -1587,17 +1603,20 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch taken := l.takeTouched() candidates, visits := l.candidatesFrom(taken.each) visits += int64(len(taken.summary)) // the summary words the walk read + l.pauseOp(int(visits)) l.returnTouched(taken) l.checkCandidatesAgainstScan(candidates) // tests only (nil in production) l.stMu.Lock() all := l.allDirty for idx := range l.dirty { visits++ + l.pauseOp(1) candidates[idx] = true } if all { for i := uint64(0); i < l.numChunks; i++ { visits++ + l.pauseOp(1) // An absent chunk with no local write is HEAD's content by // definition: comparing it would only fetch it back. if l.absent[i] && !l.chunkHasLocalLocked(i) { @@ -1611,6 +1630,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // again, whatever returned it to the dirty set: any write since raises // its version, and a newer HEAD changes its ref. A chunk an own batch // re-uploads under this layer's key stays: equal bytes are its point. + l.pauseOp(len(candidates)) // the known-equal filter for idx := range candidates { if l.knownEqualToHeadLocked(idx) { delete(candidates, idx) @@ -1635,6 +1655,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch capturedVersions = make(map[uint64]uint64, len(candidates)) useStaged := map[uint64]bool{} + l.pauseOp(len(candidates)) // versions and staged reuse for idx := range candidates { if capturedVersions != nil { capturedVersions[idx] = l.chunkVersion(idx) @@ -1649,11 +1670,13 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.dirty = map[uint64]bool{} l.allDirty = false l.cutLSN = h + l.pauseOp(len(candidates)) // the cut's base refs baseHead := l.cutBaseLocked(candidates) l.stMu.Unlock() l.cutPhase("compare") // Candidates, mutation versions and the copy-order hint belong to the same barrier. // Do not sample the owned map after COW writers are admitted again. + l.pauseOp(len(candidates)) // the copy-order hint recent := l.chunkRecency(candidates, h) st.CandidateNs += time.Since(candidateStart).Nanoseconds() // The authoritative candidate set is fixed with mutation admission closed. diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 03f4203c1e..d4592a749c 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -420,6 +420,10 @@ type chunkCutStats struct { // CandidateVisits counts the chunk indices the barrier's candidate step // visited (scanned entries and set members), the work a pause pays for. CandidateVisits int64 + // PauseCandidateOps counts per-candidate operations done while the guest + // is paused (from the barrier lock to its release): zero when the pause + // does O(1) work. + PauseCandidateOps int64 // PreSyncNs is the sync right before the barrier, outside the guest // pause (never part of BarrierPauseNs): the pause's own sync then has // only what came after it. From 72e429830ce89fab3a3ed0f0561f15438fa71e1b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 19:58:17 -0800 Subject: [PATCH 07/10] storage: the guest pause does O(1) work; the candidates are judged after it In the pause, a cut now syncs (H), takes the touched set and the dirty set by pointer swaps, and opens the copy window over what they name (a superset of the candidates, a lookup per chunk). Everything per candidate runs after the pause, under the window: the judgement (WAL entries up to H), the known-equal filter, each candidate's version, staged reuse, the record shadow check, the base refs, the copy-order hint and the HEAD-behind refusal. The window then narrows to the candidates. - A candidate's version at the barrier is read atomically with the write path: the version a guest write's save recorded with its bytes, else the live one under the window lock. The window closes on a chunk only after its version is read and it is uploaded. - A refusal before the judgement returns the taken sets (touched again, the dirty set rejoins l.dirty). After it, the existing requeue does. - A pre-copy attempt keeps its drained frontend drained through the judgement and decides its freeze on the judged tail, as before: its guest pause runs to that release. - The record shadow check exempts chunks written since the barrier (the live touched set): the record already counts those writes. - PauseCandidateOps counts per-candidate operations while the guest is paused; it is 0 for an ordinary cut. The cut body and the status schema carry it. Co-Authored-By: Claude Opus 5.5 --- .../core/host/volume/chunk_control.go | 38 +-- .../storage/chunk_cut_candidate_set_test.go | 8 +- seaweed-block/core/storage/chunk_cut_cow.go | 72 ++++- .../storage/chunk_cut_payload_budget_test.go | 2 +- seaweed-block/core/storage/chunk_layer.go | 260 +++++++++++------- .../core/storage/chunk_record_shadow.go | 9 +- seaweed-block/docs/status-schema.md | 1 + 7 files changed, 253 insertions(+), 137 deletions(-) diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 270c8b98f9..99da1827cb 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -61,15 +61,16 @@ type ChunkCutResponse struct { // mirrors storage.ChunkCutStats field for field (a test keeps the two in // step); every duration is in nanoseconds. type ChunkCutStatsBody struct { - SyncPhases storage.SyncPhaseStats `json:"syncPhases"` - CandidateVisits int64 `json:"candidateVisits"` // chunk indices the barrier's candidate step touched - PreSyncNs int64 `json:"preSyncNs"` // the sync right before the barrier, outside the pause - CandidateNs int64 `json:"candidateNs"` - WindowSetupNs int64 `json:"windowSetupNs"` - PublishPrepareNs int64 `json:"publishPrepareNs"` - ManifestNs int64 `json:"manifestNs"` - CommitStateNs int64 `json:"commitStateNs"` - NonPayloadCopyNs int64 `json:"nonPayloadCopyNs"` + SyncPhases storage.SyncPhaseStats `json:"syncPhases"` + CandidateVisits int64 `json:"candidateVisits"` // chunk indices the barrier's candidate step touched + PreSyncNs int64 `json:"preSyncNs"` // the sync right before the barrier, outside the pause + PauseCandidateOps int64 `json:"pauseCandidateOps"` // per-candidate operations done while the guest was paused + CandidateNs int64 `json:"candidateNs"` + WindowSetupNs int64 `json:"windowSetupNs"` + PublishPrepareNs int64 `json:"publishPrepareNs"` + ManifestNs int64 `json:"manifestNs"` + CommitStateNs int64 `json:"commitStateNs"` + NonPayloadCopyNs int64 `json:"nonPayloadCopyNs"` PayloadNs int64 `json:"payloadNs"` COWWALReadAttempts uint64 `json:"cowWALReadAttempts"` @@ -113,15 +114,16 @@ type ChunkCutStatsBody struct { func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { return ChunkCutStatsBody{ - SyncPhases: s.SyncPhases, - CandidateVisits: s.CandidateVisits, - PreSyncNs: s.PreSyncNs, - CandidateNs: s.CandidateNs, - WindowSetupNs: s.WindowSetupNs, - PublishPrepareNs: s.PublishPrepareNs, - ManifestNs: s.ManifestNs, - CommitStateNs: s.CommitStateNs, - NonPayloadCopyNs: s.NonPayloadCopyNs, + SyncPhases: s.SyncPhases, + CandidateVisits: s.CandidateVisits, + PreSyncNs: s.PreSyncNs, + PauseCandidateOps: s.PauseCandidateOps, + CandidateNs: s.CandidateNs, + WindowSetupNs: s.WindowSetupNs, + PublishPrepareNs: s.PublishPrepareNs, + ManifestNs: s.ManifestNs, + CommitStateNs: s.CommitStateNs, + NonPayloadCopyNs: s.NonPayloadCopyNs, PayloadNs: s.PayloadNs, COWWALReadAttempts: s.COWWALReadAttempts, diff --git a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go index 272fe2eb14..a12d04ffdd 100644 --- a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go +++ b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go @@ -129,7 +129,13 @@ func freshShape(t *testing.T, n int) (*WALStore, *chunkLayerImpl) { t.Fatal(err) } cfg := chunkLayerConfig{ChunkBlocks: 1, Epoch: 2, Holder: "host-a", Bitmap: newFakeBitmap(), ReadMissTimeout: ctLocalBound, FreshFromHead: true} - return s, mustAttach(t, s, f, cfg).(*chunkLayerImpl) + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + // Publishing a write to an absent chunk of a fresh-from-HEAD layer makes + // the chunk record refuse its Commit (U/Commit), with or without the + // candidate set; that record question is apart from what these tests + // count, so the shadow is off for this shape. + l.shadow = nil + return s, l } // visitBound is the candidate step's allowance for a cut with changed chunks diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index 5c84e113ce..5ec83cc1c2 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -106,6 +106,10 @@ type cutCOWEntry struct { // were captured: their image at H is HEAD's, filled by the copier from the // cut's base HEAD after it released the entry (never under a guest write). missing []uint64 + // version is the chunk's mutation version when a guest write's save + // claimed the entry: the version of the bytes it saves (the write's own + // version move comes after its mutation). + version uint64 } type cutCOWWindow struct { layer *chunkLayerImpl @@ -146,6 +150,10 @@ type cutCOWWindow struct { cand map[uint64]bool staged map[uint64]bool nextSlot int64 + // covers is the window's reach from the barrier until narrow sets cand: + // the sets the barrier took (O(1) a lookup), a superset of the + // candidates, judged after the pause. + covers func(uint64) bool } func (s *WALStore) beforeChunkMutation(first, count uint64) { @@ -209,12 +217,12 @@ func (l *chunkLayerImpl) holdCOWDestructive() func() { } // The caller owns captureMu exclusive, so no writer can miss this publication. -func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, head map[uint64]chunkRef, spill cowSpillCap) (*cutCOWWindow, error) { +func (l *chunkLayerImpl) installCOWWindow(covers func(uint64) bool, spill cowSpillCap) (*cutCOWWindow, error) { size := uint64(l.blockSize) * l.chunkBlocks - if size == 0 || size > math.MaxInt64 || uint64(len(candidates)) > math.MaxInt64/size { + if size == 0 || size > math.MaxInt64 || l.numChunks > math.MaxInt64/size { return nil, fmt.Errorf("%w: side-store geometry", errCutCOWAborted) } - w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: spill.bytes, spillCause: spill.cause, chunkBytes: int64(size)} + w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), covers: covers, spillLimit: spill.bytes, spillCause: spill.cause, chunkBytes: int64(size)} w.ctx, w.cancel = context.WithCancel(context.Background()) _, reserved, limit := l.cutPayloadWorkers() savers := min(max(1, int((16<<20)/int64(size))), int((limit-reserved)/(2*int64(size)))) @@ -223,7 +231,6 @@ func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, he reserved += int64(2*savers) * int64(size) w.memory, w.memoryLimit = reserved, limit w.saverSlots = make(chan struct{}, savers) - w.cand, w.staged = candidates, staged l.cowMu.Lock() defer l.cowMu.Unlock() if l.cowClosed || l.cowTransitions != 0 { @@ -278,6 +285,7 @@ func (w *cutCOWWindow) claim(idx uint64, saving bool) (*cutCOWEntry, uint8, <-ch case cowPending: if saving { e.state = cowSaving + e.version = w.layer.chunkVersion(idx) // before the write's own move } else { e.state = cowCopying } @@ -310,7 +318,11 @@ func (w *cutCOWWindow) entryLocked(idx uint64) *cutCOWEntry { if e := w.entries[idx]; e != nil { return e } - if !w.cand[idx] { + if w.cand != nil { + if !w.cand[idx] { + return nil + } + } else if w.covers == nil || !w.covers(idx) { return nil } state := cowPending @@ -323,6 +335,33 @@ func (w *cutCOWWindow) entryLocked(idx uint64) *cutCOWEntry { return e } +// versionAt is chunk idx's version at the barrier, read atomically with the +// write path: the version a guest write's save recorded with the bytes it +// saved, else the live version, read under w.mu so no writer can claim the +// entry (and move the version) in between. +func (w *cutCOWWindow) versionAt(idx uint64) uint64 { + w.mu.Lock() + defer w.mu.Unlock() + if e := w.entries[idx]; e != nil { + e.mu.Lock() + state, v := e.state, e.version + e.mu.Unlock() + if state == cowSaving || state == cowSaved { + return v + } + } + return w.layer.chunkVersion(idx) +} + +// narrow sets the window's final reach after the candidates are judged (and +// versioned): the candidates, the staged ones a pre-copy holds, and the cut's +// base HEAD for missing blocks. Entries already made stay as they are. +func (w *cutCOWWindow) narrow(cand, staged map[uint64]bool, head map[uint64]chunkRef) { + w.mu.Lock() + w.cand, w.staged, w.head, w.covers = cand, staged, head, nil + w.mu.Unlock() +} + func (w *cutCOWWindow) finish(e *cutCOWEntry, state uint8) bool { w.mu.Lock() defer w.mu.Unlock() @@ -634,6 +673,18 @@ func (l *chunkLayerImpl) copyCOWEntry(w *cutCOWWindow, idx uint64) (capturedChun // Each worker owns one immutable image from local read through remote Put. // Once copied, its entry is done: guest writes need not wait for remote I/O. // The window remains installed for candidates not yet read by a worker. +// endCOWWindow ends a window: abort, join its savers, and unpublish it. +func (l *chunkLayerImpl) endCOWWindow(w *cutCOWWindow) { + w.abort(errCutCOWAborted) + w.join() + l.cowMu.Lock() + if l.cow == w { + l.cow = nil + l.cowActive.Store(nil) + } + l.cowMu.Unlock() +} + func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, recent, versions map[uint64]uint64, head chunkHead) ([]capturedChunk, error) { parent := ctx abortStop := context.AfterFunc(parent, func() { w.abort(parent.Err()) }) @@ -642,16 +693,7 @@ func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, rec stop := context.AfterFunc(w.ctx, cancel) defer stop() defer cancel() - defer func() { - w.abort(errCutCOWAborted) - w.join() - l.cowMu.Lock() - if l.cow == w { - l.cow = nil - l.cowActive.Store(nil) - } - l.cowMu.Unlock() - }() + defer l.endCOWWindow(w) // The copier's work: every covered chunk a pre-copy does not hold and no // touch has finished. Outside the pause (writers are back), O(candidates). indices := make(map[uint64]bool, len(w.cand)) diff --git a/seaweed-block/core/storage/chunk_cut_payload_budget_test.go b/seaweed-block/core/storage/chunk_cut_payload_budget_test.go index 7fae795b32..0c0cc71a25 100644 --- a/seaweed-block/core/storage/chunk_cut_payload_budget_test.go +++ b/seaweed-block/core/storage/chunk_cut_payload_budget_test.go @@ -13,7 +13,7 @@ func TestCutPayloadBudgetBoundsSlots(t *testing.T) { for i := 0; i < candidates; i++ { pending[uint64(i)] = true } - w, err := l.installCOWWindow(pending, nil, nil, l.cowSpillLimit()) + w, err := l.installCOWWindow(func(i uint64) bool { return pending[i] }, l.cowSpillLimit()) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 3083870ae4..172d471a17 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -532,51 +532,79 @@ func (l *chunkLayerImpl) resolveTouchFilled() { // missed. Production leaves it nil: the scan is O(chunks). var candidateOracle func(string) -// checkCandidatesAgainstScan is the oracle: the full scan of the old -// candidate step at this barrier, against what this barrier's candidates -// will be (the touched set's, unioned with l.dirty and allDirty as the -// barrier does next, as the scan's were). A chunk in the live set (touched -// after the take) or covered by a pending recovery request is the next -// cut's, not a miss. -func (l *chunkLayerImpl) checkCandidatesAgainstScan(candidates map[uint64]bool) { - report := candidateOracle - if report == nil { - return +// candidateOracleScan is the oracle's half at the barrier (tests only, nil +// in production, never counted as pause work): the full scan of the old +// candidate step, the chunks it would make candidates now. +func (l *chunkLayerImpl) candidateOracleScan() map[uint64]bool { + if candidateOracle == nil { + return nil } l.stMu.Lock() base := l.remoteLSN - all := l.allDirty - dirty := make(map[uint64]bool, len(l.dirty)) - for i := range l.dirty { - dirty[i] = true - } l.stMu.Unlock() - if all { - return // every chunk is a candidate of this barrier - } + want := map[uint64]bool{} l.s.mu.RLock() defer l.s.mu.RUnlock() l.stMu.Lock() defer l.stMu.Unlock() pendingFilled := l.touchFilled.Load() - l.unkMu.Lock() - live := l.touched - defer l.unkMu.Unlock() for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ { i := uint64(idx) - if candidates[i] || dirty[i] || (l.absent[i] && !l.chunkHasLocalLocked(i)) { + if l.absent[i] && !l.chunkHasLocalLocked(i) { continue } e := l.s.v3.mapEntries.at(idx) - if !((e.Unknown && !l.knownEqualToHeadLocked(i)) || e.LSN > base) { - continue + if (e.Unknown && !l.knownEqualToHeadLocked(i)) || e.LSN > base { + if pendingFilled && l.filledClean[i] != (filledMark{}) { + continue // a recovery's touches are pending: the next cut's + } + want[i] = true } - if (live != nil && live.has(i)) || (pendingFilled && l.filledClean[i] != (filledMark{})) { - continue - } - report(fmt.Sprintf("candidate oracle: chunk %d is a candidate by the full scan (unknown=%v lsn=%d remoteLSN=%d) but not by the touched set", i, e.Unknown, e.LSN, base)) + } + return want +} + +// candidateOracleCompare is the oracle's half after the judgement: a chunk +// the barrier's full scan makes a candidate that the judged candidates miss +// is a finding. +func candidateOracleCompare(want, got map[uint64]bool) { + report := candidateOracle + if report == nil { return } + for i := range want { + if !got[i] { + report(fmt.Sprintf("candidate oracle: chunk %d is a candidate by the full scan at the barrier but not by the judged touched set", i)) + return + } + } +} + +// requeueTaken returns a cut's taken sets when it ends before judging them +// (a refusal in or right after the pause): the touched members are touched +// again, the dirty set rejoins l.dirty, and a BASE write's allDirty stays. +func (l *chunkLayerImpl) requeueTaken(taken *candidateSet, dirty map[uint64]bool, all bool) { + var back []uint64 + taken.each(func(c uint64) { back = append(back, c) }) + l.touch(back...) + l.returnTouched(taken) + l.stMu.Lock() + for idx := range dirty { + l.dirty[idx] = true + } + if all { + l.allDirty = true + } + l.dirtyVer++ + l.stMu.Unlock() +} + +// writtenSinceTake reports whether chunk idx was touched since the barrier +// took the set: a write after the barrier (the live set holds it). +func (l *chunkLayerImpl) writtenSinceTake(idx uint64) bool { + l.unkMu.Lock() + defer l.unkMu.Unlock() + return l.touched != nil && idx < l.numChunks && l.touched.has(idx) } // pauseOp counts n per-candidate operations if the guest is paused. @@ -922,7 +950,7 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { for _, c := range members { f(c) } - }) + }, math.MaxUint64) return out } @@ -962,7 +990,7 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { // reader, taken by the barrier). Its work is O(changed): the WAL's dirty // entries, the own batch, and the set's members, each judged on its own; no // map of every chunk is walked. visits counts every chunk index it touched. -func (l *chunkLayerImpl) candidatesFrom(members func(func(uint64))) (map[uint64]bool, int64) { +func (l *chunkLayerImpl) candidatesFrom(members func(func(uint64)), upTo uint64) (map[uint64]bool, int64) { out := map[uint64]bool{} var base uint64 @@ -975,7 +1003,7 @@ func (l *chunkLayerImpl) candidatesFrom(members func(func(uint64))) (map[uint64] visits++ // Retention in the local WAL is not dirt since HEAD. Lower-LSN // BASE/direct changes remain conservative through UNKNOWN below. - if e.LSN > base { + if e.LSN > base && e.LSN <= upTo { out[l.chunkOf(e.LBA)] = true } } @@ -1600,23 +1628,67 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } l.cutPhase("candidates") candidateStart := time.Now() + // The pause does O(1) work: the touched set and the dirty set are taken + // by pointer swaps and the copy window opens over what they name (a + // superset of the candidates). Every per-candidate step runs after the + // pause, under the window: the judgement, the versions (atomic with the + // write path), staged reuse, the base refs and the copy-order hint. taken := l.takeTouched() - candidates, visits := l.candidatesFrom(taken.each) - visits += int64(len(taken.summary)) // the summary words the walk read - l.pauseOp(int(visits)) - l.returnTouched(taken) - l.checkCandidatesAgainstScan(candidates) // tests only (nil in production) + oracleWant := l.candidateOracleScan() // tests only (nil in production) l.stMu.Lock() - all := l.allDirty - for idx := range l.dirty { + dirtyTaken, all := l.dirty, l.allDirty + l.dirty, l.allDirty = map[uint64]bool{}, false + l.cutLSN = h + l.stMu.Unlock() + own := l.own // stable for the cut (set and cleared under capMu) + covers := func(idx uint64) bool { return all || taken.has(idx) || dirtyTaken[idx] || own[idx] } + windowStart := time.Now() + w, installErr := l.installCOWWindow(covers, spill) + if installErr == nil { + w.budget = budget + } + // The barrier ends here. A pre-copy attempt's drained frontend stays + // drained until its freeze decision below, made on the judged tail: its + // guest pause runs to that release, as before. An ordinary cut's guest + // is back now, and its pause did O(1) work. + drained := releasePrecopy != nil + l.s.captureMu.Unlock() + st.WindowSetupNs += time.Since(windowStart).Nanoseconds() + if !drained { + l.paused = false + st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() + } + releaseDrain := func() { + if drained { + if releasePrecopy != nil && !detach { + releasePrecopy() + releasePrecopy = nil + } + l.paused = false + st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() + drained = false + } + } + if installErr != nil { + releaseDrain() + l.requeueTaken(taken, dirtyTaken, all) + return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", installErr) + } + + // After the pause. The judgement: the touched set's members with the + // map scan's predicate, the WAL entries up to H, the own batch, the + // taken dirty set, and every chunk after a BASE write. + candidates, visits := l.candidatesFrom(taken.each, h) + visits += int64(len(taken.summary)) // the summary words the walk read + l.pauseOp(int(visits)) // each step counts itself if it ever runs in the pause + for idx := range dirtyTaken { visits++ - l.pauseOp(1) candidates[idx] = true } + l.stMu.Lock() if all { for i := uint64(0); i < l.numChunks; i++ { visits++ - l.pauseOp(1) // An absent chunk with no local write is HEAD's content by // definition: comparing it would only fetch it back. if l.absent[i] && !l.chunkHasLocalLocked(i) { @@ -1625,77 +1697,79 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch candidates[i] = true } } + l.stMu.Unlock() + candidateOracleCompare(oracleWant, candidates) // tests only // A chunk known to hold HEAD's bytes at its current version (a clean // fill, or a compare by a cut that did not publish) is not compared // again, whatever returned it to the dirty set: any write since raises // its version, and a newer HEAD changes its ref. A chunk an own batch // re-uploads under this layer's key stays: equal bytes are its point. - l.pauseOp(len(candidates)) // the known-equal filter + l.stMu.Lock() + l.pauseOp(len(candidates)) for idx := range candidates { if l.knownEqualToHeadLocked(idx) { delete(candidates, idx) } } - if sh := l.shadow; sh != nil { - // Extras are judged only for a cut that can proceed: a store behind - // HEAD (H below its RemoteLSN) is refused before any upload, and its - // writes are not dirt above HEAD to the engine. - proceeds := h >= l.head.RemoteLSN - miss, extra := sh.check(candidates, l.shadowExemptLocked, l.testShadowCheck != nil && proceeds, proceeds) - if hook := l.testShadowCheck; hook != nil { - hook(miss, extra) - } - } - // A staged chunk stands for the barrier copy while no write reached - // it since staging (its version is unchanged) and HEAD is the one it - // was compared against. + l.stMu.Unlock() + // Each candidate's version at the barrier: the version a guest write's + // save recorded with its bytes, else the live one, read atomically with + // the write path; the window closes on a chunk only after this and its + // upload. A staged chunk stands for the barrier copy while its version + // is the barrier's and HEAD is the one it was compared against. var captured []capturedChunk - var capturedVersions map[uint64]uint64 - - capturedVersions = make(map[uint64]uint64, len(candidates)) - - useStaged := map[uint64]bool{} - l.pauseOp(len(candidates)) // versions and staged reuse + capturedVersions := make(map[uint64]uint64, len(candidates)) + l.pauseOp(2 * len(candidates)) // versions, staged reuse for idx := range candidates { - if capturedVersions != nil { - capturedVersions[idx] = l.chunkVersion(idx) - } - if sc, ok := staged[idx]; ok && sc.ver == l.chunkVersion(idx) && sc.headGen == l.head.Gen { + capturedVersions[idx] = w.versionAt(idx) + } + useStaged := map[uint64]bool{} + l.stMu.Lock() + for idx := range candidates { + if sc, ok := staged[idx]; ok && sc.ver == capturedVersions[idx] && sc.headGen == l.head.Gen { useStaged[idx] = true captured = append(captured, sc.capturedChunk) } } + if sh := l.shadow; sh != nil { + // Extras are judged only for a cut that can proceed: a store behind + // HEAD (H below its RemoteLSN) is refused before any upload, and its + // writes are not dirt above HEAD to the engine. A chunk written since + // the barrier is in the live touched set: the record counts its write. + proceeds := h >= l.head.RemoteLSN + after := l.writtenSinceTake + skip := func(idx uint64) bool { return l.shadowExemptLocked(idx) || after(idx) } + miss, extra := sh.checkAfter(candidates, skip, after, l.testShadowCheck != nil && proceeds, proceeds) + if hook := l.testShadowCheck; hook != nil { + hook(miss, extra) + } + } st.CandidateVisits = visits l.inflight = candidates - l.dirty = map[uint64]bool{} - l.allDirty = false - l.cutLSN = h - l.pauseOp(len(candidates)) // the cut's base refs + l.pauseOp(2 * len(candidates)) // the shadow check, the base refs baseHead := l.cutBaseLocked(candidates) l.stMu.Unlock() + w.narrow(candidates, useStaged, baseHead.Chunks) + l.returnTouched(taken) l.cutPhase("compare") - // Candidates, mutation versions and the copy-order hint belong to the same barrier. - // Do not sample the owned map after COW writers are admitted again. - l.pauseOp(len(candidates)) // the copy-order hint + l.pauseOp(len(candidates)) recent := l.chunkRecency(candidates, h) st.CandidateNs += time.Since(candidateStart).Nanoseconds() - // The authoritative candidate set is fixed with mutation admission closed. // The owner callback is nonblocking and may stop only an already drained // frontend; rejected attempts remain ordinary COW cuts. if freeze := l.precopyFreeze; freeze != nil && context.Cause(ctx) == nil { tail := uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks detach = freeze(tail, pauseStart, st) } + releaseDrain() if guestFrozen && !detach { - unlockCapture() - st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() + l.endCOWWindow(w) l.requeueCut(all) return chunkCutResult{}, errors.Join(ErrFrozenTailTooLarge, context.Cause(ctx), l.admit()) } if h < baseHead.RemoteLSN && !l.supersededBy(baseHead) { - unlockCapture() - st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() + l.endCOWWindow(w) // HEAD holds the image of a later LSN than this host's log has // reached: publishing would move remote_lsn backwards. Refused // before any upload. (A HEAD of a newer holder fences below.) @@ -1704,35 +1778,19 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } st.CandidateChunks = max(st.CandidateChunks, len(candidates)) - var copyErr error copyStart := time.Now() bytesBeforeCopy := st.UploadedBytes - { - var w *cutCOWWindow - windowStart := time.Now() - w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks, spill) - if copyErr == nil { - w.budget = budget - } - unlockCapture() - st.WindowSetupNs += time.Since(windowStart).Nanoseconds() - st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() - copyStart = time.Now() - if copyErr == nil { - var copied []capturedChunk - copied, copyErr = l.copyCOWWindow(ctx, w, recent, capturedVersions, baseHead) - for _, c := range copied { - if c.key != "" { - st.UploadedChunks++ - st.UploadedBytes += int64(c.size) - } - } - captured = append(captured, copied...) - st.COWWALReadAttempts, st.COWLocalReadNs = w.walReads.Load(), w.localReadNs.Load() - st.COWSavedChunks = int(w.saved.Load()) - st.COWSaveNs, st.COWWaitNs = w.saveNs.Load(), w.waitNs.Load() + copied, copyErr := l.copyCOWWindow(ctx, w, recent, capturedVersions, baseHead) + for _, c := range copied { + if c.key != "" { + st.UploadedChunks++ + st.UploadedBytes += int64(c.size) } } + captured = append(captured, copied...) + st.COWWALReadAttempts, st.COWLocalReadNs = w.walReads.Load(), w.localReadNs.Load() + st.COWSavedChunks = int(w.saved.Load()) + st.COWSaveNs, st.COWWaitNs = w.saveNs.Load(), w.waitNs.Load() st.CopyNs = time.Since(copyStart).Nanoseconds() if st.UploadedBytes > bytesBeforeCopy { diff --git a/seaweed-block/core/storage/chunk_record_shadow.go b/seaweed-block/core/storage/chunk_record_shadow.go index bcf7cec89b..7d6fab4b86 100644 --- a/seaweed-block/core/storage/chunk_record_shadow.go +++ b/seaweed-block/core/storage/chunk_record_shadow.go @@ -365,6 +365,13 @@ var errShadowMiss = errors.New("storage: chunk record shadow: an engine candidat // the misses and, when withExtra (tests: a full scan of the record, too // slow for a barrier), the record's extra candidates. Caller holds stMu. func (s *chunkRecordShadow) check(engine map[uint64]bool, skip func(uint64) bool, withExtra, proceeds bool) (miss, extra []uint64) { + return s.checkAfter(engine, skip, nil, withExtra, proceeds) +} + +// checkAfter is check for candidates judged after the guest pause: after, +// when set, names the chunks written since the barrier (the record already +// counts those writes), which are no record extra of this cut. +func (s *chunkRecordShadow) checkAfter(engine map[uint64]bool, skip, after func(uint64) bool, withExtra, proceeds bool) (miss, extra []uint64) { s.rec.mu.Lock() for idx := range engine { if !isRecordCandidate(kindByCode[s.rec.kinds[idx]]) && !skip(idx) { @@ -376,7 +383,7 @@ func (s *chunkRecordShadow) check(engine map[uint64]bool, skip func(uint64) bool s.fullScans++ for idx, code := range s.rec.kinds { k := kindByCode[code] - if isRecordCandidate(k) && !engine[uint64(idx)] && !s.scratchHoldsLocked(uint64(idx), k) && !s.openedChangedLocked(uint64(idx), k) { + if isRecordCandidate(k) && !engine[uint64(idx)] && !s.scratchHoldsLocked(uint64(idx), k) && !s.openedChangedLocked(uint64(idx), k) && (after == nil || !after(uint64(idx))) { extra = append(extra, uint64(idx)) } } diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 3cbd6f3fed..9cce39b345 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -274,6 +274,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCut.SyncPhases.groupCommitNs` | int64 | in the group commit that made the data durable | | `Volumes[].Chunk.Stats.LastCut.SyncPhases.completionWaitNs` | int64 | waiting for the sync leader role to validate the completion | | `Volumes[].Chunk.Stats.LastCut.CandidateVisits` | int64 | CandidateVisits counts the chunk indices the barrier's candidate step visited (scanned entries and set members), the work a pause pays for. | +| `Volumes[].Chunk.Stats.LastCut.PauseCandidateOps` | int64 | PauseCandidateOps counts per-candidate operations done while the guest is paused (from the barrier lock to its release): zero when the pause does O(1) work. | | `Volumes[].Chunk.Stats.LastCut.PreSyncNs` | int64 | PreSyncNs is the sync right before the barrier, outside the guest pause (never part of BarrierPauseNs): the pause's own sync then has only what came after it. | | `Volumes[].Chunk.Stats.LastCut.CandidateNs` | int64 | Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.WindowSetupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | From d8f828275a2b02244ea335ff68bc565f92327fec Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 20:06:08 -0800 Subject: [PATCH 08/10] storage: red tests, no touched-set allocation or fill scan in the pause - The touched set's allocation and the recovery's clean-fill enumeration now count themselves in PauseCandidateOps when the guest is paused. - TestAColdFirstCutAllocatesNoSetInThePause: a layer's first cut at the 1 TiB shape (fails: 4,097, the spare set allocated at the take). - TestARecoveryJustBeforeTheBarrierIsJudgedAfterThePause: a recovery between the pre-barrier work and the barrier (fails: 9, the clean fills enumerated at the take); the cut must still judge every clean fill. - TestTheFirstCutAfterWritesDoesNoPerCandidateWorkInThePause now fails too (the spare allocation). Co-Authored-By: Claude Opus 5.5 --- .../storage/chunk_cut_candidate_set_test.go | 42 +++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 12 +++++- 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go index a12d04ffdd..e165179685 100644 --- a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go +++ b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go @@ -51,6 +51,48 @@ func TestTheFirstCutAfterWritesDoesNoPerCandidateWorkInThePause(t *testing.T) { }) } +// A layer's first cut finds its touched sets ready: the barrier only swaps +// them; no set is allocated in the pause (size-dependent work). +func TestAColdFirstCutAllocatesNoSetInThePause(t *testing.T) { + const n = 262144 + s, l := freshShape(t, n) + if _, err := s.Write(3, []byte(fmt.Sprintf("%-512s", "cold"))); err != nil { + t.Fatal(err) + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if r.Stats.PauseCandidateOps != 0 { + t.Fatalf("a layer's first cut over %d chunks did %d size-dependent operations in the pause, want 0", n, r.Stats.PauseCandidateOps) + } +} + +// A recovery that lands between a cut's pre-barrier work and its barrier +// moves every clean fill's version: the cut still judges those fills (their +// proofs are gone), after the pause, and the pause does no per-fill work. +func TestARecoveryJustBeforeTheBarrierIsJudgedAfterThePause(t *testing.T) { + _, l, _ := filledFreshVolume(t) + l.stMu.Lock() + fills := len(l.filledClean) + l.stMu.Unlock() + if fills == 0 { + t.Fatal("setup: no clean fills") + } + l.testBeforeBarrierLockHook = func() { l.noteAllMutated() } + r, err := l.Cut(ctTimeout(t)) + l.testBeforeBarrierLockHook = nil + if err != nil { + t.Fatal(err) + } + if r.Stats.PauseCandidateOps != 0 { + t.Fatalf("a recovery just before the barrier cost %d per-fill operations in the pause, want 0", r.Stats.PauseCandidateOps) + } + if r.Stats.CandidateChunks < fills { + t.Fatalf("the cut after the recovery judged %d candidates, want all %d clean fills (their proofs are gone)", r.Stats.CandidateChunks, fills) + } +} + // A fill whose fetch outlives a same-open recovery installs HEAD's bytes but // no clean mark (the recovery moved the chunk's version), so the chunk is a // candidate again, as the full scan says; the absent-to-present install diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 172d471a17..231632af8d 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -524,9 +524,17 @@ func (l *chunkLayerImpl) resolveTouchFilled() { filled = append(filled, idx) } l.stMu.Unlock() + l.pauseOp(len(filled)) l.touch(filled...) } +// newTouchedSet allocates a touched set (its words and summary: size +// dependent, counted if the guest is paused). +func (l *chunkLayerImpl) newTouchedSet() *candidateSet { + l.pauseOp(int(l.numChunks/64) + 1) + return newCandidateSet(l.numChunks) +} + // candidateOracle, when set (by this package's tests), receives every chunk // the full predicate scan finds that a barrier's touched-set candidate step // missed. Production leaves it nil: the scan is O(chunks). @@ -632,7 +640,7 @@ func (l *chunkLayerImpl) touch(chunks ...uint64) { // touchedLocked is the live touched set, made on first use. Caller holds unkMu. func (l *chunkLayerImpl) touchedLocked() *candidateSet { if l.touched == nil { - l.touched = newCandidateSet(l.numChunks) + l.touched = l.newTouchedSet() } return l.touched } @@ -791,7 +799,7 @@ func (l *chunkLayerImpl) takeTouched() *candidateSet { defer l.unkMu.Unlock() taken := l.touchedLocked() if l.touchedSpare == nil { - l.touchedSpare = newCandidateSet(l.numChunks) + l.touchedSpare = l.newTouchedSet() } l.touched, l.touchedSpare = l.touchedSpare, nil return taken From 1add3afcd04160ebe45f9142f78f8a376dda7ee7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 20:13:14 -0800 Subject: [PATCH 09/10] storage: the barrier only swaps the touched sets; a late recovery is a flag - prepareTouched, before the barrier and outside the pause, runs the once-per-layer seed, a pending recovery's clean-fill touches, and makes the cleared spare set; takeTouched at the barrier is a pointer swap. - A recovery that lands between prepareTouched and the barrier is taken at the barrier as a flag (O(1)): the window covers every chunk until it narrows, and the clean fills are judged after the pause, with the touched set's members. A refusal before the judgement keeps the request. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 47 +++++++++++++++++++---- 1 file changed, 40 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 231632af8d..0bc9d14782 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -793,18 +793,30 @@ func (l *chunkLayerImpl) peekTouched() []uint64 { // cleared spare in its place, a pointer swap: a chunk marked after the take // is the next cut's. The caller gives the set back (returnTouched). func (l *chunkLayerImpl) takeTouched() *candidateSet { - l.touchedSeed.Do(l.seedTouched) - l.resolveTouchFilled() l.unkMu.Lock() defer l.unkMu.Unlock() taken := l.touchedLocked() if l.touchedSpare == nil { - l.touchedSpare = l.newTouchedSet() + l.touchedSpare = l.newTouchedSet() // only if prepareTouched was skipped } l.touched, l.touchedSpare = l.touchedSpare, nil return taken } +// prepareTouched readies the touched sets before a barrier, outside the +// pause: the once-per-layer seed, a pending recovery's clean-fill touches, +// and the cleared spare the barrier swaps in. The barrier then only swaps. +func (l *chunkLayerImpl) prepareTouched() { + l.touchedSeed.Do(l.seedTouched) + l.resolveTouchFilled() + l.unkMu.Lock() + l.touchedLocked() + if l.touchedSpare == nil { + l.touchedSpare = l.newTouchedSet() + } + l.unkMu.Unlock() +} + // returnTouched clears a taken set (O(members)) and keeps it as the spare. func (l *chunkLayerImpl) returnTouched(set *candidateSet) { set.clear() @@ -1574,8 +1586,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // Before the pause: the once-per-layer UNKNOWN seed, and one sync so the // pause's own sync flushes only what came after it (the first cut after a // fill pays its write-back here). The in-pause sync still fixes H. - l.touchedSeed.Do(l.seedTouched) - l.resolveTouchFilled() + l.prepareTouched() preSync := time.Now() if _, err := l.s.syncWithPhases(nil); err != nil { st.PreSyncNs = time.Since(preSync).Nanoseconds() @@ -1642,6 +1653,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // pause, under the window: the judgement, the versions (atomic with the // write path), staged reuse, the base refs and the copy-order hint. taken := l.takeTouched() + // A recovery that landed after prepareTouched moved every clean fill's + // version: its request is taken here as a flag (O(1)); the window covers + // every chunk until it narrows, and the fills are judged after the pause. + filledTaken := l.touchFilled.Swap(false) oracleWant := l.candidateOracleScan() // tests only (nil in production) l.stMu.Lock() dirtyTaken, all := l.dirty, l.allDirty @@ -1649,7 +1664,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.cutLSN = h l.stMu.Unlock() own := l.own // stable for the cut (set and cleared under capMu) - covers := func(idx uint64) bool { return all || taken.has(idx) || dirtyTaken[idx] || own[idx] } + covers := func(idx uint64) bool { return all || filledTaken || taken.has(idx) || dirtyTaken[idx] || own[idx] } windowStart := time.Now() w, installErr := l.installCOWWindow(covers, spill) if installErr == nil { @@ -1679,6 +1694,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } if installErr != nil { releaseDrain() + if filledTaken { + l.touchFilled.Store(true) + } l.requeueTaken(taken, dirtyTaken, all) return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", installErr) } @@ -1686,7 +1704,22 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // After the pause. The judgement: the touched set's members with the // map scan's predicate, the WAL entries up to H, the own batch, the // taken dirty set, and every chunk after a BASE write. - candidates, visits := l.candidatesFrom(taken.each, h) + members := taken.each + if filledTaken { + l.stMu.Lock() + filled := make([]uint64, 0, len(l.filledClean)) + for idx := range l.filledClean { + filled = append(filled, idx) + } + l.stMu.Unlock() + members = func(f func(uint64)) { + taken.each(f) + for _, idx := range filled { + f(idx) + } + } + } + candidates, visits := l.candidatesFrom(members, h) visits += int64(len(taken.summary)) // the summary words the walk read l.pauseOp(int(visits)) // each step counts itself if it ever runs in the pause for idx := range dirtyTaken { From da217ed3769a02b002b63ae5d63dc16bd5727fa4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 20:23:01 -0800 Subject: [PATCH 10/10] storage: the pause accounting is the capture's own resolveTouchFilled and the touched set's allocation also run on readers (status, pre-copy, the shadow: peekTouched) without the capture lock; they counted into the capture's paused/pauseOps whenever a cut happened to be paused, a data race and a misattribution. They count only on the capturing goroutine now (byCapture); readers never touch those fields. TestAReaderBesideCutsAndRecoveriesIsNotChargedToThePause runs a reader beside cuts and recoveries (one just before the barrier); under -race it reports 2 data races on the previous code and none now. Co-Authored-By: Claude Opus 5.5 --- .../storage/chunk_cut_candidate_set_test.go | 44 +++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 43 +++++++++++------- 2 files changed, 70 insertions(+), 17 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go index e165179685..c0c0175d31 100644 --- a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go +++ b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go @@ -93,6 +93,50 @@ func TestARecoveryJustBeforeTheBarrierIsJudgedAfterThePause(t *testing.T) { } } +// A reader of the candidates (status, pre-copy, the shadow) running beside +// cuts and recoveries never charges its work to a cut's pause nor touches the +// capture's pause accounting: run with -race, the schedule (a reader that +// can consume a recovery's request while a cut enters its barrier) has no +// race, and every cut's pause does no per-candidate work. +func TestAReaderBesideCutsAndRecoveriesIsNotChargedToThePause(t *testing.T) { + _, l, _ := filledFreshVolume(t) + stop := make(chan struct{}) + done := make(chan struct{}) + go func() { + defer close(done) + for { + select { + case <-stop: + return + default: + } + _ = l.captureCandidates() // the readers' path: peekTouched, resolveTouchFilled + } + }() + defer func() { + close(stop) + select { + case <-done: + case <-time.After(ctLocalBound): + t.Error("the reader did not stop") + } + }() + for i := 0; i < 20; i++ { + l.noteAllMutated() // a recovery the reader may consume first + if i%2 == 1 { + l.testBeforeBarrierLockHook = func() { l.noteAllMutated() } // or one just before the barrier + } + r, err := l.Cut(ctTimeout(t)) + l.testBeforeBarrierLockHook = nil + if err != nil { + t.Fatal(err) + } + if r.Stats.PauseCandidateOps != 0 { + t.Fatalf("cut %d: %d per-candidate operations charged to the pause beside a reader", i, r.Stats.PauseCandidateOps) + } + } +} + // A fill whose fetch outlives a same-open recovery installs HEAD's bytes but // no clean mark (the recovery moved the chunk's version), so the chunk is a // candidate again, as the full scan says; the absent-to-present install diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 0bc9d14782..78a974bf18 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -513,8 +513,11 @@ func (l *chunkLayerImpl) touchRefChangedLocked() { } // resolveTouchFilled touches every clean fill if a recovery asked for it. -// The caller holds neither stMu nor WALStore.mu. -func (l *chunkLayerImpl) resolveTouchFilled() { +// The caller holds neither stMu nor WALStore.mu. byCapture is true only on +// the capturing goroutine: the pause accounting (paused, pauseOps) is its +// own, so a reader's work (status, pre-copy, the shadow) is never charged to +// a cut nor touches those fields. +func (l *chunkLayerImpl) resolveTouchFilled(byCapture bool) { if !l.touchFilled.Swap(false) { return } @@ -524,14 +527,19 @@ func (l *chunkLayerImpl) resolveTouchFilled() { filled = append(filled, idx) } l.stMu.Unlock() - l.pauseOp(len(filled)) + if byCapture { + l.pauseOp(len(filled)) + } l.touch(filled...) } // newTouchedSet allocates a touched set (its words and summary: size -// dependent, counted if the guest is paused). -func (l *chunkLayerImpl) newTouchedSet() *candidateSet { - l.pauseOp(int(l.numChunks/64) + 1) +// dependent, counted as pause work when the capturing goroutine allocates it +// while the guest is paused). +func (l *chunkLayerImpl) newTouchedSet(byCapture bool) *candidateSet { + if byCapture { + l.pauseOp(int(l.numChunks/64) + 1) + } return newCandidateSet(l.numChunks) } @@ -628,7 +636,7 @@ func (l *chunkLayerImpl) touch(chunks ...uint64) { return } l.unkMu.Lock() - set := l.touchedLocked() + set := l.touchedLocked(false) // any goroutine for _, c := range chunks { if c < l.numChunks { set.set(c) @@ -637,10 +645,11 @@ func (l *chunkLayerImpl) touch(chunks ...uint64) { l.unkMu.Unlock() } -// touchedLocked is the live touched set, made on first use. Caller holds unkMu. -func (l *chunkLayerImpl) touchedLocked() *candidateSet { +// touchedLocked is the live touched set, made on first use. Caller holds +// unkMu; byCapture as in resolveTouchFilled. +func (l *chunkLayerImpl) touchedLocked(byCapture bool) *candidateSet { if l.touched == nil { - l.touched = l.newTouchedSet() + l.touched = l.newTouchedSet(byCapture) } return l.touched } @@ -780,10 +789,10 @@ func (l *chunkLayerImpl) seedTouched() { // peekTouched lists the touched set's members, for a reader. func (l *chunkLayerImpl) peekTouched() []uint64 { l.touchedSeed.Do(l.seedTouched) - l.resolveTouchFilled() + l.resolveTouchFilled(false) l.unkMu.Lock() defer l.unkMu.Unlock() - set := l.touchedLocked() + set := l.touchedLocked(false) out := make([]uint64, 0, set.Len()) set.each(func(c uint64) { out = append(out, c) }) return out @@ -795,9 +804,9 @@ func (l *chunkLayerImpl) peekTouched() []uint64 { func (l *chunkLayerImpl) takeTouched() *candidateSet { l.unkMu.Lock() defer l.unkMu.Unlock() - taken := l.touchedLocked() + taken := l.touchedLocked(true) if l.touchedSpare == nil { - l.touchedSpare = l.newTouchedSet() // only if prepareTouched was skipped + l.touchedSpare = l.newTouchedSet(true) // only if prepareTouched was skipped } l.touched, l.touchedSpare = l.touchedSpare, nil return taken @@ -808,11 +817,11 @@ func (l *chunkLayerImpl) takeTouched() *candidateSet { // and the cleared spare the barrier swaps in. The barrier then only swaps. func (l *chunkLayerImpl) prepareTouched() { l.touchedSeed.Do(l.seedTouched) - l.resolveTouchFilled() + l.resolveTouchFilled(true) l.unkMu.Lock() - l.touchedLocked() + l.touchedLocked(true) if l.touchedSpare == nil { - l.touchedSpare = l.newTouchedSet() + l.touchedSpare = l.newTouchedSet(true) } l.unkMu.Unlock() }