diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go new file mode 100644 index 0000000000..4ddf562718 --- /dev/null +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -0,0 +1,705 @@ +package storage + +import ( + "bytes" + "encoding/binary" + "errors" + "path/filepath" + "testing" + "time" +) + +func TestChunkLayerV3_CheckpointProgressUnderContinuousAppends(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + remote := newFakeChunkRemote() + mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(0, blk(1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + realSync := s.v3.ownedMap.syncFile + t.Cleanup(func() { s.v3.ownedMap.syncFile = realSync }) + refusals := 0 + previousCP := uint64(0) + for round := uint32(0); round < 8; round++ { + injected := false + s.v3.ownedMap.syncFile = func() error { + if !injected { + injected = true + if _, err := s.Write(round+1, blk(byte(round+2))); err != nil { + return err + } + } + return realSync() + } + err := s.flusher.flushOnce() + s.v3.ownedMap.syncFile = realSync + if err != nil && !errors.Is(err, ErrMapCoverageStale) { + t.Fatal(err) + } + if errors.Is(err, ErrMapCoverageStale) { + refusals++ + } + if !injected { + t.Fatal("cycle did not overlap a write") + } + if cp := s.CheckpointLSN(); cp <= previousCP { + t.Fatalf("cycle %d: checkpoint %d did not advance beyond %d", round, cp, previousCP) + } else { + previousCP = cp + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + cp := s.CheckpointLSN() + t.Logf("continuous writes: cycles8 refusals%d cp%d wack%d dirty%d", refusals, cp, s.v3.wack.Load(), s.dm.len()) + if cp == 0 { + t.Fatal("checkpoint made no progress across eight completed extent/map persistence cycles while newer appends continued") + } +} + +func TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + remote := newFakeChunkRemote() + layer := mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(1, blk(0x11)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + s.v3.testMapPrepared = func() { + if _, err := s.WriteBatch(1, [][]byte{blk(0xB2), blk(0xC3)}); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + s.v3.testMapPrepared = nil + d := s.v3.pub.current() + if d.CheckpointLSN != 1 || d.MapCoveredCheckpoint != 1 || s.dm.len() != 2 { + t.Fatalf("prefix cp=%d C=%d dirty=%d", d.CheckpointLSN, d.MapCoveredCheckpoint, s.dm.len()) + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err = r.Recover(); err != nil { + t.Fatal(err) + } + for lba, want := range map[uint32][]byte{1: blk(0xB2), 2: blk(0xC3)} { + if !bytes.Equal(readV3(t, r, lba), want) { + t.Fatalf("replayed LBA%d lost", lba) + } + } + restored := mustAttach(t, r, remote, ctConfig(1)) + cut, err := restored.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + image := remote.imageOf(t, cut.Head) + if !bytes.Equal(image[4096:8192], blk(0xB2)) || !bytes.Equal(image[8192:12288], blk(0xC3)) { + t.Fatal("capture omitted newer replayed batch") + } +} + +func TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + h := beginV3(t, s, 0, idA) + cp := s.CheckpointLSN() + prepared, err := s.prepareOwnedMapCheckpointV3(cp) + if err != nil { + t.Fatal(err) + } + before := s.v3.pub.current() + if err = h.WriteBase(1, blk(0xA7)); err != nil { + t.Fatal(err) + } + if _, err = s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("effective BASE mutation proof accepted: %v", err) + } + if s.v3.pub.current() != before { + t.Fatal("stale BASE candidate changed slots") + } +} + +// Removing append-driven increments must not bypass terminal exhaustion. +func TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend(t *testing.T) { + for _, batch := range []bool{false, true} { + s, _ := newMappedCheckpointStoreV3(t) + before := s.NextLSN() + s.v3.mapProof.mutation.Store(counterMaxV3) + var err error + if batch { + _, err = s.WriteBatch(1, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.Write(1, blk(1)) + } + if !errors.Is(err, ErrCounterExhausted) || s.NextLSN() != before || s.dm.len() != 0 { + t.Fatalf("exhaustion bypassed: batch=%t err=%v next=%d dirty=%d", batch, err, s.NextLSN(), s.dm.len()) + } + } +} + +// A write's real fallback rollover can run after a map candidate was prepared. +// It preserves the older prefix and the later append remains available to replay. +func TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(1) + writeSynced(t, s, 1, 2) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(2) + if err != nil { + t.Fatal(err) + } + tail := s.v3.w.reclaimThroughV3(2) + before := s.v3.pub.current() + if tail <= before.RetainedTail { + t.Fatal("setup: no releasable retained record") + } + // One real slot publication advances the current tail only. The next Write + // must bring the fallback forward before it can reuse that released range. + if _, err := s.v3.pub.publish(nil, nil, func(d *descriptorV3) error { + d.RetainedTail = tail + d.RetainedHead = max(d.RetainedHead, tail) + return nil + }); err != nil { + t.Fatal(err) + } + current, floor, ok := s.v3.pub.walSnapshotV3() + if !ok || floor >= tail { + t.Fatal("setup: fallback did not pin rollover") + } + if lsn, err := s.Write(3, blk(0xD3)); err != nil || lsn != 3 { + t.Fatalf("write: lsn %d err %v", lsn, err) + } + after := s.v3.pub.current() + if after.SlotGen != current.SlotGen+1 { + t.Fatal("Write did not execute the fallback rollover") + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatalf("prefix publication after rollover: %v", err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + d, floor, ok := s.v3.pub.walSnapshotV3() + if !ok || d.CheckpointLSN != 2 || d.MapCoveredCheckpoint != 2 || d.W < 3 || floor != tail || d.RetainedTail != tail { + t.Fatalf("prefix/suffix boundary: cp%d C%d W%d floor%d tail%d want%d", d.CheckpointLSN, d.MapCoveredCheckpoint, d.W, floor, d.RetainedTail, tail) + } + s.SetRecoveryRetentionLSNs(1) + var scanned []RecoveryEntry + if err := s.ScanLBAs(3, func(e RecoveryEntry) error { scanned = append(scanned, e); return nil }); err != nil || len(scanned) != 1 || scanned[0].LSN != 3 || !bytes.Equal(scanned[0].Data, blk(0xD3)) { + t.Fatalf("retained suffix: %+v err %v", scanned, err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if !bytes.Equal(readV3(t, r, 3), blk(0xD3)) { + t.Fatal("retained suffix lost after reopen") + } +} + +func TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix(t *testing.T) { + path := filepath.Join(t.TempDir(), "hydrating") + s, err := createMappedWALStoreV3ForTest(path, ctNumBlocks, ctBlockSize, v3TestWAL, WModeStrict, ctChunkBlocks) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + image := make([]byte, ctNumBlocks*ctBlockSize) + copy(image[9*ctBlockSize:], blk(0xA9)) + remote := newFakeChunkRemote() + remote.seedHead(t, image, 10, 1) + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + layer := mustAttach(t, s, remote, cfg).(*chunkLayerImpl) + prepared, err := s.prepareOwnedMapCheckpointV3(10) + if err != nil { + t.Fatal(err) + } + layer.stMu.Lock() + absent := layer.absent[2] + layer.stMu.Unlock() + if !absent { + t.Fatal("setup: chunk is not absent") + } + if got, err := s.Read(9); err != nil || !bytes.Equal(got, blk(0xA9)) { + t.Fatalf("lazy read: %v", err) + } + layer.stMu.Lock() + absent = layer.absent[2] + layer.stMu.Unlock() + if absent { + t.Fatal("read did not hydrate chunk") + } + if !prepared.proof.validV3(s.v3.mapProof) { + t.Fatal("lazy fill invalidated the checkpoint prefix") + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatalf("publish after lazy fill: %v", err) + } +} + +// At every cycle the ring reaches the real admission soft-pressure range. +// An append overlaps map persistence, yet each completed cycle must reclaim; +// none may require a cut or new remote HEAD to escape repeated proof refusal. +func TestChunkLayerV3_CheckpointProgressAtWALPressure(t *testing.T) { + for _, mode := range []WMode{WModeStrict, WModeLagged} { + t.Run(map[WMode]string{WModeStrict: "A", WModeLagged: "C"}[mode], func(t *testing.T) { + path := filepath.Join(t.TempDir(), "pressure") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 64*1024, mode, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + realSync := s.v3.ownedMap.syncFile + t.Cleanup(func() { s.v3.ownedMap.syncFile = realSync }) + previousCP := uint64(0) + expected := make(map[uint32][]byte) + write := func() error { + lsn := s.NextLSN() + lba := uint32(lsn % 64) + data := checkpointProgressBlock(lsn) + if _, err := s.Write(lba, data); err != nil { + return err + } + expected[lba] = data + return nil + } + for cycle := 0; cycle < 8; cycle++ { + for s.walUsedFraction() < 0.72 { + if err := write(); err != nil { + t.Fatal(err) + } + } + injected := false + s.v3.ownedMap.syncFile = func() error { + if !injected { + injected = true + if err := write(); err != nil { + return err + } + } + return realSync() + } + err := s.flusher.flushOnce() + s.v3.ownedMap.syncFile = realSync + if err != nil { + t.Fatalf("pressure cycle%d: %v", cycle, err) + } + cp := s.CheckpointLSN() + if !injected || cp <= previousCP { + t.Fatalf("no progress cycle%d cp%d previous%d", cycle, cp, previousCP) + } + previousCP = cp + } + floor, ok := s.v3.pub.reuseFloor() + if !ok || floor < 5*64*1024 { + t.Fatalf("no sustained ring reuse: floor%d", floor) + } + for lba, want := range expected { + if got, err := s.Read(lba); err != nil || !bytes.Equal(got, want) { + t.Fatalf("no-Flush readback LBA%d: %v", lba, err) + } + } + t.Logf("no client Sync: cycles8 checkpoint%d floor%d busy0", previousCP, floor) + }) + } +} + +func checkpointProgressBlock(lsn uint64) []byte { + data := make([]byte, 4096) + for i := 0; i < len(data); i += 8 { + binary.LittleEndian.PutUint64(data[i:i+8], lsn*4096+uint64(i)) + } + return data +} + +// An active history pin gives one bounded, typed refusal; local flusher work +// after releasing it restores progress without a client Sync or new remote cut. +func TestCheckpointV3_NoFlushPressureWithRealPin(t *testing.T) { + path := filepath.Join(t.TempDir(), "pinned") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 64*1024, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 0, anyActive: true}) + expected := make(map[uint32][]byte) + for s.walUsedFraction() < 0.90 { + lsn := s.NextLSN() + lba := uint32(lsn) + data := checkpointProgressBlock(lsn) + if _, err := s.Write(lba, data); err != nil { + t.Fatal(err) + } + expected[lba] = data + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if s.CheckpointLSN() != 0 || s.v3.wack.Load() == 0 { + t.Fatal("real retention pin did not constrain an internally synced checkpoint") + } + next := s.NextLSN() + start := time.Now() + _, err = s.Write(uint32(next), checkpointProgressBlock(next)) + elapsed := time.Since(start) + if !errors.Is(err, ErrWALPressureTimeout) || elapsed >= 5*time.Second || s.NextLSN() != next { + t.Fatalf("pinned busy: err%v elapsed%v next%d want%d", err, elapsed, s.NextLSN(), next) + } + count := 0 + if err := s.ScanLBAs(1, func(e RecoveryEntry) error { + count++ + if e.LSN != uint64(count) || !bytes.Equal(e.Data, expected[e.LBA]) { + return errors.New("pinned retained prefix differs from submitted bytes") + } + return nil + }); err != nil || count != len(expected) { + t.Fatalf("pinned exact prefix count%d want%d: %v", count, len(expected), err) + } + s.SetRecycleFloorSource(nil) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } // no Write/Sync wakes it + if s.CheckpointLSN() != next-1 { + t.Fatal("released pin did not permit passive local checkpoint progress") + } + if lsn, err := s.Write(uint32(next), checkpointProgressBlock(next)); err != nil || lsn != next { + t.Fatalf("retry: %d %v", lsn, err) + } + expected[uint32(next)] = checkpointProgressBlock(next) + for lba, want := range expected { + if got, err := s.Read(lba); err != nil || !bytes.Equal(got, want) { + t.Fatalf("pinned readback LBA%d: %v", lba, err) + } + } + t.Logf("busy1 elapsed%v retained%d checkpoint%d", elapsed, count, s.CheckpointLSN()) +} + +func TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(1) + writeSynced(t, s, 1, 2) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(2) + if err != nil { + t.Fatal(err) + } + tail := s.v3.w.reclaimThroughV3(2) + if _, err := s.v3.pub.publish(nil, nil, func(d *descriptorV3) error { + d.RetainedTail = tail + d.RetainedHead = max(d.RetainedHead, tail) + return nil + }); err != nil { + t.Fatal(err) + } + before := s.v3.pub.current() + _, floor, ok := s.v3.pub.walSnapshotV3() + if !ok || floor >= tail { + t.Fatal("setup: no pinned fallback") + } + injected := errors.New("append rollover slot fault") + s.v3.testBeforeSlotWrite = func() error { return injected } + _, err = s.Write(3, blk(0xD3)) + s.v3.testBeforeSlotWrite = nil + if !errors.Is(err, injected) || s.stickyIOFault() == nil || s.NextLSN() != 3 || s.dm.len() != 0 { + t.Fatalf("rollover fault: %v next%d dirty%d", err, s.NextLSN(), s.dm.len()) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err == nil { + t.Fatal("held candidate published through sticky rollover failure") + } + if s.v3.pub.current() != before { + t.Fatal("rollover fault changed authoritative tuple") + } + if nextFloor, valid := s.v3.pub.reuseFloor(); valid || nextFloor != 0 { + t.Fatal("uncertain rollover must disable reuse until reopen") + } +} + +// Max-LSN map entries may include unsynced writes above both cp and W. A +// reused LSN can then set UNKNOWN without changing the prefix proof token. +func TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + remote := newFakeChunkRemote() + layer := mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(1, blk(0xA1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if s.v3.mapEntries[0].Unknown { + t.Fatal("setup: initial definite cut did not clear UNKNOWN") + } + if _, err := s.Write(1, blk(0xA2)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, blk(0xA3)); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + e := prepared.candidate.entries[0] + if e.LSN != 3 || e.Unknown || d.CheckpointLSN != 1 || d.W != 1 { + t.Fatalf("speculative maximum: entry%+v cp%d W%d", e, d.CheckpointLSN, d.W) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatal(err) + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + damageRecord(t, path, 2) // unacknowledged record2 tears; the following3 is dropped + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if r.NextLSN() != 2 || r.v3.mapEntries[0].LSN != 3 { + t.Fatal("dropped suffix did not leave the conservative persisted maximum") + } + held, err := r.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + if held.candidate.entries[0].Unknown { + t.Fatal("setup: held candidate already UNKNOWN") + } + if lsn, err := r.Write(1, blk(0xB2)); err != nil || lsn != 2 { + t.Fatalf("reused LSN: %d %v", lsn, err) + } + if !r.v3.mapEntries[0].Unknown || r.v3.mapEntries[0].LSN != 3 { + t.Fatal("reused LSN did not conservatively set UNKNOWN beneath the high maximum") + } + if !held.proof.validV3(r.v3.mapProof) { + t.Fatal("reused ordered append invalidated the older prefix") + } + if _, err := r.v3.pub.publishMapV3(&r.mu, nil, held, nil); err != nil { + t.Fatal(err) + } + if _, err := r.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, r) + r.mu.Lock() + r.closed = true + r.mu.Unlock() + r2, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r2.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r2.Close() }) + if _, err := r2.Recover(); err != nil { + t.Fatal(err) + } + if !r2.v3.mapEntries[0].Unknown || !bytes.Equal(readV3(t, r2, 1), blk(0xB2)) { + t.Fatal("replay did not restore UNKNOWN and exact reused-LSN bytes") + } + restored := mustAttach(t, r2, remote, ctConfig(2)) + cut, err := restored.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + image := remote.imageOf(t, cut.Head) + if !bytes.Equal(image[4096:8192], blk(0xB2)) { + t.Fatal("capture treated the speculative maximum as remotely clean") + } +} + +func TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush(t *testing.T) { + for _, flush := range []bool{false, true} { + t.Run(map[bool]string{false: "wal", true: "extent"}[flush], func(t *testing.T) { + path := filepath.Join(t.TempDir(), "hydrating") + s, err := createMappedWALStoreV3ForTest(path, ctNumBlocks, ctBlockSize, v3TestWAL, WModeStrict, ctChunkBlocks) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + image := make([]byte, ctNumBlocks*ctBlockSize) + copy(image[8*ctBlockSize:], blk(0xA8)) + copy(image[9*ctBlockSize:], blk(0xA9)) + remote := newFakeChunkRemote() + remote.seedHead(t, image, 10, 1) + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + layer := mustAttach(t, s, remote, cfg) + held, err := s.prepareOwnedMapCheckpointV3(10) + if err != nil { + t.Fatal(err) + } + entered, release := holdNextGet(t, remote) + done := make(chan error, 1) + joined := make(chan struct{}) + // Release the fetch before joining, including failures before release(). + // Register before launch so store/layer cleanup never precedes the join. + t.Cleanup(func() { + release() + select { + case <-joined: + case <-time.After(ctLocalBound): + t.Errorf("held hydration reader did not settle within %v after release", ctLocalBound) + } + }) + go func() { + defer close(joined) + got, err := s.Read(9) + if err == nil && !bytes.Equal(got, blk(0xB9)) { + err = errors.New("held read did not return newer local bytes") + } + done <- err + }() + waitKey(t, entered, "cold fill before a competing local write") + within(t, "local write and optional flush while hydration is held", func() error { + if _, err := s.Write(9, blk(0xB9)); err != nil { + return err + } + if flush { + if _, err := s.Sync(); err != nil { + return err + } + return s.flusher.flushOnce() + } + return nil + }) + dirty := s.dm.len() + release() + if err := waitErr(t, done, "fill and post-miss WAL recheck"); err != nil { + t.Fatal(err) + } + if s.dm.len() != dirty || !held.proof.validV3(s.v3.mapProof) { + t.Fatal("hydration manufactured logical dirt or invalidated the prefix proof") + } + before := s.v3.pub.current() + _, err = s.v3.pub.publishMapV3(&s.mu, nil, held, nil) + if flush { + if !errors.Is(err, ErrMapCoverageStale) || s.v3.pub.current() != before { + t.Fatalf("superseded candidate after flush: %v", err) + } + } else if err != nil { + t.Fatal(err) + } + // Cover the hydrated extent bytes too before the reopen oracle. + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if !bytes.Equal(readV3(t, s, 8), blk(0xA8)) || !bytes.Equal(readV3(t, s, 9), blk(0xB9)) { + t.Fatal("HEAD fill or local write was overwritten") + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if !bytes.Equal(readV3(t, r, 8), blk(0xA8)) || !bytes.Equal(readV3(t, r, 9), blk(0xB9)) { + t.Fatal("reopen lost exact hydrated/local bytes") + } + }) + } +} + +func TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + layer := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + writeSynced(t, s, 1, 1) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + held, err := s.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + if !s.v3.mapEntries[0].Unknown { + t.Fatal("setup: no UNKNOWN to clear") + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if s.v3.mapEntries[0].Unknown { + t.Fatal("definite cut did not clear UNKNOWN") + } + // Inspect the proof itself so the newer map generation cannot mask a missing + // clear-invalidation guard in the publication refusal below. + if held.proof.validV3(s.v3.mapProof) { + t.Fatal("capture UNKNOWN clearing left the old proof valid") + } + before := s.v3.pub.current() + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, held, nil); !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("old capture proof: %v", err) + } + if s.v3.pub.current() != before { + t.Fatal("capture-stale candidate changed a slot") + } +} diff --git a/seaweed-block/core/storage/checkpoint_diagnostics_test.go b/seaweed-block/core/storage/checkpoint_diagnostics_test.go index 8ce1cbcd80..3834cecd57 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics_test.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics_test.go @@ -19,6 +19,10 @@ func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) { if _, err := s.Write(2, blk(2)); err != nil { t.Fatal(err) } + // Simulate the effective-mutation class; newer WAL appends alone are safe. + if err := s.v3.mapProof.mutatedV3(); err != nil { + t.Fatal(err) + } } before := s.v3.pub.current() err := s.flusher.flushOnce() @@ -73,6 +77,9 @@ func TestCheckpointDiagnostics_PrepareRefusalAndIOFailure(t *testing.T) { if _, err := s.Write(2, blk(2)); err != nil { t.Fatal(err) } + if err := s.v3.mapProof.mutatedV3(); err != nil { + t.Fatal(err) + } } return realSync() } diff --git a/seaweed-block/core/storage/chunk_layer_map_v3.go b/seaweed-block/core/storage/chunk_layer_map_v3.go index 295c436f5e..28b62756b0 100644 --- a/seaweed-block/core/storage/chunk_layer_map_v3.go +++ b/seaweed-block/core/storage/chunk_layer_map_v3.go @@ -9,7 +9,8 @@ func (l *chunkLayerImpl) usesOwnedMapV3() bool { return l.s.v3 != nil && l.s.v3. // (or an authority-checked no-op), outside bmMu/stMu and the capture barrier. // The capture's mutation versions were sampled under the quiesced barrier. // Store.mu prevents a WAL append from slipping between the version check and -// the UNKNOWN update. A later write updates max LSN and invalidates proofs. +// the UNKNOWN update. A later WAL append updates max LSN and stays retained; +// an effective UNKNOWN change or lifecycle transition invalidates proofs. // A failed map publication leaves the old disk UNKNOWN conservative; a map // persistence failure also latches the store, while the remote HEAD remains // the successfully captured image. No remote durability claim is undone. diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index c8273bb740..ee902f622d 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -7,6 +7,8 @@ package storage // Caller holds WALStore.mu. Higher-LSN writes update the max; a reused or // lower/equal effective LSN is conservative UNKNOWN, independent of the max. +// A reused ordered LSN below a speculative max can set UNKNOWN here without +// invalidating a prefix proof; the max and retained suffix stay conservative. // Capture is the only future owner allowed to clear UNKNOWN after a version // check. Keeping it set here cannot manufacture a remotely clean chunk. func (s *WALStore) recordMapWriteV3(lba, lsn uint64) { @@ -36,6 +38,8 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati return nil, mapCoverageRefusal("map_binding_changed") } proof := domain.snapshotV3() + // Entries may already contain LSNs above cp or W from earlier appends: max-LSN + // entries are monotone and idempotent under retained-suffix replay. entries := append([]chunkLSNEntryV3(nil), v.mapEntries...) v.pub.descMu.Unlock() s.mu.RUnlock() diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go index b479497f55..27bba23235 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go @@ -144,8 +144,10 @@ func TestWALStoreV3_PreparedCheckpointRefusesChangedProof(t *testing.T) { release() select { case err := <-done: - if !errors.Is(err, ErrMapCoverageStale) { + if event == "recover" && !errors.Is(err, ErrMapCoverageStale) { t.Errorf("stale prepared checkpoint=%v", err) + } else if event == "write" && err != nil { + t.Errorf("newer retained append invalidated prefix coverage: %v", err) } case <-time.After(5 * time.Second): t.Fatal("flusher did not settle") @@ -156,8 +158,10 @@ func TestWALStoreV3_PreparedCheckpointRefusesChangedProof(t *testing.T) { t.Fatal("flusher result without join") } s.v3.testMapPrepared = nil - if s.v3.pub.current() != before { + if event == "recover" && s.v3.pub.current() != before { t.Error("stale proof published a checkpoint") + } else if event == "write" && s.CheckpointLSN() != 1 { + t.Error("newer retained append blocked the older checkpoint") } if s.stickyIOFault() != nil { t.Error("proof refusal incorrectly latched a persistence fault") diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 95b44551c3..8e50399835 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -665,12 +665,11 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64, budget fun if s.v3.w == nil { return 0, errWALBindingV3 // a half-published reset before its Recover } - // Reserve proof invalidation before the WAL can change. This is under - // the existing store lock; a refused append only causes conservative retry. - if s.v3.mapProof != nil { - if err := s.v3.mapProof.mutatedV3(); err != nil { - return 0, err - } + // A strictly newer append stays in the retained WAL suffix. It cannot + // invalidate coverage of an older checkpoint prefix. BASE writes, capture + // UNKNOWN clearing and lifecycle mutations still invalidate at their seams. + if p := s.v3.mapProof; p != nil && p.mutation.Load() >= counterMaxV3 { + return 0, ErrCounterExhausted } if err := s.rolloverCheckpointV3Locked(); err != nil { return 0, err @@ -724,10 +723,8 @@ func (s *WALStore) writeBatchV3Locked(startLBA uint32, blocks [][]byte, firstLSN s.instr.recordWALCopy(len(payload), time.Since(copyStart)) n := uint64(len(blocks)) lastLSN := firstLSN + n - 1 - if s.v3.mapProof != nil { - if err := s.v3.mapProof.mutatedV3(); err != nil { - return nil, err - } + if p := s.v3.mapProof; p != nil && p.mutation.Load() >= counterMaxV3 { + return nil, ErrCounterExhausted } e := walEntryV3{LSN: firstLSN, BatchCount: n, Type: walEntryWriteBatch, LBA: uint64(startLBA), Length: uint32(len(payload)), Data: payload} if err := s.rolloverCheckpointV3Locked(); err != nil { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 80bd9fb7df..71a6273f44 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -338,7 +338,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | | `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-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`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`, `TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof`, `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. 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 | @@ -358,7 +358,7 @@ Notes: - `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged. - `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. -- `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-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. The entry snapshot may already contain LSNs above cp or W from pre-snapshot appends; max-LSN entries remain monotone and idempotent under replay. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. BASE writes, capture UNKNOWN clearing and lifecycle boundaries still invalidate proofs. A reused ordered LSN below a speculative retained map maximum can set UNKNOWN without invalidating the prefix; the high max and replayed retained suffix remain conservative. Recover rebuilds the 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. 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.