From 570b884018ab6ec069b6a40949ad28d5da3952c0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 11:55:19 -0800 Subject: [PATCH 1/8] storage: drive the chunk record from the engine's events, in shadow The chunk record (chunk-kernel/2) runs beside the engine's maps: every write, fill, cut hash, commit and evict reaches it through the kernel, and each cut's barrier checks that the record names every chunk the engine captures. It decides nothing and writes no page yet. A HEAD that moves the chunk root without superseding this holder now fences the layer (errChunkForeignRoot). Co-Authored-By: Claude Opus 5.5 --- .../storage/chunk_compare_progress_test.go | 4 +- .../core/storage/chunk_cut_payload.go | 3 + .../chunk_fresh_readback_candidates_test.go | 4 +- seaweed-block/core/storage/chunk_layer.go | 184 +++++++- .../core/storage/chunk_record_runtime.go | 37 +- .../core/storage/chunk_record_shadow.go | 275 ++++++++++++ .../storage/chunk_record_shadow_main_test.go | 50 +++ .../core/storage/chunk_record_shadow_test.go | 411 ++++++++++++++++++ 8 files changed, 957 insertions(+), 11 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_record_shadow.go create mode 100644 seaweed-block/core/storage/chunk_record_shadow_main_test.go create mode 100644 seaweed-block/core/storage/chunk_record_shadow_test.go diff --git a/seaweed-block/core/storage/chunk_compare_progress_test.go b/seaweed-block/core/storage/chunk_compare_progress_test.go index 49e3a55519..794146965c 100644 --- a/seaweed-block/core/storage/chunk_compare_progress_test.go +++ b/seaweed-block/core/storage/chunk_compare_progress_test.go @@ -119,9 +119,7 @@ func TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest(t *testing.T) t.Fatal(err) } } - l.stMu.Lock() - l.filledClean = map[uint64]filledMark{} // what a restart leaves: no clean-fill records - l.stMu.Unlock() + forgetMarksAsARestart(t, l) // what a restart leaves: no clean-fill records // The first request runs out of time a third of the way through. ctx, cancel := context.WithCancel(ctTimeout(t)) diff --git a/seaweed-block/core/storage/chunk_cut_payload.go b/seaweed-block/core/storage/chunk_cut_payload.go index 5547a8dfb0..95a455950f 100644 --- a/seaweed-block/core/storage/chunk_cut_payload.go +++ b/seaweed-block/core/storage/chunk_cut_payload.go @@ -103,6 +103,9 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, // from there (the same mark the cut records for all of them after the // compare loop). func (l *chunkLayerImpl) markEqualNow(c capturedChunk, head chunkHead) { + if sh := l.shadow; sh != nil { + sh.hashed(c, func() uint64 { return l.chunkVersion(c.idx) }, head) + } ref, had := head.Chunks[c.idx] if (c.zero && !had) || unchangedFromHead(c, ref, had) { l.stMu.Lock() 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 145d086b06..370e53c949 100644 --- a/seaweed-block/core/storage/chunk_fresh_readback_candidates_test.go +++ b/seaweed-block/core/storage/chunk_fresh_readback_candidates_test.go @@ -271,9 +271,7 @@ func TestABaseInstallAfterCleanFillsEndsTheirRecords(t *testing.T) { func unknownFilledVolume(t *testing.T) (*WALStore, *chunkLayerImpl, *fakeChunkRemote) { t.Helper() s, l, f := filledFreshVolume(t) - l.stMu.Lock() - l.filledClean = map[uint64]filledMark{} - l.stMu.Unlock() + forgetMarksAsARestart(t, l) return s, l, f } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 63621354e2..4cd41bfc0f 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -213,6 +213,13 @@ type chunkLayerImpl struct { presenceVer uint64 savedPresVer uint64 dirtyVer uint64 + + // shadow is the chunk record driven beside the maps above (set at + // attach, before the hooks publish; nil only in a layer built by hand). + shadow *chunkRecordShadow + // testShadowCheck receives each barrier's misses and extra record + // candidates; set, it also makes the barrier collect the extras. + testShadowCheck func(miss, extra []uint64) } func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) (chunkLayer, error) { @@ -348,6 +355,10 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.cancel() return nil, err } + if l.shadow, err = newChunkRecordShadow(l); err != nil { + l.cancel() + return nil, err + } hooks := &chunkHooks{sink: l, closer: l.Close, mutated: l.noteMutation, recovered: l.noteAllMutated} hooks.baseTransitionV3 = l.holdBaseTransitionV3 @@ -433,6 +444,9 @@ func (l *chunkLayerImpl) OnExtentWrite(lba uint64, lsn uint64) { if l.absent[idx] { l.localBlocks[lba] = true l.presenceVer++ + if sh := l.shadow; sh != nil && l.chunkLocalLocked(idx) { + sh.landed(idx) + } } if lsn == 0 { // a BASE block lands in the extent directly l.noteMutation(lba) @@ -445,6 +459,10 @@ func (l *chunkLayerImpl) OnExtentWrite(lba uint64, lsn uint64) { // first either sees the new bytes or a stale count (never reused). func (l *chunkLayerImpl) noteMutation(lba uint64) { if idx := l.chunkOf(lba); idx < uint64(len(l.chunkMut)) { + if sh := l.shadow; sh != nil { + sh.write(idx, func() { l.chunkMut[idx].Add(1) }) + return + } l.chunkMut[idx].Add(1) } } @@ -456,6 +474,77 @@ func (l *chunkLayerImpl) noteAllMutated() { for i := range l.chunkMut { l.chunkMut[i].Add(1) } + if sh := l.shadow; sh != nil { + l.recoveredLocked(sh) + } +} + +// recoveredLocked tells the record which chunks Recover changed: the +// version bump above is bookkeeping, the store fact is the dirt Recover +// republished, a WAL entry or a map position above HEAD's. Each such chunk +// gets Changed with its coverage from the store: all for a present chunk; +// for an absent one, the blocks landed locally or held in the WAL (none, +// some or all). A clean chunk's bytes did not change and get no event. +// Recover holds s.mu (write); the WAL and map are read directly. +func (l *chunkLayerImpl) recoveredLocked(sh *chunkRecordShadow) { + l.stMu.Lock() + defer l.stMu.Unlock() + base := l.remoteLSN + wal := map[uint64]map[uint64]bool{} // chunk -> blocks with a WAL entry above HEAD + for _, e := range l.s.dm.snapshot() { + if e.LSN > base { + idx := l.chunkOf(e.LBA) + if wal[idx] == nil { + wal[idx] = map[uint64]bool{} + } + wal[idx][e.LBA] = true + } + } + changed := map[uint64]bool{} + for idx := range wal { + changed[idx] = true + } + for idx, e := range l.s.v3.mapEntries { + if e.LSN > base { + changed[uint64(idx)] = true + } + } + // Clean marks Recover's bumps alone killed: the chunk is not dirt, and + // its version is one above the mark's, or one above the version an + // earlier Recover left. + for idx, m := range l.filledClean { + v := l.chunkVersion(idx) + prev, again := sh.recoverKilled(idx) + if !changed[idx] && (v == m.version+1 || (again && v == prev+1)) { + sh.noteRecoverKilled(idx, v) + } + } + for idx := range changed { + if idx >= l.numChunks { + continue + } + cov := "all" + if l.absent[idx] { + n, total := uint64(0), uint64(0) + for i := uint64(0); i < l.chunkBlocks; i++ { + b := idx*l.chunkBlocks + i + if b >= uint64(l.s.NumBlocks()) { + break + } + total++ + if l.localBlocks[b] || wal[idx][b] { + n++ + } + } + switch { + case n == 0: + cov = "none" + case n < total: + cov = "some" + } + } + sh.changed(idx, cov) + } } // captureCandidates includes current WAL entries and impl3 owned-map dirt. @@ -540,6 +629,9 @@ func (l *chunkLayerImpl) BeforeCheckpointAdvance(lsn uint64) error { l.filledClean = map[uint64]filledMark{} l.presenceVer++ l.stMu.Unlock() + if sh := l.shadow; sh != nil { + sh.changedAll() + } } return l.persistPresence() } @@ -605,6 +697,9 @@ func (l *chunkLayerImpl) fillOnce(ctx context.Context, idx, gen uint64, ref chun if !l.chunkHasLocalLocked(idx) && l.chunkVersion(idx) == version { l.filledClean[idx] = filledMark{version: version, ref: ref} } + if sh := l.shadow; sh != nil { + sh.fill(idx, ref.SHA256) + } delete(l.absent, idx) for i := uint64(0); i < l.chunkBlocks; i++ { delete(l.localBlocks, first+i) @@ -787,6 +882,36 @@ func (l *chunkLayerImpl) ObserveRemoteError(err error) error { return l.latchIde // recordCapturedEqualMarks shares the success and copy-abort proof rule. // A mark names the barrier-captured version and base HEAD ref, never bytes // uploaded but not committed or a version written after that barrier. +// shadowExemptLocked names the engine candidates the record need not name: +// a chunk an own batch re-uploads (a candidate by choice, not by change), +// and a chunk whose clean mark Recover's bookkeeping bump alone killed (its +// bytes did not change: the version is still the one Recover left, and the +// mark still names HEAD's ref). A write since, with or without its event, +// moves the version on and ends the exemption. Caller holds stMu. +func (l *chunkLayerImpl) shadowExemptLocked(idx uint64) bool { + if l.own[idx] { + return true + } + v, ok := l.shadow.recoverKilled(idx) + m, marked := l.filledClean[idx] + return ok && marked && v == l.chunkVersion(idx) && l.head.Chunks[idx] == m.ref +} + +// shadowCommit is the record's E6: the HEAD just installed names every +// captured chunk's hash at its captured version. +func (l *chunkLayerImpl) shadowCommit(captured []capturedChunk, versions map[uint64]uint64) { + sh := l.shadow + if sh == nil { + return + } + for _, c := range captured { + if v, ok := versions[c.idx]; ok { + c.version = v + sh.commit(c, func() uint64 { return l.chunkVersion(c.idx) }) + } + } +} + func (l *chunkLayerImpl) recordCapturedEqualMarks(captured []capturedChunk, versions map[uint64]uint64, head chunkHead) { for _, c := range captured { if v, ok := versions[c.idx]; ok { @@ -1024,6 +1149,12 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch delete(candidates, idx) } } + if sh := l.shadow; sh != nil { + miss, extra := sh.check(candidates, l.shadowExemptLocked, l.testShadowCheck != nil) + 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. @@ -1264,6 +1395,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.cutPhase("settle") next.Gen = gen finishCapturedCut(next, h, changed, newKeys) + l.shadowCommit(captured, capturedVersions) persistCapturedMap(capturedVersions) return l.cutDone(chunkCutResult{H: h, Head: copyHead(next), FullHash: all}, detach), nil } @@ -1304,6 +1436,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if sameProposal(cur, next) { st.CASResult = "resolved-by-reread" finishCapturedCut(cur, h, changed, newKeys) + l.shadowCommit(captured, capturedVersions) persistCapturedMap(capturedVersions) return l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil } @@ -1320,8 +1453,12 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch return chunkCutResult{}, errors.Join(errChunkLayerFenced, casErr) } l.stMu.Lock() - l.head = copyHead(cur) + foreign := l.adoptHeadLocked(cur) l.stMu.Unlock() + if foreign != nil { + l.abortCOW(errChunkLayerFenced) + return chunkCutResult{}, errors.Join(foreign, casErr) + } // HEAD moved past the CAS's base without it, and not to a holder that // supersedes this one: a head conflict, whatever error the CAS returned. if !errors.Is(casErr, errChunkHeadPrecondition) { @@ -1422,7 +1559,9 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle l.head = copyHead(cur) return detachFenced, chunkCutResult{}, nil default: - l.head = copyHead(cur) + if l.adoptHeadLocked(cur) != nil { + return detachFenced, chunkCutResult{}, nil + } return detachNotPublished, chunkCutResult{}, nil } } @@ -1618,11 +1757,47 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { default: // HEAD moved past the unresolved CAS's base without it: that CAS // can never land. - l.head = copyHead(cur) + return l.adoptHeadLocked(cur) } return nil } +// errChunkForeignRoot fences a layer whose HEAD moved, without superseding +// it, to a chunk root it did not propose. The only writers that may move +// HEAD past this holder without superseding it write metadata (snapshot +// delete, cleaning) and keep the root: every chunk the layer holds clean +// still has the bytes HEAD names. A changed root breaks that, so the layer +// stops publishing rather than serve chunks it calls clean against a root +// that no longer names them. +var errChunkForeignRoot = fmt.Errorf("%w: HEAD moved to a chunk root this holder did not propose, without superseding it", errChunkLayerFenced) + +// adoptHeadLocked installs a HEAD that moved past this holder's base +// without superseding it and is not its own proposal. Its chunk root must be +// the one the layer holds; otherwise the layer is fenced +// (errChunkForeignRoot). Caller holds stMu. +func (l *chunkLayerImpl) adoptHeadLocked(cur chunkHead) error { + same := sameChunkRoot(l.head.Chunks, cur.Chunks) + l.head = copyHead(cur) + if !same { + l.fenced = true + log.Printf("level=WARN storage: chunk layer fenced: HEAD gen %d moved the chunk root without superseding holder %q epoch %d", cur.Gen, l.cfg.Holder, l.cfg.Epoch) + return errChunkForeignRoot + } + return nil +} + +func sameChunkRoot(a, b map[uint64]chunkRef) bool { + if len(a) != len(b) { + return false + } + for idx, ra := range a { + if rb, ok := b[idx]; !ok || rb != ra { + return false + } + } + return true +} + // recordCut updates the cumulative counters after one cut attempt. func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error) { l.stMu.Lock() @@ -1928,6 +2103,9 @@ func (l *chunkLayerImpl) EvictChunk(idx uint64) error { delete(l.localBlocks, first+i) } l.presenceVer++ + if sh := l.shadow; sh != nil { + sh.evict(idx) + } l.stMu.Unlock() return l.persistPresence() } diff --git a/seaweed-block/core/storage/chunk_record_runtime.go b/seaweed-block/core/storage/chunk_record_runtime.go index 6238b4e0d8..b9e5b3a8cd 100644 --- a/seaweed-block/core/storage/chunk_record_runtime.go +++ b/seaweed-block/core/storage/chunk_record_runtime.go @@ -97,6 +97,9 @@ type chunkRecordRuntime struct { maxEntries int maxAge time.Duration + // noPages keeps the record in memory only: no page is written, an + // evict's included (the engine's shadow until pages are wired). + noPages bool testBeforePageWrite func(seg uint64) // tests only: runs outside mu, under pubMu, before a page write @@ -149,11 +152,35 @@ func (r *chunkRecordRuntime) Kind(chunk uint64) chunkkernel.Kind { // Apply runs one kernel event on a chunk. hash is the evidence the event // carries (the chunk's hash for Hash and Fill, the captured hash for Commit). func (r *chunkRecordRuntime) Apply(chunk uint64, ev chunkkernel.Event, arg chunkkernel.Arg, hash *[32]byte) (chunkkernel.Effect, error) { + eff, _, err := r.ApplyIf(chunk, ev, func(chunkkernel.Kind) chunkkernel.Arg { return arg }, hash, nil) + return eff, err +} + +// ApplyIf is Apply with the shell's premise checked under the record's lock: +// cond (nil for none) decides from the chunk's state, and whatever shell +// fact it reads, whether the event happens at all, and argFor chooses the +// argument from the state. A shell event that changes the chunk (a write) +// changes the fact cond reads (its version) inside its own cond, so an event +// guarded by cond either sees that change and is skipped, or lands before it. +// ok reports whether cond held. The callbacks run under r.mu: they may read +// and bump atomics only, take no other lock (the caller may hold stMu: stMu +// is taken before r.mu, never after), do no I/O and never call the record. +func (r *chunkRecordRuntime) ApplyIf(chunk uint64, ev chunkkernel.Event, argFor func(chunkkernel.Kind) chunkkernel.Arg, hash *[32]byte, cond func(chunkkernel.Kind) bool) (eff chunkkernel.Effect, ok bool, err error) { r.mu.Lock() if chunk >= r.chunks { r.mu.Unlock() - return chunkkernel.None, fmt.Errorf("storage: chunk record: chunk %d out of range", chunk) + return chunkkernel.None, false, fmt.Errorf("storage: chunk record: chunk %d out of range", chunk) } + if cond != nil && !cond(r.kinds[chunk]) { + r.mu.Unlock() + return chunkkernel.None, false, nil + } + eff, err = r.applyLocked(chunk, ev, argFor(r.kinds[chunk]), hash) + return eff, err == nil, err +} + +// applyLocked steps the kernel with r.mu held and releases it. +func (r *chunkRecordRuntime) applyLocked(chunk uint64, ev chunkkernel.Event, arg chunkkernel.Arg, hash *[32]byte) (chunkkernel.Effect, error) { res, eff, err := chunkkernel.Step(chunkkernel.State{Kind: r.kinds[chunk]}, ev, arg) if err != nil { r.mu.Unlock() @@ -190,7 +217,7 @@ func (r *chunkRecordRuntime) Apply(chunk uint64, ev chunkkernel.Event, arg chunk r.changes[seg]++ } r.mu.Unlock() - if eff == chunkkernel.PageBeforeBytes { + if eff == chunkkernel.PageBeforeBytes && !r.noPages { r.pubMu.Lock() defer r.pubMu.Unlock() if err := r.writeSegmentLocked(seg); err != nil { @@ -258,6 +285,9 @@ func (r *chunkRecordRuntime) Flush() error { // position and the positions at which still-dirty pages went dirty, when it // is above the G already written. pubMu is held. func (r *chunkRecordRuntime) writeHeaderLocked() error { + if r.noPages { + return nil + } r.mu.Lock() g := r.appliedPos() for seg := range r.dirtyVer { @@ -283,6 +313,9 @@ func (r *chunkRecordRuntime) writeHeaderLocked() error { // is snapshotted under mu, valid through the applied position read with it, // and written outside mu; its trigger state is reset by what was taken. func (r *chunkRecordRuntime) writeSegmentLocked(seg uint64) error { + if r.noPages { + return nil + } r.mu.Lock() ver := r.dirtyVer[seg] if ver == r.writtenVer[seg] { diff --git a/seaweed-block/core/storage/chunk_record_shadow.go b/seaweed-block/core/storage/chunk_record_shadow.go new file mode 100644 index 0000000000..c397623fc2 --- /dev/null +++ b/seaweed-block/core/storage/chunk_record_shadow.go @@ -0,0 +1,275 @@ +package storage + +import ( + "crypto/sha256" + "errors" + "fmt" + "log" + "sync" + + "github.com/seaweedfs/seaweed-block/core/chunkkernel" +) + +// chunkRecordShadow drives the chunk record from the engine's own events, +// beside the engine's maps, and checks at each cut's barrier that the +// record names every chunk the engine will capture. It decides nothing: the +// engine's candidates are the ones captured, and the record writes no page. +// +// - EVERY EVENT GOES THROUGH THE KERNEL (chunkRecordRuntime.ApplyIf); an +// event the kernel refuses is a shell defect, counted and logged, never +// an engine error. +// - A WRITE CHANGES THE CHUNK'S VERSION AND ITS STATE TOGETHER: noteMutation +// bumps the version inside the record's lock, in the same step as its +// Write. An event bound to a captured version (Hash, Commit) checks that +// version in the same lock, so it either lands before the write or is +// skipped; it never meets the state the write left. +// - RECORD CANDIDATES COVER THE ENGINE'S: at the barrier every engine +// candidate is P, U or HU in the record, except the chunks an own batch +// re-uploads (they are candidates by choice, not by change). +type chunkRecordShadow struct { + rec *chunkRecordRuntime + zeroSum [32]byte + + mu sync.Mutex + defects int // kernel refusals and evidence refusals of shell events + skippedEvicts int // evicts that met a chunk a write had changed + misses uint64 // engine candidates the record did not name, over all cuts + extra uint64 // record candidates the engine did not name, over all cuts + // scratchP: chunks a cut hashed while their absence stood (P), from a + // scratch merge of the missing blocks. They get no event and stay P, an + // extra candidate the full check exempts and names (model answer M1). + scratchP map[uint64]bool + // killed: chunks whose clean mark only Recover's version bump killed, + // with the version Recover left (an exemption the checker names). + killed map[uint64]uint64 +} + +func (s *chunkRecordShadow) noteRecoverKilled(chunk, version uint64) { + s.mu.Lock() + defer s.mu.Unlock() + if s.killed == nil { + s.killed = map[uint64]uint64{} + } + s.killed[chunk] = version +} + +func (s *chunkRecordShadow) recoverKilled(chunk uint64) (uint64, bool) { + s.mu.Lock() + defer s.mu.Unlock() + v, ok := s.killed[chunk] + return v, ok +} + +// shadowFindings, when set (by this package's tests), receives every +// defect and miss; the tests fail on any. +var shadowFindings func(string) + +func isRecordCandidate(k chunkkernel.Kind) bool { + return k == chunkkernel.Partial || k == chunkkernel.Unknown || k == chunkkernel.HashUnpublished +} + +// newChunkRecordShadow builds the record from the engine's state at attach: +// an absent chunk is A, or P when it has a local block or is a candidate; a +// present candidate is U; any other chunk holds HEAD's bytes (HP, with HEAD's +// hash, or the zero chunk's when HEAD has none). Caller holds no lock; the +// hooks are not yet published, so nothing changes under it. +func newChunkRecordShadow(l *chunkLayerImpl) (*chunkRecordShadow, error) { + zero := sha256.Sum256(make([]byte, int(l.chunkBlocks)*l.blockSize)) + cands := l.captureCandidates() + l.stMu.Lock() + all := l.allDirty + for idx := range l.dirty { + cands[idx] = true + } + kinds := make([]chunkkernel.Kind, l.numChunks) + hashes := make([][32]byte, l.numChunks) + for i := uint64(0); i < l.numChunks; i++ { + switch { + case l.absent[i] && (l.chunkHasLocalLocked(i) || cands[i]): + kinds[i] = chunkkernel.Partial + case l.absent[i]: + kinds[i] = chunkkernel.Absent + case all || cands[i]: + kinds[i] = chunkkernel.Unknown + default: + kinds[i] = chunkkernel.HashPublished + hashes[i] = zero + if ref, ok := l.head.Chunks[i]; ok { + hashes[i] = ref.SHA256 + } + } + } + l.stMu.Unlock() + segs := chunkRecordSegments(l.numChunks) + rec, err := newChunkRecordRuntime("", l.numChunks, l.cfg.Epoch, func() uint64 { return 0 }, kinds, hashes, make([]uint64, segs), 0, nil) + if err != nil { + return nil, err + } + rec.noPages = true + return &chunkRecordShadow{rec: rec, zeroSum: zero}, nil +} + +func (s *chunkRecordShadow) defect(chunk uint64, ev chunkkernel.Event, err error) { + s.mu.Lock() + s.defects++ + s.mu.Unlock() + msg := fmt.Sprintf("chunk record shadow: chunk %d %s: %v", chunk, ev, err) + log.Printf("level=WARN %s", msg) + if f := shadowFindings; f != nil { + f(msg) + } +} + +// write is E1: a write's version bump and its Write, in one step. The +// argument is the resulting chunk's coverage: some while its absence stands +// (A, P), all once its bytes are local. +func (s *chunkRecordShadow) write(chunk uint64, bump func()) { + _, _, err := s.rec.ApplyIf(chunk, chunkkernel.Write, func(k chunkkernel.Kind) chunkkernel.Arg { + if k == chunkkernel.Absent || k == chunkkernel.Partial { + return chunkkernel.Arg{Value: "some"} + } + return chunkkernel.Arg{Value: "all"} + }, nil, func(chunkkernel.Kind) bool { bump(); return true }) + if err != nil { + s.defect(chunk, chunkkernel.Write, err) + } +} + +// landed is E1b: the engine's per-block bitmap of an absent chunk now +// covers every block, so the chunk's bytes are all local. Caller holds stMu +// (the bitmap's lock). +func (s *chunkRecordShadow) landed(chunk uint64) { + if _, err := s.rec.Apply(chunk, chunkkernel.Write, chunkkernel.Arg{Value: "all"}, nil); err != nil { + s.defect(chunk, chunkkernel.Write, err) + } +} + +// fill is E3: a fill resolved the chunk's absence with bytes hashing to +// sum. With no write since the absence began (A) the chunk holds those +// bytes; after one (P) its bytes are local and unknown. +func (s *chunkRecordShadow) fill(chunk uint64, sum [32]byte) { + if _, err := s.rec.Apply(chunk, chunkkernel.Fill, chunkkernel.Arg{Value: "-"}, &sum); err != nil { + s.defect(chunk, chunkkernel.Fill, err) + } +} + +// hashed is E4 and E5: a cut read the chunk at version and hashed it to +// sum. When those bytes are the ones head names (or both are the zero chunk +// and head has none), head published them: Commit follows. Both are skipped +// when the chunk was written since version. +func (s *chunkRecordShadow) hashed(c capturedChunk, current func() uint64, head chunkHead) { + if c.idx >= s.rec.chunks { + return // a synthetic capture beyond the volume (tests drive the payload stream directly) + } + same := capturedAt(c.version, current) + partial := false + guard := func(k chunkkernel.Kind) bool { partial = k == chunkkernel.Partial; return same(k) } + _, ok, err := s.rec.ApplyIf(c.idx, chunkkernel.Hash, dash, &c.sum, guard) + if partial { + s.mu.Lock() + if s.scratchP == nil { + s.scratchP = map[uint64]bool{} + } + s.scratchP[c.idx] = true + s.mu.Unlock() + } + if err != nil { + s.defect(c.idx, chunkkernel.Hash, err) + return + } else if !ok { + return + } + ref, had := head.Chunks[c.idx] + if (c.zero && !had) || (had && !c.zero && ref.SHA256 == c.sum) { + s.commit(c, current) + } +} + +// commit is E5 and E6: a HEAD names the chunk's captured hash. Skipped when +// the chunk was written since its capture. +func (s *chunkRecordShadow) commit(c capturedChunk, current func() uint64) { + if c.idx >= s.rec.chunks { + return + } + same := capturedAt(c.version, current) + if _, _, err := s.rec.ApplyIf(c.idx, chunkkernel.Commit, dash, &c.sum, same); err != nil { + s.defect(c.idx, chunkkernel.Commit, err) + } +} + +// capturedAt is E4-E6's guard: the chunk still has the version its cut +// read, and its absence does not stand (P: the cut hashed a scratch payload +// that filled the missing blocks, the local extent is still partial; that +// chunk gets no event and stays a candidate, pending the model's answer). +func capturedAt(version uint64, current func() uint64) func(chunkkernel.Kind) bool { + return func(k chunkkernel.Kind) bool { return k != chunkkernel.Partial && current() == version } +} + +// evict is E7: the engine made a clean chunk absent, in the same stMu +// section as its clean check. A write that landed between them left the +// chunk U: the evict is skipped and the chunk stays a candidate. +func (s *chunkRecordShadow) evict(chunk uint64) { + clean := func(k chunkkernel.Kind) bool { return k == chunkkernel.HashPublished || k == chunkkernel.Absent } + if _, ok, err := s.rec.ApplyIf(chunk, chunkkernel.Evict, dash, nil, clean); err != nil { + s.defect(chunk, chunkkernel.Evict, err) + } else if !ok { + s.mu.Lock() + s.skippedEvicts++ + s.mu.Unlock() + } +} + +// changedAll is a BASE install completing (before the checkpoint passes +// it): the base is whole and local, so every chunk's coverage is all and its +// bytes are not known equal to HEAD's (U). Changed fires at run time from a +// store fact; every result of Changed is a candidate or absent, never clean. +func (s *chunkRecordShadow) changedAll() { + for i := uint64(0); i < s.rec.chunks; i++ { + s.changed(i, "all") + } +} + +// changed is Changed with coverage cov (none, some, all) from the store. +func (s *chunkRecordShadow) changed(chunk uint64, cov string) { + if _, err := s.rec.Apply(chunk, chunkkernel.Changed, chunkkernel.Arg{Value: cov}, nil); err != nil { + s.defect(chunk, chunkkernel.Changed, err) + } +} + +func dash(chunkkernel.Kind) chunkkernel.Arg { return chunkkernel.Arg{Value: "-"} } + +// errShadowMiss is what a test sees when the record missed a candidate. +var errShadowMiss = errors.New("storage: chunk record shadow: an engine candidate is not a record candidate") + +// check compares the engine's candidates at a barrier with the record's. +// skip names the chunks exempt from coverage (an own batch's). It returns +// 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 bool) (miss, extra []uint64) { + s.rec.mu.Lock() + for idx := range engine { + if !isRecordCandidate(s.rec.kinds[idx]) && !skip(idx) { + miss = append(miss, idx) + } + } + s.mu.Lock() + for idx, k := range s.rec.kinds { + if withExtra && isRecordCandidate(k) && !engine[uint64(idx)] && !(k == chunkkernel.Partial && s.scratchP[uint64(idx)]) { + extra = append(extra, uint64(idx)) + } + } + s.mu.Unlock() + s.rec.mu.Unlock() + s.mu.Lock() + s.misses += uint64(len(miss)) + s.extra += uint64(len(extra)) + s.mu.Unlock() + if len(miss) > 0 { + msg := fmt.Sprintf("chunk record shadow: %d engine candidates are not record candidates (first chunk %d, kind %s): %v", len(miss), miss[0], s.rec.Kind(miss[0]), errShadowMiss) + log.Printf("level=WARN %s", msg) + if f := shadowFindings; f != nil { + f(msg) + } + } + return miss, extra +} diff --git a/seaweed-block/core/storage/chunk_record_shadow_main_test.go b/seaweed-block/core/storage/chunk_record_shadow_main_test.go new file mode 100644 index 0000000000..c763a84378 --- /dev/null +++ b/seaweed-block/core/storage/chunk_record_shadow_main_test.go @@ -0,0 +1,50 @@ +package storage + +import ( + "fmt" + "os" + "sync" + "testing" +) + +// TestMain runs every test in this package with the chunk record's shadow +// strict: a kernel refusal of a shell event, or an engine candidate the +// record does not name, anywhere in the suite fails the run. +func TestMain(m *testing.M) { + var mu sync.Mutex + var found []string + shadowFindings = func(msg string) { + mu.Lock() + found = append(found, msg) + mu.Unlock() + } + code := m.Run() + mu.Lock() + defer mu.Unlock() + if len(found) > 0 && !shadowFindingsExpected { + fmt.Fprintf(os.Stderr, "FAIL: %d chunk record shadow findings; first: %s\n", len(found), found[0]) + if code == 0 { + code = 1 + } + } + os.Exit(code) +} + +// shadowFindingsExpected is set by no test today; it exists so a focused +// run can inspect findings without failing (go test -run X with it set). +var shadowFindingsExpected = os.Getenv("SHADOW_FINDINGS_OK") != "" + +// forgetMarksAsARestart drops the clean marks, which are memory only, as a +// restart does, and rebuilds the chunk record from the engine's state as a +// restart's attach builds it (the record is memory only in shadow mode too). +func forgetMarksAsARestart(t *testing.T, l *chunkLayerImpl) { + t.Helper() + l.stMu.Lock() + l.filledClean = map[uint64]filledMark{} + l.stMu.Unlock() + sh, err := newChunkRecordShadow(l) + if err != nil { + t.Fatal(err) + } + l.shadow = sh +} diff --git a/seaweed-block/core/storage/chunk_record_shadow_test.go b/seaweed-block/core/storage/chunk_record_shadow_test.go new file mode 100644 index 0000000000..8d3a832b84 --- /dev/null +++ b/seaweed-block/core/storage/chunk_record_shadow_test.go @@ -0,0 +1,411 @@ +package storage + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "testing" + + "github.com/seaweedfs/seaweed-block/core/chunkkernel" +) + +// lazyFreshVolume is a fresh-from-HEAD volume no read has filled: every +// chunk HEAD names is absent. Its flusher runs only when a test asks. +func lazyFreshVolume(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) + s.DisableAutoFlushForRecoveryTest() + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + return s, mustAttach(t, s, f, cfg).(*chunkLayerImpl), f +} + +func shadowKind(l *chunkLayerImpl, idx uint64) chunkkernel.Kind { return l.shadow.rec.Kind(idx) } + +func shadowDefects(l *chunkLayerImpl) int { + l.shadow.mu.Lock() + defer l.shadow.mu.Unlock() + return l.shadow.defects +} + +// E1a/E1b: a write's argument is the store bitmap's coverage after it. +// - A guest write to an absent chunk is P (some): the per-block bitmap of +// an absent chunk (localBlocks) records only blocks that land in the +// extent directly, and a flushed WAL write does not land that way on v3. +// Writing every block and flushing leaves P; a cut of it is a scratch cut +// (M1): no Hash, no Commit, no refusal. +// - Blocks landing directly (a BASE block) fill the bitmap: P while it is +// partial, U on the last block (never all from one block). Mutant (E1b +// removed): the chunk stays P. +func TestShadowWriteCoverageFollowsTheStoreBitmap(t *testing.T) { + s, l, _ := lazyFreshVolume(t) + const idx = 1 + for i := uint32(0); i < ctChunkBlocks; i++ { + if _, err := s.Write(idx*ctChunkBlocks+i, makeBlock(ctBlockSize, byte(0xC0+i))); err != nil { + t.Fatal(err) + } + if k := shadowKind(l, idx); k != chunkkernel.Partial { + t.Fatalf("after %d of %d blocks in the WAL: %s, want P", i+1, ctChunkBlocks, k) + } + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if k := shadowKind(l, idx); k != chunkkernel.Partial { + t.Fatalf("flushed guest writes: %s, want P (no direct landing)", k) + } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if n := shadowDefects(l); n != 0 { + t.Fatalf("%d shell events refused", n) + } + + const base = 2 + for i := uint64(0); i < ctChunkBlocks; i++ { + l.OnExtentWrite(base*ctChunkBlocks+i, 0) // a block landing directly + want := chunkkernel.Partial + if i == ctChunkBlocks-1 { + want = chunkkernel.Unknown + } + if k := shadowKind(l, base); k != want { + t.Fatalf("after %d of %d direct blocks: %s, want %s", i+1, ctChunkBlocks, k, want) + } + } + if n := shadowDefects(l); n != 0 { + t.Fatalf("%d shell events refused", n) + } +} + +// E3: a fill that a write raced still resolves the absence (the engine's +// generation and HEAD ref guard), and the record follows the table: the +// write made the chunk P, the fill makes it U, not HP. A fill no write +// raced makes it HP with HEAD's hash. +func TestShadowFillRacedByAWriteEndsUnknown(t *testing.T) { + s, l, f := lazyFreshVolume(t) + const idx = 2 + release, held := make(chan struct{}), make(chan string, 1) + f.mu.Lock() + f.getHoldOne, f.getHoldIn = release, held + f.mu.Unlock() + read := make(chan error, 1) + go func() { _, err := s.Read(idx * ctChunkBlocks); read <- err }() + <-held + if _, err := s.Write(idx*ctChunkBlocks+2, makeBlock(ctBlockSize, 0xE1)); err != nil { + t.Fatal(err) + } + if k := shadowKind(l, idx); k != chunkkernel.Partial { + t.Fatalf("a write during the fetch: %s, want P", k) + } + close(release) + if err := <-read; err != nil { + t.Fatal(err) + } + if k := shadowKind(l, idx); k != chunkkernel.Unknown { + t.Fatalf("the raced fill: %s, want U", k) + } + if _, err := s.Read(3 * ctChunkBlocks); err != nil { + t.Fatal(err) + } + if k := shadowKind(l, 3); k != chunkkernel.HashPublished { + t.Fatalf("an unraced fill: %s, want HP", k) + } + l.stMu.Lock() + want := l.head.Chunks[3].SHA256 + l.stMu.Unlock() + l.shadow.rec.mu.Lock() + got := l.shadow.rec.hashes[3] + l.shadow.rec.mu.Unlock() + if got != want { + t.Fatal("the unraced fill's HP does not carry HEAD's hash") + } +} + +// M1: a cut of a chunk whose absence still stands (one block written, the +// others only in HEAD) hashes a payload whose missing blocks were merged +// from HEAD, not the local extent. The record gets no Hash or Commit for +// it, keeps it P (a candidate), and names it as a scratch cut; nothing is +// refused. If the engine filled the chunk instead, the record followed +// that fill. +func TestShadowCutOfAPartialChunkKeepsItPartial(t *testing.T) { + s, l, _ := lazyFreshVolume(t) + const idx = 3 + if _, err := s.Write(idx*ctChunkBlocks+1, makeBlock(ctBlockSize, 0xD1)); err != nil { + t.Fatal(err) + } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + l.stMu.Lock() + absent := l.absent[idx] + l.stMu.Unlock() + k := shadowKind(l, idx) + l.shadow.mu.Lock() + scratch := l.shadow.scratchP[idx] + l.shadow.mu.Unlock() + switch { + case absent && (k != chunkkernel.Partial || !scratch): + t.Fatalf("absent after the cut: %s (scratch %v), want P from a scratch cut", k, scratch) + case !absent && k != chunkkernel.HashPublished: + t.Fatalf("filled by the cut: %s, want HP", k) + } + if n := shadowDefects(l); n != 0 { + t.Fatalf("%d shell events refused", n) + } +} + +// E8: with no HEAD, a write checkpointed out of the WAL before attach stays +// a candidate (the map's dirt), so the record starts it U, never HP. +func TestShadowAttachKeepsACheckpointedWriteACandidate(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 5, 5) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + cfg := ctConfig(1) + cfg.Bitmap = nil + cfg.FreshFromHead = true + l := mustAttach(t, s, newFakeChunkRemote(), cfg).(*chunkLayerImpl) + idx := uint64(5 / ctChunkBlocks) + if k := shadowKind(l, idx); k != chunkkernel.Unknown { + t.Fatalf("checkpointed write's chunk: %s, want U", k) + } + cands := l.captureCandidates() + l.stMu.Lock() + miss, _ := l.shadow.check(cands, func(uint64) bool { return false }, false) + l.stMu.Unlock() + if len(miss) != 0 { + t.Fatalf("attach: engine candidates %v are not record candidates", miss) + } +} + +// E4-E6: a write between a cut's compare and its marks (and commit) is +// never met by the Hash or Commit bound to the captured version: both are +// skipped, nothing is refused, and the chunk stays U for the next cut, +// which publishes the write. +func TestShadowWriteRacingHashAndCommitIsSkippedNotRefused(t *testing.T) { + s, l, f := filledFreshVolume(t) + if _, err := s.Write(0, makeBlock(ctBlockSize, 0xB0)); err != nil { // chunk 0: a candidate + t.Fatal(err) + } + local := makeBlock(ctBlockSize, 0xB7) + l.testBeforeRecordMarksHook = func() { + l.testBeforeRecordMarksHook = nil + if _, err := s.Write(1, local); err != nil { // chunk 0 again, after the barrier + t.Error(err) + } + } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if k := shadowKind(l, 0); k != chunkkernel.Unknown { + t.Fatalf("written after its capture: %s, want U", k) + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(blockOf(f.imageOf(t, r.Head), 1), local) { + t.Fatal("the next cut lost the write") + } + if k := shadowKind(l, 0); k != chunkkernel.HashPublished { + t.Fatalf("after the next cut: %s, want HP", k) + } + if n := shadowDefects(l); n != 0 { + t.Fatalf("%d shell events refused", n) + } +} + +// E7: an evict of a clean chunk makes it A; ZERO in HEAD and an already +// absent chunk get no event (HP and A stay); an evict that meets a chunk a +// write changed (U) is skipped and counted, never refused. +func TestShadowEvictEdges(t *testing.T) { + s, l, f := filledFreshVolume(t) + if err := l.EvictChunk(2); err != nil { + t.Fatal(err) + } + if k := shadowKind(l, 2); k != chunkkernel.Absent { + t.Fatalf("evicted clean chunk: %s, want A", k) + } + if err := l.EvictChunk(2); err != nil { // already absent + t.Fatal(err) + } + if k := shadowKind(l, 2); k != chunkkernel.Absent { + t.Fatalf("evicted again: %s, want A", k) + } + // Chunk 4 becomes ZERO in HEAD through a cut. + for i := uint32(0); i < ctChunkBlocks; i++ { + if _, err := s.Write(4*ctChunkBlocks+i, make([]byte, ctBlockSize)); err != nil { + t.Fatal(err) + } + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if _, inHead := r.Head.Chunks[4]; inHead { + t.Fatal("setup: the zeroed chunk is still in HEAD") + } + if err := l.EvictChunk(4); err != nil { + t.Fatal(err) + } + if k := shadowKind(l, 4); k != chunkkernel.HashPublished { + t.Fatalf("ZERO in HEAD after an evict: %s, want HP", k) + } + _ = f + // The record meets an evict after a write it saw and the engine's clean + // check did not: skipped and counted. + l.shadow.write(5, func() {}) + l.shadow.evict(5) + l.shadow.mu.Lock() + skipped := l.shadow.skippedEvicts + l.shadow.mu.Unlock() + if k := shadowKind(l, 5); k != chunkkernel.Unknown || skipped != 1 { + t.Fatalf("evict after a write: %s, %d skipped; want U, 1", k, skipped) + } + if n := shadowDefects(l); n != 0 { + t.Fatalf("%d shell events refused", n) + } +} + +// In shadow mode the record writes no page and no header: not for an +// evict's page-before-bytes, not for a flush. Mutant (noPages false): the +// evict writes its page. +func TestShadowRecordWritesNoPage(t *testing.T) { + for _, shadow := range []bool{true, false} { + dir := filepath.Join(t.TempDir(), "rec") + r, err := newChunkRecordRuntime(dir, 2, 7, func() uint64 { return 1 }, + []chunkkernel.Kind{chunkkernel.HashPublished, chunkkernel.Unknown}, make([][32]byte, 2), make([]uint64, 1), 0, nil) + if err != nil { + t.Fatal(err) + } + r.noPages = shadow + if eff, err := r.Apply(0, chunkkernel.Evict, chunkkernel.Arg{Value: "-"}, nil); err != nil || eff != chunkkernel.PageBeforeBytes { + t.Fatalf("evict: %v %v", eff, err) + } + if shadow { + if err := r.Flush(); err != nil { + t.Fatal(err) + } + } + _, statErr := os.Stat(dir) + wrote := statErr == nil + if wrote == shadow { + t.Fatalf("noPages=%v: record directory written=%v", shadow, wrote) + } + } +} + +// The checker at the barrier is exact on a plain cut sequence: no engine +// candidate missing from the record, no record candidate the engine does +// not name. A write the record never heard of (its event removed) is a +// miss the checker reports. +func TestShadowCheckerIsExactAndCatchesAMissingWrite(t *testing.T) { + s, l, _ := filledFreshVolume(t) + var misses, extras [][]uint64 + l.testShadowCheck = func(miss, extra []uint64) { misses, extras = append(misses, miss), append(extras, extra) } + if _, err := s.Write(ctChunkBlocks+1, makeBlock(ctBlockSize, 0xA1)); err != nil { + t.Fatal(err) + } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if len(misses) != 1 || len(misses[0]) != 0 || len(extras[0]) != 0 { + t.Fatalf("plain cut: misses %v extras %v, want none", misses, extras) + } + // Remove E1a for one write: the record does not hear of it. + found := 0 + prev := shadowFindings + shadowFindings = func(string) { found++ } + defer func() { shadowFindings = prev }() + sh := l.shadow + l.shadow = nil + if _, err := s.Write(2*ctChunkBlocks, makeBlock(ctBlockSize, 0xA2)); err != nil { + t.Fatal(err) + } + l.shadow = sh + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if last := misses[len(misses)-1]; len(last) != 1 || last[0] != 2 || found != 1 { + t.Fatalf("a write with no event: misses %v, findings %d; want [2], 1", last, found) + } +} + +// M2: a HEAD that moved past this holder's base without superseding it and +// changed the chunk root fences the layer with errChunkForeignRoot; the +// record gets no event. A metadata-only move (same root) does not fence. +func TestShadowForeignRootWithoutSupersedeFences(t *testing.T) { + for _, foreign := range []bool{false, true} { + s, l, f := filledFreshVolume(t) + if _, err := s.Write(0, makeBlock(ctBlockSize, 0x91)); err != nil { + t.Fatal(err) + } + f.mu.Lock() + f.beforeCAS = func(f *fakeChunkRemote) { + cur := copyHead(f.head) + if foreign { + ref := cur.Chunks[6] + ref.Key += "-foreign" + cur.Chunks[6] = ref + } + f.installLocked(cur) // same holder and epoch: no supersede + } + f.mu.Unlock() + before := shadowKind(l, 6) + _, err := l.Cut(ctTimeout(t)) + if foreign { + if !errors.Is(err, errChunkForeignRoot) || !errors.Is(err, errChunkLayerFenced) || !l.Fenced() { + t.Fatalf("foreign root: err %v fenced %v; want errChunkForeignRoot and fenced", err, l.Fenced()) + } + } else if l.Fenced() || errors.Is(err, errChunkForeignRoot) { + t.Fatalf("metadata-only move: err %v fenced %v; want no fence", err, l.Fenced()) + } + if after := shadowKind(l, 6); after != before { + t.Fatalf("foreign=%v: chunk 6 went %s -> %s; want no event", foreign, before, after) + } + } +} + +// M4: Recover's republished dirt reaches the record as Changed for the +// chunks it names; a clean chunk is untouched. Mutant (the Recover event +// removed): the recovered chunk stays HP and the checker reports it. +func TestShadowRecoverChangesOnlyTheRecoveredChunks(t *testing.T) { + s, l, _ := filledFreshVolume(t) + s.DisableAutoFlushForRecoveryTest() + if _, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x81)); err != nil { // chunk 1 + t.Fatal(err) + } + // Forget the write in the record only, as if its event were lost: only + // Recover's event can bring the chunk back. + l.shadow.rec.mu.Lock() + l.shadow.rec.kinds[1] = chunkkernel.HashPublished + l.shadow.rec.mu.Unlock() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if k := shadowKind(l, 1); k != chunkkernel.Unknown { + t.Fatalf("recovered chunk: %s, want U", k) + } + if k := shadowKind(l, 2); k != chunkkernel.HashPublished { + t.Fatalf("clean chunk after Recover: %s, want HP", k) + } + var misses []uint64 + l.testShadowCheck = func(miss, _ []uint64) { misses = append(misses, miss...) } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if len(misses) != 0 { + t.Fatalf("after Recover the checker missed %v", misses) + } +} From 8db613cb0163590d0da14a84874cd218cd548353 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 11:57:08 -0800 Subject: [PATCH 2/8] storage: test the chunk record's BASE-completion event Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_record_shadow_test.go | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/seaweed-block/core/storage/chunk_record_shadow_test.go b/seaweed-block/core/storage/chunk_record_shadow_test.go index 8d3a832b84..e379ede156 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_test.go @@ -409,3 +409,45 @@ func TestShadowRecoverChangesOnlyTheRecoveredChunks(t *testing.T) { t.Fatalf("after Recover the checker missed %v", misses) } } + +// M3: a BASE install completing makes the local image authoritative for +// every chunk: before the checkpoint passes it, each chunk gets Changed with +// coverage all, so no chunk the record held clean stays clean, and the next +// cut's checker finds every engine candidate named. Mutant (the completion +// event removed): the formerly clean chunk stays HP and the checker +// reports it. +func TestShadowBaseInstallCompletingChangesEveryChunk(t *testing.T) { + s, _, l := mappedBASELayerV3(t) + writeSynced(t, s, 5, 5) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + const clean = 9 + if k := shadowKind(l, clean); k != chunkkernel.HashPublished { + t.Fatalf("setup: chunk %d is %s after the first cut, want HP", clean, k) + } + h, err := s.BeginBaseInstall(7, idA) + if err != nil { + t.Fatal(err) + } + if err := h.WriteBase(5, blk(0x55)); err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + if k := shadowKind(l, clean); k != chunkkernel.Unknown { + t.Fatalf("after the BASE install completed: chunk %d is %s, want U", clean, k) + } + var misses []uint64 + l.testShadowCheck = func(miss, _ []uint64) { misses = append(misses, miss...) } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if len(misses) != 0 { + t.Fatalf("after the BASE install the checker missed %v", misses) + } + if n := shadowDefects(l); n != 0 { + t.Fatalf("%d shell events refused", n) + } +} From 6075b713c5ce0819f7cdd804c74b6beb8b003bbe Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 12:01:24 -0800 Subject: [PATCH 3/8] docs: invariant rows for the chunk record shadow and the foreign-root fence Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6bcc916940..3d93588bc6 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -617,6 +617,8 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-CHUNK-RECORD-PAGES-CURRENT-001` | An unfinished chunk record is used, and its header written, only when every page passes its check and is valid through exactly the store's synced position after recovery (behind: missed writes; ahead: not durable); an unmarked store discards it; the header follows the two-slot fence. | M1 Opened (chunk record load, v1.1 upgrade) | `core/storage/chunk_record.go` `loadChunkRecord`, `completeChunkRecord` | `TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted`, `TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded`, `TestStalePagesAreNeverCompleted`, `TestUnfinishedPagesAheadOfTheStoreAreNotTrusted`, `TestCompleteRecordAheadOfTheStoreIsNotTrusted`, `TestCompleteRecordPagePositions`, `TestRecordHeaderWaitsForTheFence`, `TestRecordHeaderIsNotWrittenAheadOfTheSyncedStore`, `TestDamagedPage` (`core/storage/chunk_record_test.go`) | SlotFence `PagesCurrent`, `FenceHolds`; pages carry chunk-kernel/2 states (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-UPGRADE-PASS-CURSOR-001` | Upgrade pass: rewinds only at open, before Run; a failed rewind latches it until reopen; the persisted cursor is only ever min(earliest unpublished rewind, last written-through position); a restart resumes there; while it runs, a request needing every hash answers in_progress. | M1 Opened (v1.1 upgrade compare pass) | `core/storage/chunk_upgrade_pass.go` `upgradePass.Run`, `advance`, `Rewind`, `Admit` | `TestUpgradePassCursorFollowsThePagesBehindIt`, `TestUpgradePassRestartContinuesAtTheCursor`, `TestUpgradePassRefusesWithProgress`, `TestUpgradePassRewindAtOpenAfterARebuiltPage`, `TestUpgradePassPauseAndHurry`, `TestUpgradePassFailedRewindLatchesUntilReopen`, `TestUpgradePassRewindOnlyBeforeRun`, `TestUpgradePassKeepsItsCountAcrossRuns`, `TestUpgradePassCursorRuleUnderInterleavings` (`core/storage/chunk_upgrade_pass_test.go`) | UpgradePass `BehindCursorKnown`, `NoWorkTwice`; UpgradeWide3 rows 119 to 124, rewinds at restart only (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-RECORD-RUNTIME-001` | While serving: state only via the kernel, a known hash only with its evidence; a page dirties only when a state or hash changes, is written by its own count or age, an evict's at once, in snapshot order; header G = min(applied, dirty pages' dirty-from). | M3 Serving (chunk record runtime) | `core/storage/chunk_record_runtime.go` `chunkRecordRuntime.Apply`, `Due`, `WriteDue`, `WriteThrough`, `Flush` | `TestRecordRuntimeAppliesTheKernel`, `TestRecordRuntimeEvictWritesThePageFirst`, `TestRecordRuntimeSchedulePerPage`, `TestRecordRuntimeFlushIsLoadedBack`, `TestRecordRuntimeWriteThrough`, `TestRecordRuntimeAnUnchangedStateWritesNothing`, `TestRecordRuntimeHeaderMovesUnderWrites`, `TestRecordRuntimeEvictDuringAFlushLandsLast`, `TestRecordRuntimePageWritesFollowChangesNotSize`, `TestRecordRuntimePageWritersPublishInOrder`, `TestRecordRuntimeHashEvidence`, `TestRecordRuntimeCopiesItsInputs`, `TestRecordRuntimeAPageChangedAtOpenHoldsG` (`core/storage/chunk_record_runtime_test.go`) | chunk-kernel/2; ChunkPages rule 1 (pages before the header) and rule 3 (an evict writes its page first) (the per-chunk state models are not in this repository) | STUB | +| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events through the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. The record decides nothing and writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`; `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE | +| `INV-CHUNK-FOREIGN-ROOT-FENCE-001` | A HEAD that moved past the holder's base without superseding it and is not its own proposal must keep the chunk root; one that changed it fences the layer (`errChunkForeignRoot`), so no chunk is held clean against a root that no longer names it. | M5 Commit (head conflict, settlement) | `core/storage/chunk_layer.go` `adoptHeadLocked` (from `captureLocked`, `SettleDetach`, `resolvePending`) | `TestShadowForeignRootWithoutSupersedeFences` (`core/storage/chunk_record_shadow_test.go`) | HeadWriters (only metadata writers move HEAD without superseding; not in this repository) | ACTIVE | | `INV-CHUNK-RECORD-PAYLOAD-001` | Persisting and loading a chunk record preserves every entry's state and hash, including entries on either side of a segment boundary. | M1 chunk record codec (caller not wired) | `core/storage/chunk_record.go` `encodeChunkRecordPage`, `decodeChunkRecordPage` | `TestRecordEntryPayloadRoundTripsAcrossSegments` (`core/storage/chunk_record_test.go`; state-zero and one-entry hash-drop controls) | Encoding fidelity; no state transition change | 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 | | `INV-WAL-V3-DESCRIPTOR-CONFLICT-001` | Open is refused when both v3 descriptor slots are valid but carry the same slotGen with different bytes, or disagree on the UUID or the geometry. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3`, `sameGeometryV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`) | — | ACTIVE | From 9146ecf5985101913eecf1ddb0846bf79e8b2699 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 12:27:18 -0800 Subject: [PATCH 4/8] storage: chunk record shadow review fixes - the barrier check scans only the engine's candidates; the full scan of the record is test-only - a pending proposal's captured chunks are committed in the record at the settlement that finds it landed (resolvePending, SettleDetach) - extra record candidates are findings across the whole package's tests - M5 diagram and table show the foreign-root fence Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 39 ++++++++++++-- .../core/storage/chunk_record_shadow.go | 48 +++++++++++++---- .../core/storage/chunk_record_shadow_test.go | 54 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 5 +- 4 files changed, 133 insertions(+), 13 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 4cd41bfc0f..52b5691cfc 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -150,6 +150,10 @@ type chunkLayerImpl struct { // pendingAborted says the unresolved detach in pending was settled // by its caller (ForgetAbortedDetach): it is never proposed again. pendingAborted bool + // pendingCaptured: the unresolved proposal's captured chunks (index, + // captured version and hash, no bytes): the record's Commit for them + // waits for the settlement that finds the proposal landed. + pendingCaptured []capturedChunk pendingCut chunkCutResult // pendingBase is the version the unresolved CAS expected. While HEAD is // still at it, that CAS may still land, so a read alone never settles it. @@ -892,6 +896,9 @@ func (l *chunkLayerImpl) shadowExemptLocked(idx uint64) bool { if l.own[idx] { return true } + if v, ok := l.shadow.settledAt(idx); ok && v == l.chunkVersion(idx) { + return true // committed at a delayed settlement, unchanged since + } v, ok := l.shadow.recoverKilled(idx) m, marked := l.filledClean[idx] return ok && marked && v == l.chunkVersion(idx) && l.head.Chunks[idx] == m.ref @@ -900,18 +907,36 @@ func (l *chunkLayerImpl) shadowExemptLocked(idx uint64) bool { // shadowCommit is the record's E6: the HEAD just installed names every // captured chunk's hash at its captured version. func (l *chunkLayerImpl) shadowCommit(captured []capturedChunk, versions map[uint64]uint64) { + l.shadowCommitCaptured(pendingCapture(captured, versions), false) +} + +// shadowCommitCaptured is E6 for chunks whose captured versions are set: at +// once after a commit, or at the settlement that finds a pending proposal +// landed. A chunk written since its capture is skipped by the guard. +func (l *chunkLayerImpl) shadowCommitCaptured(captured []capturedChunk, delayed bool) { sh := l.shadow if sh == nil { return } for _, c := range captured { - if v, ok := versions[c.idx]; ok { - c.version = v - sh.commit(c, func() uint64 { return l.chunkVersion(c.idx) }) + if sh.commit(c, func() uint64 { return l.chunkVersion(c.idx) }) && delayed { + sh.noteSettled(c.idx, c.version) } } } +// pendingCapture keeps what the record's Commit needs of each captured +// chunk (index, hash, captured version), without its bytes. +func pendingCapture(captured []capturedChunk, versions map[uint64]uint64) []capturedChunk { + out := make([]capturedChunk, 0, len(captured)) + for _, c := range captured { + if v, ok := versions[c.idx]; ok { + out = append(out, capturedChunk{idx: c.idx, version: v, sum: c.sum, zero: c.zero}) + } + } + return out +} + func (l *chunkLayerImpl) recordCapturedEqualMarks(captured []capturedChunk, versions map[uint64]uint64, head chunkHead) { for _, c := range captured { if v, ok := versions[c.idx]; ok { @@ -1406,6 +1431,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch p := copyHead(next) l.pending = &p l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = detach, chunkCutResult{H: h, FullHash: all}, expected, false + l.pendingCaptured = pendingCapture(captured, capturedVersions) l.stMu.Unlock() // The session stays open: the commit may still land, and the // settlement replays it in the same session (resolvePending). @@ -1545,10 +1571,13 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle cut := l.pendingCut l.pending = nil l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = false, chunkCutResult{}, chunkHeadVersion{}, false + landed := l.pendingCaptured + l.pendingCaptured = nil switch { case sameProposal(cur, *pending): l.noteSettled(l.head, cur) l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN + l.shadowCommitCaptured(landed, true) cut.Head = copyHead(cur) l.detached = &cut r := cut @@ -1741,10 +1770,13 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { l.pending = nil wasDetach, cut := l.pendingDetach, l.pendingCut l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = false, chunkCutResult{}, chunkHeadVersion{}, false + landed := l.pendingCaptured + l.pendingCaptured = nil switch { case sameProposal(cur, *pending): l.noteSettled(l.head, cur) l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN + l.shadowCommitCaptured(landed, true) if wasDetach { cut.Head = copyHead(cur) l.detached = &cut @@ -2036,6 +2068,7 @@ func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, n defer l.stMu.Unlock() l.noteSettled(l.head, head) l.head, l.remoteLSN, l.pending = copyHead(head), h, nil + l.pendingCaptured = nil l.reusable = nil l.inflight = map[uint64]bool{} l.hdr = chunkBitmapHeader{BaseLSN: h, HeadGen: head.Gen, Epoch: head.Epoch, Base: chunkBaseNone} diff --git a/seaweed-block/core/storage/chunk_record_shadow.go b/seaweed-block/core/storage/chunk_record_shadow.go index c397623fc2..7f2ee2d310 100644 --- a/seaweed-block/core/storage/chunk_record_shadow.go +++ b/seaweed-block/core/storage/chunk_record_shadow.go @@ -41,7 +41,28 @@ type chunkRecordShadow struct { scratchP map[uint64]bool // killed: chunks whose clean mark only Recover's version bump killed, // with the version Recover left (an exemption the checker names). - killed map[uint64]uint64 + killed map[uint64]uint64 + settled map[uint64]uint64 +} + +// settled: chunks a delayed settlement committed, with their captured +// version. The engine returned them to its dirty set when the outcome was +// unknown and compares them again; their bytes are the ones HEAD names +// while the version holds (an exemption the checker names). +func (s *chunkRecordShadow) noteSettled(chunk, version uint64) { + s.mu.Lock() + defer s.mu.Unlock() + if s.settled == nil { + s.settled = map[uint64]uint64{} + } + s.settled[chunk] = version +} + +func (s *chunkRecordShadow) settledAt(chunk uint64) (uint64, bool) { + s.mu.Lock() + defer s.mu.Unlock() + v, ok := s.settled[chunk] + return v, ok } func (s *chunkRecordShadow) noteRecoverKilled(chunk, version uint64) { @@ -187,14 +208,16 @@ func (s *chunkRecordShadow) hashed(c capturedChunk, current func() uint64, head // commit is E5 and E6: a HEAD names the chunk's captured hash. Skipped when // the chunk was written since its capture. -func (s *chunkRecordShadow) commit(c capturedChunk, current func() uint64) { +func (s *chunkRecordShadow) commit(c capturedChunk, current func() uint64) bool { if c.idx >= s.rec.chunks { - return + return false } same := capturedAt(c.version, current) - if _, _, err := s.rec.ApplyIf(c.idx, chunkkernel.Commit, dash, &c.sum, same); err != nil { + _, ok, err := s.rec.ApplyIf(c.idx, chunkkernel.Commit, dash, &c.sum, same) + if err != nil { s.defect(c.idx, chunkkernel.Commit, err) } + return ok && err == nil } // capturedAt is E4-E6's guard: the chunk still has the version its cut @@ -252,18 +275,25 @@ func (s *chunkRecordShadow) check(engine map[uint64]bool, skip func(uint64) bool miss = append(miss, idx) } } - s.mu.Lock() - for idx, k := range s.rec.kinds { - if withExtra && isRecordCandidate(k) && !engine[uint64(idx)] && !(k == chunkkernel.Partial && s.scratchP[uint64(idx)]) { - extra = append(extra, uint64(idx)) + if withExtra || shadowFindings != nil { // tests only: O(chunks), never at a production barrier + s.mu.Lock() + for idx, k := range s.rec.kinds { + if isRecordCandidate(k) && !engine[uint64(idx)] && !(k == chunkkernel.Partial && s.scratchP[uint64(idx)]) { + extra = append(extra, uint64(idx)) + } } + s.mu.Unlock() } - s.mu.Unlock() s.rec.mu.Unlock() s.mu.Lock() s.misses += uint64(len(miss)) s.extra += uint64(len(extra)) s.mu.Unlock() + if len(extra) > 0 && shadowFindings != nil { + msg := fmt.Sprintf("chunk record shadow: %d record candidates the engine does not name (first chunk %d, kind %s)", len(extra), extra[0], s.rec.Kind(extra[0])) + log.Printf("level=WARN %s", msg) + shadowFindings(msg) + } if len(miss) > 0 { msg := fmt.Sprintf("chunk record shadow: %d engine candidates are not record candidates (first chunk %d, kind %s): %v", len(miss), miss[0], s.rec.Kind(miss[0]), errShadowMiss) log.Printf("level=WARN %s", msg) diff --git a/seaweed-block/core/storage/chunk_record_shadow_test.go b/seaweed-block/core/storage/chunk_record_shadow_test.go index e379ede156..e03f1c8776 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_test.go @@ -451,3 +451,57 @@ func TestShadowBaseInstallCompletingChangesEveryChunk(t *testing.T) { t.Fatalf("%d shell events refused", n) } } + +// E6 at a delayed settlement: a cut whose CAS outcome is unknown leaves its +// captured chunk HU; the settlement that later finds the proposal landed +// commits it (HP). A write before the settlement keeps the chunk a +// candidate: its old Commit is skipped, and the next cut publishes it. +func TestShadowDelayedSettlementCommitsTheCapturedChunks(t *testing.T) { + for _, writeFirst := range []bool{false, true} { + s, l, f := filledFreshVolume(t) + if _, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x61)); err != nil { // chunk 1 + t.Fatal(err) + } + f.mu.Lock() + f.casModes = []fakeCASMode{casDeferred} + f.mu.Unlock() + if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) { + t.Fatalf("setup: cut with a retained CAS: %v", err) + } + if k := shadowKind(l, 1); k != chunkkernel.HashUnpublished { + t.Fatalf("captured, outcome unknown: %s, want HU", k) + } + if f.releaseDeferredCAS() != 1 { + t.Fatal("setup: the retained CAS did not apply") + } + local := makeBlock(ctBlockSize, 0x62) + if writeFirst { + if _, err := s.Write(ctChunkBlocks+1, local); err != nil { + t.Fatal(err) + } + } + if err := l.resolvePending(ctTimeout(t)); err != nil { + t.Fatal(err) + } + want := chunkkernel.HashPublished + if writeFirst { + want = chunkkernel.Unknown + } + if k := shadowKind(l, 1); k != want { + t.Fatalf("writeFirst=%v: after the settlement %s, want %s", writeFirst, k, want) + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if writeFirst && !bytes.Equal(blockOf(f.imageOf(t, r.Head), ctChunkBlocks+1), local) { + t.Fatal("the next cut lost the write made before the settlement") + } + if k := shadowKind(l, 1); k != chunkkernel.HashPublished { + t.Fatalf("writeFirst=%v: after the next cut %s, want HP", writeFirst, k) + } + if n := shadowDefects(l); n != 0 { + t.Fatalf("%d shell events refused", n) + } + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 3d93588bc6..3c5b4ee3cc 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -389,6 +389,8 @@ stateDiagram-v2 CAS --> Pending: outcome unknown and HEAD unchanged CAS --> Fenced: HEAD moved to a superseding holder CAS --> Refused: HEAD moved otherwise (conflict) + CAS --> Fenced: HEAD moved without superseding and changed the chunk root (foreign root) + Pending --> Fenced: its settlement finds a foreign root Pending --> Admit: next cut settles it first ``` @@ -413,6 +415,7 @@ stateDiagram-v2 | No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-SNAPK-HEAD-WRITE-001` | | Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-SNAPK-HEAD-WRITE-001` | | CAS | conditional update on `{gen, epoch}`, with `RemoteLSN = H`; refused for a lower epoch, a lower `RemoteLSN`, or a HEAD in a delete state | `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.CASHead` | `INV-SNAPK-HEAD-WRITE-001`, `INV-WS-HEAD-MONOTONE-001`, `INV-HEAD-DELETE-FROZEN-001` | +| Foreign root | a HEAD that moved past the base without superseding the holder and is not its own proposal must keep the chunk root (only metadata writers move HEAD that way); one that changed it fences the layer, at the CAS conflict and at a pending or detach settlement | `core/storage/chunk_layer.go` `adoptHeadLocked` (from `captureLocked`, `resolvePending`, `SettleDetach`) | `INV-CHUNK-FOREIGN-ROOT-FENCE-001` | | Settled | a landed commit ends its session; settle native map capture tokens, keeping chunks dirtied after the cut; a refused current-lineage point retains its session and reusable uploads until retry, supersession or Close; an unresolved commit keeps its session | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | | Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its open session for settlement | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` | @@ -617,7 +620,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-CHUNK-RECORD-PAGES-CURRENT-001` | An unfinished chunk record is used, and its header written, only when every page passes its check and is valid through exactly the store's synced position after recovery (behind: missed writes; ahead: not durable); an unmarked store discards it; the header follows the two-slot fence. | M1 Opened (chunk record load, v1.1 upgrade) | `core/storage/chunk_record.go` `loadChunkRecord`, `completeChunkRecord` | `TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted`, `TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded`, `TestStalePagesAreNeverCompleted`, `TestUnfinishedPagesAheadOfTheStoreAreNotTrusted`, `TestCompleteRecordAheadOfTheStoreIsNotTrusted`, `TestCompleteRecordPagePositions`, `TestRecordHeaderWaitsForTheFence`, `TestRecordHeaderIsNotWrittenAheadOfTheSyncedStore`, `TestDamagedPage` (`core/storage/chunk_record_test.go`) | SlotFence `PagesCurrent`, `FenceHolds`; pages carry chunk-kernel/2 states (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-UPGRADE-PASS-CURSOR-001` | Upgrade pass: rewinds only at open, before Run; a failed rewind latches it until reopen; the persisted cursor is only ever min(earliest unpublished rewind, last written-through position); a restart resumes there; while it runs, a request needing every hash answers in_progress. | M1 Opened (v1.1 upgrade compare pass) | `core/storage/chunk_upgrade_pass.go` `upgradePass.Run`, `advance`, `Rewind`, `Admit` | `TestUpgradePassCursorFollowsThePagesBehindIt`, `TestUpgradePassRestartContinuesAtTheCursor`, `TestUpgradePassRefusesWithProgress`, `TestUpgradePassRewindAtOpenAfterARebuiltPage`, `TestUpgradePassPauseAndHurry`, `TestUpgradePassFailedRewindLatchesUntilReopen`, `TestUpgradePassRewindOnlyBeforeRun`, `TestUpgradePassKeepsItsCountAcrossRuns`, `TestUpgradePassCursorRuleUnderInterleavings` (`core/storage/chunk_upgrade_pass_test.go`) | UpgradePass `BehindCursorKnown`, `NoWorkTwice`; UpgradeWide3 rows 119 to 124, rewinds at restart only (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-RECORD-RUNTIME-001` | While serving: state only via the kernel, a known hash only with its evidence; a page dirties only when a state or hash changes, is written by its own count or age, an evict's at once, in snapshot order; header G = min(applied, dirty pages' dirty-from). | M3 Serving (chunk record runtime) | `core/storage/chunk_record_runtime.go` `chunkRecordRuntime.Apply`, `Due`, `WriteDue`, `WriteThrough`, `Flush` | `TestRecordRuntimeAppliesTheKernel`, `TestRecordRuntimeEvictWritesThePageFirst`, `TestRecordRuntimeSchedulePerPage`, `TestRecordRuntimeFlushIsLoadedBack`, `TestRecordRuntimeWriteThrough`, `TestRecordRuntimeAnUnchangedStateWritesNothing`, `TestRecordRuntimeHeaderMovesUnderWrites`, `TestRecordRuntimeEvictDuringAFlushLandsLast`, `TestRecordRuntimePageWritesFollowChangesNotSize`, `TestRecordRuntimePageWritersPublishInOrder`, `TestRecordRuntimeHashEvidence`, `TestRecordRuntimeCopiesItsInputs`, `TestRecordRuntimeAPageChangedAtOpenHoldsG` (`core/storage/chunk_record_runtime_test.go`) | chunk-kernel/2; ChunkPages rule 1 (pages before the header) and rule 3 (an evict writes its page first) (the per-chunk state models are not in this repository) | STUB | -| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events through the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. The record decides nothing and writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`; `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE | +| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events through the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. The record decides nothing and writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE | | `INV-CHUNK-FOREIGN-ROOT-FENCE-001` | A HEAD that moved past the holder's base without superseding it and is not its own proposal must keep the chunk root; one that changed it fences the layer (`errChunkForeignRoot`), so no chunk is held clean against a root that no longer names it. | M5 Commit (head conflict, settlement) | `core/storage/chunk_layer.go` `adoptHeadLocked` (from `captureLocked`, `SettleDetach`, `resolvePending`) | `TestShadowForeignRootWithoutSupersedeFences` (`core/storage/chunk_record_shadow_test.go`) | HeadWriters (only metadata writers move HEAD without superseding; not in this repository) | ACTIVE | | `INV-CHUNK-RECORD-PAYLOAD-001` | Persisting and loading a chunk record preserves every entry's state and hash, including entries on either side of a segment boundary. | M1 chunk record codec (caller not wired) | `core/storage/chunk_record.go` `encodeChunkRecordPage`, `decodeChunkRecordPage` | `TestRecordEntryPayloadRoundTripsAcrossSegments` (`core/storage/chunk_record_test.go`; state-zero and one-entry hash-drop controls) | Encoding fidelity; no state transition change | 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 f0c11ac1810b02ebc22ee88f6959d2300ecaeb4c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 12:32:57 -0800 Subject: [PATCH 5/8] storage: chunk record shadow: bounded production check test; extras judged for cuts that proceed Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 6 +++- .../core/storage/chunk_record_shadow.go | 7 +++-- .../core/storage/chunk_record_shadow_test.go | 30 ++++++++++++++++++- seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 40 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 52b5691cfc..c06713cc56 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1175,7 +1175,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } } if sh := l.shadow; sh != nil { - miss, extra := sh.check(candidates, l.shadowExemptLocked, l.testShadowCheck != 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) } diff --git a/seaweed-block/core/storage/chunk_record_shadow.go b/seaweed-block/core/storage/chunk_record_shadow.go index 7f2ee2d310..d4ab1a8ef9 100644 --- a/seaweed-block/core/storage/chunk_record_shadow.go +++ b/seaweed-block/core/storage/chunk_record_shadow.go @@ -43,6 +43,8 @@ type chunkRecordShadow struct { // with the version Recover left (an exemption the checker names). killed map[uint64]uint64 settled map[uint64]uint64 + // fullScans counts the test-only scans of the whole record. + fullScans int } // settled: chunks a delayed settlement committed, with their captured @@ -268,15 +270,16 @@ var errShadowMiss = errors.New("storage: chunk record shadow: an engine candidat // skip names the chunks exempt from coverage (an own batch's). It returns // 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 bool) (miss, extra []uint64) { +func (s *chunkRecordShadow) check(engine map[uint64]bool, skip func(uint64) bool, withExtra, proceeds bool) (miss, extra []uint64) { s.rec.mu.Lock() for idx := range engine { if !isRecordCandidate(s.rec.kinds[idx]) && !skip(idx) { miss = append(miss, idx) } } - if withExtra || shadowFindings != nil { // tests only: O(chunks), never at a production barrier + if withExtra || (shadowFindings != nil && proceeds) { // tests only: O(chunks), never at a production barrier s.mu.Lock() + s.fullScans++ for idx, k := range s.rec.kinds { if isRecordCandidate(k) && !engine[uint64(idx)] && !(k == chunkkernel.Partial && s.scratchP[uint64(idx)]) { extra = append(extra, uint64(idx)) diff --git a/seaweed-block/core/storage/chunk_record_shadow_test.go b/seaweed-block/core/storage/chunk_record_shadow_test.go index e03f1c8776..a82b79a4bd 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_test.go @@ -182,7 +182,7 @@ func TestShadowAttachKeepsACheckpointedWriteACandidate(t *testing.T) { } cands := l.captureCandidates() l.stMu.Lock() - miss, _ := l.shadow.check(cands, func(uint64) bool { return false }, false) + miss, _ := l.shadow.check(cands, func(uint64) bool { return false }, false, true) l.stMu.Unlock() if len(miss) != 0 { t.Fatalf("attach: engine candidates %v are not record candidates", miss) @@ -505,3 +505,31 @@ func TestShadowDelayedSettlementCommitsTheCapturedChunks(t *testing.T) { } } } + +// The production barrier check is bounded by the engine's candidates: on a +// 262,144-chunk record with one candidate it looks that candidate up and +// never scans the record (the full scan is the test build's). +func TestShadowProductionCheckDoesNotScanTheRecord(t *testing.T) { + const chunks = 262144 + kinds := make([]chunkkernel.Kind, chunks) + for i := range kinds { + kinds[i] = chunkkernel.HashPublished + } + kinds[7] = chunkkernel.Unknown + rec, err := newChunkRecordRuntime("", chunks, 1, func() uint64 { return 0 }, kinds, make([][32]byte, chunks), make([]uint64, chunkRecordSegments(chunks)), 0, nil) + if err != nil { + t.Fatal(err) + } + rec.noPages = true + sh := &chunkRecordShadow{rec: rec} + prev := shadowFindings + shadowFindings = nil // as in production + defer func() { shadowFindings = prev }() + miss, extra := sh.check(map[uint64]bool{7: true}, func(uint64) bool { return false }, false, true) + if len(miss) != 0 || extra != nil || sh.fullScans != 0 { + t.Fatalf("production check: miss %v extra %v full scans %d; want none, none, 0", miss, extra, sh.fullScans) + } + if _, extra = sh.check(map[uint64]bool{}, func(uint64) bool { return false }, true, true); sh.fullScans != 1 || len(extra) != 1 || extra[0] != 7 { + t.Fatalf("test check: extra %v full scans %d; want [7], 1", extra, sh.fullScans) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 3c5b4ee3cc..4f223fc60d 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -620,7 +620,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-CHUNK-RECORD-PAGES-CURRENT-001` | An unfinished chunk record is used, and its header written, only when every page passes its check and is valid through exactly the store's synced position after recovery (behind: missed writes; ahead: not durable); an unmarked store discards it; the header follows the two-slot fence. | M1 Opened (chunk record load, v1.1 upgrade) | `core/storage/chunk_record.go` `loadChunkRecord`, `completeChunkRecord` | `TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted`, `TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded`, `TestStalePagesAreNeverCompleted`, `TestUnfinishedPagesAheadOfTheStoreAreNotTrusted`, `TestCompleteRecordAheadOfTheStoreIsNotTrusted`, `TestCompleteRecordPagePositions`, `TestRecordHeaderWaitsForTheFence`, `TestRecordHeaderIsNotWrittenAheadOfTheSyncedStore`, `TestDamagedPage` (`core/storage/chunk_record_test.go`) | SlotFence `PagesCurrent`, `FenceHolds`; pages carry chunk-kernel/2 states (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-UPGRADE-PASS-CURSOR-001` | Upgrade pass: rewinds only at open, before Run; a failed rewind latches it until reopen; the persisted cursor is only ever min(earliest unpublished rewind, last written-through position); a restart resumes there; while it runs, a request needing every hash answers in_progress. | M1 Opened (v1.1 upgrade compare pass) | `core/storage/chunk_upgrade_pass.go` `upgradePass.Run`, `advance`, `Rewind`, `Admit` | `TestUpgradePassCursorFollowsThePagesBehindIt`, `TestUpgradePassRestartContinuesAtTheCursor`, `TestUpgradePassRefusesWithProgress`, `TestUpgradePassRewindAtOpenAfterARebuiltPage`, `TestUpgradePassPauseAndHurry`, `TestUpgradePassFailedRewindLatchesUntilReopen`, `TestUpgradePassRewindOnlyBeforeRun`, `TestUpgradePassKeepsItsCountAcrossRuns`, `TestUpgradePassCursorRuleUnderInterleavings` (`core/storage/chunk_upgrade_pass_test.go`) | UpgradePass `BehindCursorKnown`, `NoWorkTwice`; UpgradeWide3 rows 119 to 124, rewinds at restart only (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-RECORD-RUNTIME-001` | While serving: state only via the kernel, a known hash only with its evidence; a page dirties only when a state or hash changes, is written by its own count or age, an evict's at once, in snapshot order; header G = min(applied, dirty pages' dirty-from). | M3 Serving (chunk record runtime) | `core/storage/chunk_record_runtime.go` `chunkRecordRuntime.Apply`, `Due`, `WriteDue`, `WriteThrough`, `Flush` | `TestRecordRuntimeAppliesTheKernel`, `TestRecordRuntimeEvictWritesThePageFirst`, `TestRecordRuntimeSchedulePerPage`, `TestRecordRuntimeFlushIsLoadedBack`, `TestRecordRuntimeWriteThrough`, `TestRecordRuntimeAnUnchangedStateWritesNothing`, `TestRecordRuntimeHeaderMovesUnderWrites`, `TestRecordRuntimeEvictDuringAFlushLandsLast`, `TestRecordRuntimePageWritesFollowChangesNotSize`, `TestRecordRuntimePageWritersPublishInOrder`, `TestRecordRuntimeHashEvidence`, `TestRecordRuntimeCopiesItsInputs`, `TestRecordRuntimeAPageChangedAtOpenHoldsG` (`core/storage/chunk_record_runtime_test.go`) | chunk-kernel/2; ChunkPages rule 1 (pages before the header) and rule 3 (an evict writes its page first) (the per-chunk state models are not in this repository) | STUB | -| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events through the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. The record decides nothing and writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE | +| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events through the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. The record decides nothing and writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks`, `TestShadowProductionCheckDoesNotScanTheRecord` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE | | `INV-CHUNK-FOREIGN-ROOT-FENCE-001` | A HEAD that moved past the holder's base without superseding it and is not its own proposal must keep the chunk root; one that changed it fences the layer (`errChunkForeignRoot`), so no chunk is held clean against a root that no longer names it. | M5 Commit (head conflict, settlement) | `core/storage/chunk_layer.go` `adoptHeadLocked` (from `captureLocked`, `SettleDetach`, `resolvePending`) | `TestShadowForeignRootWithoutSupersedeFences` (`core/storage/chunk_record_shadow_test.go`) | HeadWriters (only metadata writers move HEAD without superseding; not in this repository) | ACTIVE | | `INV-CHUNK-RECORD-PAYLOAD-001` | Persisting and loading a chunk record preserves every entry's state and hash, including entries on either side of a segment boundary. | M1 chunk record codec (caller not wired) | `core/storage/chunk_record.go` `encodeChunkRecordPage`, `decodeChunkRecordPage` | `TestRecordEntryPayloadRoundTripsAcrossSegments` (`core/storage/chunk_record_test.go`; state-zero and one-entry hash-drop controls) | Encoding fidelity; no state transition change | 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 65795f420631734a2b3710cc96f8c6730ac1866f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 12:37:48 -0800 Subject: [PATCH 6/8] storage: SPACE red for the chunk record shadow at the 1 TiB shape Heap per chunk after a cut, 262,144 chunks: stated 520 B in total and 56 B for the shadow's share (measured 481 and 48). Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_record_space_test.go | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_record_space_test.go diff --git a/seaweed-block/core/storage/chunk_record_space_test.go b/seaweed-block/core/storage/chunk_record_space_test.go new file mode 100644 index 0000000000..55f2b5f7b2 --- /dev/null +++ b/seaweed-block/core/storage/chunk_record_space_test.go @@ -0,0 +1,78 @@ +package storage + +import ( + "crypto/sha256" + "encoding/binary" + "fmt" + "path/filepath" + "runtime" + "testing" +) + +// spaceVolume attaches a layer over a 1 TiB-shaped volume (262,144 chunks, +// every one named by HEAD), reads it whole so every chunk is present, and +// runs one cut. It returns the heap growth per chunk from before the store +// was created to after the cut, with the layer still attached. +func spacePerChunk(t *testing.T, shadow bool) float64 { + t.Helper() + 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() + runtime.GC() + var before runtime.MemStats + runtime.ReadMemStats(&before) + s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "vol.bin"), 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} + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + if !shadow { + l.shadow = nil + } + if _, err := s.Write(0, make([]byte, bs)); err != nil { + t.Fatal(err) + } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + runtime.GC() + var after runtime.MemStats + runtime.ReadMemStats(&after) + runtime.KeepAlive(l) + return float64(int64(after.HeapAlloc)-int64(before.HeapAlloc)) / n +} + +// SPACE at the 1 TiB shape (262,144 chunks): the heap the attached layer +// holds per chunk after a cut, with the chunk record's shadow, stays within +// the stated bytes; the shadow's own share is its 48 bytes per chunk (a +// 16-byte state and a 32-byte hash) and no more. +func TestSpaceChunkRecordShadowAtOneTiB(t *testing.T) { + if testing.Short() { + t.Skip("262,144 chunks") + } + with := spacePerChunk(t, true) + without := spacePerChunk(t, false) + t.Logf("heap per chunk after a cut: %.0f B with the shadow, %.0f B without (shadow %.0f B)", with, without, with-without) + // Stated bytes for this step (measured 481 and 48 on this branch, + // with about 8% headroom); later V4-B steps state lower totals. + const statedTotal, statedShadow = 520.0, 56.0 + if with > statedTotal || with-without > statedShadow { + t.Fatalf("heap per chunk %.0f B (stated %.0f), shadow share %.0f B (stated %.0f)", with, statedTotal, with-without, statedShadow) + } +} From 691a95750efe73cf08c76bfaeca08f0c1040764f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 13:45:51 -0800 Subject: [PATCH 7/8] storage: describe the SPACE fixture's lazy attached shape Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_record_space_test.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/storage/chunk_record_space_test.go b/seaweed-block/core/storage/chunk_record_space_test.go index 55f2b5f7b2..c7824b6668 100644 --- a/seaweed-block/core/storage/chunk_record_space_test.go +++ b/seaweed-block/core/storage/chunk_record_space_test.go @@ -9,10 +9,12 @@ import ( "testing" ) -// spaceVolume attaches a layer over a 1 TiB-shaped volume (262,144 chunks, -// every one named by HEAD), reads it whole so every chunk is present, and -// runs one cut. It returns the heap growth per chunk from before the store -// was created to after the cut, with the layer still attached. +// spacePerChunk attaches a lazy fresh-from-HEAD layer over a 1 TiB-shaped +// volume (262,144 chunks, every one named by HEAD and absent locally: none +// is read), writes one block and runs one cut. It returns the heap growth +// per chunk from before the store was created to after the cut, with the +// layer still attached. It measures that attached, lazy shape, not a volume +// whose chunks are all present locally. func spacePerChunk(t *testing.T, shadow bool) float64 { t.Helper() const n, bs = 262144, 512 From cde7dfac64cbc488cf3db10cfebb47381f044f53 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 14:01:24 -0800 Subject: [PATCH 8/8] storage: chunk record shadow: bind the scratch exemption to its version; no strict-suite bypass - the scratch-cut exemption holds only while the chunk keeps the version the scratch cut captured; a stale capture grants nothing - TestMain has no switch that turns the strict findings off - the raced-fill test bounds every wait and always releases and joins its reader Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_record_shadow.go | 32 +++++-- .../storage/chunk_record_shadow_main_test.go | 6 +- .../core/storage/chunk_record_shadow_test.go | 87 +++++++++++++++++-- seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 108 insertions(+), 19 deletions(-) diff --git a/seaweed-block/core/storage/chunk_record_shadow.go b/seaweed-block/core/storage/chunk_record_shadow.go index d4ab1a8ef9..6da4bd59d1 100644 --- a/seaweed-block/core/storage/chunk_record_shadow.go +++ b/seaweed-block/core/storage/chunk_record_shadow.go @@ -38,7 +38,10 @@ type chunkRecordShadow struct { // scratchP: chunks a cut hashed while their absence stood (P), from a // scratch merge of the missing blocks. They get no event and stay P, an // extra candidate the full check exempts and names (model answer M1). - scratchP map[uint64]bool + scratchP map[uint64]uint64 // chunk -> the version the scratch cut captured + // version reads a chunk's mutation version (the engine's counter): a + // scratch exemption holds only while the chunk keeps its captured one. + version func(uint64) uint64 // killed: chunks whose clean mark only Recover's version bump killed, // with the version Recover left (an exemption the checker names). killed map[uint64]uint64 @@ -129,7 +132,7 @@ func newChunkRecordShadow(l *chunkLayerImpl) (*chunkRecordShadow, error) { return nil, err } rec.noPages = true - return &chunkRecordShadow{rec: rec, zeroSum: zero}, nil + return &chunkRecordShadow{rec: rec, zeroSum: zero, version: l.chunkVersion}, nil } func (s *chunkRecordShadow) defect(chunk uint64, ev chunkkernel.Event, err error) { @@ -185,15 +188,20 @@ func (s *chunkRecordShadow) hashed(c capturedChunk, current func() uint64, head return // a synthetic capture beyond the volume (tests drive the payload stream directly) } same := capturedAt(c.version, current) - partial := false - guard := func(k chunkkernel.Kind) bool { partial = k == chunkkernel.Partial; return same(k) } + // A scratch cut is evidence only at the version it captured: a stale + // capture (the chunk written since) proves nothing. + scratch := false + guard := func(k chunkkernel.Kind) bool { + scratch = k == chunkkernel.Partial && current() == c.version + return same(k) + } _, ok, err := s.rec.ApplyIf(c.idx, chunkkernel.Hash, dash, &c.sum, guard) - if partial { + if scratch { s.mu.Lock() if s.scratchP == nil { - s.scratchP = map[uint64]bool{} + s.scratchP = map[uint64]uint64{} } - s.scratchP[c.idx] = true + s.scratchP[c.idx] = c.version s.mu.Unlock() } if err != nil { @@ -263,6 +271,14 @@ func (s *chunkRecordShadow) changed(chunk uint64, cov string) { func dash(chunkkernel.Kind) chunkkernel.Arg { return chunkkernel.Arg{Value: "-"} } +// scratchHoldsLocked reports whether a P chunk's scratch-cut exemption +// still holds: the chunk keeps the version the scratch cut captured. A +// write since (P stays P) ends it. Caller holds s.mu. +func (s *chunkRecordShadow) scratchHoldsLocked(chunk uint64, k chunkkernel.Kind) bool { + v, ok := s.scratchP[chunk] + return ok && k == chunkkernel.Partial && s.version != nil && s.version(chunk) == v +} + // errShadowMiss is what a test sees when the record missed a candidate. var errShadowMiss = errors.New("storage: chunk record shadow: an engine candidate is not a record candidate") @@ -281,7 +297,7 @@ func (s *chunkRecordShadow) check(engine map[uint64]bool, skip func(uint64) bool s.mu.Lock() s.fullScans++ for idx, k := range s.rec.kinds { - if isRecordCandidate(k) && !engine[uint64(idx)] && !(k == chunkkernel.Partial && s.scratchP[uint64(idx)]) { + if isRecordCandidate(k) && !engine[uint64(idx)] && !s.scratchHoldsLocked(uint64(idx), k) { extra = append(extra, uint64(idx)) } } 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 c763a84378..7fef233d0d 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_main_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_main_test.go @@ -21,7 +21,7 @@ func TestMain(m *testing.M) { code := m.Run() mu.Lock() defer mu.Unlock() - if len(found) > 0 && !shadowFindingsExpected { + if len(found) > 0 { fmt.Fprintf(os.Stderr, "FAIL: %d chunk record shadow findings; first: %s\n", len(found), found[0]) if code == 0 { code = 1 @@ -30,10 +30,6 @@ func TestMain(m *testing.M) { os.Exit(code) } -// shadowFindingsExpected is set by no test today; it exists so a focused -// run can inspect findings without failing (go test -run X with it set). -var shadowFindingsExpected = os.Getenv("SHADOW_FINDINGS_OK") != "" - // forgetMarksAsARestart drops the clean marks, which are memory only, as a // restart does, and rebuilds the chunk record from the engine's state as a // restart's attach builds it (the record is memory only in shadow mode too). diff --git a/seaweed-block/core/storage/chunk_record_shadow_test.go b/seaweed-block/core/storage/chunk_record_shadow_test.go index a82b79a4bd..f3a81ce5ae 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_test.go @@ -5,7 +5,9 @@ import ( "errors" "os" "path/filepath" + "sync" "testing" + "time" "github.com/seaweedfs/seaweed-block/core/chunkkernel" ) @@ -99,17 +101,43 @@ func TestShadowFillRacedByAWriteEndsUnknown(t *testing.T) { f.getHoldOne, f.getHoldIn = release, held f.mu.Unlock() read := make(chan error, 1) + var once sync.Once + letGo := func() { once.Do(func() { close(release) }) } + // Registered before the reader starts: a failed check below still + // releases the held fetch and joins the reader before the store closes. + t.Cleanup(func() { + letGo() + select { + case <-read: + case <-time.After(ctLocalBound): + t.Error("the reader did not return") + } + }) go func() { _, err := s.Read(idx * ctChunkBlocks); read <- err }() - <-held + select { + case <-held: + case err := <-read: + read <- err // keep it for the cleanup's join + t.Fatalf("setup: the read returned before its fetch was held: %v", err) + case <-time.After(ctLocalBound): + t.Fatal("setup: the fetch was never held") + } if _, err := s.Write(idx*ctChunkBlocks+2, makeBlock(ctBlockSize, 0xE1)); err != nil { t.Fatal(err) } if k := shadowKind(l, idx); k != chunkkernel.Partial { t.Fatalf("a write during the fetch: %s, want P", k) } - close(release) - if err := <-read; err != nil { - t.Fatal(err) + letGo() + var readErr error + select { + case readErr = <-read: + read <- readErr // keep it for the cleanup's join + case <-time.After(ctLocalBound): + t.Fatal("the released read did not return") + } + if readErr != nil { + t.Fatal(readErr) } if k := shadowKind(l, idx); k != chunkkernel.Unknown { t.Fatalf("the raced fill: %s, want U", k) @@ -151,7 +179,7 @@ func TestShadowCutOfAPartialChunkKeepsItPartial(t *testing.T) { l.stMu.Unlock() k := shadowKind(l, idx) l.shadow.mu.Lock() - scratch := l.shadow.scratchP[idx] + _, scratch := l.shadow.scratchP[idx] l.shadow.mu.Unlock() switch { case absent && (k != chunkkernel.Partial || !scratch): @@ -533,3 +561,52 @@ func TestShadowProductionCheckDoesNotScanTheRecord(t *testing.T) { t.Fatalf("test check: extra %v full scans %d; want [7], 1", extra, sh.fullScans) } } + +// The scratch-cut exemption holds only at the version the scratch cut +// captured: a write since (the chunk stays P) ends it, and a stale capture +// (taken before a write) never grants it. Each case leaves a P chunk the +// engine does not name, and only the unchanged post-scratch case is exempt. +func TestShadowScratchExemptionIsBoundToItsCapturedVersion(t *testing.T) { + for _, c := range []struct { + name string + before bool // a write before the capture is hashed (the capture is stale) + after bool // a write after the scratch capture + exempt bool + }{{"unchanged after the scratch cut", false, false, true}, {"written after it", false, true, false}, {"stale capture", true, false, false}} { + t.Run(c.name, func(t *testing.T) { + s, l, _ := lazyFreshVolume(t) + const idx = 3 + if _, err := s.Write(idx*ctChunkBlocks+1, makeBlock(ctBlockSize, 0xD1)); err != nil { + t.Fatal(err) + } + captured := capturedChunk{idx: idx, version: l.chunkVersion(idx), sum: [32]byte{1}} + if c.before { + if _, err := s.Write(idx*ctChunkBlocks+2, makeBlock(ctBlockSize, 0xD2)); err != nil { + t.Fatal(err) + } + } + l.shadow.hashed(captured, func() uint64 { return l.chunkVersion(idx) }, chunkHead{}) + if c.after { + if _, err := s.Write(idx*ctChunkBlocks+2, makeBlock(ctBlockSize, 0xD3)); err != nil { + t.Fatal(err) + } + } + if k := shadowKind(l, idx); k != chunkkernel.Partial { + t.Fatalf("setup: %s, want P", k) + } + prev := shadowFindings + shadowFindings = nil // this control asserts its own extra + defer func() { shadowFindings = prev }() + l.stMu.Lock() + _, extra := l.shadow.check(map[uint64]bool{}, func(uint64) bool { return false }, true, true) + l.stMu.Unlock() + named := false + for _, e := range extra { + named = named || e == idx + } + if named == c.exempt { + t.Fatalf("chunk %d reported as an extra: %v, want %v", idx, named, !c.exempt) + } + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 4f223fc60d..181a9a9b36 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -620,7 +620,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-CHUNK-RECORD-PAGES-CURRENT-001` | An unfinished chunk record is used, and its header written, only when every page passes its check and is valid through exactly the store's synced position after recovery (behind: missed writes; ahead: not durable); an unmarked store discards it; the header follows the two-slot fence. | M1 Opened (chunk record load, v1.1 upgrade) | `core/storage/chunk_record.go` `loadChunkRecord`, `completeChunkRecord` | `TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted`, `TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded`, `TestStalePagesAreNeverCompleted`, `TestUnfinishedPagesAheadOfTheStoreAreNotTrusted`, `TestCompleteRecordAheadOfTheStoreIsNotTrusted`, `TestCompleteRecordPagePositions`, `TestRecordHeaderWaitsForTheFence`, `TestRecordHeaderIsNotWrittenAheadOfTheSyncedStore`, `TestDamagedPage` (`core/storage/chunk_record_test.go`) | SlotFence `PagesCurrent`, `FenceHolds`; pages carry chunk-kernel/2 states (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-UPGRADE-PASS-CURSOR-001` | Upgrade pass: rewinds only at open, before Run; a failed rewind latches it until reopen; the persisted cursor is only ever min(earliest unpublished rewind, last written-through position); a restart resumes there; while it runs, a request needing every hash answers in_progress. | M1 Opened (v1.1 upgrade compare pass) | `core/storage/chunk_upgrade_pass.go` `upgradePass.Run`, `advance`, `Rewind`, `Admit` | `TestUpgradePassCursorFollowsThePagesBehindIt`, `TestUpgradePassRestartContinuesAtTheCursor`, `TestUpgradePassRefusesWithProgress`, `TestUpgradePassRewindAtOpenAfterARebuiltPage`, `TestUpgradePassPauseAndHurry`, `TestUpgradePassFailedRewindLatchesUntilReopen`, `TestUpgradePassRewindOnlyBeforeRun`, `TestUpgradePassKeepsItsCountAcrossRuns`, `TestUpgradePassCursorRuleUnderInterleavings` (`core/storage/chunk_upgrade_pass_test.go`) | UpgradePass `BehindCursorKnown`, `NoWorkTwice`; UpgradeWide3 rows 119 to 124, rewinds at restart only (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-RECORD-RUNTIME-001` | While serving: state only via the kernel, a known hash only with its evidence; a page dirties only when a state or hash changes, is written by its own count or age, an evict's at once, in snapshot order; header G = min(applied, dirty pages' dirty-from). | M3 Serving (chunk record runtime) | `core/storage/chunk_record_runtime.go` `chunkRecordRuntime.Apply`, `Due`, `WriteDue`, `WriteThrough`, `Flush` | `TestRecordRuntimeAppliesTheKernel`, `TestRecordRuntimeEvictWritesThePageFirst`, `TestRecordRuntimeSchedulePerPage`, `TestRecordRuntimeFlushIsLoadedBack`, `TestRecordRuntimeWriteThrough`, `TestRecordRuntimeAnUnchangedStateWritesNothing`, `TestRecordRuntimeHeaderMovesUnderWrites`, `TestRecordRuntimeEvictDuringAFlushLandsLast`, `TestRecordRuntimePageWritesFollowChangesNotSize`, `TestRecordRuntimePageWritersPublishInOrder`, `TestRecordRuntimeHashEvidence`, `TestRecordRuntimeCopiesItsInputs`, `TestRecordRuntimeAPageChangedAtOpenHoldsG` (`core/storage/chunk_record_runtime_test.go`) | chunk-kernel/2; ChunkPages rule 1 (pages before the header) and rule 3 (an evict writes its page first) (the per-chunk state models are not in this repository) | STUB | -| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events through the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. The record decides nothing and writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks`, `TestShadowProductionCheckDoesNotScanTheRecord` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE | +| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events through the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. The record decides nothing and writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks`, `TestShadowProductionCheckDoesNotScanTheRecord`, `TestShadowScratchExemptionIsBoundToItsCapturedVersion` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE | | `INV-CHUNK-FOREIGN-ROOT-FENCE-001` | A HEAD that moved past the holder's base without superseding it and is not its own proposal must keep the chunk root; one that changed it fences the layer (`errChunkForeignRoot`), so no chunk is held clean against a root that no longer names it. | M5 Commit (head conflict, settlement) | `core/storage/chunk_layer.go` `adoptHeadLocked` (from `captureLocked`, `SettleDetach`, `resolvePending`) | `TestShadowForeignRootWithoutSupersedeFences` (`core/storage/chunk_record_shadow_test.go`) | HeadWriters (only metadata writers move HEAD without superseding; not in this repository) | ACTIVE | | `INV-CHUNK-RECORD-PAYLOAD-001` | Persisting and loading a chunk record preserves every entry's state and hash, including entries on either side of a segment boundary. | M1 chunk record codec (caller not wired) | `core/storage/chunk_record.go` `encodeChunkRecordPage`, `decodeChunkRecordPage` | `TestRecordEntryPayloadRoundTripsAcrossSegments` (`core/storage/chunk_record_test.go`; state-zero and one-entry hash-drop controls) | Encoding fidelity; no state transition change | 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 |