Merge pull request #237 from seaweedfs/fix/chunkmap-bounded

fix(storage): bound the v3 owned-map file by reusing unreferenced extents
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-19 07:08:03 -08:00
commit 4b5320f3ea
9 files changed
+871 -15

No files matched your search

@@ -517,6 +517,7 @@ func (s *WALStore) markBaseCompleteV3(id [16]byte) error {
v.syncMu.Lock()
defer v.syncMu.Unlock()
if !v.flushLifetimeValidV3(gen) {
prepared.abandonV3()
return ErrMapCoverageStale // a recovery or reset ran meanwhile
}
installed := func(n *descriptorV3) error {
+63 -10
View File
@@ -1,7 +1,9 @@
package storage
// Dark impl-3 COW map, DESIGN r15 9.2-9.5. All bytes are append-only;
// neither fallback slots nor pending candidates can lose a dependency.
// Impl-3 COW map. Pages and roots are immutable once written; their extents
// are reused only after no live root references them
// (chunk_map_extents_v3.go), so neither slot root nor a pending candidate can
// lose a dependency.
import (
"bytes"
"crypto/sha256"
@@ -242,6 +244,14 @@ type chunkLSNMapV3 struct {
syncFile func() error
syncDirectory func() error
latchPersistence func(error)
// liveMu guards live (chunk_map_extents_v3.go); never held across I/O.
liveMu sync.Mutex
live chunkMapLiveV3
}
func (m *chunkLSNMapV3) initLiveV3() {
m.live.roots = map[mapRootKeyV3]mapRootExtentsV3{}
m.live.inflight = map[mapRootKeyV3]bool{}
}
func createChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3, error) {
@@ -256,6 +266,7 @@ func createChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3
return nil, e
}
m := &chunkLSNMapV3{fd: f, identity: d, chunkBlocks: cb}
m.initLiveV3()
m.syncFile = f.Sync
m.syncDirectory = func() error { return syncDir(filepath.Dir(path)) }
if e = m.syncFile(); e == nil {
@@ -281,6 +292,13 @@ func openChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3,
return nil, nil, e
}
m := &chunkLSNMapV3{fd: f, identity: d, chunkBlocks: cb, lastGeneration: d.MapGeneration}
m.initLiveV3()
if s, e := mapShapeForV3(d, cb); e == nil {
m.registerRootV3(d.MapGeneration, d.MapRootLocator, s.aligned, refs)
}
if info, e := f.Stat(); e == nil && info.Size() > 0 {
m.live.fileBytes.Store(uint64(info.Size()))
}
m.syncFile = f.Sync
m.syncDirectory = func() error { return syncDir(filepath.Dir(path)) }
c := &chunkMapCandidateV3{owner: m, generation: d.MapGeneration, covered: d.MapCoveredCheckpoint, rootOffset: d.MapRootLocator, hash: d.MapRootHash, refs: refs, entries: es}
@@ -291,7 +309,9 @@ func openChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3,
// It returns a pinned tuple, never a descriptor publication or reuse authority.
// Preflight and Stat errors do not latch. Once the append transaction starts,
// an error latches and refuses subsequent persistence I/O until reopen.
// No pages are reclaimed in this append-only implementation.
// New pages and the root go into extents no live root references
// (chunk_map_extents_v3.go); the candidate stays live until a publication
// names it or supersedes it.
func (m *chunkLSNMapV3) Prepare(g, C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (out *chunkMapCandidateV3, err error) {
m.mu.Lock()
defer m.mu.Unlock()
@@ -300,7 +320,8 @@ func (m *chunkLSNMapV3) Prepare(g, C uint64, entries []chunkLSNEntryV3, prior *c
// Generation reservation and persistence share the existing sidecar mutex.
// Concurrent preparers cannot select the same generation; no new lock or
// scheduler is introduced, and aborted candidates remain immutable orphans.
// scheduler is introduced. A candidate known never to reach a slot is
// released (abandonCandidateV3); an uncertain one stays pinned until reopen.
func (m *chunkLSNMapV3) prepareNextV3(C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (*chunkMapCandidateV3, error) {
m.mu.Lock()
defer m.mu.Unlock()
@@ -342,11 +363,14 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3,
if info.Size() < 0 {
return nil, ErrMapInvalid
}
off := uint64(info.Size())
if off > math.MaxInt64-4095 {
fileBytes := uint64(info.Size())
if fileBytes > math.MaxInt64-4095 {
return nil, ErrCounterExhausted
}
off = (off + 4095) &^ uint64(4095)
// The live set: every page and root extent a live root references.
// Roots are only added here (under m.mu); the publisher's report only
// removes them, so this snapshot is a superset for the whole prepare.
used, liveBytes := usedPagesV3(m.liveSnapshotV3())
defer func() {
if err != nil {
m.failed = err
@@ -355,19 +379,39 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3,
}
}
}()
// Bounded file: truncate the free tail once the file exceeds 4 x the
// live bytes. Nothing at or below the highest live page is touched, so
// a root the fallback slot names stays readable.
if liveBytes > 0 && fileBytes > 4*liveBytes {
keep := (used[len(used)-1] + 1) * 4096
if keep < fileBytes {
if e := m.fd.Truncate(int64(keep)); e != nil {
return nil, e
}
fileBytes = keep
m.live.fileBytes.Store(keep) // the file is shorter even if the fsync fails
m.live.truncations.Add(1)
if e := m.syncFile(); e != nil {
return nil, e
}
}
}
alloc := newExtentAllocatorV3(used, fileBytes)
write := func(b []byte) (uint64, error) {
if uint64(len(b)) > math.MaxInt64-off {
at := alloc.alloc(uint64(len(b)+4095) / 4096)
if uint64(len(b)) > math.MaxInt64-at {
return 0, ErrCounterExhausted
}
at := off
n, e := m.fd.WriteAt(b, int64(at))
if end := at + uint64(n); end > m.live.fileBytes.Load() {
m.live.fileBytes.Store(end) // also on a failed or short write
}
if e == nil && n != len(b) {
e = io.ErrShortWrite
}
if e != nil {
return 0, e
}
off += uint64(len(b))
return at, nil
}
refs := make([]mapPageRefV3, s.pages)
@@ -416,6 +460,15 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3,
}
m.lastGeneration = g
out = &chunkMapCandidateV3{owner: m, generation: g, covered: C, rootOffset: at, hash: mapDigestV3(mapRootDomainV3, root[:s.raw-32]), refs: refs, entries: append([]chunkLSNEntryV3(nil), entries...)}
// The candidate is live (in flight) until a publication names it or
// supersedes it.
x := rootExtentsV3(at, s.aligned, refs)
m.liveMu.Lock()
k := mapRootKeyV3{at, g}
m.live.roots[k] = x
m.live.inflight[k] = true
m.liveMu.Unlock()
m.live.fileBytes.Store(max(alloc.end*4096, fileBytes))
return out, nil
}
func (m *chunkLSNMapV3) Close() error {
@@ -0,0 +1,221 @@
package storage
import (
"sort"
"sync/atomic"
)
// The owned-map file reuses space. A candidate's new pages and root go into
// 4 KiB extents that no live root references, and the file's free tail is
// truncated once the file exceeds 4x the live bytes.
//
// Live roots are the roots the two descriptor slots name and every prepared
// candidate not yet published or superseded (an uncertain candidate stays
// live, because a failed publication latches the publisher). An extent is
// released only after a publication leaves neither slot naming it. New
// pages and the root are fsynced before a publication names them, so a
// crash leaves every slot-named root intact. Roots and pages are addressed
// by offset and SHA-256, so the on-disk format is unchanged.
//
// Map pages are read by offset only at open, before any candidate exists;
// other openers take the same exclusive volume lock.
//
// Lock order: WALStore.mu -> descMu -> liveMu (the publisher's report and
// the definite-abandon path run under descMu), and chunkLSNMapV3.mu ->
// liveMu (a prepare snapshots and registers under it). liveMu is held only
// for map and slice bookkeeping (it may allocate a slice or a map entry),
// never across I/O, sorting or extent allocation,
// and nothing holding liveMu takes another lock.
type mapRootKeyV3 struct{ off, gen uint64 }
type mapRootExtentsV3 struct {
rootOff, rootLen uint64 // bytes, 4 KiB aligned
pages []uint64 // page offsets (every page the root references)
}
// chunkMapLiveV3 is the live set of one owned map.
type chunkMapLiveV3 struct {
roots map[mapRootKeyV3]mapRootExtentsV3
inflight map[mapRootKeyV3]bool
truncations atomic.Uint64
fileBytes atomic.Uint64 // set at open, after each prepare and truncation
}
// ChunkMapStats reports the owned map file's size, the bytes its live roots
// reference, and how many times its free tail was truncated.
type ChunkMapStats struct {
FileBytes, LiveBytes, Truncations uint64
}
// registerRootV3 records a slot-named root read at open. Caller holds no lock
// other than possibly m.mu.
func (m *chunkLSNMapV3) registerRootV3(gen, rootOff, rootLen uint64, refs []mapPageRefV3) {
m.liveMu.Lock()
defer m.liveMu.Unlock()
m.live.roots[mapRootKeyV3{rootOff, gen}] = rootExtentsV3(rootOff, rootLen, refs)
}
func rootExtentsV3(rootOff, rootLen uint64, refs []mapPageRefV3) mapRootExtentsV3 {
x := mapRootExtentsV3{rootOff: rootOff, rootLen: rootLen, pages: make([]uint64, len(refs))}
for i, r := range refs {
x.pages[i] = r.Offset
}
return x
}
// slotsPublishedV3 is the publisher's report after a successful publication
// (under descMu). Roots named by neither slot are released, and so is every
// in-flight candidate the new current generation supersedes (it can never
// be published: a publication needs a strictly higher generation).
func (m *chunkLSNMapV3) slotsPublishedV3(cur, other descriptorV3, otherValid bool) {
m.liveMu.Lock()
defer m.liveMu.Unlock()
keep := map[mapRootKeyV3]bool{{cur.MapRootLocator, cur.MapGeneration}: true}
if otherValid {
keep[mapRootKeyV3{other.MapRootLocator, other.MapGeneration}] = true
}
for k := range m.live.roots {
if keep[k] {
delete(m.live.inflight, k)
continue
}
if m.live.inflight[k] && k.gen > cur.MapGeneration {
continue // a newer candidate, still publishable
}
delete(m.live.roots, k)
delete(m.live.inflight, k)
}
}
// abandonCandidateV3 releases a prepared candidate that is known never to
// have reached a descriptor slot: its publication was refused before any
// slot I/O (a stale proof, a validation refusal, a latched fault), or its
// caller gave up before publishing. A candidate whose publication I/O
// started stays pinned (uncertain) until reopen.
func (m *chunkLSNMapV3) abandonCandidateV3(c *chunkMapCandidateV3) {
m.liveMu.Lock()
defer m.liveMu.Unlock()
k := mapRootKeyV3{c.rootOffset, c.generation}
if m.live.inflight[k] {
delete(m.live.inflight, k)
delete(m.live.roots, k)
}
}
// abandonV3 is the definite-abandon path for a prepared publication.
func (p *preparedMapPublicationV3) abandonV3() {
if p != nil && p.candidate != nil && p.candidate.owner != nil {
p.candidate.owner.abandonCandidateV3(p.candidate)
}
}
// liveSnapshotV3 copies the live roots' extents under liveMu.
func (m *chunkLSNMapV3) liveSnapshotV3() []mapRootExtentsV3 {
m.liveMu.Lock()
defer m.liveMu.Unlock()
out := make([]mapRootExtentsV3, 0, len(m.live.roots))
for _, x := range m.live.roots {
out = append(out, x)
}
return out
}
// usedPagesV3 returns the sorted, distinct 4 KiB page indexes a live-set
// snapshot references, and the live byte count. It needs no lock.
func usedPagesV3(roots []mapRootExtentsV3) ([]uint64, uint64) {
set := map[uint64]bool{}
for _, x := range roots {
for p := x.rootOff / 4096; p < (x.rootOff+x.rootLen)/4096; p++ {
set[p] = true
}
for _, off := range x.pages {
set[off/4096] = true
}
}
used := make([]uint64, 0, len(set))
for p := range set {
used = append(used, p)
}
sort.Slice(used, func(i, j int) bool { return used[i] < used[j] })
return used, uint64(len(used)) * 4096
}
// extentAllocatorV3 hands out free 4 KiB-aligned runs, lowest first, given
// the pages in use; it grows the file only when no free run fits.
type extentAllocatorV3 struct {
used map[uint64]bool
end uint64 // page index just past the file's last page
next uint64 // scan start: pages below it were found used or allocated
}
func newExtentAllocatorV3(used []uint64, fileBytes uint64) *extentAllocatorV3 {
a := &extentAllocatorV3{used: make(map[uint64]bool, len(used)), end: (fileBytes + 4095) / 4096}
for _, p := range used {
a.used[p] = true
}
return a
}
// alloc reserves n contiguous pages and returns the byte offset.
func (a *extentAllocatorV3) alloc(n uint64) uint64 {
run, start := uint64(0), uint64(0)
for p := a.next; p < a.end; p++ {
if a.used[p] {
run = 0
if p == a.next {
a.next++
}
continue
}
if run == 0 {
start = p
}
run++
if run == n {
for q := start; q < start+n; q++ {
a.used[q] = true
}
if start == a.next {
a.next = start + n
}
return start * 4096
}
}
if run > 0 && start+run == a.end { // a free run at the end grows in place
for q := start; q < a.end; q++ {
a.used[q] = true
}
need := n - run
for q := a.end; q < a.end+need; q++ {
a.used[q] = true
}
a.end += need
return start * 4096
}
off := a.end * 4096
for q := a.end; q < a.end+n; q++ {
a.used[q] = true
}
a.end += n
return off
}
// Stats reports the map file's size, live bytes and truncations. The live
// bytes are computed on demand from a snapshot.
func (m *chunkLSNMapV3) Stats() ChunkMapStats {
_, live := usedPagesV3(m.liveSnapshotV3())
return ChunkMapStats{FileBytes: m.live.fileBytes.Load(), LiveBytes: live, Truncations: m.live.truncations.Load()}
}
// ChunkMapStatsV3 reports the owned map file's bounded-growth counters, or
// the zero value when the store has no owned map. Close clears the map
// under lifecycleMu, so the read holds it shared.
func (s *WALStore) ChunkMapStatsV3() ChunkMapStats {
s.lifecycleMu.RLock()
defer s.lifecycleMu.RUnlock()
if s.v3 == nil || s.v3.ownedMap == nil {
return ChunkMapStats{}
}
return s.v3.ownedMap.Stats()
}
@@ -0,0 +1,508 @@
package storage
import (
"os"
"path/filepath"
"testing"
)
// Extent reuse in the owned-map file.
// Map-level schedules on a one-page map (mapDescriptorV3: one chunk), with
// the publisher's slot report driven directly so each schedule is exact.
func extentsMapV3(t *testing.T) (*chunkLSNMapV3, descriptorV3, string) {
t.Helper()
d := mapDescriptorV3(t)
path := filepath.Join(t.TempDir(), "map")
m, err := createChunkLSNMapV3(path, d, 1)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { m.Close() })
return m, d, path
}
func prepV3(t *testing.T, m *chunkLSNMapV3, g uint64, prior *chunkMapCandidateV3) *chunkMapCandidateV3 {
t.Helper()
c, err := m.Prepare(g, 7, []chunkLSNEntryV3{{LSN: 100 + g}}, prior)
if err != nil {
t.Fatalf("prepare gen %d: %v", g, err)
}
return c
}
func readsV3(t *testing.T, m *chunkLSNMapV3, d descriptorV3, c *chunkMapCandidateV3, what string) {
t.Helper()
es, _, err := readChunkLSNMapV3(m.fd, c.descriptor(d), m.chunkBlocks)
if err != nil {
t.Fatalf("%s (gen %d at %d) unreadable: %v", what, c.generation, c.rootOffset, err)
}
if es[0].LSN != 100+c.generation {
t.Fatalf("%s (gen %d) reads LSN %d", what, c.generation, es[0].LSN)
}
}
func publishV3(m *chunkLSNMapV3, d descriptorV3, cur, other *chunkMapCandidateV3) {
m.slotsPublishedV3(cur.descriptor(d), other.descriptor(d), true)
}
func mapFileSizeV3(t *testing.T, path string) int64 {
t.Helper()
fi, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
return fi.Size()
}
// Every publication leaves the previous generation in the fallback slot. Its
// root and page must stay readable after every later candidate, and the file
// stays within 8 one-page maps. Mutants: a live set without the fallback
// slot (a later candidate overwrites the fallback's extents) and an
// append-only allocator (the file grows by a page and a root per candidate).
func TestChunkMapExtentsV3FallbackRootIsNeverReused(t *testing.T) {
m, d, path := extentsMapV3(t)
prev := prepV3(t, m, 1, nil)
publishV3(m, d, prev, prev)
for g := uint64(2); g <= 60; g++ {
c := prepV3(t, m, g, prev)
publishV3(m, d, c, prev)
readsV3(t, m, d, c, "current")
readsV3(t, m, d, prev, "fallback")
prev = c
}
if size := mapFileSizeV3(t, path); size > 8*2*4096 {
t.Fatalf("map file %d B after 60 generations, bound %d B", size, 8*2*4096)
}
}
// A candidate prepared after another one that is not yet published (two
// preparers) is newer than the generation the first publication makes
// current, so it stays live and the next candidate must not reuse its
// extents. Mutant: releasing every unpublished candidate at a publication
// overwrites it.
func TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused(t *testing.T) {
m, d, _ := extentsMapV3(t)
c1 := prepV3(t, m, 1, nil)
publishV3(m, d, c1, c1)
c2 := prepV3(t, m, 2, c1)
c3 := prepV3(t, m, 3, c1) // a second preparer, not yet published
publishV3(m, d, c2, c1)
c4 := prepV3(t, m, 4, c2)
readsV3(t, m, d, c3, "in-flight gen 3")
readsV3(t, m, d, c4, "gen 4")
readsV3(t, m, d, c1, "fallback")
}
// A crash after a candidate was written into reused extents but before any
// publication named it: the reopen of the selected slot and its fallback
// reads both intact, because a candidate only ever takes extents no slot
// names.
func TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent(t *testing.T) {
m, d, path := extentsMapV3(t)
prev := prepV3(t, m, 1, nil)
publishV3(m, d, prev, prev)
var cur *chunkMapCandidateV3
for g := uint64(2); g <= 10; g++ {
cur = prepV3(t, m, g, prev)
publishV3(m, d, cur, prev)
prev, cur = cur, prev
}
cur, prev = prev, cur // cur = gen 10, prev = gen 9
orphan := prepV3(t, m, 11, cur)
if orphan.rootOffset+4096 >= uint64(mapFileSizeV3(t, path)) {
t.Fatalf("setup: gen 11's root at %d did not reuse a freed extent", orphan.rootOffset)
}
if err := m.Close(); err != nil {
t.Fatal(err)
}
r, rc, err := openChunkLSNMapV3(path, cur.descriptor(d), 1)
if err != nil {
t.Fatalf("reopen of the selected slot after the crash: %v", err)
}
defer r.Close()
if rc.entries[0].LSN != 100+cur.generation {
t.Fatalf("selected slot reads LSN %d", rc.entries[0].LSN)
}
if _, _, err := readChunkLSNMapV3(r.fd, prev.descriptor(d), 1); err != nil {
t.Fatalf("fallback after the crash: %v", err)
}
}
// Truncation while the fallback slot's root lies at the file's tail: a burst
// of unpublished candidates raises the high-water mark; the fallback then is
// the highest of them and the current one lands low. The next candidate
// must not truncate below the fallback; once a later publication releases
// it, the free tail is truncated. Mutant: truncating above the lowest live
// page cuts the fallback's root away.
func TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail(t *testing.T) {
m, d, path := extentsMapV3(t)
c := prepV3(t, m, 1, nil)
publishV3(m, d, c, c)
var burst []*chunkMapCandidateV3
for g := uint64(2); g <= 21; g++ {
burst = append(burst, prepV3(t, m, g, c)) // unpublished: the file grows
}
top := burst[len(burst)-1] // gen 21, the highest extents
publishV3(m, d, top, c) // releases gens 2..20
low := prepV3(t, m, 22, top)
if low.rootOffset > top.rootOffset {
t.Fatalf("setup: gen 22 at %d did not land below gen 21 at %d", low.rootOffset, top.rootOffset)
}
publishV3(m, d, low, top) // fallback = gen 21 at the tail
next := prepV3(t, m, 23, low)
readsV3(t, m, d, top, "fallback at the tail")
publishV3(m, d, next, low) // releases gen 21
before := mapFileSizeV3(t, path)
last := prepV3(t, m, 24, next)
readsV3(t, m, d, last, "gen 24")
readsV3(t, m, d, next, "gen 23")
if after := mapFileSizeV3(t, path); after >= before || m.Stats().Truncations == 0 {
t.Fatalf("free tail not truncated: %d B -> %d B, truncations %d", before, after, m.Stats().Truncations)
}
}
// Repeated publications refused before any slot I/O (a stale proof) release
// their candidates at once, so the file and the live set stay bounded.
// Mutant: no definite-abandon path keeps every rejected candidate pinned
// until a later successful publication and the file grows by a root each.
func TestChunkMapExtentsV3RejectedPublicationsStayBounded(t *testing.T) {
s, path := newMappedCheckpointStoreV3(t)
writeSynced(t, s, 1, 1)
if err := s.flusher.flushOnceInternal(false); err != nil {
t.Fatal(err)
}
cp := s.v3.pub.current().CheckpointLSN
for i := 0; i < 300; i++ {
prepared, err := s.prepareOwnedMapCheckpointV3(cp)
if err != nil {
t.Fatalf("prepare %d: %v", i, err)
}
if err := s.v3.pub.invalidateMapProofV3(); err != nil {
t.Fatal(err)
}
if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err == nil {
t.Fatal("a stale-proof publication succeeded")
}
}
st := s.ChunkMapStatsV3()
fi, err := os.Stat(path + ".chunkmap")
if err != nil {
t.Fatal(err)
}
if fi.Size() > 8*2*4096 || st.LiveBytes > 4*2*4096 {
t.Fatalf("after 300 rejected publications: file %d B, live %d B", fi.Size(), st.LiveBytes)
}
}
// damageNewestSlotV3 corrupts the slot with the higher generation so the
// next open selects the fallback slot.
func damageNewestSlotV3(t *testing.T, path string) {
t.Helper()
f, err := os.OpenFile(path, os.O_RDWR, 0)
if err != nil {
t.Fatal(err)
}
defer f.Close()
var gens [2]uint64
offs := [2]int64{slotAOffsetV3, slotBOffsetV3}
for i, off := range offs {
b := make([]byte, slotSizeV3)
if _, err := f.ReadAt(b, off); err != nil {
t.Fatal(err)
}
if d, err := decodeSlotV3(b, nil); err == nil {
gens[i] = d.SlotGen
}
}
off := offs[0]
if gens[1] > gens[0] {
off = offs[1]
}
if _, err := f.WriteAt([]byte{0xFF, 0xFF, 0xFF, 0xFF}, off+64); err != nil {
t.Fatal(err)
}
if err := f.Sync(); err != nil {
t.Fatal(err)
}
}
// A real two-slot reopen registers BOTH slot roots read from disk, so a
// candidate prepared before the open's first publication (which would
// re-report both slots) cannot take the fallback root's extents. The
// candidates are prepared right after the open, none is published, and the
// store crashes; with the newest slot damaged, the reopen selects the
// fallback slot and its map must validate. Mutant: an open that does not
// register the fallback slot's root lets the candidates overwrite it.
func TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot(t *testing.T) {
path := filepath.Join(t.TempDir(), "mapped")
s, err := createMappedWALStoreV3ForTest(path, 64, 4096, v3TestWAL, WModeStrict, 4)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
for i := uint32(0); i < 10; i++ {
writeSynced(t, s, i, i)
if err := s.flusher.flushOnceInternal(false); err != nil {
t.Fatal(err)
}
}
// One more map publication without the checkpoint's rollover, so the two
// slots name different map roots at the crash.
writeSynced(t, s, 12, 12)
prepared, err := s.prepareOwnedMapCheckpointV3(s.v3.pub.current().CheckpointLSN)
if err != nil {
t.Fatal(err)
}
if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil {
t.Fatal(err)
}
crashRecoveryHardeningStore(t, s)
r, err := openWALStoreV3ForTest(path)
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
cp := r.v3.pub.current().CheckpointLSN
r.v3.pub.descMu.Lock()
cur, other, otherValid := r.v3.pub.cur, r.v3.pub.other, r.v3.pub.otherValid
r.v3.pub.descMu.Unlock()
if !otherValid || cur.MapGeneration == other.MapGeneration {
t.Fatalf("setup: slots name map generations %d and %d (fallback valid %v)", cur.MapGeneration, other.MapGeneration, otherValid)
}
for i := 0; i < 20; i++ { // unpublished candidates fill every free extent
if _, err := r.prepareOwnedMapCheckpointV3(cp); err != nil {
t.Fatal(err)
}
}
crashRecoveryHardeningStore(t, r)
damageNewestSlotV3(t, path)
q, err := openWALStoreV3ForTest(path)
if err != nil {
t.Fatalf("reopen from the fallback slot: %v", err)
}
q.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { crashRecoveryHardeningStore(t, q) })
if _, err := q.Recover(); err != nil {
t.Fatalf("recover from the fallback slot: %v", err)
}
}
// A failed fsync of the tail truncation itself (the first fsync of the
// prepare) latches the map: the prepare and every later one fail. The slot
// roots stay readable, because the truncation only removes extents above
// the highest live page.
func TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots(t *testing.T) {
m, d, path := extentsMapV3(t)
c := prepV3(t, m, 1, nil)
publishV3(m, d, c, c)
var top *chunkMapCandidateV3
for g := uint64(2); g <= 21; g++ {
top = prepV3(t, m, g, c)
}
publishV3(m, d, top, c)
low := prepV3(t, m, 22, top)
publishV3(m, d, low, top)
next := prepV3(t, m, 23, low)
publishV3(m, d, next, low) // gen 21 released: the tail is free
before := mapFileSizeV3(t, path)
orig, calls := m.syncFile, 0
m.syncFile = func() error {
calls++
if calls == 1 {
return os.ErrInvalid // the truncation's fsync
}
return orig()
}
if _, err := m.Prepare(24, 7, []chunkLSNEntryV3{{LSN: 124}}, next); err == nil {
t.Fatal("prepare across a failed truncation fsync succeeded")
}
if calls != 1 || mapFileSizeV3(t, path) >= before {
t.Fatalf("setup: %d fsyncs, file %d B -> %d B; want the truncation's fsync to fail", calls, before, mapFileSizeV3(t, path))
}
if got, want := m.Stats().FileBytes, uint64(mapFileSizeV3(t, path)); got != want {
t.Fatalf("stats after a truncation whose fsync failed: file bytes %d, file is %d B", got, want)
}
if _, err := m.Prepare(25, 7, []chunkLSNEntryV3{{LSN: 125}}, next); err == nil || calls != 1 {
t.Fatalf("the map did not latch: err %v, fsyncs %d", err, calls)
}
if err := m.Close(); err != nil {
t.Fatal(err)
}
r, rc, err := openChunkLSNMapV3(path, next.descriptor(d), 1)
if err != nil {
t.Fatalf("reopen after the truncation fault: %v", err)
}
defer r.Close()
if rc.entries[0].LSN != 100+next.generation {
t.Fatalf("selected root reads LSN %d", rc.entries[0].LSN)
}
if _, _, err := readChunkLSNMapV3(r.fd, low.descriptor(d), 1); err != nil {
t.Fatalf("fallback after the truncation fault: %v", err)
}
}
// A publication whose slot I/O failed leaves an uncertain candidate: the
// publisher latches and the candidate stays pinned until reopen. A later
// admitted prepare must not reuse its extents, and both the uncertain
// candidate and the slot roots stay readable. Mutant: abandoning the
// uncertain candidate like a refused one lets the later prepare overwrite it.
func TestChunkMapExtentsV3UncertainCandidateStaysPinned(t *testing.T) {
s, _ := newMappedCheckpointStoreV3(t)
writeSynced(t, s, 1, 1)
cp := s.v3.pub.current().CheckpointLSN
prepared, err := s.prepareOwnedMapCheckpointV3(cp)
if err != nil {
t.Fatal(err)
}
s.v3.testBeforeSlotWrite = func() error { return os.ErrInvalid }
if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err == nil {
t.Fatal("a publication with a failed slot write succeeded")
}
s.v3.testBeforeSlotWrite = nil
m := s.v3.ownedMap
unc := prepared.candidate
for i := 0; i < 5; i++ { // admitted prepares after the failure
if _, err := m.prepareNextV3(cp, append([]chunkLSNEntryV3(nil), s.v3.mapEntries...), unc); err != nil {
t.Fatalf("admitted prepare %d: %v", i, err)
}
}
d := s.v3.pub.current()
if _, _, err := readChunkLSNMapV3(m.fd, unc.descriptor(d), m.chunkBlocks); err != nil {
t.Fatalf("uncertain candidate overwritten: %v", err)
}
if _, _, err := readChunkLSNMapV3(m.fd, d, m.chunkBlocks); err != nil {
t.Fatalf("selected slot root overwritten: %v", err)
}
}
// ChunkMapStatsV3 is correct right after a reopen: the file size and the
// live bytes of the two slot roots read from disk, not zero.
func TestChunkMapExtentsV3StatsAfterReopen(t *testing.T) {
path := filepath.Join(t.TempDir(), "mapped")
s, err := createMappedWALStoreV3ForTest(path, 64, 4096, v3TestWAL, WModeStrict, 4)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
for i := uint32(0); i < 5; i++ {
writeSynced(t, s, i, i)
if err := s.flusher.flushOnceInternal(false); err != nil {
t.Fatal(err)
}
}
crashRecoveryHardeningStore(t, s)
fi, err := os.Stat(path + ".chunkmap")
if err != nil {
t.Fatal(err)
}
r, err := openWALStoreV3ForTest(path)
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { crashRecoveryHardeningStore(t, r) })
st := r.ChunkMapStatsV3()
if st.FileBytes != uint64(fi.Size()) || st.LiveBytes == 0 || st.LiveBytes > st.FileBytes {
t.Fatalf("stats after reopen: %+v, file %d B", st, fi.Size())
}
}
// A candidate that is prepared successfully but whose proof went stale
// during its file I/O (a guest write changed the map meanwhile) is
// refused before publication and must be released at once, so a steady
// stream of such refusals keeps the file bounded. Both preparation paths
// are covered: the checkpoint's and prepareMapPublicationV3. Mutant: not
// abandoning after the proof check pins every refused candidate.
func TestChunkMapExtentsV3ProofStalePreparesStayBounded(t *testing.T) {
s, path := newMappedCheckpointStoreV3(t)
writeSynced(t, s, 1, 1)
if err := s.flusher.flushOnceInternal(false); err != nil {
t.Fatal(err)
}
m := s.v3.ownedMap
orig := m.syncFile
m.syncFile = func() error { // the proof goes stale during the prepare's I/O
if err := s.v3.mapProof.mutatedV3(); err != nil {
return err
}
return orig()
}
cp := s.v3.pub.current().CheckpointLSN
for i := 0; i < 150; i++ {
if _, err := s.prepareOwnedMapCheckpointV3(cp); err != ErrMapCoverageStale {
t.Fatalf("checkpoint prepare %d: err = %v, want ErrMapCoverageStale", i, err)
}
}
g := s.v3.pub.current().MapGeneration
for i := 0; i < 150; i++ {
g += 1000
entries := append([]chunkLSNEntryV3(nil), s.v3.mapEntries...)
if _, err := prepareMapPublicationV3(m, s.v3.mapProof, g, cp, entries, nil); err != ErrMapCoverageStale {
t.Fatalf("publication prepare %d: err = %v, want ErrMapCoverageStale", i, err)
}
}
m.syncFile = orig
fi, err := os.Stat(path + ".chunkmap")
if err != nil {
t.Fatal(err)
}
if st := s.ChunkMapStatsV3(); fi.Size() > 8*2*4096 || st.LiveBytes > 4*2*4096 {
t.Fatalf("after 300 proof-stale prepares: file %d B, live %d B", fi.Size(), st.LiveBytes)
}
}
// A publication whose slot write and fsync both happened, but which a fault
// latched meanwhile refuses at its success boundary, may be named by the
// slot on disk. Its candidate stays pinned: an already admitted preparer
// does not reuse its extents, and after a crash the reopen selects that
// slot and its map validates. Mutant: treating that refusal like one before
// slot I/O abandons the candidate and the preparer overwrites it.
func TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned(t *testing.T) {
path := filepath.Join(t.TempDir(), "mapped")
s, err := createMappedWALStoreV3ForTest(path, 64, 4096, v3TestWAL, WModeStrict, 4)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
for i := uint32(0); i < 4; i++ {
writeSynced(t, s, i, i)
if err := s.flusher.flushOnceInternal(false); err != nil {
t.Fatal(err)
}
}
writeSynced(t, s, 9, 9)
cp := s.v3.pub.current().CheckpointLSN
prepared, err := s.prepareOwnedMapCheckpointV3(cp)
if err != nil {
t.Fatal(err)
}
orig := s.v3.pub.io.fsync
s.v3.pub.io.fsync = func() error { // the slot reaches disk, then a fault latches
err := orig()
s.latchV3(os.ErrInvalid)
return err
}
if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err == nil {
t.Fatal("a publication refused at its success boundary returned no error")
}
s.v3.pub.io.fsync = orig
m := s.v3.ownedMap
for i := 0; i < 10; i++ { // an already admitted preparer keeps going
entries := append([]chunkLSNEntryV3(nil), s.v3.mapEntries...)
entries[0].LSN += uint64(i + 1)
if _, err := m.prepareNextV3(cp, entries, prepared.candidate); err != nil {
t.Fatalf("admitted prepare %d: %v", i, err)
}
}
crashRecoveryHardeningStore(t, s)
r, err := openWALStoreV3ForTest(path)
if err != nil {
t.Fatalf("reopen of the durable slot: %v", err)
}
r.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { crashRecoveryHardeningStore(t, r) })
if g := r.v3.pub.current().MapGeneration; g != prepared.candidate.generation {
t.Fatalf("reopen selected map generation %d, want the durable one %d", g, prepared.candidate.generation)
}
}
@@ -65,6 +65,7 @@ func prepareMapPublicationV3(m *chunkLSNMapV3, d *mapProofEpochV3, g, C uint64,
return nil, e
}
if !proof.validV3(d) {
m.abandonCandidateV3(c) // prepared but never publishable
return nil, ErrMapCoverageStale
}
return &preparedMapPublicationV3{candidate: c, proof: proof}, nil
@@ -137,7 +138,7 @@ func (p *descriptorPublisherV3) publishMapV3(storeMu sync.Locker, snap func(), p
if prepared == nil || prepared.candidate == nil {
return descriptorV3{}, ErrMapCoverageStale
}
return p.publishWithMapV3(storeMu, snap, func(d *descriptorV3) error {
d, err := p.publishWithMapV3(storeMu, snap, func(d *descriptorV3) error {
if mutate != nil {
if e := mutate(d); e != nil {
return e
@@ -146,6 +147,18 @@ func (p *descriptorPublisherV3) publishMapV3(storeMu sync.Locker, snap func(), p
*d = prepared.candidate.descriptor(*d)
return nil
}, prepared)
if err != nil {
// Definite abandon: unless the slot I/O started (the candidate is
// the uncertain one, pinned until reopen), no slot can name it.
c := prepared.candidate
p.descMu.Lock()
unc := p.uncertain
if unc == nil || unc.MapRootLocator != c.rootOffset || unc.MapGeneration != c.generation {
prepared.abandonV3()
}
p.descMu.Unlock()
}
return d, err
}
// invalidateMapProofV3 is called under WALStore.mu at a lifecycle boundary.
@@ -187,7 +200,12 @@ func openDescriptorMapV3(path string, selected descriptorV3, fallback *descripto
if fallback.UUID != selected.UUID || fallback.MapLineage != selected.MapLineage || !sameGeometryV3(*fallback, selected) {
err = ErrMapInvalid
} else {
_, _, err = readChunkLSNMapV3(m.fd, *fallback, cb)
var refs []mapPageRefV3
if _, refs, err = readChunkLSNMapV3(m.fd, *fallback, cb); err == nil {
if sh, e := mapShapeForV3(*fallback, cb); e == nil {
m.registerRootV3(fallback.MapGeneration, fallback.MapRootLocator, sh.aligned, refs)
}
}
}
if err != nil {
_ = m.Close()
@@ -0,0 +1,41 @@
package storage
import (
"os"
"testing"
)
// The v3 owned-map file must stay bounded under steady writes. Each cycle
// writes, syncs and checkpoints, so every cycle publishes a new map
// generation with a changed page. After 300 checkpoints the file must not
// exceed a small multiple of one full map (pages + root, each 4 KiB
// aligned): the live map of the two descriptor slots plus one in-flight
// candidate, with slack.
func TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints(t *testing.T) {
s, path := newMappedCheckpointStoreV3(t)
shape, err := mapShapeForV3(s.v3.pub.current(), s.v3.ownedMap.chunkBlocks)
if err != nil {
t.Fatal(err)
}
rootBytes := (120 + 40*shape.pages + 4095) &^ 4095
fullMap := int64(shape.pages*4096 + rootBytes)
bound := 8 * fullMap
const cycles = 300
for i := 0; i < cycles; i++ {
writeSynced(t, s, uint32(i%64), uint32(i%64))
if err := s.flusher.flushOnceInternal(false); err != nil {
t.Fatal(err)
}
}
gen := s.v3.pub.current().MapGeneration
if gen < cycles {
t.Fatalf("setup: %d map generations after %d checkpoint cycles", gen, cycles)
}
fi, err := os.Stat(path + ".chunkmap")
if err != nil {
t.Fatal(err)
}
if fi.Size() > bound {
t.Fatalf("chunkmap is %d B after %d generations; bound %d B (8 x one full map of %d B)", fi.Size(), gen, bound, fullMap)
}
}
+12 -1
View File
@@ -257,8 +257,12 @@ func (p *descriptorPublisherV3) publishLockedCoreV3(mutate func(next *descriptor
return descriptorV3{}, err // refused before any I/O (a latched fault)
}
// Success boundary: a fault latched by another path while this
// publication was in flight still refuses it (#172).
// publication was in flight still refuses it (#172). The slot write and
// its fsync did happen, so the slot on disk may name this generation:
// its dependencies stay pinned as an uncertain candidate until reopen.
if err := p.io.sticky(); err != nil {
uncertain := next
p.uncertain = &uncertain
return descriptorV3{}, err
}
p.other, p.otherValid = p.cur, true
@@ -266,6 +270,13 @@ func (p *descriptorPublisherV3) publishLockedCoreV3(mutate func(next *descriptor
if prepared != nil {
p.mapCurrent = prepared.candidate
}
// Report the slot tuples to the owned map (descMu -> liveMu): roots
// neither slot names any more, and superseded candidates, are released.
// A publication before the map is bound reports nothing; that only
// delays a release until the next report.
if p.mapCurrent != nil && p.mapCurrent.owner != nil {
p.mapCurrent.owner.slotsPublishedV3(p.cur, p.other, p.otherValid)
}
return next, nil
}
@@ -44,6 +44,7 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati
return nil, err
}
if !proof.validV3(domain) {
v.ownedMap.abandonCandidateV3(c) // prepared but never publishable
return nil, ErrMapCoverageStale
}
return &preparedMapPublicationV3{candidate: c, proof: proof}, nil
@@ -116,6 +117,7 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64)
// The candidate proof alone is insufficient: it was prepared after extent
// I/O and could belong to a newer Recover lifetime than those bytes.
if !v.flushLifetimeValidV3(recoveryGen) {
prepared.abandonV3()
return descriptorV3{}, ErrMapCoverageStale
}
wack := v.wack.Load()
@@ -123,6 +125,7 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64)
wack = max(wack, cp)
}
if wack < cp {
prepared.abandonV3()
return descriptorV3{}, ErrMapCoverageStale
}
s.mu.RLock()
+2 -2
View File
@@ -337,7 +337,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB |
| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB |
| `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB |
| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Append-only retention preserves both slots and pending candidates. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB |
| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB |
| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB |
| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB |
@@ -357,7 +357,7 @@ Notes:
- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. Writes invalidate proofs before append and update per-chunk max LSN under store.mu, while Recover rebuilds that volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads.
- `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. No sidecar page reclamation is implemented, so fallback or uncertain generations remain pinned conservatively.
- `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. Sidecar extents are reused only after neither slot nor a pending or uncertain candidate references them; see `chunk_map_extents_v3.go` and its tests.
- `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only.
- `INV-FE-FLUSH-SYNC-001`: NVMe/TCP also asserts failed-Sync status and reason logging through the actual session dispatch, and success produces no failure log.