From f2b9d388853b1485571dbe2b25939566ace55494 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 29 Nov 2026 04:01:57 -0800 Subject: [PATCH] fix(storage): a cut marks each chunk equal to HEAD as soon as it compares it A cut recorded its equal-to-HEAD marks only after the whole compare loop, so a cut that ran out of time kept nothing and the next request compared every chunk again. After a holder restart a restore target's read-filled chunks are all candidates of its first cut (the clean-fill records live in memory only), so at 1 TiB that compare is growing work under one request's fixed bound. Each equal chunk is now marked at its compare, at the version the barrier captured and only while the chunk still has it (the same mark as after the loop), so the next request continues from there. Co-Authored-By: Claude Opus 5.5 --- .../storage/chunk_compare_progress_test.go | 163 ++++++++++++++++++ .../core/storage/chunk_cut_payload.go | 23 +++ seaweed-block/core/storage/chunk_layer.go | 1 + seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 188 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/storage/chunk_compare_progress_test.go diff --git a/seaweed-block/core/storage/chunk_compare_progress_test.go b/seaweed-block/core/storage/chunk_compare_progress_test.go new file mode 100644 index 0000000000..49e3a55519 --- /dev/null +++ b/seaweed-block/core/storage/chunk_compare_progress_test.go @@ -0,0 +1,163 @@ +package storage + +import ( + "context" + "crypto/sha256" + "encoding/binary" + "fmt" + "path/filepath" + "sync" + "sync/atomic" + "testing" +) + +// After a holder restart, every chunk a restore target filled by reading is +// a candidate of its first cut again: the clean-fill records live only in +// memory, and the filled chunks' map entries stay UNKNOWN. +func TestFilledChunksAreFirstCutCandidatesAfterARestart(t *testing.T) { + src := make([]byte, ctNumBlocks*ctBlockSize) + for lba := 0; lba < ctNumBlocks; lba++ { + copy(src[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(0x40+lba))) + } + f := newFakeChunkRemote() + f.seedHead(t, src, 10, 1) + path := filepath.Join(t.TempDir(), "vol.bin") + s, err := CreateWALStoreWithOptions(path, ctNumBlocks, ctBlockSize, WALStoreOptions{ChunkBlocks: ctChunkBlocks}) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + l, err := attachChunkLayer(s, f, cfg) + if err != nil { + t.Fatal(err) + } + for lba := uint32(0); lba < ctNumBlocks; lba++ { // read-fill every chunk + if _, err := s.Read(lba); err != nil { + t.Fatal(err) + } + } + // The flusher saves the presence (the fills are no longer absent) in + // production; this store runs without it, so save it as it would. + if err := l.(*chunkLayerImpl).persistPresence(); err != nil { + t.Fatal(err) + } + if err := l.Close(); err != nil { + t.Fatal(err) + } + closeBounded(t, s) + + s2, err := OpenWALStore(path) // the holder restarts + if err != nil { + t.Fatal(err) + } + s2.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { closeBounded(t, s2) }) + if _, err := s2.Recover(); err != nil { + t.Fatal(err) + } + l2 := mustAttach(t, s2, f, ctConfig(2)).(*chunkLayerImpl) + l2.stMu.Lock() + absent := len(l2.absent) + l2.stMu.Unlock() + unknown := 0 + s2.mu.RLock() + for _, e := range s2.v3.mapEntries { + if e.Unknown { + unknown++ + } + } + s2.mu.RUnlock() + t.Logf("after the restart: %d chunks absent, %d map entries UNKNOWN", absent, unknown) + r, err := l2.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if n := ctNumBlocks / ctChunkBlocks; r.Stats.CandidateChunks != n { + t.Fatalf("the first cut after a restart compared %d of %d read-filled chunks", r.Stats.CandidateChunks, n) + } +} + +// A first cut over 262,144 candidates that runs out of time mid-compare +// keeps every chunk it compared equal; the next request compares only the +// rest, none of those again, and completes. +func TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest(t *testing.T) { + if testing.Short() { + t.Skip("262,144 chunks") + } + const n, bs = 262144, 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"), n, bs, WALStoreOptions{ChunkBlocks: 1}) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + 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} + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + for lba := uint32(0); lba < n; lba++ { + if _, err := s.Read(lba); err != nil { + t.Fatal(err) + } + } + l.stMu.Lock() + l.filledClean = map[uint64]filledMark{} // what a restart leaves: no clean-fill records + l.stMu.Unlock() + + // The first request runs out of time a third of the way through. + ctx, cancel := context.WithCancel(ctTimeout(t)) + var compared atomic.Int64 + l.testAfterCompareHook = func(uint64) { + if compared.Add(1) == n/3 { + cancel() + } + } + if _, err := l.Cut(ctx); err == nil { + t.Fatal("setup: the cut-off cut published") + } + l.stMu.Lock() + kept := make(map[uint64]bool, len(l.filledClean)) + for idx := range l.filledClean { + kept[idx] = true + } + l.stMu.Unlock() + if len(kept) < n/3 { + t.Fatalf("the cut-off cut kept %d of the %d chunks it compared", len(kept), n/3) + } + + var mu sync.Mutex + again := 0 + l.testAfterCompareHook = func(idx uint64) { + if kept[idx] { + mu.Lock() + again++ + mu.Unlock() + } + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if again != 0 || r.Stats.CandidateChunks != n-len(kept) { + t.Fatalf("the rerun compared %d chunks (%d already compared equal), want %d and 0", r.Stats.CandidateChunks, again, n-len(kept)) + } +} diff --git a/seaweed-block/core/storage/chunk_cut_payload.go b/seaweed-block/core/storage/chunk_cut_payload.go index dae777d5f7..ae80610f51 100644 --- a/seaweed-block/core/storage/chunk_cut_payload.go +++ b/seaweed-block/core/storage/chunk_cut_payload.go @@ -70,6 +70,9 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, } } l.rememberPayload(c, head.Gen, staging) + if !staging { + l.markEqualNow(c, head) + } c.data = nil out[i] = c return nil @@ -80,6 +83,26 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, return out, nil } +// markEqualNow records a captured chunk that compared equal to HEAD as a +// clean mark as soon as it is compared, at the version the barrier captured +// and only while the chunk still has it, so a cut that runs out of time +// keeps every chunk it finished comparing and the next request continues +// from there (the same mark the cut records for all of them after the +// compare loop). +func (l *chunkLayerImpl) markEqualNow(c capturedChunk, head chunkHead) { + ref, had := head.Chunks[c.idx] + if (c.zero && !had) || unchangedFromHead(c, ref, had) { + l.stMu.Lock() + if l.chunkVersion(c.idx) == c.version { + l.filledClean[c.idx] = filledMark{version: c.version, ref: ref} + } + l.stMu.Unlock() + } + if hook := l.testAfterCompareHook; hook != nil { + hook(c.idx) + } +} + func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64, versions map[uint64]uint64, head chunkHead, st *chunkCutStats) (map[uint64]stagedChunk, error) { out, err := l.streamCutPayloads(ctx, batch, head, true, func(ctx context.Context, idx uint64) (capturedChunk, error) { data, err := l.readChunk(idx) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 9bc2efe184..d8ebe3cb32 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -153,6 +153,7 @@ type chunkLayerImpl struct { testAfterBarrierSyncHook func(h uint64) // under the capture barrier, right after Sync fixed H testBeforeBarrierLockHook func() // right before the capture barrier's Lock request testBeforeRecordMarksHook func() // after a cut's compare, before it records its marks + testAfterCompareHook func(idx uint64) // after a captured chunk is compared (and marked if equal) syncDirFn func(dir string) error // directory fsync after a rename; syncDir in production // Absence: chunks whose local bytes are not authoritative (fresh host, diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 283665234c..b72a1cf4f1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -591,7 +591,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-COMPARED-001` | A chunk a cut compared equal to HEAD and did not publish, or filled cleanly, is not compared again, whatever made it a candidate, while it has no mutation since and HEAD still names that ref; a chunk an own batch re-uploads stays a candidate. | M5 candidate selection | `chunk_layer.go` `capture`, `fillOnce` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey` | Conservative reachability unchanged; narrower redundant work | ACTIVE | +| `INV-WAL-V3-CAPTURE-COMPARED-001` | A chunk a cut compared equal to HEAD (marked at its compare, kept by a cut out of time) and did not publish, or filled cleanly, is not compared again, whatever made it a candidate, while it has no mutation since and HEAD still names that ref; a chunk an own batch re-uploads stays a candidate. | M5 candidate selection | `chunk_layer.go` `capture`, `fillOnce`; `chunk_cut_payload.go` `markEqualNow` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest`, `TestFilledChunksAreFirstCutCandidatesAfterARestart`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey` | Conservative reachability unchanged; narrower redundant work | ACTIVE | | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | ACTIVE |