From 912fdea4ea199ffcfe67311411261cec10b9865e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 02:20:34 -0800 Subject: [PATCH] storage: a clean-fill touch request cannot hide from a cut A recovery asks the next touched-set user to touch every clean fill. A reader cleared that request before its touches reached the set, so a cut in between saw neither and judged without the fills. The request is now a generation: a reader clears it (compare-and-swap) only after its touches are in the set, and the barrier takes the request before the set, so a cut sees the request or the touches. A reader's listing of the touched set copies the non-empty words under the set's lock and lists their chunks after releasing it, so a barrier's take waits only for the copy. Co-Authored-By: Claude Opus 5.5 --- .../storage/chunk_cut_candidate_set_test.go | 127 ++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 58 ++++++-- .../core/storage/chunk_record_candidates.go | 30 +++++ seaweed-block/docs/design/invariants.md | 1 + 4 files changed, 203 insertions(+), 13 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 c0c0175d31..f1d061a893 100644 --- a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go +++ b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go @@ -7,6 +7,8 @@ import ( "errors" "fmt" "path/filepath" + "sync" + "sync/atomic" "testing" "time" ) @@ -370,3 +372,128 @@ func TestCandidateSetOrBackKeepsTheSummary(t *testing.T) { t.Fatalf("a cleared set lists %v", got) } } + +// A reader that has listed the clean fills of a recovery's request but not +// yet touched them must not hide the request from a cut that runs in that +// window: the reader clears the request only after its touches are in the +// set, and the cut takes the request before the set, so the cut sees one or +// the other. (A reader that cleared the request first left the cut with +// neither: the full-scan oracle finds the fills missing.) +func TestAReaderMidResolveDoesNotHideARecoveryFromACut(t *testing.T) { + _, l, _ := filledFreshVolume(t) + // A first cut consumes the once-per-layer seed (which touches every + // UNKNOWN chunk) and empties the touched set: from here only the + // recovery's request can make the clean fills candidates again. + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if got := l.captureCandidates(); len(got) != 0 { + t.Fatalf("setup: %d candidates before the recovery, want none", len(got)) + } + var mu sync.Mutex + var findings []string + saved := candidateOracle + candidateOracle = func(msg string) { + mu.Lock() + findings = append(findings, msg) + mu.Unlock() + if saved != nil { + saved(msg) + } + } + t.Cleanup(func() { candidateOracle = saved }) + listed, release := make(chan struct{}), make(chan struct{}) + var first atomic.Bool + l.testResolveFilled = func() { + if first.CompareAndSwap(false, true) { // only the reader's resolve pauses; the cut's own runs through + close(listed) + <-release + } + } + t.Cleanup(func() { l.testResolveFilled = nil }) + l.noteAllMutated() // a recovery: every clean fill must become a candidate + done := make(chan struct{}) + go func() { + defer close(done) + _ = l.captureCandidates() // the readers' path: listed, then paused before touching + }() + select { + case <-listed: + case <-time.After(ctLocalBound): + close(release) + t.Fatal("the reader did not reach its resolve") + } + _, err := l.Cut(ctTimeout(t)) + close(release) + select { + case <-done: + case <-time.After(ctLocalBound): + t.Error("the reader did not finish") + } + if err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + if len(findings) != 0 { + t.Fatalf("a cut during a reader's resolve missed %d candidates; first: %s", len(findings), findings[0]) + } +} + +// A reader that resolves a recovery's request completely while the barrier +// is between its two takes (the request, then the touched set) must not +// hide it: the barrier takes the request first, so a reader resolving after +// that finds nothing to clear. (Taking the set first would leave the cut an +// empty set and, once the reader cleared the request, no request either.) +func TestAReaderResolvingInsideTheBarrierDoesNotHideARecovery(t *testing.T) { + _, l, _ := filledFreshVolume(t) + if _, err := l.Cut(ctTimeout(t)); err != nil { // consume the seed, empty the set + t.Fatal(err) + } + var mu sync.Mutex + var findings []string + saved := candidateOracle + candidateOracle = func(msg string) { + mu.Lock() + findings = append(findings, msg) + mu.Unlock() + if saved != nil { + saved(msg) + } + } + t.Cleanup(func() { candidateOracle = saved }) + l.testBeforeBarrierLockHook = func() { l.noteAllMutated() } // a recovery after prepareTouched + l.testBetweenTakes = func() { l.resolveTouchFilled(false) } // a reader, inside the barrier + t.Cleanup(func() { l.testBeforeBarrierLockHook, l.testBetweenTakes = nil, nil }) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + if len(findings) != 0 { + t.Fatalf("a reader resolving inside the barrier hid %d candidates; first: %s", len(findings), findings[0]) + } +} + +// The reader's listing (the set's non-empty words copied under the lock, +// their chunks listed after it) is the set's own walk, in chunk order. +func TestCandidateSetCopiedWordsListTheMembers(t *testing.T) { + const chunks = 70000 + s := newCandidateSet(chunks) + for _, c := range []uint64{0, 1, 63, 64, 4095, 4096, 4097, 65535, 69999} { + s.set(c) + } + var want []uint64 + s.each(func(c uint64) { want = append(want, c) }) + words := s.nonEmptyWords() + s.set(100) // a change after the copy is not in the reader's listing + got := chunksOfWords(words) + if len(got) != len(want) { + t.Fatalf("listed %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("listed %v, want %v", got, want) + } + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index a3b5527934..eefbe8a971 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -209,8 +209,19 @@ type chunkLayerImpl struct { 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 + // knownEqual proofs, at a point that may hold the layer's locks. It holds + // the pending request's generation (0: none, from touchFilledSeq): a + // reader clears it only after its touches are in the set, and only if no + // newer request replaced it, so a cut always sees the request or the + // touches. + touchFilled atomic.Uint64 + touchFilledSeq atomic.Uint64 + // testResolveFilled, when set, runs in resolveTouchFilled after the fills + // are listed and before they are touched. Tests only. + testResolveFilled func() + // testBetweenTakes, when set, runs in the barrier between taking the + // fill request and taking the touched set. Tests only. + testBetweenTakes func() cutLSN uint64 // H of the latest cut taken (in flight or installed) // chunkMut counts the mutations of each chunk: every dirty-map insert @@ -570,7 +581,8 @@ func (l *chunkLayerImpl) touchRefChangedLocked() { // 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) { + g := l.touchFilled.Load() + if g == 0 { return } l.stMu.Lock() @@ -579,10 +591,23 @@ func (l *chunkLayerImpl) resolveTouchFilled(byCapture bool) { filled = append(filled, idx) } l.stMu.Unlock() + if h := l.testResolveFilled; h != nil { + h() + } if byCapture { l.pauseOp(len(filled)) } l.touch(filled...) + // Clear the request only now that its touches are in the set, and only + // if no newer one replaced it: a cut that took the set before these + // touches still finds the request (and covers every chunk). + l.touchFilled.CompareAndSwap(g, 0) +} + +// requestTouchFilled records a pending clean-fill touch request under a new +// generation (a recovery, or a capture that gives its taken request back). +func (l *chunkLayerImpl) requestTouchFilled() { + l.touchFilled.Store(l.touchFilledSeq.Add(1)) } // newTouchedSet allocates a touched set (its words and summary: size @@ -615,7 +640,7 @@ func (l *chunkLayerImpl) candidateOracleScan() map[uint64]bool { defer l.s.mu.RUnlock() l.stMu.Lock() defer l.stMu.Unlock() - pendingFilled := l.touchFilled.Load() + pendingFilled := l.touchFilled.Load() != 0 for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ { i := uint64(idx) if l.absent[i] && !l.chunkHasLocalLocked(i) { @@ -842,12 +867,13 @@ func (l *chunkLayerImpl) seedTouched() { func (l *chunkLayerImpl) peekTouched() []uint64 { l.touchedSeed.Do(l.seedTouched) l.resolveTouchFilled(false) + // Copy the set's non-empty words under unkMu, and list their chunks + // after releasing it: a barrier's take (which needs unkMu) waits only + // for the copy, never for a reader's walk of the members. l.unkMu.Lock() - defer l.unkMu.Unlock() - set := l.touchedLocked(false) - out := make([]uint64, 0, set.Len()) - set.each(func(c uint64) { out = append(out, c) }) - return out + words := l.touchedLocked(false).nonEmptyWords() + l.unkMu.Unlock() + return chunksOfWords(words) } // takeTouched hands the touched set to a capture's barrier and puts the @@ -943,7 +969,7 @@ func (l *chunkLayerImpl) noteAllMutated() { for i := range l.chunkMut { l.chunkMut[i].Add(1) } - l.touchFilled.Store(true) + l.requestTouchFilled() if sh := l.shadow; sh != nil { l.recoveredLocked(sh) } @@ -1725,11 +1751,17 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // 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() // 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) + // The flag is taken BEFORE the set: a reader clears the flag only after + // its touches are in the set, so either this take sees the request or the + // set taken next holds the touches. + filledTaken := l.touchFilled.Swap(0) != 0 + if h := l.testBetweenTakes; h != nil { + h() + } + taken := l.takeTouched() oracleWant := l.candidateOracleScan() // tests only (nil in production) l.stMu.Lock() dirtyTaken, all := l.dirty, l.allDirty @@ -1768,7 +1800,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if installErr != nil { releaseDrain() if filledTaken { - l.touchFilled.Store(true) + l.requestTouchFilled() } l.requeueTaken(taken, dirtyTaken, all) return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", installErr) diff --git a/seaweed-block/core/storage/chunk_record_candidates.go b/seaweed-block/core/storage/chunk_record_candidates.go index 6f1012d21e..1689adbc76 100644 --- a/seaweed-block/core/storage/chunk_record_candidates.go +++ b/seaweed-block/core/storage/chunk_record_candidates.go @@ -45,6 +45,36 @@ func (s *candidateSet) each(f func(chunk uint64)) { } } +// wordAt is one non-empty word of a set: its index and its bits. +type wordAt struct{ w, bits uint64 } + +// nonEmptyWords copies the set's non-empty words: O(summary + members/64), +// for a reader that lists the chunks after releasing the set's lock. +func (s *candidateSet) nonEmptyWords() []wordAt { + var out []wordAt + for si, sw := range s.summary { + for sw != 0 { + w := uint64(si)*64 + uint64(bits.TrailingZeros64(sw)) + sw &= sw - 1 + if word := s.words[w]; word != 0 { + out = append(out, wordAt{w, word}) + } + } + } + return out +} + +// chunksOfWords lists the chunks of copied words, in chunk order. +func chunksOfWords(words []wordAt) []uint64 { + var out []uint64 + for _, wa := range words { + for word := wa.bits; word != 0; word &= word - 1 { + out = append(out, wa.w*64+uint64(bits.TrailingZeros64(word))) + } + } + return out +} + // or adds every chunk of o (same shape). func (s *candidateSet) or(o *candidateSet) { o.each(s.set) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ccbed3adf2..4b35989873 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -641,6 +641,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `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-TOUCH-FILLED-ORDER-001` | A recovery's clean-fill touch request is cleared only after its touches are in the touched set, and the barrier takes the request before the set, so a cut always sees the request or the touches. | M5 candidate selection | `core/storage/chunk_layer.go` `resolveTouchFilled`, `requestTouchFilled`, `captureLocked` | `TestAReaderMidResolveDoesNotHideARecoveryFromACut`, `TestAReaderResolvingInsideTheBarrierDoesNotHideARecovery` (`core/storage/chunk_cut_candidate_set_test.go`) | — | 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 |