From 68ddd3bd92019541b9d29e771845e224cfb5c717 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 27 Nov 2026 22:09:41 -0800 Subject: [PATCH 1/3] fix(storage): a chunk filled from HEAD is not a cut candidate while unchanged A fresh-from-HEAD volume (a restore target) fills a chunk from HEAD on read, but its owned-map entry stays UNKNOWN, so every filled chunk was a cut candidate: the next cut re-read and re-hashed it locally only to find HEAD's bytes. A target read back in full made its detach's final cut as long as reading the whole volume, with nothing to upload. fillOnce records the chunk's version when it filled the chunk wholly from HEAD with no local block and no mutation during the fill; captureCandidates does not count UNKNOWN alone for such a chunk while that version holds. Memory only, reset by a BASE install; the UNKNOWN bits are untouched. Co-Authored-By: Claude Opus 5.5 --- .../durable/first_cut_known_zero_test.go | 37 ++++++ .../chunk_fresh_readback_candidates_test.go | 118 ++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 20 ++- seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 175 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_fresh_readback_candidates_test.go diff --git a/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go b/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go index 49c8daaa61..d9a3aa00d6 100644 --- a/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go +++ b/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go @@ -155,6 +155,43 @@ func TestFirstCutOfARestoreTargetKeepsItsHydrationPath(t *testing.T) { } } +// TestARestoreTargetThatOnlyReadCutsNothing: a restore target whose reads +// filled HEAD's chunks holds HEAD's bytes in them, so its next cut (the final +// cut of a detach included) compares nothing. Comparing every filled chunk +// makes the detach of a fully read target as long as reading the target. +func TestARestoreTargetThatOnlyReadCutsNothing(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + first := fcutProvider(t, t.TempDir(), fixture, v1View()) + fcutOpen(t, ctx, first) + fcutWrite(t, ctx, first, pcChunkBlocks*3, 0x33) + fcutWrite(t, ctx, first, pcChunkBlocks*7, 0x37) + if _, err := first.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if err := first.Close(); err != nil { + t.Fatal(err) + } + p := fcutProvider(t, t.TempDir(), fixture, viewAs("rB", 4)) + fcutOpen(t, ctx, p) + got := make([]byte, 4096) + for _, lba := range []int{pcChunkBlocks * 3, pcChunkBlocks * 7} { + if _, err := p.Backend("v1").Read(ctx, int64(lba)*4096, got); err != nil { + t.Fatal(err) + } + } + if s := fcutStats(t, p); s.AbsentChunks != 0 { + t.Fatalf("setup: %d chunks still absent after reading both HEAD-named chunks", s.AbsentChunks) + } + if _, err := p.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if got := fcutStats(t, p).LastCut.CandidateChunks; got != 0 { + t.Errorf("the cut after reads only: %d candidate chunks; want 0 (the filled chunks are HEAD's bytes)", got) + } +} + // TestExplicitWALStoreRefusesAFreshChunkRoot: a root carrying chunk metadata // (here the fresh marker of a store that never attached) is refused by an // explicitly configured plain walstore as by auto, so no write can reach a diff --git a/seaweed-block/core/storage/chunk_fresh_readback_candidates_test.go b/seaweed-block/core/storage/chunk_fresh_readback_candidates_test.go new file mode 100644 index 0000000000..cde24ccf7a --- /dev/null +++ b/seaweed-block/core/storage/chunk_fresh_readback_candidates_test.go @@ -0,0 +1,118 @@ +package storage + +import ( + "bytes" + "testing" +) + +// A volume fresh from HEAD (a restore target) that only READ its blocks back +// has nothing to compare at its next cut: a chunk filled from HEAD holds +// HEAD's bytes by construction. Re-hashing every filled chunk makes the +// final cut of a fully read volume as long as reading the whole volume. +func TestFreshFromHeadReadBackLeavesNoCutCandidates(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) + s, _ := newChunkTestStore(t) + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + for lba := uint32(0); lba < ctNumBlocks; lba++ { + got, err := s.Read(lba) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, blockOf(src, lba)) { + t.Fatalf("lba %d read back other bytes", lba) + } + } + l.stMu.Lock() + absent := len(l.absent) + l.stMu.Unlock() + if absent != 0 { + t.Fatalf("setup: %d chunks still absent after reading every block", absent) + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if r.Stats.CandidateChunks != 0 { + t.Errorf("a read-only fresh volume's cut compared %d of %d chunks (want 0): its final cut re-reads every filled chunk", r.Stats.CandidateChunks, ctNumBlocks/ctChunkBlocks) + } + again, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if again.Stats.CandidateChunks != 0 { + t.Errorf("control: the cut after a finished cut compared %d chunks", again.Stats.CandidateChunks) + } + t.Logf("first cut compared %d chunks, second %d", r.Stats.CandidateChunks, again.Stats.CandidateChunks) + assertNoRemoteMisuse(t, f) +} + +// Control: the same volume with nothing read compares nothing. +func TestFreshFromHeadUnreadLeavesNoCutCandidates(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) + s, _ := newChunkTestStore(t) + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if r.Stats.CandidateChunks != 0 { + t.Errorf("an unread fresh volume compared %d chunks", r.Stats.CandidateChunks) + } +} + +// Control: a filled chunk written locally afterwards is a candidate again, +// and its cut publishes the write. +func TestFreshFromHeadFilledThenWrittenIsACandidate(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) + s, _ := newChunkTestStore(t) + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + for lba := uint32(0); lba < ctNumBlocks; lba++ { + if _, err := s.Read(lba); err != nil { + t.Fatal(err) + } + } + local := makeBlock(ctBlockSize, 0xEE) + if _, err := s.Write(ctChunkBlocks+1, local); err != nil { + t.Fatal(err) + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if r.Stats.CandidateChunks != 1 { + t.Errorf("filled, then one chunk written: %d candidates, want 1", r.Stats.CandidateChunks) + } + if !bytes.Equal(blockOf(f.imageOf(t, r.Head), ctChunkBlocks+1), local) { + t.Fatal("the cut lost the write to a filled chunk") + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 1a5b7b2365..dfef45e1d0 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -154,6 +154,12 @@ type chunkLayerImpl struct { absent map[uint64]bool absentGen map[uint64]uint64 // bumped on every eviction; binds a fill to its generation localBlocks map[uint64]bool + // filledClean: chunks a fill wrote entirely from HEAD, with no local + // block and no mutation during the fill, at that chunk's version. While + // the version is unchanged the local bytes are HEAD's, so an UNKNOWN map + // entry alone does not make the chunk a cut candidate. Memory only: after + // a restart the next cut compares them once. + filledClean map[uint64]uint64 presenceVer uint64 savedPresVer uint64 dirtyVer uint64 @@ -236,6 +242,7 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) absent: map[uint64]bool{}, absentGen: map[uint64]uint64{}, localBlocks: map[uint64]bool{}, + filledClean: map[uint64]uint64{}, closeDone: make(chan struct{}), syncDirFn: syncDir, } @@ -415,12 +422,18 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { absent[idx] = true } } + filled := map[uint64]bool{} + for idx, v := range l.filledClean { + if l.chunkVersion(idx) == v { + filled[idx] = true + } + } l.addOwnCandidatesLocked(out) l.stMu.Unlock() l.s.mu.RLock() for idx, e := range l.s.v3.mapEntries { i := uint64(idx) - if !absent[i] && (e.Unknown || e.LSN > base) { + if !absent[i] && ((e.Unknown && !filled[i]) || e.LSN > base) { out[i] = true } } @@ -446,6 +459,7 @@ func (l *chunkLayerImpl) BeforeCheckpointAdvance(lsn uint64) error { l.stMu.Lock() l.absent = map[uint64]bool{} l.localBlocks = map[uint64]bool{} + l.filledClean = map[uint64]uint64{} l.presenceVer++ l.stMu.Unlock() } @@ -478,6 +492,7 @@ func (l *chunkLayerImpl) fillOnce(ctx context.Context, idx, gen uint64, ref chun current := func() bool { return l.absent[idx] && l.absentGen[idx] == gen && l.head.Chunks[idx] == ref } + version := l.chunkVersion(idx) // a mutation during the fill makes it unclean data, err := l.remote.Get(ctx, ref.Key) if err != nil { return false, fmt.Errorf("storage: chunk %d fetch: %w", idx, err) @@ -505,6 +520,9 @@ func (l *chunkLayerImpl) fillOnce(ctx context.Context, idx, gen uint64, ref chun if !current() { return false, nil } + if !l.chunkHasLocalLocked(idx) && l.chunkVersion(idx) == version { + l.filledClean[idx] = version + } delete(l.absent, idx) for i := uint64(0); i < l.chunkBlocks; i++ { delete(l.localBlocks, first+i) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d60d7f1b99..330b178c6e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -573,7 +573,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-LEGACY-FIXTURE-ISOLATION-001` | No default-build production code calls a legacy fixture constructor, and no legacy fixture is in the transitive import closure of the production storage packages. | M1 open/create/readonly | build layout: legacy fixtures outside the default production import closure | `TestLegacyFixtureIsolation` (`core/storage/legacy_fixture_isolation_test.go`) | — | ACTIVE | | `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. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | 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; an UNKNOWN chunk a fill wrote wholly from HEAD, with no local block and no mutation since, is not. | M5 candidate selection | `chunk_layer.go` `captureCandidates`, `fillOnce` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestARestoreTargetThatOnlyReadCutsNothing` | 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 | From 18e7f6136f02017855173b6232a8c3bd8b1ad81f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 27 Nov 2026 22:25:04 -0800 Subject: [PATCH 2/3] fix(storage): a clean-fill record also ends with its HEAD ref; guard tests The record now holds the HEAD ref the chunk was filled from as well as its version, and holds only while both are unchanged, so a HEAD that no longer names that ref makes the chunk a candidate whatever replaced it. The version at the fill's start is read under the end check's lock. Guard enumeration: a write, a flushed write, single- and multi-block batches, a replicated entry and a recovery each bump the chunk's version and make it a candidate again; a BASE install ends every record. Co-Authored-By: Claude Opus 5.5 --- .../chunk_fresh_readback_candidates_test.go | 147 ++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 33 ++-- 2 files changed, 169 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/storage/chunk_fresh_readback_candidates_test.go b/seaweed-block/core/storage/chunk_fresh_readback_candidates_test.go index cde24ccf7a..1b84944d9f 100644 --- a/seaweed-block/core/storage/chunk_fresh_readback_candidates_test.go +++ b/seaweed-block/core/storage/chunk_fresh_readback_candidates_test.go @@ -116,3 +116,150 @@ func TestFreshFromHeadFilledThenWrittenIsACandidate(t *testing.T) { t.Fatal("the cut lost the write to a filled chunk") } } + +// filledFreshVolume is a fresh-from-HEAD volume whose every chunk a read has +// filled from HEAD, with its clean-fill records in place. +func filledFreshVolume(t *testing.T) (*WALStore, *chunkLayerImpl, *fakeChunkRemote) { + t.Helper() + 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) + s, _ := newChunkTestStore(t) + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + for lba := uint32(0); lba < ctNumBlocks; lba++ { + if _, err := s.Read(lba); err != nil { + t.Fatal(err) + } + } + l.stMu.Lock() + marks := len(l.filledClean) + l.stMu.Unlock() + if marks != ctNumBlocks/ctChunkBlocks { + t.Fatalf("setup: %d clean-fill records, want %d", marks, ctNumBlocks/ctChunkBlocks) + } + return s, l, f +} + +// Guard enumeration: every path that writes a chunk's local bytes after a +// clean fill bumps that chunk's version, so the fill's record no longer +// holds and the chunk is a cut candidate again. A frontend trim or +// write-zeroes reaches the store as a write. +func TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate(t *testing.T) { + const idx = 1 + lba := uint32(idx * ctChunkBlocks) + data := makeBlock(ctBlockSize, 0xA5) + for _, tc := range []struct { + name string + do func(t *testing.T, s *WALStore) + }{ + {"write", func(t *testing.T, s *WALStore) { + if _, err := s.Write(lba+1, data); err != nil { + t.Fatal(err) + } + }}, + {"write, then flushed to the extent", func(t *testing.T, s *WALStore) { + if _, err := s.Write(lba+1, data); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + }}, + {"batch of one block", func(t *testing.T, s *WALStore) { + if _, err := s.WriteBatch(lba+1, [][]byte{data}); err != nil { + t.Fatal(err) + } + }}, + {"batch of several blocks", func(t *testing.T, s *WALStore) { + if _, err := s.WriteBatch(lba, [][]byte{data, data}); err != nil { + t.Fatal(err) + } + }}, + {"replicated entry (rebuild, catch-up)", func(t *testing.T, s *WALStore) { + if err := s.ApplyEntry(lba+1, data, s.NextLSN()); err != nil { + t.Fatal(err) + } + }}, + {"recovery republishing the WAL", func(t *testing.T, s *WALStore) { + s.noteChunkRecovery() + }}, + } { + t.Run(tc.name, func(t *testing.T) { + s, l, _ := filledFreshVolume(t) + before := l.chunkVersion(idx) + if l.captureCandidates()[idx] { + t.Fatal("setup: the clean-filled chunk is already a candidate") + } + tc.do(t, s) + if l.chunkVersion(idx) == before { + t.Errorf("chunk %d's version did not move", idx) + } + if !l.captureCandidates()[idx] { + t.Errorf("chunk %d is not a cut candidate after the local write", idx) + } + }) + } +} + +// A HEAD that no longer names the ref a chunk was filled from ends the +// fill's record, whatever replaced it: the chunk is a candidate again. +// (While attached, this layer's own cuts change only candidates' refs, and +// another publisher fences the layer; this guards any other path.) +func TestACleanFillRecordEndsWithItsHeadRef(t *testing.T) { + const idx = 2 + _, l, _ := filledFreshVolume(t) + if l.captureCandidates()[idx] { + t.Fatal("setup: the clean-filled chunk is already a candidate") + } + l.stMu.Lock() + h := copyHead(l.head) + ref := h.Chunks[idx] + ref.Key += "-replaced" + ref.SHA256[0] ^= 0xFF + h.Chunks[idx] = ref + l.head = h + l.stMu.Unlock() + if !l.captureCandidates()[idx] { + t.Fatal("a chunk whose HEAD ref changed after its fill is not a candidate") + } +} + +// Guard enumeration, BASE: a BASE install after clean fills takes local +// authority; its records end and every chunk is a candidate of the next cut. +func TestABaseInstallAfterCleanFillsEndsTheirRecords(t *testing.T) { + s, l, _ := filledFreshVolume(t) + h, err := s.BeginBaseInstall(s.NextLSN()+10, idA) + if err != nil { + t.Fatal(err) + } + if err := h.WriteBase(ctChunkBlocks+1, makeBlock(ctBlockSize, 0xB5)); err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + l.stMu.Lock() + marks := len(l.filledClean) + l.stMu.Unlock() + if marks != 0 { + t.Errorf("%d clean-fill records survived a BASE install", marks) + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if r.Stats.CandidateChunks != ctNumBlocks/ctChunkBlocks { + t.Errorf("the cut after a BASE install compared %d chunks, want all %d", r.Stats.CandidateChunks, ctNumBlocks/ctChunkBlocks) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index dfef45e1d0..cc0043fb7a 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -155,11 +155,11 @@ type chunkLayerImpl struct { absentGen map[uint64]uint64 // bumped on every eviction; binds a fill to its generation localBlocks map[uint64]bool // filledClean: chunks a fill wrote entirely from HEAD, with no local - // block and no mutation during the fill, at that chunk's version. While - // the version is unchanged the local bytes are HEAD's, so an UNKNOWN map - // entry alone does not make the chunk a cut candidate. Memory only: after - // a restart the next cut compares them once. - filledClean map[uint64]uint64 + // block and no mutation during the fill, at that chunk's version and + // HEAD ref. While both are unchanged the local bytes are that HEAD's, so + // an UNKNOWN map entry alone does not make the chunk a cut candidate. + // Memory only: after a restart the next cut compares them once. + filledClean map[uint64]filledMark presenceVer uint64 savedPresVer uint64 dirtyVer uint64 @@ -242,7 +242,7 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) absent: map[uint64]bool{}, absentGen: map[uint64]uint64{}, localBlocks: map[uint64]bool{}, - filledClean: map[uint64]uint64{}, + filledClean: map[uint64]filledMark{}, closeDone: make(chan struct{}), syncDirFn: syncDir, } @@ -423,8 +423,8 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { } } filled := map[uint64]bool{} - for idx, v := range l.filledClean { - if l.chunkVersion(idx) == v { + for idx, m := range l.filledClean { + if l.chunkVersion(idx) == m.version && l.head.Chunks[idx] == m.ref { filled[idx] = true } } @@ -443,6 +443,13 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { return out } +// filledMark is a clean fill: the chunk's version and the HEAD ref it was +// filled from. +type filledMark struct { + version uint64 + ref chunkRef +} + // chunkVersion is chunk idx's mutation count. func (l *chunkLayerImpl) chunkVersion(idx uint64) uint64 { return l.chunkMut[idx].Load() @@ -459,7 +466,7 @@ func (l *chunkLayerImpl) BeforeCheckpointAdvance(lsn uint64) error { l.stMu.Lock() l.absent = map[uint64]bool{} l.localBlocks = map[uint64]bool{} - l.filledClean = map[uint64]uint64{} + l.filledClean = map[uint64]filledMark{} l.presenceVer++ l.stMu.Unlock() } @@ -492,7 +499,11 @@ func (l *chunkLayerImpl) fillOnce(ctx context.Context, idx, gen uint64, ref chun current := func() bool { return l.absent[idx] && l.absentGen[idx] == gen && l.head.Chunks[idx] == ref } - version := l.chunkVersion(idx) // a mutation during the fill makes it unclean + // Read with the end check's lock: a mutation bumps the version after its + // dirty-map insert, so one that lands during the fill changes it. + l.stMu.Lock() + version := l.chunkVersion(idx) + l.stMu.Unlock() data, err := l.remote.Get(ctx, ref.Key) if err != nil { return false, fmt.Errorf("storage: chunk %d fetch: %w", idx, err) @@ -521,7 +532,7 @@ func (l *chunkLayerImpl) fillOnce(ctx context.Context, idx, gen uint64, ref chun return false, nil } if !l.chunkHasLocalLocked(idx) && l.chunkVersion(idx) == version { - l.filledClean[idx] = version + l.filledClean[idx] = filledMark{version: version, ref: ref} } delete(l.absent, idx) for i := uint64(0); i < l.chunkBlocks; i++ { From 443446f35bed8f1a577a8b0fec04f2e795734d25 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 27 Nov 2026 22:25:29 -0800 Subject: [PATCH 3/3] docs(invariants): bind the clean-fill guard tests to INV-WAL-V3-CAPTURE-CANDIDATES-001 Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 330b178c6e..4fd447b376 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -573,7 +573,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-LEGACY-FIXTURE-ISOLATION-001` | No default-build production code calls a legacy fixture constructor, and no legacy fixture is in the transitive import closure of the production storage packages. | M1 open/create/readonly | build layout: legacy fixtures outside the default production import closure | `TestLegacyFixtureIsolation` (`core/storage/legacy_fixture_isolation_test.go`) | — | ACTIVE | | `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; an UNKNOWN chunk a fill wrote wholly from HEAD, with no local block and no mutation since, is not. | M5 candidate selection | `chunk_layer.go` `captureCandidates`, `fillOnce` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestARestoreTargetThatOnlyReadCutsNothing` | Conservative reachability unchanged; narrower redundant work | 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; an UNKNOWN chunk a fill wrote wholly from HEAD, with no local block and no mutation since, is not. | M5 candidate selection | `chunk_layer.go` `captureCandidates`, `fillOnce` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing` | 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 |