Merge pull request #283 from seaweedfs/feat/retire-v2-local-format

storage: retire the legacy v2 local engine
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-20 09:23:08 -08:00
commit 41142f96ba
74 files changed
+2112 -11203

No files matched your search

@@ -1,103 +0,0 @@
//go:build swblock_format_v3_test
package v2legacy
import (
"encoding/binary"
"errors"
"github.com/seaweedfs/seaweed-block/core/storage"
"os"
"path/filepath"
"testing"
)
// TODO(format-v3 row 14a): retain raw-codec controls in the default suite;
// these real v2-engine fixtures remain explicit in the tagged migration suite.
func TestReadSuperblockRefusesOtherFormats(t *testing.T) {
path := filepath.Join(t.TempDir(), "v2")
s, err := storage.CreateLegacyWALStoreTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
sb, err := ReadSuperblock(raw[:SuperblockSize])
if err != nil || sb.WALOffset != SuperblockSize || sb.BlockSize != 4096 {
t.Fatalf("real v2 superblock: %+v, %v", sb, err)
}
impl2 := append([]byte(nil), raw[:SuperblockSize]...)
binary.LittleEndian.PutUint32(impl2[92:], 2)
if _, err := ReadSuperblock(impl2); !errors.Is(err, ErrImplUnsupported) {
t.Fatalf("impl version 2: err = %v, want ErrImplUnsupported", err)
}
v3 := append([]byte(nil), raw[:SuperblockSize]...)
binary.LittleEndian.PutUint16(v3[4:], 3)
if _, err := ReadSuperblock(v3); !errors.Is(err, ErrNotV2) {
t.Fatalf("version 3: err = %v, want ErrNotV2", err)
}
}
// Real v2 stores: a cleanly closed, flushed store scans clean; a store with
// synced records that were never flushed (a crash) refuses, even though
// its superblock may say head = tail (the #156 shape: bounds not persisted
// by an ordinary Sync).
func TestScanCleanOnRealV2Stores(t *testing.T) {
scan := func(t *testing.T, path string) []Finding {
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
sb, err := ReadSuperblock(raw[:SuperblockSize])
if err != nil {
t.Fatal(err)
}
return ScanClean(raw[SuperblockSize:SuperblockSize+sb.WALSize], sb.WALCheckpointLSN)
}
blk := make([]byte, 4096)
t.Run("cleanly closed", func(t *testing.T) {
path := filepath.Join(t.TempDir(), "clean")
s, err := storage.CreateLegacyWALStoreTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
for lba := uint32(0); lba < 4; lba++ {
if _, err := s.Write(lba, blk); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
if f := scan(t, path); len(f) != 0 {
t.Fatalf("a cleanly closed v2 store refused: %+v", f[0])
}
})
t.Run("synced, never flushed", func(t *testing.T) {
path := filepath.Join(t.TempDir(), "dirty")
s, err := storage.CreateLegacyWALStoreTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
for lba := uint32(0); lba < 2; lba++ {
if _, err := s.Write(lba, blk); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if f := scan(t, path); len(f) == 0 {
t.Fatal("synced unflushed v2 records scanned clean")
}
_ = s.Close()
})
}
@@ -1,188 +0,0 @@
// Package v2legacy is the frozen v2/impl1 reader used only by the offline
// migration tool (`sw-block migrate-v3`, format bump v3, DESIGN r17.4
// section 10.1; plan row 13). It is a copy of the v2 superblock layout and
// the v2 WAL entry framing as they stand before the format bump, kept here
// so that the v3 open code holds no legacy reader and row 14 can delete the
// legacy production code. Nothing here writes, recovers or replays: the
// scan only decides whether the tool must refuse.
package v2legacy
import (
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
)
// SuperblockSize is the v2 superblock region at offset 0; the v2 WAL starts
// right after it.
const SuperblockSize = 4096
const (
magic = "SWBK"
version = 2
implWALStore = 1
implVersion1 = 1
)
var (
// ErrNotV2 is any offset-0 content that is not a v2 superblock.
ErrNotV2 = errors.New("v2legacy: offset 0 is not a v2 superblock")
// ErrImplUnsupported is a v2 superblock of another impl or impl version
// (impl 2, C12, is refused by the tool, DESIGN 10).
ErrImplUnsupported = errors.New("v2legacy: not walstore impl version 1")
)
// Superblock is the frozen v2 superblock (core/storage/superblock.go at
// format version 2).
type Superblock struct {
Version uint16
Flags uint16
UUID [16]byte
VolumeSize uint64
ExtentSize uint32
BlockSize uint32
WALOffset uint64
WALSize uint64
WALHead uint64
WALTail uint64
WALCheckpointLSN uint64
CreatedAt uint64
ImplKind uint8
ImplVersion uint32
}
// ReadSuperblock decodes and validates a v2/impl1 superblock (precondition
// 2: magic, version 2, ImplKind walstore, ImplVersion 1).
func ReadSuperblock(buf []byte) (Superblock, error) {
if len(buf) < SuperblockSize {
return Superblock{}, fmt.Errorf("%w: short header (%d bytes)", ErrNotV2, len(buf))
}
le := binary.LittleEndian
if string(buf[0:4]) != magic {
return Superblock{}, fmt.Errorf("%w: bad magic", ErrNotV2)
}
var sb Superblock
sb.Version = le.Uint16(buf[4:])
if sb.Version != version {
return Superblock{}, fmt.Errorf("%w: version %d", ErrNotV2, sb.Version)
}
sb.Flags = le.Uint16(buf[6:])
copy(sb.UUID[:], buf[8:24])
sb.VolumeSize = le.Uint64(buf[24:])
sb.ExtentSize = le.Uint32(buf[32:])
sb.BlockSize = le.Uint32(buf[36:])
sb.WALOffset = le.Uint64(buf[40:])
sb.WALSize = le.Uint64(buf[48:])
sb.WALHead = le.Uint64(buf[56:])
sb.WALTail = le.Uint64(buf[64:])
sb.WALCheckpointLSN = le.Uint64(buf[72:])
sb.CreatedAt = le.Uint64(buf[80:])
sb.ImplKind = buf[88]
sb.ImplVersion = le.Uint32(buf[92:])
switch {
case sb.VolumeSize == 0, sb.BlockSize == 0, sb.ExtentSize == 0, sb.WALSize == 0:
return Superblock{}, fmt.Errorf("%w: zero geometry field", ErrNotV2)
case sb.WALOffset != SuperblockSize:
return Superblock{}, fmt.Errorf("%w: WALOffset %d", ErrNotV2, sb.WALOffset)
case sb.VolumeSize%uint64(sb.BlockSize) != 0:
return Superblock{}, fmt.Errorf("%w: VolumeSize not block aligned", ErrNotV2)
}
if sb.ImplKind != implWALStore || sb.ImplVersion != implVersion1 {
return Superblock{}, fmt.Errorf("%w: ImplKind %d ImplVersion %d", ErrImplUnsupported, sb.ImplKind, sb.ImplVersion)
}
return sb, nil
}
// The frozen v2 WAL entry framing (core/storage/wal_entry.go): a 30-byte
// prefix LSN(8) Reserved(8) Type(1) Flags(1) LBA(8) Length(4), then the
// payload (write, batch and padding only), then CRC32-IEEE(4) over prefix
// and payload, and EntrySize(4).
const (
entryPrefix = 30
entryHeader = 38
typeWrite = 0x01
typeTrim = 0x02
typeBarrier = 0x03
typeBatch = 0x04
typePadding = 0xFF
)
// Finding is one offset of the WAL region that refuses the migration.
type Finding struct {
Offset uint64 // relative to the WAL region start
Type uint8
LSN uint64 // the record's last LSN (a batch counts by its last)
Reason string
Covered bool // LSN <= checkpoint: not a refusal (reported for tests only)
}
// ScanClean is precondition 3 of DESIGN 10.1: an exhaustive,
// refusal-biased scan of the whole v2 WAL region. It tries the frozen
// decoder at every byte offset, reading circularly so a record crossing the
// region end is tried too. An offset refuses when it decodes as a known
// type whose type-derived footprint (38 + Length for write, batch and
// padding; 38 for trim and barrier) fits in the region, whose CRC and
// EntrySize are valid, and whose last LSN is above checkpoint; or when a
// CRC-valid candidate of a known type cannot be classified (a zero or
// overflowing batch count). A CRC-valid record at or below the checkpoint
// is already in the extent and is ignored. It never runs recovery or
// replay. It returns the refusing findings, in offset order.
func ScanClean(wal []byte, checkpoint uint64) []Finding {
n := uint64(len(wal))
var out []Finding
at := func(i uint64) byte { return wal[i%n] }
read := func(off, length uint64) []byte {
b := make([]byte, length)
for i := range b {
b[i] = at(off + uint64(i))
}
return b
}
for off := uint64(0); off < n && n >= entryHeader; off++ {
typ := at(off + 16)
var payload bool
switch typ {
case typeWrite, typeBatch, typePadding:
payload = true
case typeTrim, typeBarrier:
default:
continue
}
prefix := read(off, entryPrefix)
length := uint64(binary.LittleEndian.Uint32(prefix[26:]))
footprint := uint64(entryHeader)
if payload {
footprint += length
}
if footprint > n {
continue // cannot be a record of this region
}
body := read(off, footprint)
dataEnd := footprint - 8
if binary.LittleEndian.Uint32(body[dataEnd:]) != crc32.ChecksumIEEE(body[:dataEnd]) ||
uint64(binary.LittleEndian.Uint32(body[dataEnd+4:])) != footprint {
continue
}
lsn := binary.LittleEndian.Uint64(body[0:])
last := lsn
f := Finding{Offset: off, Type: typ}
if typ == typeBatch {
count := binary.LittleEndian.Uint64(body[8:])
if count == 0 || lsn+count-1 < lsn {
f.LSN, f.Reason = lsn, "CRC-valid batch with an unclassifiable block count"
out = append(out, f)
continue
}
last = lsn + count - 1
}
f.LSN = last
if last <= checkpoint {
continue // already in the extent
}
f.Reason = fmt.Sprintf("CRC-valid v2 record type %#x with LSN %d above the checkpoint %d", typ, last, checkpoint)
out = append(out, f)
}
return out
}
@@ -1,69 +0,0 @@
package v2legacy
import (
"encoding/binary"
"hash/crc32"
"testing"
)
// Plan row 13a controls (DESIGN r17.4 section 10.1 precondition 3; owner
// claude03): the frozen v2 decoder and the exhaustive, refusal-biased scan.
// encode is a test-only encoder of the frozen v2 framing.
func encode(lsn, reserved uint64, typ uint8, lba uint64, length uint32, data []byte) []byte {
b := make([]byte, entryPrefix+len(data)+8)
le := binary.LittleEndian
le.PutUint64(b[0:], lsn)
le.PutUint64(b[8:], reserved)
b[16] = typ
le.PutUint64(b[18:], lba)
le.PutUint32(b[26:], length)
copy(b[entryPrefix:], data)
end := entryPrefix + len(data)
le.PutUint32(b[end:], crc32.ChecksumIEEE(b[:end]))
le.PutUint32(b[end+4:], uint32(entryHeader+len(data)))
return b
}
func region(n int, at int, recs ...[]byte) []byte {
w := make([]byte, n)
for _, r := range recs {
for i := range r {
w[(at+i)%n] = r[i]
}
at += len(r)
}
return w
}
func write(lsn uint64) []byte { return encode(lsn, 0, typeWrite, 1, 64, make([]byte, 64)) }
func TestScanCleanFindsEveryUnflushedV2RecordShape(t *testing.T) {
cases := []struct {
name string
wal []byte
checkpoint uint64
refuse bool
}{
{"an empty region", make([]byte, 4096), 0, false},
{"a write above the checkpoint", region(4096, 100, write(5)), 4, true},
{"a write at the checkpoint is in the extent", region(4096, 100, write(5)), 5, false},
{"a record wrapping across the region end", region(4096, 4096-50, write(9)), 0, true},
{"a trim whose affected range exceeds the region (footprint 38)", region(4096, 0, encode(7, 0, typeTrim, 0, 1<<30, nil)), 6, true},
{"a barrier above the checkpoint", region(4096, 0, encode(7, 0, typeBarrier, 0, 0, nil)), 6, true},
{"a batch counts by its last LSN", region(4096, 0, encode(3, 3, typeBatch, 0, 64, make([]byte, 64))), 4, true},
{"a batch fully below the checkpoint", region(4096, 0, encode(3, 3, typeBatch, 0, 64, make([]byte, 64))), 5, false},
{"a CRC-valid batch with a zero count is unclassifiable", region(4096, 0, encode(3, 0, typeBatch, 0, 64, make([]byte, 64))), 9, true},
{"a record embedded in another record's payload", region(4096, 0, encode(2, 0, typeWrite, 1, uint32(len(write(9))), write(9))), 5, true},
{"a corrupt CRC is no record", func() []byte { w := region(4096, 0, write(9)); w[40] ^= 0xFF; return w }(), 0, false},
{"a record larger than the region cannot be one", encode(9, 0, typeWrite, 1, 100, make([]byte, 100))[:64], 0, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got := ScanClean(c.wal, c.checkpoint)
if (len(got) > 0) != c.refuse {
t.Fatalf("findings %+v, want refuse = %v", got, c.refuse)
}
})
}
}
-3
View File
@@ -77,9 +77,6 @@ func run(args []string, stdout, stderr io.Writer) int {
fmt.Fprintln(stdout, buildinfo.Version("sw-block"))
return ops.VolumeStatusExitOK
}
if args[0] == "migrate-v3" {
return runMigrateV3(args[1:], stdout, stderr)
}
if args[0] != "ops" {
fmt.Fprintf(stderr, "sw-block: unknown command %q\n", args[0])
usage(stderr)
-269
View File
@@ -1,269 +0,0 @@
package main
import (
"encoding/hex"
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"github.com/seaweedfs/seaweed-block/cmd/sw-block/internal/v2legacy"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// `sw-block migrate-v3` (format bump v3, DESIGN r17.4 section 10.1; plan row
// 13b): the offline, in-place v2/impl1 -> v3/impl3 descriptor rewrite of a
// cleanly closed volume whose WAL is fully flushed. No record is converted
// and no extent byte is touched. Every step is durable before the next.
// errMigrateNotClean is DESIGN 10.1's ErrMigrateNotClean.
var errMigrateNotClean = errors.New("migrate-v3: the volume is not cleanly flushed: open with the old binary, flush, close cleanly, retry")
// errMigrateNeitherSlot: neither offset 0 nor offset 4096 holds a valid
// slot or v2 superblock; nothing is changed.
var errMigrateNeitherSlot = errors.New("migrate-v3: no valid v2 superblock or v3 descriptor slot; nothing changed")
// migrateStepHook, when set by a test, runs after each durable step with
// its name; returning an error stops the tool there (a simulated crash).
var migrateStepHook func(step string) error
// syncDirHook, when set by a test, runs at every directory fsync; an error
// fails that fsync.
var syncDirHook func(path string) error
func runMigrateV3(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("migrate-v3", flag.ContinueOnError)
fs.SetOutput(stderr)
chunkBlocks := fs.Uint64("chunk-blocks", 0, "the provider's chunk size in blocks (the map geometry); required")
if err := fs.Parse(args); err != nil {
return 2
}
if fs.NArg() != 1 || *chunkBlocks == 0 {
fmt.Fprintln(stderr, "usage: sw-block migrate-v3 --chunk-blocks N <volume-file>")
return 2
}
if err := migrateV3(fs.Arg(0), *chunkBlocks, stdout); err != nil {
fmt.Fprintln(stderr, err)
return 1
}
return 0
}
func migrateV3(path string, chunkBlocks uint64, out io.Writer) error {
f, err := os.OpenFile(path, os.O_RDWR, 0)
if err != nil {
return err
}
defer f.Close()
if err := storage.LockWALStoreFile(f); err != nil {
return err
}
head := make([]byte, 2*storage.MigrationSlotSize)
if _, err := f.ReadAt(head, 0); err != nil {
return fmt.Errorf("migrate-v3: read the descriptor region: %w", err)
}
a, b := head[:storage.MigrationSlotSize], head[storage.MigrationSlotSize:]
sb, v2err := v2legacy.ReadSuperblock(a)
switch {
case v2err == nil:
// Not committed: restart from step 1 with a full rescan (the old
// binary may have run since; nothing earlier is trusted).
return migrateFromV2(f, path, sb, chunkBlocks, out)
case errors.Is(v2err, v2legacy.ErrImplUnsupported):
return fmt.Errorf("migrate-v3: %w (an impl-2 volume stays on its old binary)", v2err)
}
stA, genA := storage.ClassifyMigrationSlotV3(a)
stB, _ := storage.ClassifyMigrationSlotV3(b)
switch {
case stA == storage.MigrationSlotCommitted:
// Committed. Finish step 6 if B was never rewritten, then step 7.
if genA == 2 && stB != storage.MigrationSlotCommitted {
rb, err := storage.RolloverSlotV3(a)
if err != nil {
return err
}
if err := pwriteSync(f, rb, storage.MigrationSlotBOffset); err != nil {
return err
}
}
return retireC11(path)
case stB == storage.MigrationSlotCommitted:
// Committed and possibly in use: only step 7.
return retireC11(path)
case stB == storage.MigrationSlotPrepared:
// A torn step 5 or an old-binary run after preparation followed by
// damage to A: the bytes cannot tell; never guess.
return fmt.Errorf("migrate-v3: %w; nothing changed (an operator decision, using the backup)", storage.ErrMigrationIncomplete)
default:
return errMigrateNeitherSlot
}
}
func migrateFromV2(f *os.File, path string, sb v2legacy.Superblock, chunkBlocks uint64, out io.Writer) error {
src := storage.MigrationSourceV3{
UUID: sb.UUID, VolumeSize: sb.VolumeSize, ExtentSize: sb.ExtentSize, BlockSize: sb.BlockSize,
OldWALOffset: sb.WALOffset, OldWALSize: sb.WALSize, CreatedAt: sb.CreatedAt,
CheckpointLSN: sb.WALCheckpointLSN, ChunkBlocks: chunkBlocks,
}
// Precondition 4 first (read-only): the geometry, including the checked
// extent end, refuses before the WAL is read or anything is written.
if err := storage.ValidateMigrationV3(src); err != nil {
return err
}
fi, err := f.Stat()
if err != nil {
return err
}
if size := uint64(fi.Size()); sb.WALOffset > size || sb.WALSize > size-sb.WALOffset { // no wrapping sum
return fmt.Errorf("%w: the v2 WAL [%d, %d) extends past the file end %d", storage.ErrMigrateGeometry, sb.WALOffset, sb.WALOffset+sb.WALSize, fi.Size())
}
// Step 1: precondition 3, read-only and before any write.
if sb.WALHead != sb.WALTail {
return fmt.Errorf("%w (WALHead %d != WALTail %d)", errMigrateNotClean, sb.WALHead, sb.WALTail)
}
wal := make([]byte, sb.WALSize)
if _, err := f.ReadAt(wal, int64(sb.WALOffset)); err != nil {
return fmt.Errorf("migrate-v3: read the v2 WAL: %w", err)
}
if found := v2legacy.ScanClean(wal, sb.WALCheckpointLSN); len(found) > 0 {
return fmt.Errorf("%w (%d unflushed record(s); first at WAL offset %d: %s)", errMigrateNotClean, len(found), found[0].Offset, found[0].Reason)
}
if err := step("scanned"); err != nil {
return err
}
// Step 2: the atomic operator backup of the v2 superblock.
raw := make([]byte, v2legacy.SuperblockSize)
if _, err := f.ReadAt(raw, 0); err != nil {
return err
}
if err := writeFileAtomic(path+".v2-superblock.bak", raw); err != nil {
return fmt.Errorf("migrate-v3: backup: %w", err)
}
if err := step("backup"); err != nil {
return err
}
// Step 3: the initial map sidecar (all UNKNOWN), durable.
plan, err := storage.PrepareMigrationV3(path+".chunkmap", src)
if err != nil {
return fmt.Errorf("migrate-v3: initial map: %w", err)
}
if err := syncDirOf(path); err != nil {
return err
}
if err := step("map"); err != nil {
return err
}
// Step 4: the prepared slot B, over the old WAL's first 4 KiB.
if err := pwriteSync(f, plan.PreparedB, storage.MigrationSlotBOffset); err != nil {
return err
}
if err := step("prepared"); err != nil {
return err
}
// Step 5: slot A, phase 0: the commit point.
if err := pwriteSync(f, plan.CommittedA, storage.MigrationSlotAOffset); err != nil {
return err
}
if err := step("committed"); err != nil {
return err
}
// Step 6: slot B rewritten at phase 0 (two-slot redundancy).
if err := pwriteSync(f, plan.RolloverB, storage.MigrationSlotBOffset); err != nil {
return err
}
if err := step("rollover"); err != nil {
return err
}
// Step 7: retire the v2 C11 bitmap, only after the commit.
if err := retireC11(path); err != nil {
return err
}
// Step 8.
fmt.Fprintf(out, "migrated %s to v3: descriptor sha256 %s; backups left in place\n", path, hex.EncodeToString(plan.DescriptorHash[:]))
return nil
}
func step(name string) error {
if h := migrateStepHook; h != nil {
return h(name)
}
return nil
}
func pwriteSync(f *os.File, b []byte, off int64) error {
if _, err := f.WriteAt(b, off); err != nil {
return fmt.Errorf("migrate-v3: write at %d: %w", off, err)
}
if err := f.Sync(); err != nil {
return fmt.Errorf("migrate-v3: fsync: %w", err)
}
return nil
}
// writeFileAtomic writes b to name via name.tmp, fsync, rename and a
// directory fsync; a leftover .tmp from an earlier run is replaced.
func writeFileAtomic(name string, b []byte) error {
tmp := name + ".tmp"
if err := os.Remove(tmp); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
t, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
if err != nil {
return err
}
if _, err := t.Write(b); err != nil {
t.Close()
return err
}
if err := t.Sync(); err != nil {
t.Close()
return err
}
if err := t.Close(); err != nil {
return err
}
if err := os.Rename(tmp, name); err != nil {
return err
}
return syncDirOf(name)
}
// retireC11 is step 7: rename a v2 .chunkbitmap sidecar to
// <file>.v2-chunkbitmap.bak and fsync the directory. Absent is done.
func retireC11(path string) error {
err := os.Rename(path+".chunkbitmap", path+".v2-chunkbitmap.bak")
if errors.Is(err, os.ErrNotExist) {
if _, serr := os.Stat(path + ".v2-chunkbitmap.bak"); serr != nil {
return nil // there was no v2 bitmap
}
// An earlier run renamed it; its directory fsync may have failed, so
// make the rename durable now (codex01 row 13b P2).
return syncDirOf(path)
}
if err != nil {
return fmt.Errorf("migrate-v3: retire the v2 chunk bitmap: %w", err)
}
return syncDirOf(path)
}
// syncDirOf fsyncs the directory holding path. A directory cannot be
// fsynced on Windows; there it is a no-op, as in the provider.
func syncDirOf(path string) error {
if h := syncDirHook; h != nil {
if err := h(path); err != nil {
return err
}
}
if runtime.GOOS == "windows" {
return nil
}
d, err := os.Open(filepath.Dir(path))
if err != nil {
return err
}
defer d.Close()
return d.Sync()
}
@@ -1,176 +0,0 @@
//go:build swblock_format_v3_test
package main
import (
"bytes"
"errors"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func TestMigrateV3ExcludesOpenUntilCommitFinishes(t *testing.T) {
path := v2Volume(t, true)
parked, resume := make(chan struct{}), make(chan struct{})
var once sync.Once
release := func() { once.Do(func() { close(resume) }) }
defer release()
migrateStepHook = func(step string) error {
if step == "committed" {
close(parked)
<-resume
}
return nil
}
finished := make(chan error, 1)
done := make(chan struct{})
go func() {
defer close(done)
finished <- migrateV3(path, 4, &bytes.Buffer{})
}()
t.Cleanup(func() {
release()
select {
case <-done:
migrateStepHook = nil
case <-time.After(10 * time.Second):
t.Error("migration worker did not stop during cleanup")
}
})
select {
case <-parked:
case err := <-finished:
t.Fatalf("migration stopped before the held commit: %v", err)
case <-time.After(10 * time.Second):
t.Fatal("migration did not reach the held commit")
}
if s, err := storage.OpenMappedWALStoreV3Test(path); !errors.Is(err, storage.ErrWALStoreLocked) {
if s != nil {
_ = s.Close()
}
t.Fatalf("open during migration: %v, want volume locked", err)
}
release()
select {
case err := <-finished:
if err != nil {
t.Fatal(err)
}
case <-time.After(10 * time.Second):
t.Fatal("migration did not release its lock")
}
s, err := storage.OpenMappedWALStoreV3Test(path)
if err != nil {
t.Fatalf("open after migration: %v", err)
}
_ = s.Close()
}
func TestMigrateV3RefusesAnOpenV3Volume(t *testing.T) {
path := filepath.Join(t.TempDir(), "volume")
s, err := storage.CreateMappedWALStoreV3Test(path, 64, migBlock, 4)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.DisableAutoFlushForRecoveryTest()
// Windows byte-range locks reject reads through a second handle. Snapshot
// only while no owner is open, then hold the real owner for the CLI call.
if err := s.Close(); err != nil {
t.Fatal(err)
}
before := snapshotFiles(t, path)
s, err = storage.OpenMappedWALStoreV3Test(path)
if err != nil {
t.Fatal(err)
}
code, msg := migrate(t, path)
if code != 1 || !strings.Contains(msg, "locked") {
t.Fatalf("migration must refuse an open v3 volume: exit=%d message=%s", code, msg)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
if !sameFiles(before, snapshotFiles(t, path)) {
t.Fatal("refused migration modified the open volume")
}
if code, msg := migrate(t, path); code != 0 {
t.Fatalf("migration after owner close: exit=%d message=%s", code, msg)
}
}
// Row 13b through the actual v3 open (tag swblock_format_v3_test).
// A migrated volume opens as v3 and serves the v2 blocks unchanged; its
// map is the initial one (all UNKNOWN, covered = the v2 checkpoint); a
// v3 write and a reopen work. Mutant: an initial map with clean entries
// fails here.
func TestMigrateV3VolumeOpensAsV3(t *testing.T) {
path := v2Volume(t, true)
if code, msg := migrate(t, path); code != 0 {
t.Fatalf("migrate: %s", msg)
}
s, err := storage.OpenMappedWALStoreV3Test(path)
if err != nil {
t.Fatalf("v3 open of a migrated volume: %v", err)
}
if _, err := s.Recover(); err != nil {
t.Fatal(err)
}
covered, allUnknown := storage.MapCoverageV3Test(s)
if !allUnknown || covered != s.CheckpointLSN() {
t.Fatalf("initial map: covered %d (checkpoint %d), all UNKNOWN %v", covered, s.CheckpointLSN(), allUnknown)
}
for lba := uint32(0); lba < 4; lba++ {
got, err := s.Read(lba)
if err != nil || !bytes.Equal(got, migBlk(0x10+byte(lba))) {
t.Fatalf("LBA %d after migration: err %v", lba, err)
}
}
if _, err := s.Write(7, migBlk(0x77)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
r, err := storage.OpenMappedWALStoreV3Test(path)
if err != nil {
t.Fatal(err)
}
defer r.Close()
if _, err := r.Recover(); err != nil {
t.Fatal(err)
}
if got, _ := r.Read(7); !bytes.Equal(got, migBlk(0x77)) {
t.Fatal("a v3 write after migration did not survive a reopen")
}
}
// A prepared-only volume (stopped before the commit, A then damaged) is
// refused by v3 open with ErrMigrationIncomplete, as by the tool.
func TestMigrateV3PreparedOnlyRefusedByV3Open(t *testing.T) {
path := v2Volume(t, true)
migrateStepHook = func(s string) error {
if s == "prepared" {
return errors.New("stop")
}
return nil
}
migrate(t, path)
migrateStepHook = nil
damageSlotA(t, path)
if s, err := storage.OpenMappedWALStoreV3Test(path); !errors.Is(err, storage.ErrMigrationIncomplete) {
if s != nil {
_ = s.Close()
}
t.Fatalf("v3 open of a prepared-only volume: err = %v, want ErrMigrationIncomplete", err)
}
}
-467
View File
@@ -1,467 +0,0 @@
//go:build swblock_format_v3_test
package main
import (
"bytes"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/cmd/sw-block/internal/v2legacy"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// Plan row 13b controls (DESIGN r17.4 section 10.1; owner claude03), all
// through the actual CLI entry (run).
const migBlock = 4096
func migBlk(b byte) []byte { return bytes.Repeat([]byte{b}, migBlock) }
// v2Volume creates a real v2/impl1 volume with 4 written blocks; clean
// closes it (flushing), otherwise it is left synced but unflushed.
func v2Volume(t *testing.T, clean bool) string {
t.Helper()
path := filepath.Join(t.TempDir(), "vol")
s, err := storage.CreateLegacyWALStoreTest(path, 64, migBlock)
if err != nil {
t.Fatal(err)
}
if !clean {
s.DisableAutoFlushForRecoveryTest()
}
for lba := uint32(0); lba < 4; lba++ {
if _, err := s.Write(lba, migBlk(0x10+byte(lba))); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if clean {
if err := s.Close(); err != nil {
t.Fatal(err)
}
} else {
t.Cleanup(func() { _ = s.Close() })
}
return path
}
func migrate(t *testing.T, path string) (int, string) {
t.Helper()
var out, errb bytes.Buffer
code := run([]string{"migrate-v3", "--chunk-blocks", "4", path}, &out, &errb)
return code, out.String() + errb.String()
}
// snapshotFiles reads the volume and every sidecar next to it.
func snapshotFiles(t *testing.T, path string) map[string][]byte {
t.Helper()
got := map[string][]byte{}
matches, _ := filepath.Glob(path + "*")
for _, m := range matches {
b, err := os.ReadFile(m)
if err != nil {
t.Fatal(err)
}
got[filepath.Base(m)] = b
}
return got
}
func sameFiles(a, b map[string][]byte) bool {
if len(a) != len(b) {
return false
}
for k, v := range a {
if !bytes.Equal(v, b[k]) {
return false
}
}
return true
}
// A clean v2 volume migrates: slot A committed (slotGen 2), slot B rolled
// over (slotGen 3), every extent byte unchanged, the backup holds the old
// superblock, a v2 chunk bitmap is retired, the old binary now refuses the
// file, and a rerun changes no byte.
func TestMigrateV3CleanVolume(t *testing.T) {
path := v2Volume(t, true)
if err := os.WriteFile(path+".chunkbitmap", []byte("c11"), 0o644); err != nil {
t.Fatal(err)
}
before, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
sb, err := v2legacy.ReadSuperblock(before)
if err != nil {
t.Fatal(err)
}
extentBase := sb.WALOffset + sb.WALSize
if code, msg := migrate(t, path); code != 0 || !strings.Contains(msg, "descriptor sha256") {
t.Fatalf("migrate: exit %d: %s", code, msg)
}
after, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(after[extentBase:], before[extentBase:]) {
t.Fatal("the migration changed extent bytes")
}
if st, gen := storage.ClassifyMigrationSlotV3(after[:4096]); st != storage.MigrationSlotCommitted || gen != 2 {
t.Fatalf("slot A: state %d gen %d, want committed gen 2", st, gen)
}
if st, gen := storage.ClassifyMigrationSlotV3(after[4096:8192]); st != storage.MigrationSlotCommitted || gen != 3 {
t.Fatalf("slot B: state %d gen %d, want committed gen 3", st, gen)
}
if bak, err := os.ReadFile(path + ".v2-superblock.bak"); err != nil || !bytes.Equal(bak, before[:4096]) {
t.Fatalf("backup: %v", err)
}
if _, err := os.Stat(path + ".chunkbitmap"); !errors.Is(err, os.ErrNotExist) {
t.Fatal("the v2 chunk bitmap was not retired")
}
if _, err := os.Stat(path + ".v2-chunkbitmap.bak"); err != nil {
t.Fatalf("retired bitmap: %v", err)
}
if s, err := storage.OpenLegacyWALStoreTest(path); err == nil {
_ = s.Close()
t.Fatal("the old binary opened a migrated volume")
}
snap := snapshotFiles(t, path)
if code, msg := migrate(t, path); code != 0 {
t.Fatalf("rerun: exit %d: %s", code, msg)
}
if !sameFiles(snap, snapshotFiles(t, path)) {
t.Fatal("a rerun on a committed volume changed bytes")
}
}
// Refusals change no byte of the volume or any sidecar: an unflushed WAL
// (ErrMigrateNotClean with the operator remedy), an impl-2 volume, and a
// file with neither a v2 superblock nor a valid v3 slot. Mutant: skipping
// the clean scan migrates the unflushed volume and fails here.
func TestMigrateV3RefusalsChangeNothing(t *testing.T) {
t.Run("unflushed WAL", func(t *testing.T) {
path := v2Volume(t, false)
snap := snapshotFiles(t, path)
code, msg := migrate(t, path)
if code == 0 || !strings.Contains(msg, "open with the old binary, flush, close cleanly, retry") {
t.Fatalf("exit %d: %s", code, msg)
}
if !sameFiles(snap, snapshotFiles(t, path)) {
t.Fatal("a refused migration changed bytes")
}
})
t.Run("impl 2", func(t *testing.T) {
path := v2Volume(t, true)
f, err := os.OpenFile(path, os.O_RDWR, 0)
if err != nil {
t.Fatal(err)
}
if _, err := f.WriteAt([]byte{2, 0, 0, 0}, 92); err != nil {
t.Fatal(err)
}
f.Close()
snap := snapshotFiles(t, path)
if code, _ := migrate(t, path); code == 0 || !sameFiles(snap, snapshotFiles(t, path)) {
t.Fatal("an impl-2 volume was not refused unchanged")
}
})
t.Run("neither valid", func(t *testing.T) {
path := filepath.Join(t.TempDir(), "junk")
if err := os.WriteFile(path, bytes.Repeat([]byte{0xEE}, 3*4096), 0o644); err != nil {
t.Fatal(err)
}
snap := snapshotFiles(t, path)
if code, _ := migrate(t, path); code == 0 || !sameFiles(snap, snapshotFiles(t, path)) {
t.Fatal("neither-valid was not refused unchanged")
}
})
}
// A crash after each step is resumable from the slot bytes alone: before
// the commit the rerun restarts with a full rescan; after it, the rerun
// only finishes the rollover and the bitmap retirement.
func TestMigrateV3CrashAfterEachStepIsResumable(t *testing.T) {
for _, stop := range []string{"scanned", "backup", "map", "prepared", "committed", "rollover"} {
t.Run(stop, func(t *testing.T) {
path := v2Volume(t, true)
if err := os.WriteFile(path+".chunkbitmap", []byte("c11"), 0o644); err != nil {
t.Fatal(err)
}
migrateStepHook = func(s string) error {
if s == stop {
return errors.New("simulated crash after " + s)
}
return nil
}
code, _ := migrate(t, path)
migrateStepHook = nil
if code == 0 {
t.Fatal("the simulated crash did not stop the tool")
}
// Before the commit point (step 5) slot A is still the v2
// superblock and the v2 bitmap is not retired; after it A is a
// committed v3 slot.
crashed, _ := os.ReadFile(path)
_, v2err := v2legacy.ReadSuperblock(crashed[:4096])
_, bitmapErr := os.Stat(path + ".chunkbitmap")
if committed := stop == "committed" || stop == "rollover"; committed {
if st, _ := storage.ClassifyMigrationSlotV3(crashed[:4096]); st != storage.MigrationSlotCommitted {
t.Fatalf("crash after %s: slot A state %d, want committed", stop, st)
}
} else if v2err != nil || bitmapErr != nil {
t.Fatalf("crash after %s: A still v2 = %v, bitmap present = %v; want both before the commit", stop, v2err == nil, bitmapErr == nil)
}
if code, msg := migrate(t, path); code != 0 {
t.Fatalf("rerun after a crash at %s: exit %d: %s", stop, code, msg)
}
raw, _ := os.ReadFile(path)
if st, _ := storage.ClassifyMigrationSlotV3(raw[:4096]); st != storage.MigrationSlotCommitted {
t.Fatalf("after the rerun slot A state %d, want committed", st)
}
if st, _ := storage.ClassifyMigrationSlotV3(raw[4096:8192]); st != storage.MigrationSlotCommitted {
t.Fatalf("after the rerun slot B state %d, want committed", st)
}
})
}
}
// The old binary runs after preparation (A is still v2, so it opens): the
// rerun finds A still v2 and restarts with a full rescan; it refuses while
// the old binary's writes are unflushed and migrates once it flushed and
// closed. A prepared B with a damaged A is ambiguous and refused with
// ErrMigrationIncomplete, writing nothing.
func TestMigrateV3OldBinaryAfterPreparation(t *testing.T) {
path := v2Volume(t, true)
migrateStepHook = func(s string) error {
if s == "prepared" {
return errors.New("stop after preparation")
}
return nil
}
migrate(t, path)
migrateStepHook = nil
s, err := storage.OpenLegacyWALStoreTest(path)
if err != nil {
t.Fatalf("the old binary refused a prepared-only volume: %v", err)
}
s.DisableAutoFlushForRecoveryTest()
if _, err := s.Write(9, migBlk(0x99)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
snap := snapshotFiles(t, path)
if code, msg := migrate(t, path); code == 0 || !strings.Contains(msg, "not cleanly flushed") {
t.Fatalf("rerun over the old binary's unflushed write: exit %d: %s", code, msg)
}
if !sameFiles(snap, snapshotFiles(t, path)) {
t.Fatal("a refused rerun changed bytes")
}
_ = s.Close() // stopped without a flush: still not clean
if code, _ := migrate(t, path); code == 0 {
t.Fatal("the rerun migrated a volume the old binary left unflushed")
}
// The operator remedy: open with the old binary, flush, close cleanly.
s2, err := storage.OpenLegacyWALStoreTest(path)
if err != nil {
t.Fatal(err)
}
if _, err := s2.Recover(); err != nil {
t.Fatal(err)
}
if err := s2.Close(); err != nil {
t.Fatal(err)
}
if code, msg := migrate(t, path); code != 0 {
t.Fatalf("rerun after the old binary closed cleanly: exit %d: %s", code, msg)
}
t.Run("prepared B with a damaged A", func(t *testing.T) {
path := v2Volume(t, true)
migrateStepHook = func(s string) error {
if s == "prepared" {
return errors.New("stop after preparation")
}
return nil
}
migrate(t, path)
migrateStepHook = nil
f, _ := os.OpenFile(path, os.O_RDWR, 0)
_, _ = f.WriteAt(bytes.Repeat([]byte{0xEE}, 4096), 0)
f.Close()
snap := snapshotFiles(t, path)
code, msg := migrate(t, path)
if code == 0 || !strings.Contains(msg, storage.ErrMigrationIncomplete.Error()) || !sameFiles(snap, snapshotFiles(t, path)) {
t.Fatalf("exit %d: %s", code, msg)
}
})
}
// The tool never reads or restores its backup: a committed volume reruns
// to success with the backup damaged and its slots untouched.
func TestMigrateV3NeverRestoresTheBackup(t *testing.T) {
path := v2Volume(t, true)
if code, msg := migrate(t, path); code != 0 {
t.Fatalf("migrate: %s", msg)
}
if err := os.WriteFile(path+".v2-superblock.bak", []byte("damaged"), 0o644); err != nil {
t.Fatal(err)
}
raw, _ := os.ReadFile(path)
if code, msg := migrate(t, path); code != 0 {
t.Fatalf("rerun: %s", msg)
}
now, _ := os.ReadFile(path)
if !bytes.Equal(raw, now) {
t.Fatal("a rerun changed the committed volume")
}
}
// The old v2 WAL starts at offset 4096, over the prepared slot B, so an
// old-binary run can overwrite B partly or wholly (codex03 r8). Either way B
// is an invalid slot, never prepared or committed: with A still v2 the rerun
// restarts and migrates; with A damaged too, neither slot is valid and the
// rerun refuses with no byte changed.
func TestMigrateV3OldWALOverwritesThePreparedSlot(t *testing.T) {
for _, n := range []int{100, 4096} {
for _, damageA := range []bool{false, true} {
name := map[int]string{100: "partial", 4096: "full"}[n]
if damageA {
name += " with A damaged"
}
t.Run(name, func(t *testing.T) {
path := v2Volume(t, true)
migrateStepHook = func(s string) error {
if s == "prepared" {
return errors.New("stop after preparation")
}
return nil
}
migrate(t, path)
migrateStepHook = nil
f, err := os.OpenFile(path, os.O_RDWR, 0)
if err != nil {
t.Fatal(err)
}
if _, err := f.WriteAt(bytes.Repeat([]byte{0xA5}, n), 4096); err != nil {
t.Fatal(err)
}
if damageA {
if _, err := f.WriteAt(bytes.Repeat([]byte{0xEE}, 4096), 0); err != nil {
t.Fatal(err)
}
}
f.Close()
raw, _ := os.ReadFile(path)
if st, _ := storage.ClassifyMigrationSlotV3(raw[4096:8192]); st != storage.MigrationSlotInvalid {
t.Fatalf("an overwritten B classifies as %d, want invalid", st)
}
snap := snapshotFiles(t, path)
code, msg := migrate(t, path)
if damageA {
if code == 0 || !sameFiles(snap, snapshotFiles(t, path)) {
t.Fatalf("neither valid: exit %d, bytes changed: %s", code, msg)
}
return
}
if code != 0 {
t.Fatalf("rerun with A still v2: exit %d: %s", code, msg)
}
})
}
}
}
func damageSlotA(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()
if _, err := f.WriteAt(bytes.Repeat([]byte{0xEE}, 4096), 0); err != nil {
t.Fatal(err)
}
}
func patchSuperblock(t *testing.T, path string, off int64, v uint64) {
t.Helper()
f, err := os.OpenFile(path, os.O_RDWR, 0)
if err != nil {
t.Fatal(err)
}
defer f.Close()
var b [8]byte
for i := range b {
b[i] = byte(v >> (8 * i))
}
if _, err := f.WriteAt(b[:], off); err != nil {
t.Fatal(err)
}
}
// codex01 row 13b P1 and P2: geometry the v3 slot validation would refuse
// is refused before ANY write (no backup, no map, the volume unchanged):
// an aligned VolumeSize whose extent end overflows, and a v2 WAL size that
// extends past the file end (refused before the scan allocates it).
// Mutants: no checked extent end in ValidateMigrationV3, no file-size
// bound before the WAL read.
func TestMigrateV3BadGeometryRefusedBeforeAnyWrite(t *testing.T) {
for name, patch := range map[string][2]uint64{
"extent end overflows": {24, 1 << 63}, // VolumeSize, block aligned
"WAL past the file end": {48, 1<<45 + 4096}, // WALSize, v3 size aligned
"WAL region wraps": {48, ^uint64(0) - 4095}, // WALSize 2^64-4096: every sum wraps
} {
t.Run(name, func(t *testing.T) {
path := v2Volume(t, true)
patchSuperblock(t, path, int64(patch[0]), patch[1])
snap := snapshotFiles(t, path)
code, msg := migrate(t, path)
if code == 0 || !strings.Contains(msg, "cannot be migrated in place") {
t.Fatalf("exit %d: %s", code, msg)
}
if !sameFiles(snap, snapshotFiles(t, path)) {
t.Fatal("a geometry refusal wrote a backup, a map or volume bytes")
}
})
}
}
// codex01 row 13b P2: an earlier run renamed the v2 chunk bitmap but its
// directory fsync failed; the rerun (source gone) still fsyncs the
// directory so the rename is durable. Mutant: treating the missing source
// as done without the fsync fails here.
func TestMigrateV3RetirementRerunFsyncsTheDirectory(t *testing.T) {
path := v2Volume(t, true)
if err := os.WriteFile(path+".chunkbitmap", []byte("c11"), 0o644); err != nil {
t.Fatal(err)
}
failed := false
syncDirHook = func(string) error {
if _, err := os.Stat(path + ".v2-chunkbitmap.bak"); err == nil && !failed {
failed = true
return errors.New("injected directory fsync failure")
}
return nil
}
defer func() { syncDirHook = nil }()
if code, _ := migrate(t, path); code == 0 {
t.Fatal("the injected retirement fsync failure did not fail the tool")
}
calls := 0
syncDirHook = func(string) error { calls++; return nil }
if code, msg := migrate(t, path); code != 0 {
t.Fatalf("rerun: exit %d: %s", code, msg)
}
if calls == 0 {
t.Fatal("the rerun did not fsync the directory of the earlier rename")
}
}
@@ -0,0 +1,32 @@
package main
import (
"bytes"
"os"
"path/filepath"
"testing"
)
func TestRetiredMigrationCommandRefusesWithoutMutation(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "legacy")
want := []byte("unmodified legacy volume")
if err := os.WriteFile(path, want, 0600); err != nil {
t.Fatal(err)
}
var out, errout bytes.Buffer
if code := run([]string{"migrate-v3", "--path", path}, &out, &errout); code == 0 {
t.Fatal("retired converter accepted input")
}
if !bytes.Contains(errout.Bytes(), []byte("unknown command")) {
t.Fatalf("converter still dispatched: %s", errout.Bytes())
}
got, err := os.ReadFile(path)
if err != nil || !bytes.Equal(got, want) {
t.Fatalf("retired converter changed input: %v", err)
}
entries, err := os.ReadDir(dir)
if err != nil || len(entries) != 1 {
t.Fatalf("retired converter created sidecars: %v %v", entries, err)
}
}
@@ -60,7 +60,7 @@ func TestBlockMetadata_DurableBeforeTail(t *testing.T) {
}
cp, tail := s.CheckpointLSN(), walLogicalTail(s)
h.before = func(uint64) {
if s.checkpointLSN != cp || s.wal.logicalTail != tail {
if s.checkpointLSN != cp || s.v3.pub.current().RetainedTail != tail {
t.Error("tail/checkpoint advanced before hook durability")
}
}
@@ -39,13 +39,6 @@ func (l *chunkLayerImpl) holdBaseTransitionV3() (func(), error) {
d := l.s.v3.pub.current()
l.noteAllMutated()
l.stMu.Lock()
l.reconcileGen++
if l.reconciled != nil {
close(l.reconciled)
l.reconciled = nil
}
l.reconcile = map[uint64]bool{}
l.hashMode = false
l.allDirty = true
l.dirtyVer++
switch d.BaseState {
+1 -5
View File
@@ -9,11 +9,7 @@ func (l *chunkLayerImpl) captureBirths(candidates map[uint64]bool, frontier uint
l.s.mu.RLock()
defer l.s.mu.RUnlock()
for idx := range candidates {
birth := frontier
if l.usesOwnedMapV3() {
birth = min(l.s.v3.mapEntries[idx].LSN, frontier)
}
out[idx] = birth
out[idx] = min(l.s.v3.mapEntries[idx].LSN, frontier)
}
return out
}
@@ -28,7 +28,7 @@ func BenchmarkCaptureBirthsMaxVolumeDefaultChunk(b *testing.B) {
}
}
func TestCaptureBirthsIncludesStoreLockWait(t *testing.T) {
s := &WALStore{}
s := &WALStore{v3: &walStoreV3State{mapEntries: []chunkLSNEntryV3{{LSN: 7}}, mapProof: newMapProofEpochV3()}}
l := &chunkLayerImpl{s: s}
candidates := map[uint64]bool{0: true}
s.mu.Lock()
@@ -57,7 +57,7 @@ func TestCaptureBirthsIncludesStoreLockWait(t *testing.T) {
case out := <-done:
done <- out
if out[0] != 7 {
t.Fatal("legacy frontier changed")
t.Fatal("native image frontier changed")
}
case <-time.After(5 * time.Second):
t.Fatal("sampler did not finish after lock release")
@@ -2,77 +2,9 @@ package storage
import (
"bytes"
"os"
"testing"
)
func TestChunkBirthMigrationCarriesImageFrontier(t *testing.T) {
s, path := newChunkTestStore(t)
d := s.v3.pub.current()
mapPath := s.v3.ownedMap.fd.Name()
if err := s.Close(); err != nil {
t.Fatal(err)
}
src := MigrationSourceV3{UUID: d.UUID, VolumeSize: d.VolumeSize, ExtentSize: d.ExtentSize, BlockSize: d.BlockSize, OldWALOffset: 4096, OldWALSize: d.WALSize + 4096, CreatedAt: d.CreatedAt, CheckpointLSN: 7, ChunkBlocks: ctChunkBlocks}
plan, err := PrepareMigrationV3(mapPath, src)
if err != nil {
t.Fatal(err)
}
fd, err := os.OpenFile(path, os.O_RDWR, 0)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { fd.Close() })
// Actual offline migration's map and slot encoder, on a small flushed
// image. No legacy engine or fabricated in-memory owned-map entries.
for _, part := range []struct {
offset int64
data []byte
}{{MigrationSlotBOffset, plan.PreparedB}, {MigrationSlotAOffset, plan.CommittedA}, {MigrationSlotBOffset, plan.RolloverB}} {
if _, err := fd.WriteAt(part.data, part.offset); err != nil {
t.Fatal(err)
}
if err := fd.Sync(); err != nil {
t.Fatal(err)
}
}
want := makeBlock(ctBlockSize, 0x57)
if _, err := fd.WriteAt(want, int64(d.WALOffset+d.WALSize)); err != nil {
t.Fatal(err)
}
if err := fd.Sync(); err != nil {
t.Fatal(err)
}
if err := fd.Close(); err != nil {
t.Fatal(err)
}
r, err := OpenWALStoreWithOptions(path, WALStoreOptions{ChunkBlocks: ctChunkBlocks})
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { closeBounded(t, r) })
if _, err := r.Recover(); err != nil {
t.Fatal(err)
}
f := newFakeChunkRemote()
l := mustAttach(t, r, f, ctConfig(1))
newest, err := r.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x41))
if err != nil {
t.Fatal(err)
}
cut, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if cut.Head.Chunks[0].BirthLSN != 7 || cut.Head.Chunks[1].BirthLSN != newest {
t.Fatalf("migrated image birth lost: %+v", cut.Head)
}
if !bytes.Equal(f.imageOf(t, cut.Head)[:ctBlockSize], want) {
t.Fatal("migration cut changed inherited bytes")
}
}
func TestChunkBirthSeededFrontierPreservesInheritedImage(t *testing.T) {
s, _ := newChunkTestStore(t)
if err := s.SeedChunkFrontier(7); err != nil {
@@ -96,4 +28,9 @@ func TestChunkBirthSeededFrontierPreservesInheritedImage(t *testing.T) {
if cut.Head.Chunks[1].BirthLSN != 7 || cut.Head.Chunks[0].BirthLSN != newest {
t.Fatalf("seeded image birth lost: %+v", cut.Head)
}
want := bytes.Clone(image)
copy(want, makeBlock(ctBlockSize, 0x41))
if !bytes.Equal(f.imageOf(t, cut.Head), want) {
t.Fatal("seeded cut changed inherited or appended bytes")
}
}
@@ -8,33 +8,6 @@ import (
"time"
)
func TestChunkBirthLegacyEngineUsesCutFrontierUpperBound(t *testing.T) {
s, _ := newLegacyChunkTestStore(t)
f := newFakeChunkRemote()
cfg := ctConfig(1)
l := mustAttach(t, s, f, cfg)
if _, err := s.Write(0, makeBlock(ctBlockSize, 0x41)); err != nil {
t.Fatal(err)
}
last, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42))
if err != nil {
t.Fatal(err)
}
cut, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
for _, idx := range []uint64{0, 1} {
if cr := cut.Head.Chunks[idx]; cr.Encoding != "full" || cr.BirthLSN != last {
t.Fatalf("legacy chunk %d metadata %+v, want frontier %d", idx, cr, last)
}
}
want := make([]byte, ctNumBlocks*ctBlockSize)
copy(want, makeBlock(ctBlockSize, 0x41))
copy(want[ctChunkBlocks*ctBlockSize:], makeBlock(ctBlockSize, 0x42))
assertImage(t, "legacy inherited image", f.imageOf(t, cut.Head), want)
}
func TestChunkBirthBASEUsesInheritedFrontierIncludingZero(t *testing.T) {
for _, frontier := range []uint64{0, 7} {
t.Run(string(rune('0'+frontier)), func(t *testing.T) {
@@ -3,63 +3,10 @@ package storage
import (
"context"
"os"
"path/filepath"
"reflect"
"testing"
)
func TestLegacyC11FileCodec_RoundTripAndReopen(t *testing.T) {
path := filepath.Join(t.TempDir(), "vol.chunkbitmap")
b := newLegacyC11FileStore(path)
if _, _, ok, err := b.Load(); ok || err != nil {
t.Fatalf("empty store: ok %v err %v", ok, err)
}
if err := b.Save([]uint64{3, 7}); err != nil {
t.Fatal(err)
}
if err := b.WriteHeader(chunkBitmapHeader{Base: chunkBaseInstalling}); err != nil {
t.Fatal(err)
}
hdr, dirty, ok, err := b.Load()
if !ok || err != nil || hdr.Base != chunkBaseInstalling || !reflect.DeepEqual(dirty, []uint64{3, 7}) {
t.Fatalf("after Save+WriteHeader: ok %v err %v hdr %+v dirty %v", ok, err, hdr, dirty)
}
want := chunkBitmapHeader{BaseLSN: 40, HeadGen: 3, Epoch: 2}
delta := chunkDelta{FromLSN: 10, ToLSN: 40, Gen: 3, Dirty: []uint64{3}, NewKeys: map[uint64]string{3: "k3"}}
if err := b.Reset(want, []uint64{7}, delta); err != nil {
t.Fatal(err)
}
// A new instance reads exactly the durable state.
b2 := newLegacyC11FileStore(path)
hdr, dirty, ok, err = b2.Load()
if !ok || err != nil || hdr != want || !reflect.DeepEqual(dirty, []uint64{7}) {
t.Fatalf("reopened: ok %v err %v hdr %+v dirty %v", ok, err, hdr, dirty)
}
deltas, err := b2.Deltas()
if err != nil || len(deltas) != 1 || !reflect.DeepEqual(deltas[0], delta) {
t.Fatalf("delta log: %v %+v", err, deltas)
}
}
func TestLegacyC11FileCodec_CorruptStateIsLost(t *testing.T) {
path := filepath.Join(t.TempDir(), "vol.chunkbitmap")
b := newLegacyC11FileStore(path)
if err := b.Save([]uint64{1}); err != nil {
t.Fatal(err)
}
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
raw[len(raw)/2] ^= 0xFF // one flipped byte
if err := os.WriteFile(path, raw, 0o600); err != nil {
t.Fatal(err)
}
if _, _, ok, err := newLegacyC11FileStore(path).Load(); ok || err != nil {
t.Fatalf("corrupt state: ok %v err %v, want ok=false (hash-compare fallback) and no error", ok, err)
}
}
// The mapped layer and the in-memory remote: after a crash the owned map
// makes the first cut incremental and exact, without a C11 file sidecar.
func TestChunkLayer_OwnedMapIncrementalAfterRestart(t *testing.T) {
+1 -6
View File
@@ -439,12 +439,7 @@ func (l *chunkLayerImpl) readCOWChunk(w *cutCOWWindow, idx uint64) ([]byte, []ui
// write of the block waits for the caller's COW entry.
func (l *chunkLayerImpl) readLocalBlock(lba uint64, w *cutCOWWindow, dst []byte) ([]byte, bool, error) {
s := l.s
if s.v3 != nil {
if data, handled, err := s.readDirtyV3Into(uint32(lba), dst, func() { w.walReads.Add(1) }); handled {
return data, err == nil, err
}
} else if walRelOff, dataOffset, _, _, ok := s.dm.get(lba); ok {
data, err := s.readFromWAL(walRelOff, dataOffset)
if data, handled, err := s.readDirtyV3Into(uint32(lba), dst, func() { w.walReads.Add(1) }); handled {
return data, err == nil, err
}
idx := l.chunkOf(lba)
@@ -114,9 +114,7 @@ func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64,
// This cache belongs to one layer/owner lifetime. Generation equality is not
// a reuse proof across reopen or takeover; those require content-hash matching.
func (l *chunkLayerImpl) rememberPayload(c capturedChunk, gen uint64) {
if !l.usesOwnedMapV3() {
return
}
c.data = nil
l.stMu.Lock()
defer l.stMu.Unlock()
@@ -1133,67 +1133,3 @@ func waitReconciledForTest(t *testing.T, layer chunkLayer) {
time.Sleep(time.Millisecond)
}
}
// TODO(format-v3 row 14a): explicit C11 bitmap-engine fixtures only.
func newLegacyChunkTestStore(t *testing.T) (*WALStore, string) {
t.Helper()
path := filepath.Join(t.TempDir(), "vol.bin")
s, err := createLegacyWALStoreWithOptions(path, ctNumBlocks, ctBlockSize, WALStoreOptions{ChunkBlocks: ctChunkBlocks})
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { closeBounded(t, s) })
return s, path
}
// crashableStore is a store a test may crash; it is closed at cleanup only
// if it was not crashed.
func legacyCrashableStore(t *testing.T) (*WALStore, string, func()) {
t.Helper()
path := filepath.Join(t.TempDir(), "vol.bin")
s, err := createLegacyWALStoreWithOptions(path, ctNumBlocks, ctBlockSize, WALStoreOptions{ChunkBlocks: ctChunkBlocks})
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
crashed := false
t.Cleanup(func() {
if !crashed {
closeBounded(t, s)
}
})
return s, path, func() {
crashed = true
s.committer.Stop()
if err := s.fd.Close(); err != nil {
t.Fatal(err)
}
}
}
// reopen opens and recovers a crashed store; it may be crashed again.
func legacyReopen(t *testing.T, path string) (*WALStore, func()) {
t.Helper()
s, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
crashed := false
t.Cleanup(func() {
if !crashed {
closeBounded(t, s)
}
})
s.DisableAutoFlushForRecoveryTest()
if _, err := s.Recover(); err != nil {
t.Fatalf("local recovery: %v", err)
}
return s, func() {
crashed = true
s.committer.Stop()
if err := s.fd.Close(); err != nil {
t.Fatal(err)
}
}
}
+3 -44
View File
@@ -13,49 +13,9 @@ import (
// attaching the chunk layer or admitting writes. Repeating after failure is safe.
// Order: captureMu -> lifecycleMu -> mu; no remote call or layer callback.
func (s *WALStore) SeedChunkFrontier(lsn uint64) error {
if s.v3 != nil {
return s.seedChunkFrontierV3(lsn)
}
s.captureMu.Lock()
defer s.captureMu.Unlock()
s.lifecycleMu.RLock()
defer s.lifecycleMu.RUnlock()
s.mu.Lock()
defer s.mu.Unlock()
if s.closed || s.chunk.Load() != nil {
return errors.New("storage: seed frontier requires an open, unattached store")
}
if err := s.stickyIOFault(); err != nil {
return err
}
if lsn == ^uint64(0) || lsn < s.checkpointLSN || s.walHead > s.checkpointLSN || s.nextLSN > lsn+1 {
return errors.New("storage: seed frontier cannot replace local writes or wrap LSN")
}
if s.checkpointLSN == lsn && s.syncedLSN >= lsn && s.nextLSN == lsn+1 {
return nil
}
if err := s.syncCache(); err != nil {
return fmt.Errorf("storage: seed data sync: %w", err)
}
if s.metadata != nil {
if err := s.metadata.BeforeCheckpointAdvance(lsn); err != nil {
return fmt.Errorf("storage: block metadata before seed frontier %d: %w", lsn, err)
}
}
next := *s.sb
next.WALCheckpointLSN = lsn
next.WALHead = s.wal.logicalHeadValue()
buf := newSimpleByteBuf()
if _, err := next.writeTo(buf); err != nil {
return err
}
if err := s.syncFile(nil, func() error { return s.syncDirectFrontierMetadata(buf.bytes()) }); err != nil {
return fmt.Errorf("storage: seed metadata sync: %w", err)
}
*s.sb = next
s.checkpointLSN, s.syncedLSN, s.walHead, s.nextLSN = lsn, lsn, lsn, lsn+1
s.pendingDirectFrontierLSN = 0
return nil
return s.seedChunkFrontierV3(lsn)
}
// seedChunkFrontierV3 is SeedChunkFrontier on a dark v3 store (plan row 9):
@@ -135,6 +95,5 @@ func (s *WALStore) seedChunkFrontierV3Locked(lsn uint64, t *seedTimes) (err erro
s.mu.Lock()
defer s.mu.Unlock()
s.checkpointLSN, s.syncedLSN, s.walHead, s.nextLSN = lsn, lsn, lsn, lsn+1
s.pendingDirectFrontierLSN = 0
return nil
}
@@ -1,65 +0,0 @@
package storage
import (
"errors"
"testing"
)
func TestSeedChunkFrontierMetadataFailureRetry(t *testing.T) {
s, path := newLegacyChunkTestStore(t)
s.DisableAutoFlushForRecoveryTest()
syncMetadata := s.syncDirectFrontierMetadata
s.syncDirectFrontierMetadata = func([]byte) error { return errors.New("injected metadata fsync failure") }
if err := s.SeedChunkFrontier(7); err == nil {
t.Fatal("failed metadata sync accepted")
}
if next := s.NextLSN(); next != 1 {
t.Fatalf("failed seed advanced NextLSN to %d", next)
}
if r, _, h := s.Boundaries(); r != 0 || h != 0 {
t.Fatal("failed seed published frontier", r, h)
}
// The failed fsync is sticky for this open store (ErrFsyncFailed):
// neither a same-store Recover nor a seed retry may run on it.
s.syncDirectFrontierMetadata = syncMetadata
if _, err := s.Recover(); !errors.Is(err, ErrFsyncFailed) {
t.Fatalf("same-store Recover after a failed fsync: %v; want ErrFsyncFailed", err)
}
if err := s.SeedChunkFrontier(7); !errors.Is(err, ErrFsyncFailed) {
t.Fatalf("same-store seed retry after a failed fsync: %v; want ErrFsyncFailed", err)
}
_ = s.Close()
reopened, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
reopenedOpen := true
t.Cleanup(func() {
if reopenedOpen {
_ = reopened.Close()
}
})
if _, err := reopened.Recover(); err != nil {
t.Fatal(err)
}
if err := reopened.SeedChunkFrontier(7); err != nil {
t.Fatalf("seed after a reopen: %v", err)
}
if reopened.NextLSN() != 8 {
t.Fatal("seed after a reopen not applied")
}
reopened.committer.Stop()
_ = reopened.fd.Close() // crash
reopenedOpen = false
again, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
defer again.Close()
if _, err := again.Recover(); err != nil {
t.Fatal(err)
}
if r, _, h := again.Boundaries(); again.CheckpointLSN() != 7 || r != 7 || h != 7 || again.NextLSN() != 8 {
t.Fatalf("seed after a crash: checkpoint=%d R=%d H=%d next=%d want 7/7/7/8", again.CheckpointLSN(), r, h, again.NextLSN())
}
}
+75 -483
View File
@@ -6,7 +6,7 @@ package storage
//
// installMu (BASE transitions only) -> capMu -> WALStore.captureMu -> WALStore.lifecycleMu -> WALStore.mu
// extentMu[i] -> stMu
// WALStore.mu -> bmMu -> stMu (BeforeCheckpointAdvance runs under mu)
// WALStore.mu -> presMu -> stMu (BeforeCheckpointAdvance runs under mu)
//
// stMu guards the layer's in-memory state and is never held across a
// WALStore call, a bitmap store call or a remote call.
@@ -71,8 +71,8 @@ type chunkLayerImpl struct {
cowTransitions int
cowClosed bool
capMu sync.Mutex // serializes Capture, Evict, Begin/EndBaseInstall
bmMu sync.Mutex // serializes bitmap store calls
capMu sync.Mutex // serializes Capture, Evict, Begin/EndBaseInstall
presMu sync.Mutex // serializes a whole presence save: snapshot, fsync, replace, version
hydration map[uint64]*chunkHydrationFlight // under stMu
@@ -110,18 +110,8 @@ type chunkLayerImpl struct {
dirty map[uint64]bool // chunks dirtied since the cut in progress or the last HEAD
inflight map[uint64]bool // chunks captured by a cut whose HEAD is not yet installed
allDirty bool // a BASE block landed: every chunk is dirty
hashMode bool // the dirty set is unknown: reconcile every chunk against HEAD before any cut
// reconcile holds the chunks the reconciler has not compared yet;
// reconcileTotal is the size of the current reconciliation, and
// reconciled is closed when it is done or replaced (under stMu).
// reconcileGen names the current reconciliation: every start and every
// BeginBaseInstall bumps it, and a worker reads, updates and certifies
// only while its own generation is current.
reconcile map[uint64]bool
reconcileTotal int
reconciled chan struct{}
reconcileGen uint64
cutLSN uint64 // H of the latest cut taken (in flight or installed)
cutLSN uint64 // H of the latest cut taken (in flight or installed)
// chunkMut counts the mutations of each chunk: every dirty-map insert
// (any LSN, a replica apply's lower LSN included) and every BASE
// block. Flushing moves bytes without changing them and never counts.
@@ -146,19 +136,20 @@ type chunkLayerImpl struct {
// Absence: chunks whose local bytes are not authoritative (fresh host,
// evicted), and blocks written locally inside such chunks since.
absent map[uint64]bool
absentGen map[uint64]uint64 // bumped on every eviction; binds a fill to its generation
localBlocks map[uint64]bool
presenceVer uint64
savedPresVer uint64
dirtyVer uint64
savedDirtyVer uint64
absent map[uint64]bool
absentGen map[uint64]uint64 // bumped on every eviction; binds a fill to its generation
localBlocks map[uint64]bool
presenceVer uint64
savedPresVer uint64
dirtyVer uint64
}
func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) (chunkLayer, error) {
mapped := s.v3 != nil && s.v3.mapProof != nil
if remote == nil || cfg.ChunkBlocks == 0 || (!mapped && cfg.Bitmap == nil) {
return nil, errors.New("storage: chunk layer needs a remote, ChunkBlocks > 0 and a legacy bitmap unless the store owns an impl3 map")
if s.v3 == nil || s.v3.mapProof == nil {
return nil, fmt.Errorf("%w: chunk layer requires the native owned map", ErrMapInvalid)
}
if remote == nil || cfg.ChunkBlocks == 0 {
return nil, errors.New("storage: chunk layer needs a remote and ChunkBlocks > 0")
}
var localBase bool
s.captureMu.Lock()
@@ -166,7 +157,8 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
if s.attachClosed {
return nil, errChunkLayerClosed
}
if mapped {
{
// Serialize hook publication with begin/complete. Their outer hook
// snapshot is rechecked after taking this same barrier.
d := s.v3.pub.current()
@@ -178,7 +170,8 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
cfg.FreshFromHead = false
}
}
if s.v3 != nil && s.v3.ownedMap != nil && uint64(cfg.ChunkBlocks) != s.v3.ownedMap.chunkBlocks {
if s.v3.ownedMap != nil && uint64(cfg.ChunkBlocks) != s.v3.ownedMap.chunkBlocks {
return nil, fmt.Errorf("%w: chunk layer geometry differs from owned map", ErrMapInvalid)
}
if cfg.UploadConcurrency < 0 || cfg.UploadConcurrency > 64 {
@@ -228,7 +221,6 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
absent: map[uint64]bool{},
absentGen: map[uint64]uint64{},
localBlocks: map[uint64]bool{},
reconcile: map[uint64]bool{},
closeDone: make(chan struct{}),
syncDirFn: syncDir,
}
@@ -255,45 +247,9 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
// never used as this holder's publication guard.
l.fenced = l.supersededBy(head)
if mapped {
// Dirt is derived from the owned LSN map against the actual remote HEAD;
// no local HEAD-period bitmap header is loaded or created for impl3.
l.hdr = chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: head.Epoch}
} else {
hdr, saved, ok, err := cfg.Bitmap.Load()
if err != nil {
l.cancel()
return nil, fmt.Errorf("storage: chunk layer attach: load bitmap: %w", err)
}
switch {
case ok && hdr.Base == chunkBaseInstalling:
l.hdr = hdr // an interrupted BASE install: cuts stay refused
case ok && hdr.Base == chunkBaseInstalledAwaitingCut:
l.hdr, l.hashMode = hdr, true
case ok && hdr.BaseLSN == head.RemoteLSN && hdr.HeadGen == head.Gen && hdr.Epoch == head.Epoch:
l.hdr = hdr
for _, idx := range saved {
l.dirty[idx] = true
}
case !ok && cfg.FreshFromHead:
// A fresh local volume has taken no write yet (I/O waits for its
// first attach): its image is HEAD's, so nothing is dirty. Start with
// an empty bitmap bound to HEAD instead of hash mode, which stays for
// an existing volume whose bitmap is lost (integration ruling F1).
fresh := chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: head.Epoch, Base: chunkBaseNone}
if err := cfg.Bitmap.WriteHeader(fresh); err != nil {
l.hashMode = true // safe: compare every chunk on the first cut
} else {
l.hdr = fresh
}
default:
if ok {
l.hdr = hdr
}
l.hashMode = true
}
}
// Dirt is derived from the owned LSN map against the actual remote HEAD;
// no local HEAD-period bitmap header is loaded or created for impl3.
l.hdr = chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: head.Epoch}
if localBase {
// The completed BASE image is local authority, including ZERO blocks.
@@ -307,21 +263,8 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
// preserve ALL chunks as candidates for the first hash-comparing cut.
// Persist that obligation before publishing hooks/readiness.
l.hdr = chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: cfg.Epoch}
var initialDirty []uint64
l.dirty = map[uint64]bool{}
l.hashMode = !mapped && head.Gen == 0 && s.NextLSN() > 1
if l.hashMode {
for idx := uint64(0); idx < l.numChunks; idx++ {
l.dirty[idx] = true
initialDirty = append(initialDirty, idx)
}
}
if !mapped {
if err := cfg.Bitmap.Reset(l.hdr, initialDirty, chunkDelta{}); err != nil {
l.cancel()
return nil, fmt.Errorf("storage: fresh bitmap reset: %w", err)
}
}
for idx := range head.Chunks {
l.absent[idx] = true
l.absentGen[idx]++
@@ -332,11 +275,11 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
return nil, err
}
hooks := &chunkHooks{sink: l, closer: l.Close, mutated: l.noteMutation, recovered: l.noteAllMutated}
if mapped {
hooks.baseTransitionV3 = l.holdBaseTransitionV3
hooks.beforeMutation = l.beforeCOWMutation
hooks.beforeDestructive = l.holdCOWDestructive
}
hooks.baseTransitionV3 = l.holdBaseTransitionV3
hooks.beforeMutation = l.beforeCOWMutation
hooks.beforeDestructive = l.holdCOWDestructive
if !s.chunk.CompareAndSwap(nil, hooks) {
l.cancel()
return nil, errors.New("storage: a chunk layer is already attached")
@@ -346,9 +289,7 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
l.cancel()
return nil, err
}
if l.hashMode {
l.startReconcile()
}
return l, nil
}
@@ -433,21 +374,21 @@ func (l *chunkLayerImpl) noteAllMutated() {
// after the WAL entry has checkpointed and the legacy bitmap says clean.
func (l *chunkLayerImpl) captureCandidates() map[uint64]bool {
out := map[uint64]bool{}
mapped := l.usesOwnedMapV3()
var base uint64
if mapped {
l.stMu.Lock()
base = l.remoteLSN
l.stMu.Unlock()
}
l.stMu.Lock()
base = l.remoteLSN
l.stMu.Unlock()
for _, e := range l.s.dm.snapshot() {
// Retention in the local WAL is not dirt since HEAD. Lower-LSN
// BASE/direct changes remain conservative through UNKNOWN below.
if !mapped || e.LSN > base {
if e.LSN > base {
out[l.chunkOf(e.LBA)] = true
}
}
if mapped {
{
l.stMu.Lock()
absent := map[uint64]bool{}
for idx := range l.absent {
@@ -465,6 +406,7 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool {
}
l.s.mu.RUnlock()
}
return out
}
@@ -477,7 +419,7 @@ func (l *chunkLayerImpl) chunkVersion(idx uint64) uint64 {
// frontier path, under WALStore.mu: it makes the dirty set (and any changed
// absence state) durable before the checkpoint can pass the entries.
func (l *chunkLayerImpl) BeforeCheckpointAdvance(lsn uint64) error {
if l.usesOwnedMapV3() && l.s.v3.pub.current().BaseState == BaseInstalling {
if l.s.v3.pub.current().BaseState == BaseInstalling {
// Serving/capture remain blocked by the installing descriptor. Settle
// local BASE authority before the installed descriptor can publish;
// a failure leaves the volume installing, never serving a partial image.
@@ -487,68 +429,9 @@ func (l *chunkLayerImpl) BeforeCheckpointAdvance(lsn uint64) error {
l.presenceVer++
l.stMu.Unlock()
}
if err := l.saveDirty(); err != nil {
return err
}
return l.persistPresence()
}
// saveDirty persists dirty ÃÆ’Æ’Ãâ€šÂ¢ÃÆ’‹â€ÂÂ ÃÆ’‚ª inflight ÃÆ’Æ’Ãâ€šÂ¢ÃÆ’‹â€ÂÂ ÃÆ’‚ª the chunks of WAL entries still in
// the dirty map (all chunks when a BASE block landed or the set is unknown).
func (l *chunkLayerImpl) saveDirty() error {
// Impl3's actual checkpoint caller persists its owned map after this
// callback. It already tracks WAL mutations independently of this layer;
// making a second persistent C11 bitmap would add no coverage authority.
if l.usesOwnedMapV3() {
return nil
}
l.bmMu.Lock()
defer l.bmMu.Unlock()
set := l.dirtySetLocked(nil)
l.stMu.Lock()
ver := l.dirtyVer
if ver == l.savedDirtyVer && ver != 0 {
l.stMu.Unlock()
return nil
}
l.stMu.Unlock()
if err := l.cfg.Bitmap.Save(sortedKeys(set)); err != nil {
return err
}
l.stMu.Lock()
if ver > l.savedDirtyVer {
l.savedDirtyVer = ver
}
l.stMu.Unlock()
return nil
}
// dirtySetLocked returns the chunk set the persisted bitmap must cover.
// Caller holds bmMu (or capMu); stMu is taken here.
func (l *chunkLayerImpl) dirtySetLocked(extra map[uint64]bool) map[uint64]bool {
set := map[uint64]bool{}
for _, e := range l.s.dm.snapshot() {
set[l.chunkOf(e.LBA)] = true
}
l.stMu.Lock()
defer l.stMu.Unlock()
if l.allDirty || l.hashMode {
for i := uint64(0); i < l.numChunks; i++ {
set[i] = true
}
}
for idx := range l.dirty {
set[idx] = true
}
for idx := range l.inflight {
set[idx] = true
}
for idx := range extra {
set[idx] = true
}
return set
}
func sortedKeys(m map[uint64]bool) []uint64 {
out := make([]uint64, 0, len(m))
for k := range m {
@@ -640,44 +523,15 @@ func (s *WALStore) installFetchedBlock(lba uint32, data []byte, stillAbsent func
func (l *chunkLayerImpl) BeginBaseInstall() error {
l.capMu.Lock()
defer l.capMu.Unlock()
// A running reconciliation is superseded: its worker can neither
// certify a dirty set nor clear the install guard. EndBaseInstall
// starts a new one.
return l.writeBaseState(chunkBaseInstalling, func() { l.allDirty = true; l.reconcileGen++ })
return fmt.Errorf("%w: BASE state must be published by the descriptor install protocol", errV3NotYet)
}
func (l *chunkLayerImpl) EndBaseInstall(frontier uint64) error {
l.capMu.Lock()
defer l.capMu.Unlock()
if cp := l.s.CheckpointLSN(); cp < frontier {
return fmt.Errorf("storage: EndBaseInstall: frontier %d is not durable (checkpoint %d)", frontier, cp)
}
if err := l.writeBaseState(chunkBaseInstalledAwaitingCut, func() { l.hashMode = true }); err != nil {
return err
}
l.startReconcile()
return nil
}
func (l *chunkLayerImpl) writeBaseState(state chunkBaseState, apply func()) error {
if l.usesOwnedMapV3() {
return fmt.Errorf("%w: BASE state must be published by the descriptor install protocol", errV3NotYet)
}
l.bmMu.Lock()
defer l.bmMu.Unlock()
l.stMu.Lock()
hdr := l.hdr
l.stMu.Unlock()
hdr.Base = state
if err := l.cfg.Bitmap.WriteHeader(hdr); err != nil {
return err
}
l.stMu.Lock()
l.hdr = hdr
apply()
l.dirtyVer++
l.stMu.Unlock()
return nil
return fmt.Errorf("%w: BASE state must be published by the descriptor install protocol", errV3NotYet)
}
// ---- capture ----
@@ -706,7 +560,7 @@ func (l *chunkLayerImpl) admit() (err error) {
l.abortCOW(err)
}
}()
if l.usesOwnedMapV3() && l.s.v3.pub.current().BaseState == BaseInstalling {
if l.s.v3.pub.current().BaseState == BaseInstalling {
return fmt.Errorf("%w: %w", errChunkCaptureRefused, errChunkBaseInstalling)
}
l.stMu.Lock()
@@ -790,10 +644,6 @@ type stagedChunk struct {
headGen uint64
}
// chunkStageRounds bounds the pre-copy: after this many staging rounds the
// barrier copies whatever remains (correctness over pause).
const chunkStageRounds = 3
func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res chunkCutResult, err error) {
done, err := l.register()
if err != nil {
@@ -827,12 +677,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
if hook := l.testAfterAdmitHook; hook != nil {
hook()
}
l.stMu.Lock()
reconciling := l.hashMode
l.stMu.Unlock()
if reconciling { // no HEAD moves until the dirty set is known
return chunkCutResult{}, errChunkReconciling
}
ctx, cancel := l.opCtx(ctx)
defer cancel()
var budget *cutBudgetReservation
@@ -908,7 +753,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
candidates[idx] = true
}
l.stMu.Lock()
all := l.hashMode || l.allDirty
all := l.allDirty
for idx := range l.dirty {
candidates[idx] = true
}
@@ -927,9 +772,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
// was compared against.
var captured []capturedChunk
var capturedVersions map[uint64]uint64
if l.usesOwnedMapV3() {
capturedVersions = make(map[uint64]uint64, len(candidates))
}
capturedVersions = make(map[uint64]uint64, len(candidates))
useStaged := map[uint64]bool{}
for idx := range candidates {
if capturedVersions != nil {
@@ -964,7 +809,8 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
st.CandidateChunks = len(candidates)
var copyErr error
copyStart := time.Now()
if l.usesOwnedMapV3() {
{
var w *cutCOWWindow
w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks)
if copyErr == nil {
@@ -989,26 +835,12 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
st.COWSavedChunks = int(w.saved.Load())
st.COWSaveNs, st.COWWaitNs = w.saveNs.Load(), w.waitNs.Load()
}
} else {
st.BarrierCopyChunks = len(candidates) - len(useStaged)
for _, idx := range sortedKeys(candidates) {
if useStaged[idx] {
continue
}
buf, err := l.readChunk(idx)
if err != nil {
copyErr = err
break
}
captured = append(captured, capturedChunk{idx: idx, data: buf, sum: sha256.Sum256(buf), zero: isAllZero(buf)})
}
l.s.captureMu.Unlock()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
}
st.CopyNs = time.Since(copyStart).Nanoseconds()
if l.usesOwnedMapV3() {
st.UploadNs = st.CopyNs
}
st.UploadNs = st.CopyNs
if copyErr != nil {
l.abortCut(all)
l.dropIntents(ctx, intents)
@@ -1223,9 +1055,7 @@ func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) {
if r, ok := l.storedDetach(); ok {
return r, nil
}
if err := l.waitReconciled(ctx); err != nil {
return chunkCutResult{}, err
}
r, err := l.captureLocked(ctx, true)
if errors.Is(err, errChunkLayerDetached) {
if d, ok := l.storedDetach(); ok {
@@ -1525,213 +1355,16 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats {
}
out.PendingUnresolved = l.pending != nil
out.DirtyChunks = len(l.dirty)
out.Reconciling = l.hashMode
out.ReconcileTotal = l.reconcileTotal
out.ReconcileDone = l.reconcileTotal - len(l.reconcile)
out.Reconciling = false
out.ReconcileTotal = 0
out.ReconcileDone = 0
l.stMu.Unlock()
if l.usesOwnedMapV3() {
out.DirtyChunks = len(l.captureCandidates())
}
out.DirtyChunks = len(l.captureCandidates())
return out
}
// ---- reconciliation (the dirty set is unknown) ----
// reconcileSlice bounds one reconciler step; between steps it yields.
const reconcileSlice = 8
// startReconcile begins reconciling every chunk with a local copy against
// HEAD. A chunk that is absent and was never written locally is HEAD's
// content by definition and is skipped.
func (l *chunkLayerImpl) startReconcile() {
l.stMu.Lock()
set := map[uint64]bool{}
for i := uint64(0); i < l.numChunks; i++ {
if l.absent[i] && !l.chunkHasLocalLocked(i) {
continue
}
set[i] = true
}
l.reconcileGen++
gen := l.reconcileGen
if l.reconciled != nil {
close(l.reconciled) // a waiter on the replaced run re-checks
}
l.reconcile, l.reconcileTotal, l.reconciled = set, len(set), make(chan struct{})
l.stMu.Unlock()
// Nothing to compare (a fresh host: every HEAD chunk is absent and no
// block was written): the dirty set is known now, with no window in
// which cuts are refused.
if len(set) == 0 && l.cfg.testReconcileHold == nil && l.cfg.testReconcileHook == nil && l.finishReconcile(gen) {
return
}
done, err := l.register()
if err != nil {
return
}
go l.reconcileLoop(done, gen)
}
// reconcileLoop compares the chunks in the reconcile set with HEAD outside
// the capture barrier, a slice at a time: a chunk whose bytes differ from
// HEAD's becomes dirty. A write racing the comparison marks its chunk
// dirty anyway, so a chunk is never lost. When the set is empty the dirty
// set is exact: it is persisted with a header naming HEAD, and cuts resume.
func (l *chunkLayerImpl) reconcileLoop(done func(), gen uint64) {
defer done()
for {
if l.ctx.Err() != nil {
return
}
if hold := l.cfg.testReconcileHold; hold != nil {
select {
case <-hold:
case <-l.ctx.Done():
return
}
}
if hook := l.cfg.testReconcileHook; hook != nil {
hook("batch", gen)
}
l.stMu.Lock()
if l.reconcileGen != gen { // superseded
l.stMu.Unlock()
return
}
var batch []uint64
for _, idx := range sortedKeys(l.reconcile) {
if len(batch) == reconcileSlice {
break
}
batch = append(batch, idx)
}
head := copyHead(l.head)
l.stMu.Unlock()
if len(batch) == 0 {
if hook := l.cfg.testReconcileHook; hook != nil {
hook("finish", gen)
}
if l.finishReconcile(gen) {
return
}
if !l.sleep(100 * time.Millisecond) {
return
}
continue
}
for _, idx := range batch {
data, err := l.readChunk(idx)
if err != nil {
if !l.sleep(100 * time.Millisecond) { // retried; the set keeps it
return
}
break
}
ref, had := head.Chunks[idx]
same := (!had && isAllZero(data)) || (had && sha256.Sum256(data) == ref.SHA256)
if hook := l.cfg.testReconcileHook; hook != nil {
hook("compared", gen)
}
l.stMu.Lock()
if l.reconcileGen != gen { // superseded: the replacement owns the set
l.stMu.Unlock()
return
}
if !same {
l.dirty[idx] = true
l.dirtyVer++
}
delete(l.reconcile, idx)
l.stMu.Unlock()
}
}
}
// finishReconcile persists reconciliation gen's dirty set and leaves hash
// mode. It reports false when the bitmap could not be written (retried),
// and true when done or when gen is no longer current: a superseded run
// (replaced, or a BASE install began) writes nothing and certifies
// nothing. bmMu is held throughout, so no BASE state change interleaves.
func (l *chunkLayerImpl) finishReconcile(gen uint64) bool {
l.bmMu.Lock()
defer l.bmMu.Unlock()
l.stMu.Lock()
if l.reconcileGen != gen || len(l.reconcile) != 0 || l.hdr.Base == chunkBaseInstalling {
l.stMu.Unlock()
return true
}
still := map[uint64]bool{}
for idx := range l.dirty {
still[idx] = true
}
if l.allDirty {
for i := uint64(0); i < l.numChunks; i++ {
still[i] = true
}
}
hdr := chunkBitmapHeader{BaseLSN: l.head.RemoteLSN, HeadGen: l.head.Gen, Epoch: l.head.Epoch, Base: chunkBaseNone}
ver := l.dirtyVer
l.stMu.Unlock()
// The dirty set first, then the header naming HEAD: a crash between
// the two leaves the old header, which mismatches HEAD, so the next
// attach reconciles again instead of trusting an incomplete bitmap.
if !l.usesOwnedMapV3() {
if err := l.cfg.Bitmap.Save(sortedKeys(still)); err != nil {
return false
}
if err := l.cfg.Bitmap.WriteHeader(hdr); err != nil {
return false
}
}
l.stMu.Lock()
defer l.stMu.Unlock()
l.hdr, l.hashMode = hdr, false
if ver > l.savedDirtyVer {
l.savedDirtyVer = ver
}
if l.reconciled != nil {
close(l.reconciled)
l.reconciled = nil
}
return true
}
// waitReconciled returns once the layer is not reconciling, or
// errChunkReconciling when ctx ends first. A replaced run wakes its
// waiters, which re-check against the current one.
func (l *chunkLayerImpl) waitReconciled(ctx context.Context) error {
for {
l.stMu.Lock()
reconciling, ch := l.hashMode, l.reconciled
l.stMu.Unlock()
if !reconciling {
return nil
}
if ch == nil {
return errChunkReconciling
}
select {
case <-ch:
case <-ctx.Done():
return fmt.Errorf("%w: %w", errChunkReconciling, ctx.Err())
case <-l.ctx.Done():
return errors.New("storage: chunk layer closed")
}
}
}
// sleep waits d unless the layer closes first.
func (l *chunkLayerImpl) sleep(d time.Duration) bool {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-t.C:
return true
case <-l.ctx.Done():
return false
}
}
// dropIntent deletes this layer's own intent id (none if empty) once its
// cut is settled. A failed delete is kept and retried by the next cut; it
// never fails a cut whose outcome is already settled.
@@ -1792,17 +1425,11 @@ func (l *chunkLayerImpl) dropIntents(ctx context.Context, ids []string) {
// stage uploads large native dirty sets through logical reads, before fixing H.
// It stops when the spill-budget remainder is reached or a round makes no
// progress. Versions/HEAD generation bind every reusable immutable result.
// Legacy fixtures retain their bounded-count rounds.
func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint64]stagedChunk, []string, error) {
bound := l.cfg.BarrierBound
native := l.usesOwnedMapV3()
if native {
// Leave at most half the side budget exposed at the barrier. Streaming
// staging uses no local payload file, even for a much larger image.
bound = int(l.cfg.COWSpillLimit / (2 * int64(l.blockSize) * int64(l.chunkBlocks)))
} else if bound <= 0 {
return nil, nil, nil
}
// Leave at most half the side budget exposed at the barrier. Streaming
// staging uses no local payload file, even for a much larger image.
bound := int(l.cfg.COWSpillLimit / (2 * int64(l.blockSize) * int64(l.chunkBlocks)))
staged := map[uint64]stagedChunk{}
var intents []string
l.stMu.Lock()
@@ -1830,7 +1457,7 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint
for idx := range l.dirty {
consider(idx)
}
if l.hashMode || l.allDirty {
if l.allDirty {
for i := uint64(0); i < l.numChunks; i++ {
if l.absent[i] && !l.chunkHasLocalLocked(i) {
continue
@@ -1838,7 +1465,7 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint
consider(i)
}
}
if len(need) <= bound || (native && len(need) >= previous) || (!native && round >= chunkStageRounds) {
if len(need) <= bound || (len(need) >= previous) {
l.stMu.Unlock()
break
}
@@ -1847,17 +1474,15 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint
// Release layer state before sampling the store; never invert store -> stMu.
l.stMu.Unlock()
l.s.mu.RLock()
if l.usesOwnedMapV3() {
for idx := range need {
recent[idx] = l.s.v3.mapEntries[idx].LSN
}
for idx := range need {
recent[idx] = l.s.v3.mapEntries[idx].LSN
}
l.s.mu.RUnlock()
l.stMu.Lock()
batch := hotChunkKeys(need, recent)
if !native {
batch = batch[:bound]
}
vers := make(map[uint64]uint64, len(batch))
for _, idx := range batch {
vers[idx] = l.chunkVersion(idx) // before the read: a later mutation raises it
@@ -1909,46 +1534,13 @@ func (l *chunkLayerImpl) abortCut(all bool) {
// finishCut installs HEAD in memory and rolls the bitmap over: only chunks
// dirtied after the cut (and WAL entries above it) stay set.
func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, newKeys map[uint64]string) {
l.bmMu.Lock()
defer l.bmMu.Unlock()
still := map[uint64]bool{}
for _, e := range l.s.dm.snapshot() {
if e.LSN > h {
still[l.chunkOf(e.LBA)] = true
}
}
l.stMu.Lock()
for idx := range l.dirty {
still[idx] = true
}
if l.allDirty {
for i := uint64(0); i < l.numChunks; i++ {
still[i] = true
}
}
prevBase := l.hdr.BaseLSN
defer l.stMu.Unlock()
l.head, l.remoteLSN, l.pending = copyHead(head), h, nil
l.reusable = nil
l.inflight = map[uint64]bool{}
l.hashMode = false
hdr := chunkBitmapHeader{BaseLSN: h, HeadGen: head.Gen, Epoch: head.Epoch, Base: chunkBaseNone}
l.hdr = hdr
l.hdr = chunkBitmapHeader{BaseLSN: h, HeadGen: head.Gen, Epoch: head.Epoch, Base: chunkBaseNone}
l.dirtyVer++
ver := l.dirtyVer
l.stMu.Unlock()
sort.Slice(changed, func(i, j int) bool { return changed[i] < changed[j] })
delta := chunkDelta{FromLSN: prevBase, ToLSN: h, Gen: head.Gen, Dirty: changed, NewKeys: newKeys}
// HEAD is published; a failed Reset only leaves a stale header, which a
// restart treats as a mismatch (hash compare): safe.
if !l.usesOwnedMapV3() {
if err := l.cfg.Bitmap.Reset(hdr, sortedKeys(still), delta); err == nil {
l.stMu.Lock()
if ver > l.savedDirtyVer {
l.savedDirtyVer = ver
}
l.stMu.Unlock()
}
}
}
func (l *chunkLayerImpl) newKey(idx uint64) string {
@@ -1981,7 +1573,7 @@ func (l *chunkLayerImpl) EvictChunk(idx uint64) error {
dirtyCandidate := l.captureCandidates()[idx]
l.stMu.Lock()
switch {
case l.head.Gen == 0, l.hashMode, l.allDirty, l.hdr.Base != chunkBaseNone, l.dirty[idx], l.inflight[idx], dirtyCandidate:
case l.head.Gen == 0, l.allDirty, l.hdr.Base != chunkBaseNone, l.dirty[idx], l.inflight[idx], dirtyCandidate:
l.stMu.Unlock()
return fmt.Errorf("%w: chunk %d is dirty since HEAD or HEAD is unknown", errChunkEvictRefused, idx)
}
@@ -9,9 +9,6 @@ package storage
// It may over-report, never under-report. RED until the layer exists.
import (
"bytes"
"errors"
"sync"
"testing"
)
@@ -26,65 +23,8 @@ func extentBytes(t *testing.T, s *WALStore, lba uint32) []byte {
return b
}
// walLogicalTail is the WAL writer's physical recycling position.
func walLogicalTail(s *WALStore) uint64 {
if s.v3 != nil {
return s.v3.pub.current().RetainedTail
}
s.wal.mu.Lock()
defer s.wal.mu.Unlock()
return s.wal.logicalTail
}
// saveLog records, for every Save, the dirty set and the store's checkpoint
// and WAL logical tail at that moment (inside Save, before it returns).
type saveLog struct {
mu sync.Mutex
rows []savedRow
}
type savedRow struct {
checkpoint uint64
walTail uint64
dirty map[uint64]bool
}
func recordSaves(s *WALStore, bm *fakeBitmapStore) *saveLog {
l := &saveLog{}
bm.mu.Lock()
bm.onSave = func(dirty []uint64) {
// Save runs inside persistCheckpoint, under the store's publication
// lock: read the fields directly, never re-lock the store. Only the
// flusher/Sync goroutine that holds that lock writes them.
row := savedRow{checkpoint: s.checkpointLSN, walTail: s.wal.logicalTail, dirty: map[uint64]bool{}}
for _, idx := range dirty {
row.dirty[idx] = true
}
l.mu.Lock()
l.rows = append(l.rows, row)
l.mu.Unlock()
}
bm.mu.Unlock()
return l
}
// firstSaveWith returns the first recorded Save whose dirty set holds idx.
func (l *saveLog) firstSaveWith(idx uint64) (savedRow, bool) {
l.mu.Lock()
defer l.mu.Unlock()
for _, r := range l.rows {
if r.dirty[idx] {
return r, true
}
}
return savedRow{}, false
}
func (l *saveLog) count() int {
l.mu.Lock()
defer l.mu.Unlock()
return len(l.rows)
}
// walLogicalTail is the native retained cursor.
func walLogicalTail(s *WALStore) uint64 { return s.v3.pub.current().RetainedTail }
func flushWithin(t *testing.T, s *WALStore, what string) error {
t.Helper()
@@ -92,509 +32,3 @@ func flushWithin(t *testing.T, s *WALStore, what string) error {
within(t, what, func() error { ferr = s.flusher.flushOnce(); return nil })
return ferr
}
// C11 callbacks: OnExtentWrite, for a normal and a BASE block, returns at
// once while bitmap persistence and the remote are held and the store's
// publication lock is taken: no Load/Save/WriteHeader/Reset, no remote call,
// no WALStore re-entry. (A BASE mark must also be a constant-time flag; that
// cost bound is measured in the implementation PR, not proven here.)
func TestChunkLayer_C11_ExtentCallbackIsPureInMemory(t *testing.T) {
s, _ := newLegacyChunkTestStore(t)
f := newFakeChunkRemote()
cfg := ctConfig(1)
bm := cfg.Bitmap.(*fakeBitmapStore)
layer := mustAttach(t, s, f, cfg)
holdPuts(t, f)
holdGets(t, f)
block := make(chan struct{})
var unblock sync.Once
bm.mu.Lock()
bm.block = block
bm.mu.Unlock()
release := func() { unblock.Do(func() { close(block) }) }
t.Cleanup(release)
onUnblock(t, release)
callsBefore, remoteBefore := bm.callCount(), f.stats()
s.mu.Lock() // a callback that re-enters the store would block here
var unlock sync.Once
unlockStore := func() { unlock.Do(s.mu.Unlock) }
t.Cleanup(unlockStore)
onUnblock(t, unlockStore)
within(t, "OnExtentWrite for a normal block and a BASE block", func() error {
layer.OnExtentWrite(12, 7)
layer.OnExtentWrite(13, 0)
return nil
})
unlock.Do(s.mu.Unlock)
if n := bm.callCount() - callsBefore; n != 0 {
t.Fatalf("OnExtentWrite made %d bitmap store calls", n)
}
after := f.stats()
if after.puts != remoteBefore.puts || after.gets != remoteBefore.gets || after.getHeads != remoteBefore.getHeads || after.cas != remoteBefore.cas {
t.Fatal("OnExtentWrite made remote calls")
}
}
// C11 ordering and period: writes never touch the bitmap; the flusher saves
// a dirty set covering a chunk before the checkpoint or the physical WAL
// tail passes that chunk's entries; a cut archives the closed period as a
// delta and starts a new bitmap headed by the new HEAD; a failed save
// refuses the advance (checkpoint and WAL tail unchanged), and a restart
// still captures the chunk from the WAL.
func TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle(t *testing.T) {
s, path, crash := legacyCrashableStore(t)
f := newFakeChunkRemote()
cfg := ctConfig(1)
bm := cfg.Bitmap.(*fakeBitmapStore)
layer := mustAttach(t, s, f, cfg)
saves := recordSaves(s, bm)
w := newWriteLog()
var lsn uint64
within(t, "write and Sync to chunk 3 (the bitmap is off the write path)", func() error {
var err error
if lsn, err = s.Write(12, makeBlock(ctBlockSize, 0x3C)); err != nil {
return err
}
w.record(lsn, 12, makeBlock(ctBlockSize, 0x3C))
_, err = s.Sync()
return err
})
if n := saves.count(); n != 0 {
t.Fatalf("a write and Sync saved the bitmap %d times; it must stay off the write path", n)
}
tailBefore := walLogicalTail(s)
if err := flushWithin(t, s, "flush of chunk 3"); err != nil {
t.Fatal(err)
}
row, ok := saves.firstSaveWith(3)
if !ok {
t.Fatal("the flusher recycled chunk 3's WAL entries without saving a bitmap that covers chunk 3")
}
if row.checkpoint >= lsn || row.walTail != tailBefore {
t.Fatalf("chunk 3 saved at checkpoint %d / WAL tail %d; want checkpoint < %d and the tail still at %d", row.checkpoint, row.walTail, lsn, tailBefore)
}
if s.CheckpointLSN() < lsn || walLogicalTail(s) <= tailBefore || !bm.persisted(3) {
t.Fatalf("after the flush: checkpoint %d (want >= %d), WAL tail %d (want > %d), chunk 3 persisted %v", s.CheckpointLSN(), lsn, walLogicalTail(s), tailBefore, bm.persisted(3))
}
cut, err := layer.Capture(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
head := f.stats().head
hdr, deltas, _ := bm.snapshot()
if want := (chunkBitmapHeader{BaseLSN: cut, HeadGen: head.Gen, Epoch: 1}); hdr != want {
t.Fatalf("bitmap header after the cut %+v, want %+v", hdr, want)
}
if len(deltas) != 1 {
t.Fatalf("%d delta records archived, want 1", len(deltas))
}
d := deltas[0]
if d.FromLSN != 0 || d.ToLSN != cut || d.Gen != head.Gen || len(d.Dirty) != 1 || d.Dirty[0] != 3 || d.NewKeys[3] != head.Chunks[3].Key {
t.Fatalf("delta %+v, want {from 0 to %d gen %d dirty [3] key %q}", d, cut, head.Gen, head.Chunks[3].Key)
}
if bm.persisted(3) {
t.Fatal("chunk 3 is still marked dirty in the new period although the cut captured it")
}
// A failed save refuses the advance; the WAL keeps the entry.
bm.mu.Lock()
bm.failSave = errors.New("injected bitmap save failure")
bm.mu.Unlock()
lsn20 := w.write(t, s, 20, 0x50) // chunk 5
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
cpBefore, tailBefore := s.CheckpointLSN(), walLogicalTail(s)
if err := flushWithin(t, s, "flush with a failing bitmap save"); err == nil {
t.Fatal("the flusher advanced although the bitmap could not be saved")
}
if cp, tail := s.CheckpointLSN(), walLogicalTail(s); cp != cpBefore || tail != tailBefore || cp >= lsn20 {
t.Fatalf("failed save moved checkpoint %d -> %d or WAL tail %d -> %d (LSN %d unprotected)", cpBefore, cp, tailBefore, tail, lsn20)
}
bm.mu.Lock()
bm.failSave = nil
bm.mu.Unlock()
crash()
s2, _ := legacyReopen(t, path)
layer2 := mustAttach(t, s2, f, cfg)
before := f.stats()
if _, err := layer2.Capture(ctTimeout(t)); err != nil {
t.Fatalf("capture after restart: %v", err)
}
if n := f.stats().puts - before.puts; n != 1 {
t.Fatalf("capture after restart stored %d chunks, want 1 (chunk 5, known only from the WAL)", n)
}
assertEveryHeadIsPrefixImage(t, f, w)
}
// C11 rollover: while a cut's upload is held, a post-cut write is flushed
// and its WAL recycled (so only the bitmap remembers it). The cut's Reset
// must keep that chunk dirty, and after a crash the next capture uploads it.
func TestChunkLayer_C11_RolloverKeepsPostCutDirt(t *testing.T) {
s, path, crash := legacyCrashableStore(t)
f := newFakeChunkRemote()
cfg := ctConfig(1)
bm := cfg.Bitmap.(*fakeBitmapStore)
layer := mustAttach(t, s, f, cfg)
w := newWriteLog()
w.write(t, s, 4, 0x14) // chunk 1, captured by the held cut
entered, release := holdPuts(t, f)
done := startCapture(t, layer)
waitKey(t, entered, "held cut upload")
within(t, "post-cut write, sync and flush while the cut is held", func() error {
data := makeBlock(ctBlockSize, 0x26)
lsn, err := s.Write(24, data) // chunk 6, after the cut
if err != nil {
return err
}
w.record(lsn, 24, data)
if _, err := s.Sync(); err != nil {
return err
}
return s.flusher.flushOnce()
})
release()
if err := waitErr(t, done, "held cut"); err != nil {
t.Fatalf("held cut: %v", err)
}
if !bm.persisted(6) {
t.Fatal("the cut's Reset cleared chunk 6, dirtied after the cut with its WAL already recycled")
}
if bm.persisted(1) {
t.Fatal("the cut's Reset kept chunk 1, which the cut captured")
}
crash()
s2, _ := legacyReopen(t, path)
layer2 := mustAttach(t, s2, f, cfg)
before := f.stats()
if _, err := layer2.Capture(ctTimeout(t)); err != nil {
t.Fatalf("capture after restart: %v", err)
}
if n := f.stats().puts - before.puts; n != 1 {
t.Fatalf("capture after restart stored %d chunks, want 1 (chunk 6)", n)
}
assertEveryHeadIsPrefixImage(t, f, w)
}
// c11BaseFixture: HEAD covers chunks 0 and 5; then a BASE rebuild rewrites
// LBA 20 (chunk 5) and LBA 24 (chunk 6) through WriteExtentDirect, advances
// the frontier and Syncs (the direct-frontier checkpoint path).
// - failSave: the bitmap save on that path fails. Sync must return an
// error and leave the checkpoint and the physical WAL tail unchanged,
// and EndBaseInstall must refuse because the frontier is not durable.
// - otherwise the checkpoint reaches the frontier; complete then also
// calls EndBaseInstall(frontier), which must durably record the
// completed install.
//
// Then the host crashes.
func c11BaseFixture(t *testing.T, failSave, complete bool) (path string, f *fakeChunkRemote, cfg chunkLayerConfig, frontier uint64) {
t.Helper()
s, path, crash := legacyCrashableStore(t)
f = newFakeChunkRemote()
cfg = ctConfig(1)
bm := cfg.Bitmap.(*fakeBitmapStore)
layer := mustAttach(t, s, f, cfg)
w := newWriteLog()
w.write(t, s, 1, 0x01) // chunk 0
last := w.write(t, s, 21, 0x21) // chunk 5
// Flush first: the direct-frontier checkpoint below covers every LSN up
// to the frontier, so recovery would skip unflushed WAL entries (a real
// rebuild installs the whole image).
mustSyncFlush(t, s)
if _, err := layer.Capture(ctTimeout(t)); err != nil {
t.Fatal(err)
}
if err := layer.BeginBaseInstall(); err != nil {
t.Fatalf("BeginBaseInstall: %v", err)
}
if hdr, _, _ := bm.snapshot(); hdr.Base != chunkBaseInstalling {
t.Fatalf("BeginBaseInstall returned before an installing header was durable (header %+v)", hdr)
}
if _, err := layer.Capture(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) {
t.Fatalf("Capture during a BASE install: got %v, want errChunkCaptureRefused", err)
}
frontier = last + 10
for lba, fill := range map[uint32]byte{20: 0xB5, 24: 0xB6} {
if err := s.WriteExtentDirect(lba, makeBlock(ctBlockSize, fill)); err != nil {
t.Fatal(err)
}
}
if err := layer.EndBaseInstall(frontier); err == nil {
t.Fatal("EndBaseInstall accepted a frontier that is not durable yet")
}
if failSave {
bm.mu.Lock()
bm.failSave = errors.New("injected bitmap save failure")
bm.mu.Unlock()
}
s.AdvanceFrontier(frontier)
cpBefore, tailBefore := s.CheckpointLSN(), walLogicalTail(s)
_, syncErr := s.Sync() // persists the direct frontier as the checkpoint
if failSave {
if syncErr == nil {
t.Fatal("BASE Sync succeeded although its bitmap save failed")
}
if cp, tail := s.CheckpointLSN(), walLogicalTail(s); cp != cpBefore || tail != tailBefore {
t.Fatalf("failed bitmap save still moved checkpoint %d -> %d or WAL tail %d -> %d", cpBefore, cp, tailBefore, tail)
}
if err := layer.EndBaseInstall(frontier); err == nil {
t.Fatal("EndBaseInstall accepted a frontier whose checkpoint was refused")
}
bm.mu.Lock()
bm.failSave = nil
bm.mu.Unlock()
} else {
if syncErr != nil {
t.Fatalf("BASE Sync: %v", syncErr)
}
if cp := s.CheckpointLSN(); cp < frontier {
t.Fatalf("BASE Sync returned nil but the checkpoint is %d < frontier %d", cp, frontier)
}
if complete {
if err := layer.EndBaseInstall(frontier); err != nil {
t.Fatalf("EndBaseInstall after the durable frontier: %v", err)
}
if hdr, _, _ := bm.snapshot(); hdr.Base != chunkBaseInstalledAwaitingCut {
t.Fatalf("EndBaseInstall returned before the completed install was durable (header %+v)", hdr)
}
}
}
crash()
return path, f, cfg, frontier
}
// assertBaseCutUploadsChangedChunks runs the first cut after a BASE rebuild:
// a full hash compare that stores exactly chunks 5 and 6, keeps chunk 0's
// ref, publishes the BASE blocks, and leaves a normal header for the new HEAD.
func assertBaseCutUploadsChangedChunks(t *testing.T, layer chunkLayer, f *fakeChunkRemote, cfg chunkLayerConfig) {
t.Helper()
before := f.stats()
if _, err := layer.Capture(ctTimeout(t)); err != nil {
t.Fatalf("first cut after the rebuild: %v", err)
}
after := f.stats()
if n := after.puts - before.puts; n != 2 {
t.Fatalf("first cut after the rebuild stored %d chunks, want 2 (chunks 5 and 6)", n)
}
if after.head.Chunks[0] != before.head.Chunks[0] {
t.Fatal("unchanged chunk 0 was re-published")
}
for lba, fill := range map[uint32]byte{20: 0xB5, 24: 0xB6} {
if got := blockOf(f.imageOf(t, after.head), lba); !bytes.Equal(got, makeBlock(ctBlockSize, fill)) {
t.Fatalf("BASE block LBA %d missing from the post-rebuild HEAD", lba)
}
}
bm := cfg.Bitmap.(*fakeBitmapStore)
if hdr, _, _ := bm.snapshot(); hdr.Base != chunkBaseNone || hdr.HeadGen != after.head.Gen {
t.Fatalf("header after the post-rebuild cut %+v, want a normal header for HEAD gen %d", hdr, after.head.Gen)
}
assertNoRemoteMisuse(t, f)
}
// rerunBase repeats a complete BASE install of the same blocks after a
// restart, as the owner must after an interrupted one.
func rerunBase(t *testing.T, s *WALStore, layer chunkLayer, frontier uint64) {
t.Helper()
if err := layer.BeginBaseInstall(); err != nil {
t.Fatalf("BeginBaseInstall after restart: %v", err)
}
for lba, fill := range map[uint32]byte{20: 0xB5, 24: 0xB6} {
if err := s.WriteExtentDirect(lba, makeBlock(ctBlockSize, fill)); err != nil {
t.Fatal(err)
}
}
s.AdvanceFrontier(frontier)
if _, err := s.Sync(); err != nil {
t.Fatalf("BASE Sync after restart: %v", err)
}
if err := layer.EndBaseInstall(frontier); err != nil {
t.Fatalf("EndBaseInstall after restart: %v", err)
}
waitReconciledForTest(t, layer) // the BASE is reconciled against HEAD first
}
// C11 BASE: recovery never infers that an install finished. An install
// interrupted by a crash (header still installing) keeps cuts refused after
// restart until the owner completes a new install; a completed install
// (EndBaseInstall durable) allows the first cut, which hashes fully. With
// the bitmap save failing on the direct-frontier path, Sync errors and
// neither the checkpoint nor the WAL tail moves.
func TestChunkLayer_C11_BaseRebuildRecovery(t *testing.T) {
t.Run("interrupted install", func(t *testing.T) {
path, f, cfg, frontier := c11BaseFixture(t, false, false)
s2, _ := legacyReopen(t, path)
layer2 := mustAttach(t, s2, f, cfg)
before := f.stats()
if _, err := layer2.Capture(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) {
t.Fatalf("cut after an interrupted install: got %v, want errChunkCaptureRefused", err)
}
if after := f.stats(); after.puts != before.puts || after.cas != before.cas {
t.Fatal("refused cut made remote calls")
}
rerunBase(t, s2, layer2, frontier)
assertBaseCutUploadsChangedChunks(t, layer2, f, cfg)
})
t.Run("completed install", func(t *testing.T) {
path, f, cfg, _ := c11BaseFixture(t, false, true)
s2, _ := legacyReopen(t, path)
layer2 := mustAttach(t, s2, f, cfg)
assertBaseCutUploadsChangedChunks(t, layer2, f, cfg)
})
t.Run("bitmap save fails on the direct-frontier path", func(t *testing.T) {
path, f, cfg, frontier := c11BaseFixture(t, true, false)
s2, _ := legacyReopen(t, path)
layer2 := mustAttach(t, s2, f, cfg)
if _, err := layer2.Capture(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) {
t.Fatalf("cut after an install whose frontier never became durable: got %v, want errChunkCaptureRefused", err)
}
rerunBase(t, s2, layer2, frontier)
assertBaseCutUploadsChangedChunks(t, layer2, f, cfg)
})
}
// C11 over-report only: the bitmap save succeeds but the checkpoint publish
// then fails; after a crash the next capture may over-report, but its image
// is exact and nothing is missed.
func TestChunkLayer_C11_SaveThenCheckpointFailureOverReportsOnly(t *testing.T) {
s, path, crash := legacyCrashableStore(t)
f := newFakeChunkRemote()
cfg := ctConfig(1)
layer := mustAttach(t, s, f, cfg)
w := newWriteLog()
w.write(t, s, 1, 0x01)
if _, err := layer.Capture(ctTimeout(t)); err != nil {
t.Fatal(err)
}
w.write(t, s, 24, 0x24) // chunk 6
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
s.syncSuperblockMetadata = func() error { return errors.New("injected checkpoint sync failure") }
if err := flushWithin(t, s, "flush whose checkpoint publish fails"); err == nil {
t.Fatal("the flush succeeded although its checkpoint publish failed")
}
crash()
s2, _ := legacyReopen(t, path)
layer2 := mustAttach(t, s2, f, cfg)
if _, err := layer2.Capture(ctTimeout(t)); err != nil {
t.Fatalf("capture after restart: %v", err)
}
assertEveryHeadIsPrefixImage(t, f, w)
}
// c11RestartFixture: HEAD covers chunks 0 and 5; then chunk 6 is written and
// flushed (its WAL recycled, so only the persisted bitmap remembers it) and
// chunk 7 is written and synced but not flushed (only the WAL remembers
// it); then the host crashes and recovers. Whatever beforeReattach does to
// the persisted bitmap, the next capture must upload exactly chunks 6 and 7
// and keep the refs of the unchanged chunks.
func c11RestartFixture(t *testing.T, beforeReattach func(bm *fakeBitmapStore)) {
t.Helper()
s, path, crash := legacyCrashableStore(t)
f := newFakeChunkRemote()
cfg := ctConfig(1)
bm := cfg.Bitmap.(*fakeBitmapStore)
layer := mustAttach(t, s, f, cfg)
w := newWriteLog()
w.write(t, s, 1, 0x01) // chunk 0
w.write(t, s, 21, 0x21) // chunk 5
if _, err := layer.Capture(ctTimeout(t)); err != nil {
t.Fatal(err)
}
w.write(t, s, 24, 0x24) // chunk 6: flushed, WAL recycled
mustSyncFlush(t, s)
w.write(t, s, 28, 0x28) // chunk 7: synced only
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
crash()
s2, _ := legacyReopen(t, path)
if beforeReattach != nil {
bm.mu.Lock()
beforeReattach(bm)
bm.mu.Unlock()
}
layer2 := mustAttach(t, s2, f, cfg)
before := f.stats()
if _, err := layer2.Capture(ctTimeout(t)); err != nil {
t.Fatalf("capture after restart: %v", err)
}
after := f.stats()
if n := after.puts - before.puts; n != 2 {
t.Fatalf("capture after restart stored %d chunks, want exactly 2 (chunks 6 and 7)", n)
}
for _, idx := range []uint64{0, 5} {
if after.head.Chunks[idx] != before.head.Chunks[idx] {
t.Fatalf("unchanged chunk %d was re-published under a new ref", idx)
}
}
assertEveryHeadIsPrefixImage(t, f, w)
for _, h := range f.installedHeads() {
for idx, ref := range h.Chunks {
if ref.SHA256 == ([32]byte{}) {
t.Fatalf("HEAD gen %d chunk %d carries no SHA-256", h.Gen, idx)
}
}
}
}
// C11 restart, header matches HEAD: incremental, dirty = persisted bitmap ∪
// chunks of WAL entries above the checkpoint; nothing missed, nothing
// unchanged re-sent.
func TestChunkLayer_C11_IncrementalAfterRestart(t *testing.T) {
c11RestartFixture(t, nil)
}
// C11 fallback: a lost bitmap, or a header that differs from HEAD in any
// field (including a completed BASE awaiting its first cut), falls back to a per-chunk SHA-256
// compare and uploads only the chunks whose bytes differ.
func TestChunkLayer_C11_LostOrMismatchedBitmapFallsBackToHashCompare(t *testing.T) {
for name, mutate := range map[string]func(bm *fakeBitmapStore){
"lost": func(bm *fakeBitmapStore) { bm.lostNext = true },
"head gen mismatch": func(bm *fakeBitmapStore) { bm.hdr.HeadGen += 7; bm.dirty = map[uint64]bool{} },
"epoch mismatch": func(bm *fakeBitmapStore) { bm.hdr.Epoch++; bm.dirty = map[uint64]bool{} },
"base lsn mismatch": func(bm *fakeBitmapStore) { bm.hdr.BaseLSN += 3; bm.dirty = map[uint64]bool{} },
"completed BASE awaiting its first cut": func(bm *fakeBitmapStore) { bm.hdr.Base = chunkBaseInstalledAwaitingCut; bm.dirty = map[uint64]bool{} },
} {
t.Run(name, func(t *testing.T) { c11RestartFixture(t, mutate) })
}
}
// C11 replica: the replica apply path goes through the same flusher, so a
// promoted replica's bitmap covers its applied chunks before their WAL
// entries are recycled.
func TestChunkLayer_C11_ReplicaApplyKeepsBitmap(t *testing.T) {
s, _ := newLegacyChunkTestStore(t)
f := newFakeChunkRemote()
cfg := ctConfig(1)
bm := cfg.Bitmap.(*fakeBitmapStore)
mustAttach(t, s, f, cfg)
saves := recordSaves(s, bm)
const applied = 5
if err := s.ApplyEntry(16, makeBlock(ctBlockSize, 0x16), applied); err != nil { // chunk 4
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
tailBefore := walLogicalTail(s)
if err := flushWithin(t, s, "flush of the applied entry"); err != nil {
t.Fatal(err)
}
row, ok := saves.firstSaveWith(4)
if !ok {
t.Fatal("replica apply: chunk 4's WAL entry was recycled without a bitmap save covering it")
}
if row.checkpoint >= applied || row.walTail != tailBefore {
t.Fatalf("replica chunk 4 saved at checkpoint %d / WAL tail %d, after the advance (applied %d, tail before %d)", row.checkpoint, row.walTail, applied, tailBefore)
}
if got := extentBytes(t, s, 16); !bytes.Equal(got, makeBlock(ctBlockSize, 0x16)) {
t.Fatal("applied entry did not reach the extent")
}
}
@@ -44,25 +44,3 @@ func TestChunkLayer_FreshVolumeStartsWithEmptyBitmap(t *testing.T) {
})
}
}
// Control: an existing volume (not fresh) without a bitmap reconciles its
// local image against HEAD before it publishes, so a chunk that differs
// from HEAD without a recorded write is still uploaded by its first cut.
func TestChunkLayer_LostBitmapReconciles(t *testing.T) {
src := make([]byte, ctNumBlocks*ctBlockSize)
copy(src, makeBlock(ctBlockSize, 0x44)) // HEAD's block 0 differs from the local image
f := newFakeChunkRemote()
f.seedHead(t, src, 0, 0) // an older epoch: this holder may publish over it
s, _ := newLegacyChunkTestStore(t)
layer := mustAttach(t, s, f, ctConfig(1)) // waits for reconciliation
if st := layer.Stats(); st.Reconciling || st.ReconcileTotal == 0 || st.ReconcileDone != st.ReconcileTotal {
t.Fatalf("an existing volume without a bitmap did not reconcile: reconciling=%v done=%d/%d", st.Reconciling, st.ReconcileDone, st.ReconcileTotal)
}
w := newWriteLog()
w.write(t, s, ctNumBlocks-1, 0x33) // the last chunk, never HEAD's block 0 chunk
r, err := layer.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
assertImage(t, "first cut after reconciliation vs the local image", f.imageOf(t, r.Head), w.imageAt(r.H))
}
@@ -6,41 +6,6 @@ import (
"testing"
)
// HEAD's remote_lsn never decreases (B9 W2 appendix): a
// host whose log is behind HEAD (a fresh or migrated host before W4b carries
// LSN continuity) cannot cut or detach; nothing is uploaded and no CAS is
// sent. Once its log continues from HEAD's remote_lsn, it cuts.
func TestChunkCut_RemoteLSNNeverDecreases(t *testing.T) {
src := make([]byte, ctNumBlocks*ctBlockSize)
copy(src, makeBlock(ctBlockSize, 0x44))
f := newFakeChunkRemote()
f.seedHead(t, src, 10, 1)
s, _ := newLegacyChunkTestStore(t)
cfg := ctConfig(2)
cfg.FreshFromHead = true
layer := mustAttach(t, s, f, cfg)
w := newWriteLog()
w.write(t, s, 3, 0x33) // local LSN 1, HEAD remote_lsn 10
before := f.stats()
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) || !errors.Is(err, errChunkLSNBehind) {
t.Fatalf("cut behind HEAD's remote_lsn: %v; want refused with errChunkLSNBehind", err)
}
if _, err := layer.Detach(ctTimeout(t)); !errors.Is(err, errChunkLSNBehind) {
t.Fatalf("detach behind HEAD's remote_lsn: %v; want errChunkLSNBehind", err)
}
after := f.stats()
if after.cas != before.cas || after.puts != before.puts || after.head.Gen != before.head.Gen {
t.Fatalf("a refused cut published: %d CAS, %d puts, HEAD gen %d -> %d", after.cas-before.cas, after.puts-before.puts, before.head.Gen, after.head.Gen)
}
s.AdvanceFrontier(10) // continuity from HEAD (W4b's job in production)
w.write(t, s, 4, 0x34)
r, err := layer.Cut(ctTimeout(t))
if err != nil || r.Head.RemoteLSN < 10 || r.Head.Gen != before.head.Gen+1 {
t.Fatalf("cut once the log continues from HEAD: %+v %v", r.Head, err)
}
}
// MemChunkRemote refuses a proposal that lowers remote_lsn.
func TestMemChunkRemote_RefusesLowerRemoteLSN(t *testing.T) {
ctx := context.Background()
@@ -6,7 +6,7 @@ package storage
func (l *chunkLayerImpl) usesOwnedMapV3() bool { return l.s.v3 != nil && l.s.v3.mapProof != nil }
// persistCapturedMapV3 is called only after HEAD's publication is definite
// (or an authority-checked no-op), outside bmMu/stMu and the capture barrier.
// (or an authority-checked no-op), outside 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 WAL append updates max LSN and stays retained;
@@ -6,12 +6,10 @@ package storage
// write reached it since staging, so the image at H stays exact.
import (
"bytes"
"context"
"errors"
"strings"
"testing"
"time"
)
// precopyLayer attaches a fresh layer with the given barrier bound and
@@ -203,63 +201,6 @@ func TestChunkPrecopy_WriteRightAfterStagingReadIsNotLost(t *testing.T) {
assertEveryHeadIsPrefixImage(t, f, w)
}
// A replica apply may land a block at an LSN below another block of the
// same chunk (the highest LSN in the chunk does not move). It still makes
// the staged copy stale: the barrier copies the chunk again and HEAD has
// the applied bytes, whether the apply is still in the WAL or flushed.
func TestChunkPrecopy_LowerLSNApplyAfterStagingIsNotLost(t *testing.T) {
for _, flushed := range []bool{false, true} {
name := map[bool]string{true: "flushed", false: "in the WAL"}[flushed]
t.Run(name, func(t *testing.T) {
s, _ := newLegacyChunkTestStore(t)
f := newFakeChunkRemote()
cfg := ctConfig(1)
cfg.FreshFromHead = true
cfg.BarrierBound = 1
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
a, b, b2, c := makeBlock(ctBlockSize, 0xa0), makeBlock(ctBlockSize, 0xb5), makeBlock(ctBlockSize, 0xb6), makeBlock(ctBlockSize, 0xc1)
for _, e := range []struct {
lba uint32
data []byte
lsn uint64
}{{1, b, 5}, {0, a, 10}, {ctChunkBlocks, c, 11}} { // chunk 0 holds a@10 and b@5; chunk 1 c@11
if err := s.ApplyEntry(e.lba, e.data, e.lsn); err != nil {
t.Fatal(err)
}
}
applied := false
l.testAfterStageReadHook = func(idx uint64) {
if idx == 0 && !applied { // chunk 0 is staged with b@5
applied = true
if err := s.ApplyEntry(1, b2, 6); err != nil { // the production apply path
t.Errorf("apply b@6: %v", err)
}
if flushed {
mustSyncFlush(t, s)
}
}
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if !applied || r.Stats.StagedChunks == 0 {
t.Fatalf("schedule did not run: applied=%v staged=%d", applied, r.Stats.StagedChunks)
}
img := f.imageOf(t, r.Head)
for _, want := range []struct {
lba int
data []byte
}{{0, a}, {1, b2}, {ctChunkBlocks, c}} {
if got := img[want.lba*ctBlockSize : (want.lba+1)*ctBlockSize]; !bytes.Equal(got, want.data) {
t.Fatalf("HEAD at H=%d: LBA %d is %#x..., want %#x... (the b@6 apply after staging lost)", r.H, want.lba, got[0], want.data[0])
}
}
assertNoIntentsLeft(t, f)
})
}
}
// A barrier Sync that fails after staging uploaded keys is a clean abort:
// the cut's staging intents are deleted (a failed delete is kept and
// retried by the next cut), and the next cut publishes the exact image.
@@ -306,128 +247,3 @@ func TestChunkPrecopy_BarrierSyncFailureSettlesStagedIntents(t *testing.T) {
assertEveryHeadIsPrefixImage(t, f, w)
assertNoIntentsLeft(t, f)
}
// Recover republishes the dirty map outside the write path: a complete newer
// record past the head (what a failed append can leave) is published by a
// same-open Recover. A chunk staged before it must not be reused:
// HEAD at the recovered H has the recovered bytes.
func TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage(t *testing.T) {
s, f, l, _ := legacyPrecopyLayer(t, 1, 3) // chunk 0 staged in round 0; bound 1
want := makeBlock(ctBlockSize, 0xa7)
recovered := false
l.testAfterStageHook = func(round int) {
if round != 0 {
return
}
plantRecordPastHead(t, s, 0, want)
if _, err := s.Recover(); err != nil { // same open, before the barrier
t.Errorf("same-open Recover: %v", err)
return
}
if got, err := s.Read(0); err != nil || !bytes.Equal(got, want) {
t.Errorf("valid prefix not recovered: err=%v", err)
return
}
recovered = true
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if !recovered || r.Stats.StagedChunks == 0 {
t.Fatalf("schedule did not run: recovered=%v staged=%d", recovered, r.Stats.StagedChunks)
}
img := f.imageOf(t, r.Head)
if got := img[:ctBlockSize]; !bytes.Equal(got, want) {
t.Fatalf("HEAD at H=%d: LBA 0 is %#x..., want the recovered %#x... (a stage from before Recover reused)", r.H, got[0], want[0])
}
assertNoIntentsLeft(t, f)
}
// partialBatchPrefix leaves a complete, CRC-valid record for want at the
// next LSN past the head, the bytes a failed append can leave behind, without
// failing an append (which latches the open store): same-open Recover
// republishes it.
func partialBatchPrefix(t *testing.T, s *WALStore, want []byte) {
t.Helper()
plantRecordPastHead(t, s, 0, want)
}
// plantRecordPastHead writes a complete write record for lba at the next LSN
// at the WAL head, without publishing it.
func plantRecordPastHead(t *testing.T, s *WALStore, lba uint64, data []byte) {
t.Helper()
e := walEntry{LSN: s.NextLSN(), Type: walEntryWrite, LBA: lba, Length: uint32(len(data)), Data: data}
buf, err := e.encode()
if err != nil {
t.Fatal(err)
}
off := int64(s.sb.WALOffset + s.wal.physicalPos(s.wal.logicalHeadValue()))
if _, err := s.fd.WriteAt(buf, off); err != nil {
t.Fatal(err)
}
}
// A cut parked right after its barrier Sync fixed H: a same-open Recover
// that would republish a newer complete record (H+1) waits for the
// barrier, so the cut's HEAD at H never holds post-H bytes; the recovered
// bytes are published by the next cut.
func TestChunkCut_RecoverWaitsForTheCaptureBarrier(t *testing.T) {
s, f, l, w := legacyPrecopyLayer(t, 0, 2) // no bound: the barrier copies all
newer := makeBlock(ctBlockSize, 0xa7)
partialBatchPrefix(t, s, newer)
recovered := make(chan error, 1)
parked := false
l.testAfterBarrierSyncHook = func(h uint64) {
parked = true
go func() { _, err := s.Recover(); recovered <- err }()
select {
case err := <-recovered:
t.Errorf("Recover ran inside the capture barrier after Sync fixed H=%d (err %v)", h, err)
case <-time.After(300 * time.Millisecond): // held: it waits for the barrier
}
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if !parked {
t.Fatal("the cut never reached the post-Sync hook")
}
assertEveryHeadIsPrefixImage(t, f, w) // HEAD at H is the image at H: no 0xa7
if got := f.imageOf(t, r.Head)[:ctBlockSize]; bytes.Equal(got, newer) {
t.Fatalf("HEAD at H=%d holds the post-H recovered bytes", r.H)
}
select {
case err := <-recovered:
if err != nil {
t.Fatalf("Recover after the barrier: %v", err)
}
case <-time.After(ctLocalBound):
t.Fatal("Recover never ran after the barrier was released")
}
l.testAfterBarrierSyncHook = nil
r2, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if got := f.imageOf(t, r2.Head)[:ctBlockSize]; !bytes.Equal(got, newer) || r2.H <= r.H {
t.Fatalf("next cut H=%d (prev %d): LBA 0 %#x..., want the recovered %#x...", r2.H, r.H, got[0], newer[0])
}
}
// TODO(format-v3 row 14a): raw v2 surgery/nonmonotone fixture only.
func legacyPrecopyLayer(t *testing.T, bound, n int) (*WALStore, *fakeChunkRemote, *chunkLayerImpl, *writeLog) {
t.Helper()
s, _ := newLegacyChunkTestStore(t)
f := newFakeChunkRemote()
cfg := ctConfig(1)
cfg.FreshFromHead = true
cfg.BarrierBound = bound
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
w := newWriteLog()
for c := 0; c < n; c++ {
w.write(t, s, uint32(c*ctChunkBlocks+1), byte(0x10+c))
}
return s, f, l, w
}
@@ -5,10 +5,6 @@ package storage
// outside the capture barrier. No HEAD moves until it is done.
import (
"context"
"errors"
"fmt"
"sync/atomic"
"testing"
"time"
)
@@ -23,235 +19,8 @@ type reconcileFixture struct {
path string
}
// newReconcileFixture publishes chunks 0 and 5, leaves chunk 6 flushed and
// chunk 7 synced only, crashes, loses the bitmap and reattaches. With hold
// the reconciler is held before its first slice.
func newReconcileFixture(t *testing.T, hold bool) *reconcileFixture {
return newReconcileFixtureWith(t, hold, func(bm *fakeBitmapStore) { bm.lostNext = true })
}
// newReconcileFixtureWith reattaches after mutate damaged the bitmap.
func newReconcileFixtureWith(t *testing.T, hold bool, mutate func(bm *fakeBitmapStore)) *reconcileFixture {
t.Helper()
return newReconcileFixtureOpts(t, hold, mutate, nil)
}
// newReconcileFixtureOpts also lets mutateCfg adjust the reattach config.
func newReconcileFixtureOpts(t *testing.T, hold bool, mutate func(bm *fakeBitmapStore), mutateCfg func(cfg *chunkLayerConfig)) *reconcileFixture {
t.Helper()
s, path, crash := legacyCrashableStore(t)
f := newFakeChunkRemote()
cfg := ctConfig(1)
bm := cfg.Bitmap.(*fakeBitmapStore)
layer := mustAttach(t, s, f, cfg)
w := newWriteLog()
w.write(t, s, 1, 0x01) // chunk 0
w.write(t, s, 21, 0x21) // chunk 5
if _, err := layer.Capture(ctTimeout(t)); err != nil {
t.Fatal(err)
}
w.write(t, s, 24, 0x24) // chunk 6: flushed
mustSyncFlush(t, s)
w.write(t, s, 28, 0x28) // chunk 7: synced only
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
crash()
s2, _ := legacyReopen(t, path)
bm.mu.Lock()
mutate(bm)
bm.mu.Unlock()
fx := &reconcileFixture{s: s2, f: f, bm: bm, cfg: cfg, path: path}
if hold {
fx.hold = make(chan struct{})
fx.cfg.testReconcileHold = fx.hold
}
if mutateCfg != nil {
mutateCfg(&fx.cfg)
}
l, err := attachChunkLayer(s2, f, fx.cfg)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if fx.hold != nil {
select {
case <-fx.hold:
default:
close(fx.hold)
}
}
_ = l.Close()
})
fx.layer = l
return fx
}
func (fx *reconcileFixture) release() { close(fx.hold) }
func TestChunkReconcile_NoHeadMovesWhileReconciling(t *testing.T) {
fx := newReconcileFixture(t, true)
st := fx.layer.Stats()
if !st.Reconciling || st.ReconcileTotal == 0 || st.ReconcileDone != 0 {
t.Fatalf("stats while held: reconciling=%v done=%d/%d", st.Reconciling, st.ReconcileDone, st.ReconcileTotal)
}
if st.DirtyChunks != 0 {
t.Fatalf("the reconcile obligation counted as %d dirty chunks", st.DirtyChunks)
}
before := fx.f.stats()
if _, err := fx.layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkReconciling) {
t.Fatalf("Cut while reconciling: %v", err)
}
if err := fx.layer.MakeRemoteDurable(ctTimeout(t), 1); !errors.Is(err, errChunkReconciling) {
t.Fatalf("MakeRemoteDurable while reconciling: %v", err)
}
if after := fx.f.stats(); after.puts != before.puts || after.cas != before.cas || after.getHeads != before.getHeads {
t.Fatalf("refused cuts made remote calls: %+v -> %+v", before, after)
}
if got := fx.layer.Stats().CutsRefused["reconciling"]; got != 2 {
t.Fatalf("reconciling refusals %d, want 2", got)
}
fx.release()
waitReconciledForTest(t, fx.layer)
if d := fx.layer.Stats().DirtyChunks; d != 2 {
t.Fatalf("dirty chunks after reconciliation: %d, want 2 (chunks 6 and 7)", d)
}
before = fx.f.stats()
r, err := fx.layer.Cut(ctTimeout(t))
if err != nil {
t.Fatalf("Cut after reconciliation: %v", err)
}
if n := fx.f.stats().puts - before.puts; n != 2 || r.FullHash {
t.Fatalf("first cut after reconciliation stored %d chunks (fullHash=%v), want exactly 2 and no full hash", n, r.FullHash)
}
}
func TestChunkReconcile_WritesProceedWhileReconciling(t *testing.T) {
fx := newReconcileFixture(t, true)
done := make(chan error, 1)
go func() { _, err := fx.s.Write(9, makeBlock(ctBlockSize, 0x09)); done <- err }() // chunk 2
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(ctLocalBound):
t.Fatal("a write blocked behind the reconciliation")
}
if _, err := fx.s.Sync(); err != nil {
t.Fatal(err)
}
fx.release()
waitReconciledForTest(t, fx.layer)
r, err := fx.layer.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if _, ok := r.Head.Chunks[2]; !ok {
t.Fatal("the write made during reconciliation is missing from the next HEAD")
}
}
func TestChunkReconcile_DetachWaitsForReconciliation(t *testing.T) {
fx := newReconcileFixture(t, true)
errc := make(chan error, 1)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := fx.layer.Detach(ctx)
errc <- err
}()
select {
case err := <-errc:
t.Fatalf("Detach returned while reconciling: %v", err)
case <-time.After(200 * time.Millisecond):
}
fx.release()
select {
case err := <-errc:
if err != nil {
t.Fatalf("Detach after reconciliation: %v", err)
}
case <-time.After(ctLocalBound):
t.Fatal("Detach never returned after reconciliation")
}
if !chunkHeadIsDetached(fx.f.stats().head) {
t.Fatal("HEAD not detached after the waited Detach")
}
}
func TestChunkReconcile_DetachDeadlineWhileReconciling(t *testing.T) {
fx := newReconcileFixture(t, true)
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
defer cancel()
before := fx.f.stats()
errc := make(chan error, 1)
go func() { _, err := fx.layer.Detach(ctx); errc <- err }()
select {
case err := <-errc:
if !errors.Is(err, errChunkReconciling) {
t.Fatalf("Detach past its deadline while reconciling: %v", err)
}
case <-time.After(2 * time.Second):
t.Fatal("Detach ignored its deadline while reconciling")
}
if after := fx.f.stats(); after.cas != before.cas {
t.Fatal("a refused Detach issued a CAS")
}
}
// The reconciled dirty set is persisted with a header naming HEAD: a
// restart trusts it and does not reconcile again.
func TestChunkReconcile_ResultPersisted(t *testing.T) {
// A header naming another HEAD generation: the reconciled result must
// rewrite it, or the next attach mismatches and reconciles again.
fx := newReconcileFixtureWith(t, false, func(bm *fakeBitmapStore) {
bm.hdr.HeadGen += 7
bm.dirty = map[uint64]bool{}
})
waitReconciledForTest(t, fx.layer)
head := fx.f.stats().head
fx.bm.mu.Lock()
hdr, dirty := fx.bm.hdr, len(fx.bm.dirty)
fx.bm.mu.Unlock()
if hdr.HeadGen != head.Gen || hdr.Epoch != head.Epoch || hdr.BaseLSN != head.RemoteLSN || hdr.Base != chunkBaseNone || dirty != 2 {
t.Fatalf("persisted header %+v with %d dirty chunks; want HEAD gen %d epoch %d lsn %d and 2 dirty", hdr, dirty, head.Gen, head.Epoch, head.RemoteLSN)
}
if err := fx.s.Close(); err != nil { // closes the layer too
t.Fatal(err)
}
s3, _ := legacyReopen(t, fx.path)
l2, err := attachChunkLayer(s3, fx.f, fx.cfg)
if err != nil {
t.Fatal(err)
}
defer l2.Close()
if st := l2.Stats(); st.Reconciling || st.DirtyChunks != 2 {
t.Fatalf("reattach after a persisted reconciliation: reconciling=%v dirty=%d", st.Reconciling, st.DirtyChunks)
}
}
// A failed bitmap save keeps the layer reconciling (and cuts refused) until
// the result is persisted.
func TestChunkReconcile_UnpersistedResultKeepsReconciling(t *testing.T) {
fx := newReconcileFixture(t, true)
fx.bm.mu.Lock()
fx.bm.failSave = errors.New("injected save failure")
fx.bm.mu.Unlock()
fx.release()
time.Sleep(300 * time.Millisecond)
if st := fx.layer.Stats(); !st.Reconciling || st.ReconcileDone != st.ReconcileTotal {
t.Fatalf("with the save failing: reconciling=%v done=%d/%d; want every chunk compared and still reconciling", st.Reconciling, st.ReconcileDone, st.ReconcileTotal)
}
if _, err := fx.layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkReconciling) {
t.Fatalf("Cut with an unpersisted reconciliation: %v", err)
}
fx.bm.mu.Lock()
fx.bm.failSave = nil
fx.bm.mu.Unlock()
waitReconciledForTest(t, fx.layer)
}
// refusedOver asserts check() holds at every poll for d: a negative
// invariant is checked over an interval, not once.
func refusedOver(t *testing.T, d time.Duration, what string, check func() error) {
@@ -264,154 +33,3 @@ func refusedOver(t *testing.T, d time.Duration, what string, check func() error)
time.Sleep(10 * time.Millisecond)
}
}
// A worker reconciling a lost bitmap when a BASE install begins must not
// finish over it: the install guard (Base=Installing) stays in force, in
// memory and on disk, until the install itself completes.
func TestChunkReconcile_BaseInstallSupersedesRunningReconciliation(t *testing.T) {
fx := newReconcileFixture(t, true) // the worker is held before its first slice
if err := fx.layer.BeginBaseInstall(); err != nil {
t.Fatal(err)
}
fx.release() // the old worker runs on
refusedOver(t, 300*time.Millisecond, "after BeginBaseInstall", func() error {
if _, err := fx.layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkBaseInstalling) {
return fmt.Errorf("Cut admitted or refused for another cause during an incomplete BASE install: %v", err)
}
fx.bm.mu.Lock()
base := fx.bm.hdr.Base
fx.bm.mu.Unlock()
if base != chunkBaseInstalling {
return fmt.Errorf("persisted Base=%v, want the install guard (installing)", base)
}
return nil
})
// A restart still sees the incomplete install and refuses cuts.
if err := fx.s.Close(); err != nil { // closes the layer too
t.Fatal(err)
}
s3, _ := legacyReopen(t, fx.path)
defer s3.Close()
cfg := fx.cfg
cfg.testReconcileHold = nil
l2, err := attachChunkLayer(s3, fx.f, cfg)
if err != nil {
t.Fatal(err)
}
defer l2.Close()
if _, err := l2.Cut(ctTimeout(t)); !errors.Is(err, errChunkBaseInstalling) {
t.Fatalf("Cut after restart during an incomplete BASE install: %v", err)
}
}
// An old worker that saw its set empty and paused before certifying must
// not certify (or touch) the replacement reconciliation that a BASE
// install started meanwhile: cuts stay refused until the replacement is
// done.
func TestChunkReconcile_OldCompletionCannotCertifyReplacement(t *testing.T) {
var oldGen atomic.Uint64
atFinish, releaseFinish, replHold := make(chan struct{}), make(chan struct{}), make(chan struct{})
hook := func(stage string, gen uint64) {
switch {
case stage == "finish" && oldGen.CompareAndSwap(0, gen):
close(atFinish)
<-releaseFinish
case stage == "batch" && oldGen.Load() != 0 && gen != oldGen.Load():
<-replHold
}
}
fx := newReconcileFixtureOpts(t, false, func(bm *fakeBitmapStore) { bm.lostNext = true },
func(cfg *chunkLayerConfig) { cfg.testReconcileHook = hook })
// Registered after the fixture: cleanups run last-in first-out, so the
// workers are released before the layer closes and waits for them.
t.Cleanup(func() {
for _, ch := range []chan struct{}{releaseFinish, replHold} {
select {
case <-ch:
default:
close(ch)
}
}
})
select {
case <-atFinish:
case <-time.After(ctLocalBound):
t.Fatal("the first reconciliation never reached certification")
}
if err := fx.layer.BeginBaseInstall(); err != nil {
t.Fatal(err)
}
if err := fx.layer.EndBaseInstall(fx.s.CheckpointLSN()); err != nil {
t.Fatal(err)
}
total := fx.layer.Stats().ReconcileTotal
if total == 0 {
t.Fatal("the replacement reconciliation has nothing to compare; the schedule needs local chunks")
}
close(releaseFinish) // the old worker resumes into certification
refusedOver(t, 300*time.Millisecond, "after the old worker resumed", func() error {
st := fx.layer.Stats()
if !st.Reconciling || st.ReconcileTotal != total || st.ReconcileDone != 0 {
return fmt.Errorf("replacement certified or modified by the old worker: reconciling=%v done=%d/%d (total was %d)", st.Reconciling, st.ReconcileDone, st.ReconcileTotal, total)
}
if _, err := fx.layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkReconciling) {
return fmt.Errorf("Cut admitted while the replacement reconciles: %v", err)
}
return nil
})
close(replHold)
waitReconciledForTest(t, fx.layer)
if _, err := fx.layer.Cut(ctTimeout(t)); err != nil {
t.Fatalf("Cut after the replacement reconciled: %v", err)
}
}
// An old worker paused between comparing a chunk and recording it must not
// record into (or delete from) the replacement reconciliation's set.
func TestChunkReconcile_OldWorkerCannotModifyReplacementSet(t *testing.T) {
var oldGen atomic.Uint64
atCompared, releaseOld, replHold := make(chan struct{}), make(chan struct{}), make(chan struct{})
hook := func(stage string, gen uint64) {
switch {
case stage == "compared" && oldGen.CompareAndSwap(0, gen):
close(atCompared)
<-releaseOld
case stage == "batch" && oldGen.Load() != 0 && gen != oldGen.Load():
<-replHold
}
}
fx := newReconcileFixtureOpts(t, false, func(bm *fakeBitmapStore) { bm.lostNext = true },
func(cfg *chunkLayerConfig) { cfg.testReconcileHook = hook })
// Registered after the fixture: cleanups run last-in first-out, so the
// workers are released before the layer closes and waits for them.
t.Cleanup(func() {
for _, ch := range []chan struct{}{releaseOld, replHold} {
select {
case <-ch:
default:
close(ch)
}
}
})
select {
case <-atCompared:
case <-time.After(ctLocalBound):
t.Fatal("the first reconciliation never compared a chunk")
}
if err := fx.layer.BeginBaseInstall(); err != nil {
t.Fatal(err)
}
if err := fx.layer.EndBaseInstall(fx.s.CheckpointLSN()); err != nil {
t.Fatal(err)
}
total := fx.layer.Stats().ReconcileTotal
close(releaseOld)
refusedOver(t, 300*time.Millisecond, "after the paused old worker resumed", func() error {
if st := fx.layer.Stats(); st.ReconcileTotal != total || st.ReconcileDone != 0 {
return fmt.Errorf("old worker modified the replacement set: done=%d/%d (total was %d)", st.ReconcileDone, st.ReconcileTotal, total)
}
return nil
})
close(replHold)
waitReconciledForTest(t, fx.layer)
}
@@ -5,21 +5,6 @@ import (
"testing"
)
// The causes a control plane reports as typed codes (B9 W2 §2.2) stay
// reachable with errors.Is through the layer's errors.
func TestChunkCut_BaseInstallRefusalIsTyped(t *testing.T) {
s, _ := newLegacyChunkTestStore(t)
layer := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1))
newWriteLog().write(t, s, 2, 0x22)
if err := layer.BeginBaseInstall(); err != nil {
t.Fatal(err)
}
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) || !errors.Is(err, errChunkBaseInstalling) {
t.Fatalf("cut during a BASE install: %v; want refused with errChunkBaseInstalling", err)
}
}
func TestChunkCut_UploadFailureIsRemoteUnavailable(t *testing.T) {
s, _ := newMappedCheckpointStoreV3(t)
f := newFakeChunkRemote()
@@ -1,41 +1,11 @@
package storage
import (
"bytes"
"context"
"errors"
"testing"
)
func TestClaimChunkHeadClearsProductionDetachProof(t *testing.T) {
s, _ := newChunkTestStore(t)
if _, err := s.Recover(); err != nil {
t.Fatal(err)
}
remote := NewMemChunkRemote()
layer, err := AttachChunkLayer(s, remote, ChunkLayerConfig{ChunkBlocks: 4, Epoch: 1, Holder: "old"})
if err != nil {
t.Fatal(err)
}
if _, err = s.Write(0, bytes.Repeat([]byte{0xD7}, 4096)); err != nil {
t.Fatal(err)
}
detached, err := layer.Detach(context.Background())
if err != nil {
t.Fatal(err)
}
if detached.Head.State != chunkHeadDetached || detached.Head.DetachedBy == nil {
t.Fatal("producer did not detach", detached.Head)
}
claimed, err := ClaimChunkHead(context.Background(), remote, ChunkLayerConfig{Epoch: 2, Holder: "new"})
if err != nil {
t.Fatal("takeover of production detached HEAD", err)
}
if claimed.State != chunkHeadActive || claimed.DetachedBy != nil || claimed.RemoteLSN != detached.H {
t.Fatalf("takeover retained detached proof or changed frontier: %+v", claimed)
}
}
type claimFaultRemote struct {
ChunkRemote
applied, failRead, called bool
@@ -136,21 +106,6 @@ func TestClaimChunkHeadFencesNoopCut(t *testing.T) {
}
}
func TestFreshRestoreBitmapStartsAtClaimedHEAD(t *testing.T) {
s, _ := newLegacyChunkTestStore(t)
r := NewMemChunkRemote()
if _, err := r.CASHead(ctTimeout(t), ChunkHeadVersion{}, ChunkHead{Epoch: 2, Holder: "host-a", RemoteLSN: 42}); err != nil {
t.Fatal(err)
}
cfg := ctConfig(2)
cfg.FreshFromHead = true
mustAttach(t, s, r, cfg)
hdr, dirty, ok, err := cfg.Bitmap.Load()
if err != nil || !ok || hdr.BaseLSN != 42 || hdr.HeadGen != 1 || hdr.Epoch != 2 || hdr.Base != chunkBaseNone || len(dirty) != 0 {
t.Fatalf("fresh bitmap not at HEAD: hdr=%+v dirty=%v ok=%v err=%v", hdr, dirty, ok, err)
}
}
// A no-op cut still consults remote authority. An outage there is retryable
// remote unavailability, not an untyped failure or an ownership fence.
func TestClaimChunkHeadNoopCutClassifiesRemoteReadFailure(t *testing.T) {
+43 -241
View File
@@ -1,7 +1,6 @@
package storage
import (
"encoding/binary"
"fmt"
"sort"
"sync"
@@ -163,13 +162,11 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
if err := store.stickyIOFault(); err != nil {
return err // no checkpoint advance after a failed fsync
}
// Do not acquire lifecycleMu here: Close holds it while joining Stop.
// The pressure leader is released before snapshot/materialization/checkpoint.
if store.v3 != nil {
if err := store.syncWALPressureV3(); err != nil {
return fmt.Errorf("flusher: pressure WAL sync: %w", err)
}
if err := store.syncWALPressureV3(); err != nil {
return fmt.Errorf("flusher: pressure WAL sync: %w", err)
}
store.mu.RLock()
if store.closed && !allowClosed {
store.mu.RUnlock()
@@ -182,16 +179,15 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
// Bind materialization to the same Recover lifetime as this snapshot.
// Recover holds store.mu at both generation boundaries.
var recoveryGen uint64
if store.v3 != nil {
recoveryGen = store.v3.recoverGen.Load()
}
recoveryGen = store.v3.recoverGen.Load()
entries := store.dm.snapshot()
store.mu.RUnlock()
if len(entries) == 0 {
if store.v3 != nil {
return store.refreshW() // the mode-C idle refresh (DESIGN 6.2)
}
return nil
return store.refreshW() // the mode-C idle refresh (DESIGN 6.2)
}
if f.afterSnapshotForTest != nil {
f.afterSnapshotForTest()
@@ -205,8 +201,6 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
// checkpoint progress. Partial extent writes are safe because checkpoint
// publication happens only after the whole snapshot and fsync succeed.
var maxLSN uint64
var maxLSNPhys uint64
var maxLSNEntrySize uint64
writtenEntries := make([]snapshotEntry, 0, len(entries))
defer func() {
f.instr.recordWrittenOpportunity(writtenEntries, store.sb.BlockSize)
@@ -214,25 +208,17 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
// Adjacent blocks of a native batch share one immutable, validated record.
// Keep only one record (at most WALSize bytes), scoped to this Recover lifetime.
var recordCache *flushRecordCacheV3
if store.v3 != nil {
sort.Slice(entries, func(i, j int) bool {
if entries[i].WALOffset == entries[j].WALOffset {
return entries[i].DataOffset < entries[j].DataOffset
}
return entries[i].WALOffset < entries[j].WALOffset
})
recordCache = &flushRecordCacheV3{recoveryGen: recoveryGen}
}
for _, e := range entries {
var data []byte
var entrySize uint64
var err error
if recordCache != nil {
data, entrySize, err = f.readDirtyRecordV3Cached(e, recordCache)
} else {
data, entrySize, err = f.readDirtyRecord(e)
sort.Slice(entries, func(i, j int) bool {
if entries[i].WALOffset == entries[j].WALOffset {
return entries[i].DataOffset < entries[j].DataOffset
}
return entries[i].WALOffset < entries[j].WALOffset
})
recordCache := &flushRecordCacheV3{recoveryGen: recoveryGen}
for _, e := range entries {
data, _, err := f.readDirtyRecordV3Cached(e, recordCache)
if err != nil {
return err
}
@@ -252,8 +238,6 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
}
if e.LSN > maxLSN {
maxLSN = e.LSN
maxLSNPhys = e.WALOffset
maxLSNEntrySize = entrySize
}
}
// Step 2: one fsync covers all extent writes in this batch
@@ -279,22 +263,14 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
// writer may reuse those bytes.
var publishErr error
cpBefore := store.CheckpointLSN()
if store.v3 != nil {
publishErr = store.persistCheckpointV3(maxLSN, recoveryGen)
} else {
publishErr = store.persistCheckpointAndRelease(maxLSN, maxLSNPhys, maxLSNEntrySize)
}
publishErr = store.persistCheckpointV3(maxLSN, recoveryGen)
f.instr.recordCheckpoint(publishErr, cpBefore, store.CheckpointLSN(), time.Now())
if err := publishErr; err != nil {
return fmt.Errorf("flusher: persist checkpoint %d: %w", maxLSN, err)
}
if store.v3 == nil && store.CheckpointLSN() >= maxLSN {
store.mu.Lock()
if maxLSN+1 > store.walTail {
store.walTail = maxLSN + 1
}
store.mu.Unlock()
}
}
if f.afterCheckpointForTest != nil {
@@ -308,210 +284,36 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
// Keep the uncovered entries as retry work even though their extent
// bytes were fsynced: a later Sync plus cycle must advance checkpoint
// AND coverage, rather than merely refreshing W on an empty dirty map.
checkpoint := maxLSN // legacy behavior: remove the whole flushed snapshot
if store.v3 != nil {
// Serialize validation and LSN-only retirement with Recover. A new
// lifetime can reuse the same LBA, physical offset and LSN.
store.mu.Lock()
if !store.v3.flushLifetimeValidV3(recoveryGen) {
store.mu.Unlock()
return mapCoverageRefusal("recovery_lifetime_changed")
}
checkpoint = store.checkpointLSN
if checkpoint >= maxLSN && maxLSN+1 > store.walTail {
store.walTail = maxLSN + 1
}
// Serialize validation and LSN-only retirement with Recover. A new
// lifetime can reuse the same LBA, physical offset and LSN.
store.mu.Lock()
if !store.v3.flushLifetimeValidV3(recoveryGen) {
store.mu.Unlock()
return mapCoverageRefusal("recovery_lifetime_changed")
}
checkpoint := store.checkpointLSN
if checkpoint >= maxLSN && maxLSN+1 > store.walTail {
store.walTail = maxLSN + 1
}
for _, e := range entries {
if e.LSN > checkpoint {
continue
}
store.dm.compareAndDelete(e.LBA, e.LSN)
}
if store.v3 != nil {
store.mu.Unlock()
}
store.mu.Unlock()
f.flushes.Add(1)
if store.v3 != nil {
return store.refreshW() // the mode-C idle refresh (DESIGN 6.2)
}
return nil
return store.refreshW() // the mode-C idle refresh (DESIGN 6.2)
}
func (f *flusher) readDirtyRecord(e snapshotEntry) (data []byte, entrySize uint64, err error) {
if f.store.v3 != nil {
return f.readDirtyRecordV3(e)
}
store := f.store
readFailed := false
defer func() {
switch {
case err == nil:
f.instr.recordValidatedRecord()
case !readFailed:
f.instr.recordValidationFailure()
}
}()
absOff := int64(store.sb.WALOffset + e.WALOffset)
header := make([]byte, walEntryHeaderSize)
headerStart := time.Now()
n, readErr := store.fd.ReadAt(header, absOff)
f.instr.recordWALHeaderRead(n, time.Since(headerStart), readErr)
if readErr != nil {
readFailed = true
return nil, 0, fmt.Errorf("flusher: read WAL header at %d: %w", e.WALOffset, readErr)
}
return f.readDirtyRecordV3(e)
entryLSN := binary.LittleEndian.Uint64(header[0:8])
entryType := header[16]
if entryType != walEntryWriteBatch && entryLSN != e.LSN {
return nil, 0, fmt.Errorf(
"flusher: WAL slot mismatch LBA %d offset %d dirty LSN %d record LSN %d",
e.LBA, e.WALOffset, e.LSN, entryLSN)
}
if entryType != walEntryWrite && entryType != walEntryWriteBatch && entryType != walEntryTrim {
return nil, 0, fmt.Errorf(
"flusher: invalid dirty WAL record LBA %d offset %d type %d",
e.LBA, e.WALOffset, entryType)
}
payloadLen := uint64(0)
if entryType == walEntryWrite || entryType == walEntryWriteBatch {
payloadLen = uint64(parseLengthFromHeader(header))
if payloadLen == 0 {
return nil, 0, fmt.Errorf(
"flusher: invalid dirty WAL record LBA %d offset %d with zero payload",
e.LBA, e.WALOffset)
}
}
entrySize = uint64(walEntryHeaderSize) + payloadLen
if entrySize > store.sb.WALSize || e.WALOffset+entrySize > store.sb.WALSize {
return nil, 0, fmt.Errorf(
"flusher: invalid dirty WAL record LBA %d offset %d size %d WAL size %d",
e.LBA, e.WALOffset, entrySize, store.sb.WALSize)
}
full := make([]byte, entrySize)
recordStart := time.Now()
n, readErr = store.fd.ReadAt(full, absOff)
f.instr.recordWALRecordRead(n, time.Since(recordStart), readErr)
if readErr != nil {
readFailed = true
return nil, 0, fmt.Errorf("flusher: read WAL record at %d: %w", e.WALOffset, readErr)
}
entryLSN = binary.LittleEndian.Uint64(full[0:8])
entryType = full[16]
if entryType != walEntryWriteBatch && entryLSN != e.LSN {
return nil, 0, fmt.Errorf(
"flusher: WAL slot mismatch LBA %d offset %d dirty LSN %d record LSN %d",
e.LBA, e.WALOffset, e.LSN, entryLSN)
}
if entryType != walEntryWrite && entryType != walEntryWriteBatch && entryType != walEntryTrim {
return nil, 0, fmt.Errorf(
"flusher: invalid dirty WAL record LBA %d offset %d type %d",
e.LBA, e.WALOffset, entryType)
}
expectedRecordSize := uint64(walEntryHeaderSize)
if entryType == walEntryWrite || entryType == walEntryWriteBatch {
payloadLen := uint64(parseLengthFromHeader(full))
if payloadLen == 0 {
return nil, 0, fmt.Errorf(
"flusher: invalid dirty WAL record LBA %d offset %d with zero payload",
e.LBA, e.WALOffset)
}
expectedRecordSize += payloadLen
}
if expectedRecordSize != entrySize || uint64(len(full)) != entrySize {
return nil, 0, fmt.Errorf(
"flusher: invalid dirty WAL record LBA %d offset %d record size %d expected %d",
e.LBA, e.WALOffset, entrySize, expectedRecordSize)
}
decodeStart := time.Now()
entry, err := decodeWALEntry(full)
f.instr.recordWALRecordDecode(len(full), time.Since(decodeStart), err)
if err != nil {
return nil, 0, fmt.Errorf(
"flusher: invalid dirty WAL record LBA %d offset %d: %w",
e.LBA, e.WALOffset, err)
}
if entry.Flags != 0 {
return nil, 0, fmt.Errorf(
"flusher: invalid dirty WAL record LBA %d offset %d flags %d",
e.LBA, e.WALOffset, entry.Flags)
}
data, err = f.validateMaterializedDirtyEntry(e, &entry)
if err != nil {
return nil, 0, err
}
return data, entrySize, nil
}
func (f *flusher) validateMaterializedDirtyEntry(e snapshotEntry, entry *walEntry) ([]byte, error) {
blockSize := f.store.sb.BlockSize
switch entry.Type {
case walEntryWrite:
if entry.LSN != e.LSN || entry.LBA != e.LBA || e.DataOffset != 0 ||
entry.Length != blockSize || e.Length != blockSize {
return nil, fmt.Errorf(
"flusher: WAL slot mismatch LBA %d offset %d dirty LSN %d record LSN %d",
e.LBA, e.WALOffset, e.LSN, entry.LSN)
}
return entry.Data, nil
case walEntryWriteBatch:
maxBlocks := uint64(^uint32(0)) / uint64(blockSize)
if entry.Reserved == 0 || entry.Reserved > maxBlocks {
return nil, fmt.Errorf(
"flusher: invalid dirty WAL batch LBA %d offset %d",
e.LBA, e.WALOffset)
}
expectedLength := entry.Reserved * uint64(blockSize)
if uint64(entry.Length) != expectedLength ||
e.DataOffset%blockSize != 0 || e.Length != blockSize {
return nil, fmt.Errorf(
"flusher: invalid dirty WAL batch LBA %d offset %d",
e.LBA, e.WALOffset)
}
blockIndex := uint64(e.DataOffset / blockSize)
if blockIndex >= entry.Reserved || entry.LSN+blockIndex != e.LSN ||
entry.LBA+blockIndex != e.LBA {
return nil, fmt.Errorf(
"flusher: WAL slot mismatch LBA %d offset %d dirty LSN %d batch base %d block %d count %d",
e.LBA, e.WALOffset, e.LSN, entry.LSN, blockIndex, entry.Reserved)
}
start := uint64(e.DataOffset)
end := start + uint64(blockSize)
if end > uint64(len(entry.Data)) {
return nil, fmt.Errorf(
"flusher: invalid dirty WAL batch LBA %d offset %d data range [%d,%d)",
e.LBA, e.WALOffset, start, end)
}
return entry.Data[start:end], nil
case walEntryTrim:
trimBlocks := uint64(1)
if entry.Length > 0 {
if entry.Length%blockSize != 0 {
return nil, fmt.Errorf(
"flusher: invalid dirty WAL trim LBA %d offset %d length %d",
e.LBA, e.WALOffset, entry.Length)
}
trimBlocks = uint64(entry.Length / blockSize)
}
if e.DataOffset%blockSize != 0 || e.Length != blockSize {
return nil, fmt.Errorf(
"flusher: invalid dirty WAL trim LBA %d offset %d",
e.LBA, e.WALOffset)
}
blockIndex := uint64(e.DataOffset / blockSize)
if entry.LSN != e.LSN || blockIndex >= trimBlocks ||
entry.LBA+blockIndex != e.LBA {
return nil, fmt.Errorf(
"flusher: WAL slot mismatch trim LBA %d offset %d dirty LSN %d record LSN %d",
e.LBA, e.WALOffset, e.LSN, entry.LSN)
}
return make([]byte, blockSize), nil
default:
panic("validated dirty WAL type became unsupported")
}
}
@@ -2,7 +2,7 @@ package storage
import (
"errors"
"path/filepath"
"testing"
"time"
)
@@ -33,97 +33,6 @@ func TestBoundedExtentWriteOpportunity(t *testing.T) {
}
}
func TestFlusherInstrumentationCountsCompleteCycle(t *testing.T) {
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.flusher.Stop()
block := makeBlock(4096, 0x41)
if _, err := s.WriteBatch(0, [][]byte{block, block, block, block}); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
got := s.FlusherInstrumentation()
if got.CyclesStarted != 1 || got.CyclesSucceeded != 1 || got.CyclesFailed != 0 {
t.Fatalf("cycles started/succeeded/failed=%d/%d/%d want 1/1/0",
got.CyclesStarted, got.CyclesSucceeded, got.CyclesFailed)
}
if got.SnapshotEntries != 4 || got.ValidatedRecords != 4 || got.SupersededEntries != 0 {
t.Fatalf("snapshot/validated/superseded=%d/%d/%d want 4/4/0",
got.SnapshotEntries, got.ValidatedRecords, got.SupersededEntries)
}
wantRecords := uint64(4)
if s.FormatV3() {
wantRecords = 1
} // one full native batch decode, four validated blocks
if got.WALHeaderReadOps != wantRecords || got.WALRecordReadOps != wantRecords ||
got.WALRecordDecodeOps != wantRecords || got.WALRecordDecodeBytes == 0 ||
got.WALRecordDecodeDurationNanos == 0 {
t.Fatalf("header/record reads and decode ops/bytes/ns=%d/%d %d/%d/%d want actual unique-record counts/nonzero bytes and duration",
got.WALHeaderReadOps, got.WALRecordReadOps,
got.WALRecordDecodeOps, got.WALRecordDecodeBytes,
got.WALRecordDecodeDurationNanos)
}
if got.ExtentWriteOps != 4 || got.ExtentWriteBytes != 4*4096 ||
got.ExtentWriteMaxBytes != 4096 || got.ExtentWriteFailures != 0 {
t.Fatalf("extent ops/bytes/max/failures=%d/%d/%d/%d want 4/%d/4096/0",
got.ExtentWriteOps, got.ExtentWriteBytes, got.ExtentWriteMaxBytes,
got.ExtentWriteFailures, 4*4096)
}
if got.SnapshotBoundedWriteMinimum != 1 || got.SnapshotRunCount != 1 ||
got.SnapshotSingletonRuns != 0 || got.SnapshotCoalescibleEntries != 4 ||
got.SnapshotMaxContiguousRunBlocks != 4 {
t.Fatalf("opportunity minimum/runs/singletons/coalescible/max=%d/%d/%d/%d/%d want 1/1/0/4/4",
got.SnapshotBoundedWriteMinimum, got.SnapshotRunCount,
got.SnapshotSingletonRuns, got.SnapshotCoalescibleEntries,
got.SnapshotMaxContiguousRunBlocks)
}
if got.WrittenBoundedWriteMinimum != 1 || got.WrittenRunCount != 1 ||
got.WrittenSingletonRuns != 0 || got.WrittenCoalescibleEntries != 4 ||
got.WrittenMaxContiguousRunBlocks != 4 {
t.Fatalf("written opportunity minimum/runs/singletons/coalescible/max=%d/%d/%d/%d/%d want 1/1/0/4/4",
got.WrittenBoundedWriteMinimum, got.WrittenRunCount,
got.WrittenSingletonRuns, got.WrittenCoalescibleEntries,
got.WrittenMaxContiguousRunBlocks)
}
if got.ValidationFailures != 0 ||
got.WALHeaderReadFailures != 0 ||
got.WALRecordReadFailures != 0 {
t.Fatalf("validation/header-read/record-read failures=%d/%d/%d want 0/0/0",
got.ValidationFailures, got.WALHeaderReadFailures,
got.WALRecordReadFailures)
}
if got.ExtentSyncOps != 1 || got.ExtentSyncFailures != 0 ||
got.CheckpointMetadataWriteOps != 1 ||
got.CheckpointMetadataSyncOps != 1 {
t.Fatalf("extent-sync/failures/checkpoint-write/checkpoint-sync=%d/%d/%d/%d want 1/0/1/1",
got.ExtentSyncOps, got.ExtentSyncFailures,
got.CheckpointMetadataWriteOps, got.CheckpointMetadataSyncOps)
}
if got.CheckpointMetadataWriteFailures != 0 ||
got.CheckpointMetadataSyncFailures != 0 {
t.Fatalf("checkpoint write/sync failures=%d/%d want 0/0",
got.CheckpointMetadataWriteFailures, got.CheckpointMetadataSyncFailures)
}
if got.CycleDurationNanos == 0 || got.CycleMaxDurationNanos == 0 {
t.Fatal("cycle timing evidence is zero")
}
if got.CycleDurationNanos < got.SnapshotDurationNanos+got.OpportunityAnalysisNanos {
t.Fatalf("cycle duration=%d excludes snapshot+opportunity=%d",
got.CycleDurationNanos,
got.SnapshotDurationNanos+got.OpportunityAnalysisNanos)
}
}
func TestFlusherInstrumentationSeparatesSnapshotAndWrittenOpportunity(t *testing.T) {
entries := []snapshotEntry{{LBA: 0}, {LBA: 1}, {LBA: 2}}
var instr flusherInstrumentation
@@ -147,90 +56,6 @@ func TestFlusherInstrumentationSeparatesSnapshotAndWrittenOpportunity(t *testing
}
}
func TestFlusherInstrumentationCountsCheckpointFailure(t *testing.T) {
tests := []struct {
name string
inject func(*WALStore)
wantWriteFailure uint64
wantWriteBytes uint64
wantSyncOps uint64
wantSyncFailure uint64
}{
{
name: "write",
inject: func(s *WALStore) {
s.writeSuperblockMetadata = func([]byte) error {
return errors.New("injected checkpoint write failure")
}
},
wantWriteFailure: 1,
},
{
name: "sync",
inject: func(s *WALStore) {
s.syncSuperblockMetadata = func() error {
return errors.New("injected checkpoint sync failure")
}
},
wantWriteBytes: superblockSize,
wantSyncOps: 1,
wantSyncFailure: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
if err := s.flusher.Stop(); err != nil {
t.Fatal(err)
}
if _, err := s.Write(0, makeBlock(4096, 0x52)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
savedWrite := s.writeSuperblockMetadata
savedSync := s.syncSuperblockMetadata
tt.inject(s)
err = s.flusher.flushOnce()
s.writeSuperblockMetadata = savedWrite
s.syncSuperblockMetadata = savedSync
if err == nil {
t.Fatal("flush succeeded despite checkpoint failure")
}
got := s.FlusherInstrumentation()
if got.CyclesStarted != 1 || got.CyclesSucceeded != 0 || got.CyclesFailed != 1 {
t.Fatalf("cycles started/succeeded/failed=%d/%d/%d want 1/0/1",
got.CyclesStarted, got.CyclesSucceeded, got.CyclesFailed)
}
if got.ExtentWriteOps != 1 || got.ExtentWriteFailures != 0 ||
got.ExtentSyncOps != 1 || got.ExtentSyncFailures != 0 {
t.Fatalf("extent writes/failures/syncs/failures=%d/%d/%d/%d want 1/0/1/0",
got.ExtentWriteOps, got.ExtentWriteFailures,
got.ExtentSyncOps, got.ExtentSyncFailures)
}
if got.CheckpointMetadataWriteOps != 1 ||
got.CheckpointMetadataWriteFailures != tt.wantWriteFailure ||
got.CheckpointMetadataWriteBytes != tt.wantWriteBytes ||
got.CheckpointMetadataSyncOps != tt.wantSyncOps ||
got.CheckpointMetadataSyncFailures != tt.wantSyncFailure {
t.Fatalf("checkpoint write ops/failures/bytes/sync ops/failures=%d/%d/%d/%d/%d want 1/%d/%d/%d/%d",
got.CheckpointMetadataWriteOps, got.CheckpointMetadataWriteFailures,
got.CheckpointMetadataWriteBytes, got.CheckpointMetadataSyncOps,
got.CheckpointMetadataSyncFailures, tt.wantWriteFailure,
tt.wantWriteBytes, tt.wantSyncOps, tt.wantSyncFailure)
}
})
}
}
func TestFlusherInstrumentationCountsExtentFailures(t *testing.T) {
var instr flusherInstrumentation
injected := errors.New("injected extent failure")
@@ -263,77 +88,3 @@ func TestFlusherInstrumentationCountsExtentFailures(t *testing.T) {
got.WALRecordDecodeOps, got.WALRecordDecodeFailures, got.WALRecordDecodeBytes)
}
}
func TestFlusherInstrumentationCountsWALReadFailures(t *testing.T) {
tests := []struct {
name string
breakFile func(*testing.T, *WALStore, int64)
wantHeaderReadFailures uint64
wantRecordReadFailures uint64
}{
{
name: "header",
breakFile: func(t *testing.T, s *WALStore, _ int64) {
t.Helper()
if err := s.fd.Close(); err != nil {
t.Fatal(err)
}
},
wantHeaderReadFailures: 1,
},
{
name: "record",
breakFile: func(t *testing.T, s *WALStore, absoluteOffset int64) {
t.Helper()
if err := s.fd.Truncate(absoluteOffset + walEntryHeaderSize); err != nil {
t.Fatal(err)
}
},
wantRecordReadFailures: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
if err := s.flusher.Stop(); err != nil {
t.Fatal(err)
}
if _, err := s.Write(0, makeBlock(4096, 0x63)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
walOffset, _, _, _, ok := s.dm.get(0)
if !ok {
t.Fatal("dirty entry missing")
}
s.committer.Stop()
absoluteOffset := int64(s.sb.WALOffset + walOffset)
tt.breakFile(t, s, absoluteOffset)
if err := s.flusher.flushOnce(); err == nil {
t.Fatal("flush succeeded despite WAL read failure")
}
got := s.FlusherInstrumentation()
if got.WALHeaderReadFailures != tt.wantHeaderReadFailures ||
got.WALRecordReadFailures != tt.wantRecordReadFailures ||
got.ValidationFailures != 0 ||
got.CyclesFailed != 1 {
t.Fatalf("header/record/validation/cycle failures=%d/%d/%d/%d want %d/%d/0/1",
got.WALHeaderReadFailures, got.WALRecordReadFailures,
got.ValidationFailures, got.CyclesFailed,
tt.wantHeaderReadFailures, tt.wantRecordReadFailures)
}
if tt.name == "record" {
if err := s.fd.Close(); err != nil {
t.Fatal(err)
}
}
})
}
}
@@ -1,151 +0,0 @@
package storage
import (
"bytes"
"fmt"
"path/filepath"
"testing"
"time"
)
// Force a Write+Sync between scans of shard 0 and shard 5. The older
// snapshot entry is also superseded, so it cannot cover the omitted write.
func TestFlusherSnapshotCutPreservesSyncedWrites(t *testing.T) {
for _, replicated := range []bool{false, true} {
mode := "write"
if replicated {
mode = "supplied-lsn"
}
t.Run(mode, func(t *testing.T) {
for _, finishFlush := range []bool{false, true} {
name := "crash-after-first-cycle"
if finishFlush {
name = "next-cycle-makes-progress"
}
t.Run(name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
s, err := createLegacyWALStoreForTest(path, 128, 4096)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
crashed := false
t.Cleanup(func() {
if !crashed {
_ = s.Close()
}
})
if _, err := s.Write(0, bytes.Repeat([]byte{0x11}, 4096)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
a := bytes.Repeat([]byte{0xAA}, 4096)
b := bytes.Repeat([]byte{0xBB}, 4096)
fired := false
var low, high uint64
done := make(chan error, 1)
waitWriter := func() {
t.Helper()
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(5 * time.Second):
t.Fatal("writer blocked after snapshot")
}
}
waited := false
s.dm.afterSnapshotShard = func(shard int) {
if shard != 0 || fired {
return
}
fired = true
// No timing race: if publication is excluded by the snapshot,
// let the real writer finish after it. Otherwise force completion
// before shard 5 is copied (the broken implementation).
canPublish := s.mu.TryLock()
if canPublish {
s.mu.Unlock()
}
go func() {
var err error
if replicated {
low, high = 20, 30
err = s.ApplyEntry(0, a, low)
if err == nil {
err = s.ApplyEntry(5, b, high)
}
} else {
low, err = s.Write(0, a)
if err == nil {
high, err = s.Write(5, b)
}
}
if err == nil {
var acked uint64
acked, err = s.Sync()
if err == nil && acked < high {
err = fmt.Errorf("Sync=%d below %d", acked, high)
}
}
done <- err
}()
if canPublish {
waitWriter()
waited = true
}
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
s.dm.afterSnapshotShard = nil
if !waited {
waitWriter()
}
wantLow, wantHigh := uint64(2), uint64(3)
if replicated {
wantLow, wantHigh = 20, 30
}
if !fired || low != wantLow || high != wantHigh {
t.Fatalf("interleaving not reached: fired=%v LSNs=%d/%d", fired, low, high)
}
t.Logf("first-cycle checkpoint=%d omitted-synced-LSN=%d tail=%d", s.CheckpointLSN(), low, s.wal.logicalTailValue())
if finishFlush {
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
if s.CheckpointLSN() < high || s.dm.len() != 0 {
t.Fatalf("next flush did not drain: checkpoint=%d dirty=%d", s.CheckpointLSN(), s.dm.len())
}
}
// Close only the committer and descriptor: normal Close would flush.
s.committer.Stop()
if err := s.fd.Close(); err != nil {
t.Fatal(err)
}
crashed = true
reopened, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = reopened.Close() })
if _, err := reopened.Recover(); err != nil {
t.Fatal(err)
}
for lba, want := range map[uint32][]byte{0: a, 5: b} {
got, err := reopened.Read(lba)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, want) {
t.Errorf("Sync-acked LBA %d lost after crash: got first byte %#x, want %#x", lba, got[0], want[0])
}
}
})
}
})
}
}
-599
View File
@@ -1,599 +0,0 @@
package storage
import (
"bytes"
"os"
"path/filepath"
"testing"
"time"
)
// TestFlusher_AdvancesCheckpointBeforeReadFromExtent proves the
// flusher actually drains dirty entries to extent and advances the
// on-disk checkpoint LSN. After a few flush cycles, reads of those
// LBAs come from the extent (not the WAL via dirty map).
func TestFlusher_AdvancesCheckpointBeforeReadFromExtent(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "store.bin")
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
defer s.Close()
// Write some blocks and Sync to make them durable in the WAL.
for i := uint32(0); i < 4; i++ {
if _, err := s.Write(i, makeBlock(4096, byte(0xA0+i))); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
// Wait for the flusher to drain — default interval 50ms; allow
// generous slack for slow CI.
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if s.CheckpointLSN() >= 4 {
break
}
time.Sleep(20 * time.Millisecond)
}
if s.CheckpointLSN() < 4 {
t.Fatalf("flusher never advanced checkpoint: got %d, want >= 4", s.CheckpointLSN())
}
// Reads should still return correct bytes (whether from WAL or
// extent — caller doesn't care).
for i := uint32(0); i < 4; i++ {
got, err := s.Read(i)
if err != nil {
t.Fatal(err)
}
want := makeBlock(4096, byte(0xA0+i))
if !bytes.Equal(got, want) {
t.Fatalf("LBA %d: bytes wrong after flush: got[0]=%02x want[0]=%02x",
i, got[0], want[0])
}
}
}
// TestFlusher_ReleasesWALPressureAfterCheckpoint pins the pressure
// feedback loop: after dirty entries are flushed and checkpointed, the
// circular WAL tail must advance so admission sees free space again.
// Without this, long-running writers eventually hit "WAL region full"
// even though the flusher is successfully writing data to the extent.
func TestFlusher_ReleasesWALPressureAfterCheckpoint(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "store.bin")
s := createLegacyWALStoreWithWALSizeForTest(t, path, 128, 4096, 256*1024)
defer s.Close()
for i := uint32(0); i < 32; i++ {
if _, err := s.Write(i, makeBlock(4096, byte(0x80+i))); err != nil {
t.Fatalf("Write(%d): %v", i, err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatalf("Sync: %v", err)
}
if got := s.wal.usedFraction(); got == 0 {
t.Fatal("test setup did not create WAL pressure")
}
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if s.CheckpointLSN() >= 32 && s.wal.usedFraction() == 0 {
break
}
time.Sleep(20 * time.Millisecond)
}
if got := s.CheckpointLSN(); got < 32 {
t.Fatalf("flusher never checkpointed writes: got %d, want >= 32", got)
}
if used := s.wal.usedFraction(); used != 0 {
t.Fatalf("WAL pressure after checkpoint = %.3f, want 0", used)
}
}
func TestWALWriter_AdvanceTailPastEntryIsIdempotent(t *testing.T) {
w := &walWriter{
walSize: 64,
logicalHead: 40,
logicalTail: 0,
}
w.advanceTailPastEntry(0, 10)
if got := w.logicalTailValue(); got != 10 {
t.Fatalf("first advance tail=%d, want 10", got)
}
w.advanceTailPastEntry(0, 10)
if got := w.logicalTailValue(); got != 10 {
t.Fatalf("repeated advance tail=%d, want still 10", got)
}
}
func TestWALWriter_AdvanceTailPastWrappedEntry(t *testing.T) {
w := &walWriter{
walSize: 64,
logicalHead: 80,
logicalTail: 60,
}
w.advanceTailPastEntry(0, 10)
if got := w.logicalTailValue(); got != 74 {
t.Fatalf("wrapped advance tail=%d, want 74", got)
}
}
func createLegacyWALStoreWithWALSizeForTest(t *testing.T, path string, numBlocks uint32, blockSize int, walSize uint64) *WALStore {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o644)
if err != nil {
t.Fatalf("create: %v", err)
}
sb, err := newSuperblock(uint64(numBlocks)*uint64(blockSize), createOptions{
BlockSize: uint32(blockSize),
ExtentSize: uint32(blockSize),
WALSize: walSize,
ImplKind: ImplKindWALStore,
ImplVersion: 1, // frozen v2 engine fixture, not the production selector
})
if err != nil {
_ = f.Close()
t.Fatalf("newSuperblock: %v", err)
}
totalSize := int64(superblockSize) + int64(sb.WALSize) + int64(sb.VolumeSize)
if err := f.Truncate(totalSize); err != nil {
_ = f.Close()
t.Fatalf("truncate: %v", err)
}
if _, err := sb.writeTo(f); err != nil {
_ = f.Close()
t.Fatalf("write superblock: %v", err)
}
if err := f.Sync(); err != nil {
_ = f.Close()
t.Fatalf("sync superblock: %v", err)
}
s, err := openInitialized(path, f, &sb)
if err != nil {
_ = f.Close()
t.Fatalf("openInitialized: %v", err)
}
return s
}
// TestFlusher_RecoveryHonorsCheckpoint: after the flusher has
// advanced the checkpoint and written through the superblock, a
// subsequent reopen+Recover skips the checkpointed records (they're
// already in extent) and the data is still readable.
func TestFlusher_RecoveryHonorsCheckpoint(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "store.bin")
{
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
for i := uint32(0); i < 4; i++ {
_, _ = s.Write(i, makeBlock(4096, byte(0xA0+i)))
}
_, _ = s.Sync()
// Wait for flush to advance checkpoint.
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if s.CheckpointLSN() >= 4 {
break
}
time.Sleep(20 * time.Millisecond)
}
if s.CheckpointLSN() < 4 {
t.Fatal("flusher never advanced checkpoint pre-close")
}
_ = s.Close() // clean close — superblock fully persisted
}
// Reopen + Recover. The checkpointed records should be skipped;
// extent should serve all reads.
s, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
defer s.Close()
if _, err := s.Recover(); err != nil {
t.Fatal(err)
}
for i := uint32(0); i < 4; i++ {
got, _ := s.Read(i)
want := makeBlock(4096, byte(0xA0+i))
if !bytes.Equal(got, want) {
t.Fatalf("LBA %d: bytes did not survive checkpointed restart", i)
}
}
if s.CheckpointLSN() < 4 {
t.Fatalf("Recover did not load checkpoint from superblock: got %d", s.CheckpointLSN())
}
}
// TestCrashFamily_AbruptKillAtMultipleWindows is the Phase 08 crash
// proof family. Each subtest simulates an abrupt kill at a different
// point in the local data process and verifies:
//
// - acked writes (covered by a successful Sync) survive the kill
// - unacked writes may be lost but never corrupt acked data
// - recovery is deterministic
//
// The "abrupt kill" is simulated by stopping background goroutines
// then dropping the file handle without going through Close —
// no implicit fsync, no superblock update.
func TestCrashFamily_AbruptKillAtMultipleWindows(t *testing.T) {
cases := []struct {
name string
nBefore int // writes (each followed by Sync) before the danger zone
nDuring int // writes during the danger zone (no Sync)
waitFlush bool // give the flusher a chance to advance checkpoint before the kill
}{
{
name: "kill_pre_sync",
nBefore: 0,
nDuring: 3, // 3 writes, no Sync, then kill
},
{
name: "kill_post_sync_pre_flush",
nBefore: 3, // 3 writes + Sync, then immediate kill
nDuring: 0,
},
{
name: "kill_post_flush",
nBefore: 3, // 3 writes + Sync, wait for flush, then kill
nDuring: 0,
waitFlush: true,
},
{
name: "kill_post_flush_then_more_unacked_writes",
nBefore: 3, // first batch acked + flushed
nDuring: 2, // second batch unacked
waitFlush: true,
},
}
for _, c := range cases {
c := c
t.Run(c.name, func(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "store.bin")
func() {
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
// Acked writes: those covered by Sync.
for i := 0; i < c.nBefore; i++ {
if _, err := s.Write(uint32(i), makeBlock(4096, byte(0xA0+i))); err != nil {
t.Fatal(err)
}
}
if c.nBefore > 0 {
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
}
if c.waitFlush {
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if s.CheckpointLSN() >= uint64(c.nBefore) {
break
}
time.Sleep(20 * time.Millisecond)
}
}
// Unacked writes: NOT followed by Sync.
for i := 0; i < c.nDuring; i++ {
if _, err := s.Write(uint32(c.nBefore+i), makeBlock(4096, byte(0xB0+i))); err != nil {
t.Fatal(err)
}
}
// Abrupt kill: stop background goroutines so they
// don't race the file close, then drop fd directly
// without going through Close().
s.flusher.Stop()
s.committer.Stop()
_ = s.fd.Close()
}()
// Reopen + Recover. Verify acked survives, unacked
// is either present-as-written or absent, never corrupt.
s, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatalf("reopen after %s: %v", c.name, err)
}
defer s.Close()
if _, err := s.Recover(); err != nil {
t.Fatalf("recover after %s: %v", c.name, err)
}
for i := 0; i < c.nBefore; i++ {
got, err := s.Read(uint32(i))
if err != nil {
t.Fatal(err)
}
want := makeBlock(4096, byte(0xA0+i))
if !bytes.Equal(got, want) {
t.Fatalf("ACKED LBA %d did not survive %s: got[0]=%02x want[0]=%02x",
i, c.name, got[0], want[0])
}
}
zero := make([]byte, 4096)
for i := 0; i < c.nDuring; i++ {
got, err := s.Read(uint32(c.nBefore + i))
if err != nil {
t.Fatal(err)
}
want := makeBlock(4096, byte(0xB0+i))
if !bytes.Equal(got, want) && !bytes.Equal(got, zero) {
t.Fatalf("UNACKED LBA %d under %s: got neither write nor zero — corruption: got[0]=%02x",
c.nBefore+i, c.name, got[0])
}
}
})
}
}
// TestFlusher_ManyDirtyEntriesCheckpointStaysCorrect is the
// regression test for the architect-flagged "checkpoint can advance
// past unflushed records" bug.
//
// The earlier flusher truncated the dirty snapshot to maxBatch
// entries (in arbitrary map order), then advanced the checkpoint to
// the highest LSN in that PARTIAL batch. If the truncated portion
// contained entries with smaller LSNs, the checkpoint would jump
// past them and recovery would later skip records that hadn't been
// flushed → data loss.
//
// The fix removed the maxBatch cutoff (V2 has no such cutoff). This
// test writes many entries, forces flush, then crashes-without-Close
// and verifies all blocks are recoverable via the extent. If a
// checkpoint ever jumps past an unflushed entry again, this test
// will catch it because that LBA's read will return zeros instead
// of the written bytes.
func TestFlusher_ManyDirtyEntriesCheckpointStaysCorrect(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "store.bin")
const n = 300 // > any plausible old maxBatch (which was 256)
{
s, err := createLegacyWALStoreForTest(path, n+10, 4096)
if err != nil {
t.Fatal(err)
}
for i := uint32(0); i < n; i++ {
if _, err := s.Write(i, makeBlock(4096, byte(i%256))); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
// Wait for the flusher to drain enough that the checkpoint
// has advanced. With 300 entries and the V2-faithful
// "process whole snapshot in one cycle" rule, one flush
// cycle should drain all of them.
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
if s.CheckpointLSN() >= uint64(n) {
break
}
time.Sleep(20 * time.Millisecond)
}
if s.CheckpointLSN() < uint64(n) {
t.Fatalf("flusher did not drain all %d entries: checkpoint=%d", n, s.CheckpointLSN())
}
// Abrupt kill: bypass Close so we exercise recovery from the
// post-flush state, not a clean-shutdown path.
s.flusher.Stop()
s.committer.Stop()
_ = s.fd.Close()
}
// Reopen + Recover. Every LBA must be readable with the bytes
// we wrote — the checkpoint advance must have only covered
// LBAs whose data is actually in the extent.
s, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
defer s.Close()
if _, err := s.Recover(); err != nil {
t.Fatal(err)
}
for i := uint32(0); i < n; i++ {
got, _ := s.Read(i)
want := makeBlock(4096, byte(i%256))
if !bytes.Equal(got, want) {
t.Fatalf("LBA %d: bytes lost — checkpoint advanced past unflushed record",
i)
}
}
}
// TestFlusher_ConcurrentWriteRaceLBAStaysFresh is the regression
// test for the architect-flagged "flusher deletes newer concurrent
// write" bug.
//
// The earlier flusher snapshotted {LBA, oldLSN}, wrote oldLSN's
// data to extent, and unconditionally deleted the dirty map entry
// by LBA. If a concurrent Write() updated that LBA to {LBA, newLSN}
// after the snapshot, the unconditional delete would also drop the
// newer entry, and reads would fall back to the stale extent bytes.
//
// The fix uses compareAndDelete(LBA, expectedLSN) — only delete if
// the entry's LSN still matches the snapshot LSN. Newer entries are
// left in place.
//
// We construct the race deterministically: write a value, sneak in a
// second write to the same LBA before the flusher cycle, then read
// back. The read must reflect the SECOND write, not the first.
func TestFlusher_ConcurrentWriteRaceLBAStaysFresh(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "store.bin")
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
defer s.Close()
first := makeBlock(4096, 0xAA)
second := makeBlock(4096, 0xBB)
// First write to LBA 5.
if _, err := s.Write(5, first); err != nil {
t.Fatal(err)
}
// Hammer the LBA with the SECOND write in a loop while the
// background flusher (interval 100ms) ticks. Each iteration
// could land in a different position relative to the flusher's
// snapshot/cleanup. Across ~50 iterations there is high
// probability that at least one iteration interleaves the
// write between the flusher's snapshot and its cleanup. With
// the bug, that interleaving causes the dirty entry to be
// dropped and the next read to return `first` (from extent)
// instead of `second`.
for iter := 0; iter < 50; iter++ {
if _, err := s.Write(5, second); err != nil {
t.Fatal(err)
}
// Give the flusher a tick or two to potentially race.
time.Sleep(120 * time.Millisecond)
got, err := s.Read(5)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, second) {
t.Fatalf("iter %d: LBA 5 reads %02x, want second-write byte %02x — flusher ate the newer entry",
iter, got[0], second[0])
}
}
}
// TestAllBlocks_ReturnsBlocksAfterFlush is the regression test for
// the architect-flagged "AllBlocks contract violation" bug. The
// LogicalStorage contract says AllBlocks() returns every WRITTEN
// LBA's current bytes. The earlier WALStore.AllBlocks() returned
// only the dirty-map entries, which means flushed blocks would
// disappear from the result.
//
// The fix reads every LBA via Read() (which falls back to extent
// for non-dirty LBAs) and filters zeros. After the flusher drains
// every entry, all written LBAs are still returned.
func TestAllBlocks_ReturnsBlocksAfterFlush(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "store.bin")
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
defer s.Close()
if _, err := s.Write(1, makeBlock(4096, 0x11)); err != nil {
t.Fatal(err)
}
if _, err := s.Write(7, makeBlock(4096, 0x77)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
// Wait for the flusher to drain — both LBAs out of the dirty
// map and into the extent.
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if s.CheckpointLSN() >= 2 {
break
}
time.Sleep(20 * time.Millisecond)
}
if s.CheckpointLSN() < 2 {
t.Fatal("flusher did not advance checkpoint")
}
// AllBlocks must still return both written LBAs even though
// they're no longer in the dirty map.
all, snapshotErr := s.AllBlocks()
if snapshotErr != nil {
t.Fatal(snapshotErr)
}
if len(all) != 2 {
t.Fatalf("AllBlocks after flush returned %d entries, want 2", len(all))
}
if all[1][0] != 0x11 {
t.Fatalf("AllBlocks LBA 1: got %02x, want 11", all[1][0])
}
if all[7][0] != 0x77 {
t.Fatalf("AllBlocks LBA 7: got %02x, want 77", all[7][0])
}
}
// TestRecovery_DeterministicAcrossMultipleOpens: after a crash + a
// recovered open, calling Recover again on the same on-disk state
// yields exactly the same in-memory state.
func TestRecovery_DeterministicAcrossMultipleOpens(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "store.bin")
{
s, _ := createLegacyWALStoreForTest(path, 16, 4096)
for i := uint32(0); i < 5; i++ {
_, _ = s.Write(i, makeBlock(4096, byte(0x10+i)))
}
_, _ = s.Sync()
// Skip Close — simulate crash.
s.flusher.Stop()
s.committer.Stop()
_ = s.fd.Close()
}
// First reopen + Recover.
s1, _ := openLegacyWALStoreForTest(path)
r1, err := s1.Recover()
if err != nil {
t.Fatal(err)
}
contents1 := make([][]byte, 5)
for i := uint32(0); i < 5; i++ {
contents1[i], _ = s1.Read(i)
}
_ = s1.Close()
// Second reopen + Recover on the same file.
s2, _ := openLegacyWALStoreForTest(path)
r2, err := s2.Recover()
if err != nil {
t.Fatal(err)
}
for i := uint32(0); i < 5; i++ {
got, _ := s2.Read(i)
if !bytes.Equal(got, contents1[i]) {
t.Fatalf("LBA %d differs across two open+recover cycles", i)
}
}
_ = s2.Close()
if r1 != r2 {
t.Fatalf("Recover frontier not deterministic across reopens: r1=%d r2=%d", r1, r2)
}
}
@@ -125,12 +125,3 @@ func DamageV3RecordTest(path string, lsn uint64) error {
}
return fmt.Errorf("no v3 record with LSN %d", lsn)
}
// Legacy fixtures only; unavailable in production builds.
// TODO(format-v3 row 14a): replace with captured migration fixtures.
func CreateLegacyWALStoreTest(path string, blocks uint32, blockSize int) (*WALStore, error) {
return createLegacyWALStoreWithOptions(path, blocks, blockSize, WALStoreOptions{})
}
func OpenLegacyWALStoreTest(path string) (*WALStore, error) {
return openLegacyWALStoreWithOptions(path, WALStoreOptions{})
}
@@ -1,178 +0,0 @@
package storage
// legacyC11FileStore preserves the retired C11 file codec for historical tests.
// It is compiled only into this package's tests: one state file
// (header + dirty-since-HEAD chunks, with a SHA-256 over its body) replaced
// atomically on every change, plus an append-only delta log with one JSON
// record per closed HEAD period. Every method is durable on return.
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
)
type legacyC11FileStore struct {
path string
mu sync.Mutex
loaded bool
stored bool
hdr chunkBitmapHeader
dirty []uint64
}
// newLegacyC11FileStore returns a store at path (the delta log is
// path + ".deltas").
func newLegacyC11FileStore(path string) *legacyC11FileStore {
return &legacyC11FileStore{path: path}
}
type chunkBitmapFile struct {
Version int `json:"version"`
Header chunkBitmapHeader `json:"header"`
Dirty []uint64 `json:"dirty"`
}
type chunkBitmapEnvelope struct {
Body json.RawMessage `json:"body"`
SHA256 string `json:"sha256"`
}
func (b *legacyC11FileStore) loadLocked() error {
if b.loaded {
return nil
}
b.loaded = true
raw, err := os.ReadFile(b.path)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return fmt.Errorf("storage: chunk bitmap read: %w", err)
}
var env chunkBitmapEnvelope
if json.Unmarshal(raw, &env) != nil {
return nil // corrupt: treated as lost (hash-compare fallback)
}
sum := sha256.Sum256(env.Body)
if hex.EncodeToString(sum[:]) != env.SHA256 {
return nil
}
var f chunkBitmapFile
if json.Unmarshal(env.Body, &f) != nil || f.Version != 1 {
return nil
}
b.stored, b.hdr, b.dirty = true, f.Header, f.Dirty
return nil
}
func (b *legacyC11FileStore) writeLocked(hdr chunkBitmapHeader, dirty []uint64) error {
body, err := json.Marshal(chunkBitmapFile{Version: 1, Header: hdr, Dirty: dirty})
if err != nil {
return err
}
sum := sha256.Sum256(body)
raw, err := json.Marshal(chunkBitmapEnvelope{Body: body, SHA256: hex.EncodeToString(sum[:])})
if err != nil {
return err
}
if err := writeFileDurable(b.path, raw); err != nil {
return fmt.Errorf("storage: chunk bitmap write: %w", err)
}
// Durable on return includes the rename itself.
if err := syncDir(filepath.Dir(b.path)); err != nil {
return fmt.Errorf("storage: chunk bitmap: fsync directory: %w", err)
}
b.stored, b.hdr, b.dirty = true, hdr, append([]uint64(nil), dirty...)
return nil
}
func (b *legacyC11FileStore) Load() (chunkBitmapHeader, []uint64, bool, error) {
b.mu.Lock()
defer b.mu.Unlock()
if err := b.loadLocked(); err != nil {
return chunkBitmapHeader{}, nil, false, err
}
if !b.stored {
return chunkBitmapHeader{}, nil, false, nil
}
return b.hdr, append([]uint64(nil), b.dirty...), true, nil
}
func (b *legacyC11FileStore) Save(dirty []uint64) error {
b.mu.Lock()
defer b.mu.Unlock()
if err := b.loadLocked(); err != nil {
return err
}
return b.writeLocked(b.hdr, dirty)
}
func (b *legacyC11FileStore) WriteHeader(hdr chunkBitmapHeader) error {
b.mu.Lock()
defer b.mu.Unlock()
if err := b.loadLocked(); err != nil {
return err
}
return b.writeLocked(hdr, b.dirty)
}
func (b *legacyC11FileStore) Reset(hdr chunkBitmapHeader, stillDirty []uint64, delta chunkDelta) error {
b.mu.Lock()
defer b.mu.Unlock()
if err := b.loadLocked(); err != nil {
return err
}
rec, err := json.Marshal(delta)
if err != nil {
return err
}
f, err := os.OpenFile(b.path+".deltas", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
return fmt.Errorf("storage: chunk delta log: %w", err)
}
if _, err := f.Write(append(rec, '\n')); err != nil {
f.Close()
return fmt.Errorf("storage: chunk delta log: %w", err)
}
if err := f.Sync(); err != nil {
f.Close()
return fmt.Errorf("storage: chunk delta log: %w", err)
}
if err := f.Close(); err != nil {
return err
}
return b.writeLocked(hdr, stillDirty)
}
// Deltas returns the archived delta records, oldest first.
func (b *legacyC11FileStore) Deltas() ([]chunkDelta, error) {
raw, err := os.ReadFile(b.path + ".deltas")
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var out []chunkDelta
for _, line := range bytes.Split(bytes.TrimSpace(raw), []byte("\n")) {
if len(line) == 0 {
continue
}
var d chunkDelta
if err := json.Unmarshal(line, &d); err != nil {
return nil, fmt.Errorf("storage: chunk delta log: %w", err)
}
out = append(out, d)
}
return out, nil
}
var _ chunkBitmapStore = (*legacyC11FileStore)(nil)
@@ -0,0 +1,110 @@
//go:build linux
package storage
import (
"bytes"
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"syscall"
"testing"
"time"
)
func TestNativeReplacementCheckpointSIGKILL(t *testing.T) {
const phaseEnv, pathEnv = "SW_BLOCK_NATIVE_CHECKPOINT_KILL", "SW_BLOCK_NATIVE_CHECKPOINT_PATH"
const skipHookEnv = "SW_BLOCK_NATIVE_CHECKPOINT_SKIP_HOOK"
if phase := os.Getenv(phaseEnv); phase != "" {
s, err := createMappedWALStoreV3ForTest(os.Getenv(pathEnv), 16, 4096, 64*1024, WModeStrict, 4)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
if _, err := s.Write(3, blk(0x7C)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
kill := func() error { return syscall.Kill(os.Getpid(), syscall.SIGKILL) }
switch phase {
case "extent_sync":
s.flusher.afterExtentSyncForTest = func() { _ = kill() }
case "slot_pwrite":
if os.Getenv(skipHookEnv) != phase {
s.v3.pub.io.fsync = kill
}
case "slot_sync":
real := s.v3.pub.io.fsync
if os.Getenv(skipHookEnv) != phase {
s.v3.pub.io.fsync = func() error {
if err := real(); err != nil {
return err
}
return kill()
}
}
case "tail_publication":
default:
t.Fatal("unknown native checkpoint crash phase", phase)
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
if phase == "tail_publication" {
_ = kill()
t.Fatal("SIGKILL returned")
}
t.Fatal("flush returned without reaching crash hook", phase)
}
for _, phase := range []string{"extent_sync", "slot_pwrite", "slot_sync", "tail_publication"} {
t.Run(phase, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "volume")
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestNativeReplacementCheckpointSIGKILL$")
cmd.Env = append(os.Environ(), phaseEnv+"="+phase, pathEnv+"="+path)
out, err := cmd.CombinedOutput()
var exited *exec.ExitError
if ctx.Err() != nil || !errors.As(err, &exited) || exited.ProcessState.Sys().(syscall.WaitStatus).Signal() != syscall.SIGKILL {
t.Fatalf("helper did not reach its own crash hook: %v ctx=%v output=%s", err, ctx.Err(), out)
}
r, err := OpenWALStore(path)
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = r.Close() })
cp := r.CheckpointLSN()
if cp > 1 || (phase == "extent_sync" && cp != 0) || ((phase == "slot_sync" || phase == "tail_publication") && cp != 1) {
t.Fatalf("%s checkpoint=%d", phase, cp)
}
if _, err := r.Recover(); err != nil {
t.Fatal(err)
}
if got, err := r.Read(3); err != nil || !bytes.Equal(got, blk(0x7C)) {
t.Fatalf("acknowledged bytes lost at %s: %v", phase, err)
}
if r.NextLSN() != 2 {
t.Fatalf("recovered allocator=%d", r.NextLSN())
}
})
}
for _, phase := range []string{"slot_pwrite", "slot_sync"} {
t.Run("missing_hook_"+phase, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "volume")
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestNativeReplacementCheckpointSIGKILL$")
cmd.Env = append(os.Environ(), phaseEnv+"="+phase, pathEnv+"="+path, skipHookEnv+"="+phase)
out, err := cmd.CombinedOutput()
var exited *exec.ExitError
if ctx.Err() != nil || !errors.As(err, &exited) || exited.ProcessState.Sys().(syscall.WaitStatus).Signaled() || !bytes.Contains(out, []byte("flush returned without reaching crash hook")) {
t.Fatalf("missing %s hook was not detected: %v ctx=%v output=%s", phase, err, ctx.Err(), out)
}
})
}
}
@@ -14,15 +14,13 @@ import (
"time"
)
// The old engine remains only for explicit fixtures until row 14a. The
// production import closure must not bring in its frozen tool/test package,
// and no production source may call the legacy constructor chain.
// The retired engine must not return through constructors or import aliases.
func TestLegacyFixtureIsolation(t *testing.T) {
entries, err := os.ReadDir(".")
if err != nil {
t.Fatal(err)
}
forbidden := map[string]bool{"createLegacyWALStoreWithOptions": true, "openLegacyWALStoreWithOptions": true, "openLegacyReadOnlyWithOptions": true}
forbidden := map[string]bool{"createLegacyWALStoreWithOptions": true, "openLegacyWALStoreWithOptions": true, "openLegacyReadOnlyWithOptions": true, "newWALWriter": true, "decodeWALEntry": true, "encodeWALPadding": true, "recoverWAL": true, "walEntry": true}
for _, e := range entries {
n := e.Name()
if e.IsDir() || !strings.HasSuffix(n, ".go") || strings.HasSuffix(n, "_test.go") || n == "format_v3_test_support.go" {
@@ -74,16 +72,8 @@ func TestLegacyFixtureIsolation(t *testing.T) {
func legacyConstructorReferences(f *ast.File, forbidden map[string]bool) []string {
var refs []string
// A constructor declaration is retained for test linking, but every use
// (including function values, aliases and arguments) is forbidden.
declarations := map[*ast.Ident]bool{}
for _, decl := range f.Decls {
if fn, ok := decl.(*ast.FuncDecl); ok {
declarations[fn.Name] = true
}
}
ast.Inspect(f, func(n ast.Node) bool {
if id, ok := n.(*ast.Ident); ok && forbidden[id.Name] && !declarations[id] {
if id, ok := n.(*ast.Ident); ok && forbidden[id.Name] {
refs = append(refs, id.Name)
}
return true
@@ -95,6 +85,7 @@ func TestLegacyFixtureIsolationRejectsFunctionValues(t *testing.T) {
const name = "createLegacyWALStoreWithOptions"
for _, body := range []string{
"func use() { createLegacyWALStoreWithOptions() }",
"func createLegacyWALStoreWithOptions() {}",
"var constructor = createLegacyWALStoreWithOptions",
"func use() { constructor := createLegacyWALStoreWithOptions; constructor() }",
"func use() { accept(createLegacyWALStoreWithOptions) }",
@@ -109,11 +100,4 @@ func TestLegacyFixtureIsolationRejectsFunctionValues(t *testing.T) {
}
})
}
f, err := parser.ParseFile(token.NewFileSet(), "legacy.go", "package storage\nfunc createLegacyWALStoreWithOptions() {}", 0)
if err != nil {
t.Fatal(err)
}
if refs := legacyConstructorReferences(f, map[string]bool{name: true}); len(refs) != 0 {
t.Fatalf("declaration is not a use: %v", refs)
}
}
@@ -1,14 +0,0 @@
package storage
// TODO(format-v3 row 14a): relocate or retire only the inventory-listed v2
// engine controls after the named v3 replacements and migration receipts pass.
// These explicit fixture constructors are never production selectors.
func createLegacyWALStoreForTest(path string, blocks uint32, blockSize int) (*WALStore, error) {
return createLegacyWALStoreWithOptions(path, blocks, blockSize, WALStoreOptions{})
}
func openLegacyWALStoreForTest(path string) (*WALStore, error) {
return openLegacyWALStoreWithOptions(path, WALStoreOptions{})
}
func openLegacyReadOnlyForTest(path string) (*WALStoreReader, error) {
return openLegacyReadOnlyWithOptions(path, WALStoreOptions{})
}
File diff suppressed because it is too large. Load diff
@@ -10,10 +10,10 @@ import (
// Control the legal scheduler order between a completed physical callback and
// its caller publishing/reading the global stable frontier in Sync.
func TestWALGenerationFirstCallerReturnOrdering(t *testing.T) {
func TestNativeReplacementSyncCallerReturnOrdering(t *testing.T) {
for _, laterPublishesFirst := range []bool{false, true} {
t.Run(fmt.Sprintf("later_publishes_first=%v", laterPublishesFirst), func(t *testing.T) {
s := newLegacyGenerationStore(t)
s, _ := newMappedCheckpointStoreV3(t)
firstEntered, secondEntered, firstCacheReturned := make(chan struct{}), make(chan struct{}), make(chan struct{})
releaseFirst, releaseSecond, publishFirst := make(chan struct{}), make(chan struct{}), make(chan struct{})
var workers sync.WaitGroup
@@ -68,13 +68,18 @@ func TestWALGenerationFirstCallerReturnOrdering(t *testing.T) {
return err
}
type result struct {
frontier uint64
err error
frontier uint64
completed int32
err error
}
leader, followers := make(chan result, 1), make(chan result, 1)
start := func(out chan<- result) {
workers.Add(1)
go func() { defer workers.Done(); n, err := s.Sync(); out <- result{n, err} }()
go func() {
defer workers.Done()
n, err := s.Sync()
out <- result{frontier: n, completed: completed.Load(), err: err}
}()
}
await := func(ch <-chan struct{}, label string) {
t.Helper()
@@ -133,27 +138,18 @@ func TestWALGenerationFirstCallerReturnOrdering(t *testing.T) {
} else {
closeOnce(publishFirst)
}
first := receive(leader)
// Sync returns the current global stable frontier, not its own cut.
// A later return may include a newer independently completed fsync.
wantFirst := uint64(1)
if laterPublishesFirst {
wantFirst = 2
}
if first.frontier != wantFirst {
t.Fatalf("first batch frontier=%d want %d (completed physical syncs=%d laterPublishesFirst=%v)", first.frontier, wantFirst, completed.Load(), laterPublishesFirst)
}
// Strict v3 may wait for the shared-file sync before publishing
// its descriptor. It need not return before the second caller.
if !laterPublishesFirst {
if completed.Load() != 1 {
t.Fatal("held second fsync unexpectedly completed")
}
closeOnce(releaseSecond)
for i := 0; i < 1; i++ {
if r := receive(followers); r.frontier != 2 {
t.Fatal("follower frontier", r)
}
if r := receive(followers); r.frontier != 2 || r.completed < 2 {
t.Fatal("follower frontier without completed physical sync", r)
}
}
first := receive(leader)
if first.frontier < 1 || first.frontier > uint64(first.completed) {
t.Fatalf("first frontier exceeds completed physical syncs: %+v", first)
}
if completed.Load() != 2 || s.WALSyncCount() != 2 {
t.Fatalf("physical counts completed=%d attempts=%d", completed.Load(), s.WALSyncCount())
}
-211
View File
@@ -1,211 +0,0 @@
package storage
import (
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"math"
"os"
)
// Tool-only exports for the offline migration `sw-block migrate-v3` (format
// bump v3, DESIGN r17.4 section 10.1; plan row 13b). They reuse the row-1
// slot codec and the row-6 map codec; there is no second encoder. Nothing
// here opens, recovers or serves a store, and the v3 open code calls none of
// it.
var (
// ErrMigrateGeometry: the v2 geometry cannot be expressed as v3 without
// moving data (DESIGN 10.1 precondition 4).
ErrMigrateGeometry = errors.New("storage: v2 geometry cannot be migrated in place to v3")
)
// MigrationSlotAOffset and MigrationSlotBOffset are the v3 slot positions.
const (
MigrationSlotAOffset = slotAOffsetV3
MigrationSlotBOffset = slotBOffsetV3
MigrationSlotSize = slotSizeV3
// migratedWALMinV3 is the provisional impl-3 minimum WAL size for a
// migrated volume: at least 64 KiB and two single-block records.
migratedWALMinV3 = 64 * 1024
)
// MigrationSourceV3 is what the tool read from the v2 superblock.
type MigrationSourceV3 struct {
UUID [16]byte
VolumeSize uint64
ExtentSize uint32
BlockSize uint32
OldWALOffset uint64 // must be 4096
OldWALSize uint64
CreatedAt uint64
CheckpointLSN uint64
ChunkBlocks uint64 // the map's chunk geometry (the provider's)
}
// MigrationPlanV3 is the v3 image of a migration: the descriptor slot
// images in their write order and the new descriptor's hash.
type MigrationPlanV3 struct {
PreparedB []byte // step 4: slot B, slotGen 1, MigrationPhase prepared
CommittedA []byte // step 5: slot A, slotGen 2, phase 0 (the commit point)
RolloverB []byte // step 6: slot B, slotGen 3, phase 0
// DescriptorHash is the SHA-256 of CommittedA, printed at step 8.
DescriptorHash [32]byte
}
// migrationDescriptorV3 is the v3 descriptor for src (DESIGN 10.1 step 4):
// WALOffset 8192 and WALSize = old WALSize - 4096, so the extent base
// WALOffset + WALSize is unchanged; CheckpointLSN = W = the v2 checkpoint;
// an empty cursor space; BaseState none; WMode C.
func migrationDescriptorV3(src MigrationSourceV3) (descriptorV3, error) {
if src.OldWALOffset != superblockSize {
return descriptorV3{}, fmt.Errorf("%w: v2 WALOffset %d, want %d", ErrMigrateGeometry, src.OldWALOffset, superblockSize)
}
if src.BlockSize == 0 || src.OldWALSize <= slotSizeV3 {
return descriptorV3{}, fmt.Errorf("%w: v2 WAL size %d", ErrMigrateGeometry, src.OldWALSize)
}
walSize := src.OldWALSize - slotSizeV3
if walSize%uint64(src.BlockSize) != 0 || walSize < migratedWALMinV3 ||
walSize < 2*(walEntryHeaderSizeV3+uint64(src.BlockSize)) {
return descriptorV3{}, fmt.Errorf("%w: v3 WAL size %d is not block aligned or below the minimum", ErrMigrateGeometry, walSize)
}
if src.CheckpointLSN > counterMaxV3 {
return descriptorV3{}, fmt.Errorf("%w: checkpoint %d", ErrMigrateGeometry, src.CheckpointLSN)
}
// The checked extent end (codex01 row 13b P1): the same bounds the slot
// validation applies, here, before any backup or sidecar write.
if src.VolumeSize == 0 || src.ExtentSize == 0 || src.VolumeSize%uint64(src.BlockSize) != 0 {
return descriptorV3{}, fmt.Errorf("%w: volume %d, extent %d, block %d", ErrMigrateGeometry, src.VolumeSize, src.ExtentSize, src.BlockSize)
}
if end, ok := checkedAddV3(walOffsetV3, walSize); !ok {
return descriptorV3{}, fmt.Errorf("%w: the WAL region overflows", ErrMigrateGeometry)
} else if fileEnd, ok := checkedAddV3(end, src.VolumeSize); !ok || fileEnd > math.MaxInt64 {
return descriptorV3{}, fmt.Errorf("%w: the extent region overflows", ErrMigrateGeometry)
}
d := descriptorV3{
ImplKind: ImplKindWALStore, ImplVersion: walStoreImplVersion3, UUID: src.UUID,
VolumeSize: src.VolumeSize, ExtentSize: src.ExtentSize, BlockSize: src.BlockSize,
WALOffset: walOffsetV3, WALSize: walSize, CreatedAt: src.CreatedAt,
CheckpointLSN: src.CheckpointLSN, W: src.CheckpointLSN, WMode: WModeLagged,
MapFormatID: mapFormatIDV1, MapGeneration: 1, SlotGen: 1,
}
if walOffsetV3+walSize != src.OldWALOffset+src.OldWALSize {
return descriptorV3{}, fmt.Errorf("%w: the extent base would move", ErrMigrateGeometry)
}
if _, err := mapShapeForV3(d, src.ChunkBlocks); err != nil {
return descriptorV3{}, fmt.Errorf("%w: map geometry: %w", ErrMigrateGeometry, err)
}
return d, nil
}
// ValidateMigrationV3 checks precondition 4 (geometry) without writing.
func ValidateMigrationV3(src MigrationSourceV3) error {
_, err := migrationDescriptorV3(src)
return err
}
// PrepareMigrationV3 runs DESIGN 10.1 step 3 and builds the slot images of
// steps 4 to 6. It (re)creates the initial map sidecar at mapPath durably:
// generation 1, every chunk UNKNOWN with its inherited checkpoint frontier,
// coveredCheckpoint =
// the v2 checkpoint (a fully flushed WAL is not remote-clean). The slots
// carry a fresh random nonce and the map fields of that root. It writes
// nothing to the store file.
func PrepareMigrationV3(mapPath string, src MigrationSourceV3) (MigrationPlanV3, error) {
d, err := migrationDescriptorV3(src)
if err != nil {
return MigrationPlanV3{}, err
}
for _, b := range [][]byte{d.Nonce[:], d.MapLineage[:]} {
for b2 := b; ; {
if _, err := rand.Read(b2); err != nil {
return MigrationPlanV3{}, err
}
if !allZero(b2) {
break
}
}
}
if err := os.Remove(mapPath); err != nil && !errors.Is(err, os.ErrNotExist) {
return MigrationPlanV3{}, err // a rerun rewrites the map (10.1 rerun table)
}
m, err := createChunkLSNMapV3(mapPath, d, src.ChunkBlocks)
if err != nil {
return MigrationPlanV3{}, err
}
shape, err := mapShapeForV3(d, src.ChunkBlocks)
if err != nil {
_ = m.Close()
return MigrationPlanV3{}, err
}
entries := make([]chunkLSNEntryV3, int(shape.chunks))
for i := range entries {
entries[i].Unknown = true
entries[i].LSN = src.CheckpointLSN
}
c, err := m.Prepare(1, src.CheckpointLSN, entries, nil)
if err = errors.Join(err, m.Close()); err != nil {
return MigrationPlanV3{}, err
}
d = c.descriptor(d)
d.SlotGen, d.MigrationPhase = 1, MigrationPrepared
if err := d.validate(nil); err != nil {
return MigrationPlanV3{}, err
}
var plan MigrationPlanV3
plan.PreparedB = d.encode()
d.SlotGen, d.MigrationPhase = 2, MigrationNormal
if err := d.validate(nil); err != nil {
return MigrationPlanV3{}, err
}
plan.CommittedA = d.encode()
plan.DescriptorHash = sha256.Sum256(plan.CommittedA)
d.SlotGen = 3
plan.RolloverB = d.encode()
return plan, nil
}
// RolloverSlotV3 is step 6 for a rerun that finds a committed slot A of
// slotGen 2: the same descriptor at slotGen 3, phase 0.
func RolloverSlotV3(committedA []byte) ([]byte, error) {
d, err := decodeSlotV3(committedA, nil)
if err != nil {
return nil, err
}
if d.MigrationPhase != MigrationNormal || d.SlotGen != 2 {
return nil, fmt.Errorf("%w: slot A is not a fresh migration commit", errSuperblockInvalid)
}
d.SlotGen = 3
return d.encode(), nil
}
// MigrationSlotStateV3 classifies one raw v3 slot for the rerun table.
type MigrationSlotStateV3 int
const (
MigrationSlotInvalid MigrationSlotStateV3 = iota // not a valid v3 slot
MigrationSlotPrepared // valid, MigrationPhase prepared
MigrationSlotCommitted // valid and selectable (phase 0)
)
// ClassifyMigrationSlotV3 reports a slot's state and slotGen.
func ClassifyMigrationSlotV3(raw []byte) (MigrationSlotStateV3, uint64) {
d, err := decodeSlotV3(raw, nil)
if err != nil {
return MigrationSlotInvalid, 0
}
if d.MigrationPhase == MigrationPrepared {
return MigrationSlotPrepared, d.SlotGen
}
return MigrationSlotCommitted, d.SlotGen
}
func allZero(b []byte) bool {
for _, x := range b {
if x != 0 {
return false
}
}
return true
}
@@ -1,41 +0,0 @@
package storage
import (
"io"
"os"
"path/filepath"
"testing"
)
func TestMultiBlockRecordsRequireDistinctOnDiskImplVersion(t *testing.T) {
if os.Getenv("SEAWEED_KNOWN_BUGS") != "1" {
t.Skip("known bug #189 (open): reproduction runs with SEAWEED_KNOWN_BUGS=1; the fix PR removes this skip")
}
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store"), 64, 4096)
if err != nil {
t.Fatal(err)
}
defer s.Close()
s.flusher.Stop()
s.SetMultiBlockRecords(true)
if _, err := s.WriteBatch(2, [][]byte{makeBlock(4096, 0x41), makeBlock(4096, 0x42)}); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
header := make([]byte, walEntryHeaderSize)
if _, err := s.fd.ReadAt(header, int64(s.sb.WALOffset)); err != nil {
t.Fatal(err)
}
if header[16] != walEntryWriteBatch {
t.Fatalf("setup record type=%d, want batch", header[16])
}
disk, err := readSuperblock(io.NewSectionReader(s.fd, 0, superblockSize))
if err != nil {
t.Fatal(err)
}
if disk.ImplVersion == 1 {
t.Fatal("synced type0x04 multi-block record still advertises legacy impl version1; a pre-multiblock opener cannot reject the incompatible file by version")
}
}
@@ -0,0 +1,23 @@
package storage
import (
"errors"
"testing"
)
func TestChunkAttachRefusesAnUnmappedNativeStore(t *testing.T) {
s, _ := newStoreV3(t, WModeStrict)
t.Cleanup(func() { _ = s.Close() })
f := newFakeChunkRemote()
l, err := attachChunkLayerImpl(s, f, ctConfig(1))
if l != nil {
defer l.Close()
}
if !errors.Is(err, ErrMapInvalid) {
t.Fatalf("unmapped native store fell back to the retired bitmap engine: %v", err)
}
st := f.stats()
if st.puts != 0 || st.gets != 0 || st.getHeads != 0 || st.cas != 0 {
t.Fatal("map admission contacted remote before refusing")
}
}
-458
View File
@@ -1,458 +0,0 @@
package storage
import (
"encoding/binary"
"fmt"
"log"
"os"
"sort"
)
// recoveryResult summarizes what RecoverWAL did on one open.
type recoveryResult struct {
EntriesReplayed int // valid entries past checkpoint that were replayed
HighestLSN uint64 // highest LSN observed across the whole scan
WALHead uint64 // reconstructed logical byte head of retained WAL
WALTail uint64 // reconstructed logical byte tail of retained WAL
TornEntries int // entries discarded due to CRC failure or truncation
DefensiveScan bool // true when the superblock was empty and we scanned the whole region
// HoleSuspected: a bad entry was followed by a valid later entry
// (issue #51). Detection only: it changes nothing about what is
// replayed. HoleDetail says where.
HoleSuspected bool
HoleDetail string
}
// recoverWAL scans the WAL region and replays any entries that have
// not yet been checkpointed into the extent. Replayed entries are
// inserted into the dirty map so subsequent reads can find them and
// the flusher can apply them to the extent.
//
// Recovery is deliberately defensive: even when the superblock says
// WAL is empty, the scanner walks the whole region looking for valid
// entries past the recorded head. CRC validation is the stop signal
// — the first record that fails CRC marks where torn writes begin
// and scanning halts.
//
// On a clean shutdown the first byte past head is zero or padding,
// CRC fails immediately, and the defensive scan adds zero overhead.
//
// Side effects: if the extended scan finds entries past the
// superblock's recorded head, sb.WALHead is bumped so the writer
// resumes after them.
func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, error) {
result := recoveryResult{}
type retainedRecord struct {
firstLSN uint64
start uint64
end uint64
}
var retainedRecords []retainedRecord
logicalHead := sb.WALHead
logicalTail := sb.WALTail
walOffset := sb.WALOffset
walSize := sb.WALSize
checkpointLSN := sb.WALCheckpointLSN
type scanRange = recoveryScanRange
var ranges []scanRange
// lastLSN is the highest LSN decoded so far (detection only).
var lastLSN uint64
if logicalHead == logicalTail && logicalHead%walSize != 0 {
// The superblock records an empty WAL at this position (a full
// checkpoint persists head == tail). Sync does not persist the
// head, so later appends continue contiguously from here: scan
// from it. Scanning from offset 0 would let a torn record wrapped
// there hide the synced run behind it.
start := logicalHead % walSize
ranges = append(ranges, scanRange{start, walSize}, scanRange{0, start})
result.DefensiveScan = true
log.Printf("storage: recovery from an empty superblock window (head==tail=%d checkpoint=%d)",
logicalHead, checkpointLSN)
} else if logicalHead == logicalTail {
// A pre-boundary-persistence crash can leave a wrapped retained
// window while the superblock still says empty. Find the high
// physical run from record footers, then scan high and low as
// disjoint ranges so neither side is hidden behind the gap.
highStart, found := findDefensiveHighRunStart(fd, walOffset, walSize)
if found && highStart > 0 {
ranges = append(
ranges,
scanRange{highStart, walSize},
scanRange{0, highStart},
)
} else {
ranges = append(ranges, scanRange{0, walSize})
}
result.DefensiveScan = true
log.Printf("storage: recovery defensive scan (head==tail=%d checkpoint=%d)",
logicalHead, checkpointLSN)
} else {
physHead := logicalHead % walSize
physTail := logicalTail % walSize
if physHead > physTail {
ranges = append(ranges, scanRange{physTail, physHead})
ranges = append(ranges, scanRange{physHead, walSize})
if physTail > 0 {
ranges = append(ranges, scanRange{0, physTail})
}
} else {
ranges = append(ranges, scanRange{physTail, walSize})
if physHead > 0 {
ranges = append(ranges, scanRange{0, physHead})
}
if physHead < physTail {
ranges = append(ranges, scanRange{physHead, physTail})
}
}
}
for ri, r := range ranges {
pos := r.start
for pos < r.end {
remaining := r.end - pos
if remaining < uint64(walEntryHeaderSize) {
break
}
headerBuf := make([]byte, walEntryHeaderSize)
absOff := int64(walOffset + pos)
if _, err := fd.ReadAt(headerBuf, absOff); err != nil {
return result, fmt.Errorf("storage: recovery read header at %d: %w", pos, err)
}
entryType := headerBuf[16]
lengthField := parseLengthFromHeader(headerBuf)
if entryType == walEntryPadding {
pos += uint64(walEntryHeaderSize) + uint64(lengthField)
continue
}
var payloadLen uint64
if entryType == walEntryWrite || entryType == walEntryWriteBatch {
payloadLen = uint64(lengthField)
}
entrySize := uint64(walEntryHeaderSize) + payloadLen
if entrySize > remaining {
result.TornEntries++
if err := detectHole(&result, fd, walOffset, ranges, ri, pos, headerBuf, max(lastLSN, checkpointLSN), sb.BlockSize, nil); err != nil {
return result, err
}
break
}
fullBuf := make([]byte, entrySize)
if _, err := fd.ReadAt(fullBuf, absOff); err != nil {
return result, fmt.Errorf("storage: recovery read entry at %d: %w", pos, err)
}
entry, err := decodeWALEntry(fullBuf)
if err != nil {
// Torn write or trailing zeros — stop scanning this range.
result.TornEntries++
if herr := detectHole(&result, fd, walOffset, ranges, ri, pos, headerBuf, max(lastLSN, checkpointLSN), sb.BlockSize, err); herr != nil {
return result, herr
}
break
}
highestEntryLSN := entry.LSN
if entry.Type == walEntryWriteBatch {
maxBlocks := uint64(^uint32(0)) / uint64(sb.BlockSize)
if entry.Reserved == 0 ||
entry.Reserved > maxBlocks ||
entry.Reserved-1 > ^uint64(0)-entry.LSN ||
uint64(entry.Length) != entry.Reserved*uint64(sb.BlockSize) {
return result, NewWALIntegrityFailure(
nil,
fmt.Sprintf(
"invalid walstore batch at offset=%d LSN=%d reserved=%d length=%d block_size=%d",
pos, entry.LSN, entry.Reserved, entry.Length, sb.BlockSize,
),
)
}
highestEntryLSN = entry.LSN + entry.Reserved - 1
}
if highestEntryLSN > lastLSN {
lastLSN = highestEntryLSN
}
if highestEntryLSN <= checkpointLSN {
pos += entrySize
continue
}
firstRetainedLSN := entry.LSN
if firstRetainedLSN <= checkpointLSN {
firstRetainedLSN = checkpointLSN + 1
}
retainedRecords = append(retainedRecords, retainedRecord{
firstLSN: firstRetainedLSN,
start: pos,
end: pos + entrySize,
})
switch entry.Type {
case walEntryWrite:
blocks := entry.Length / sb.BlockSize
for i := uint32(0); i < blocks; i++ {
dm.putAtIfNewer(
entry.LBA+uint64(i), pos, i*sb.BlockSize,
entry.LSN, sb.BlockSize,
)
}
result.EntriesReplayed++
case walEntryWriteBatch:
blocks := uint32(entry.Reserved)
for i := uint32(0); i < blocks; i++ {
lsn := entry.LSN + uint64(i)
if lsn <= checkpointLSN {
continue
}
dm.putAtIfNewer(
entry.LBA+uint64(i), pos, i*sb.BlockSize,
lsn, sb.BlockSize,
)
}
result.EntriesReplayed++
case walEntryTrim:
blocks := entry.Length / sb.BlockSize
if blocks == 0 {
blocks = 1
}
for i := uint32(0); i < blocks; i++ {
dm.putAtIfNewer(
entry.LBA+uint64(i), pos, i*sb.BlockSize,
entry.LSN, sb.BlockSize,
)
}
result.EntriesReplayed++
case walEntryBarrier:
// no data; skip
}
if highestEntryLSN > result.HighestLSN {
result.HighestLSN = highestEntryLSN
}
pos += entrySize
}
}
sort.Slice(retainedRecords, func(left, right int) bool {
return retainedRecords[left].firstLSN < retainedRecords[right].firstLSN
})
if len(retainedRecords) > 0 {
result.WALTail = retainedRecords[0].start
result.WALHead = retainedRecords[0].end
previousStart := retainedRecords[0].start
var wrapBase uint64
for _, record := range retainedRecords[1:] {
if record.start < previousStart {
wrapBase += walSize
}
logicalStart := wrapBase + record.start
logicalEnd := wrapBase + record.end
if logicalStart < result.WALHead || logicalEnd-logicalStart > walSize {
return result, NewWALIntegrityFailure(
nil,
fmt.Sprintf(
"invalid walstore recovery order at LSN=%d offset=%d",
record.firstLSN, record.start,
),
)
}
result.WALHead = logicalEnd
previousStart = record.start
}
if result.WALHead < result.WALTail ||
result.WALHead-result.WALTail > walSize {
return result, NewWALIntegrityFailure(
nil,
fmt.Sprintf(
"invalid walstore recovery bounds tail=%d head=%d size=%d",
result.WALTail, result.WALHead, walSize,
),
)
}
}
if result.DefensiveScan && result.EntriesReplayed > 0 {
log.Printf(
"storage: recovery reconstructed WAL bytes tail=%d head=%d frontier=%d (%d replayed)",
result.WALTail, result.WALHead, result.HighestLSN, result.EntriesReplayed,
)
}
return result, nil
}
func findDefensiveHighRunStart(
fd *os.File,
walOffset uint64,
walSize uint64,
) (uint64, bool) {
maxGap := uint64(walEntryHeaderSize - 1)
if maxGap >= walSize {
maxGap = walSize - 1
}
for gap := uint64(0); gap <= maxGap; gap++ {
cursor := walSize - gap
start, entry, ok := previousValidWALRecord(fd, walOffset, cursor)
if !ok {
continue
}
earliest := start
foundData := entry.Type != walEntryPadding
cursor = start
for cursor > 0 {
previousStart, previous, ok := previousValidWALRecord(
fd, walOffset, cursor,
)
if !ok {
break
}
earliest = previousStart
if previous.Type != walEntryPadding {
foundData = true
}
cursor = previousStart
}
if foundData {
return earliest, true
}
}
return 0, false
}
func previousValidWALRecord(
fd *os.File,
walOffset uint64,
end uint64,
) (uint64, walEntry, bool) {
if end < 4 {
return 0, walEntry{}, false
}
var sizeBytes [4]byte
if _, err := fd.ReadAt(sizeBytes[:], int64(walOffset+end-4)); err != nil {
return 0, walEntry{}, false
}
size := uint64(binary.LittleEndian.Uint32(sizeBytes[:]))
if size < uint64(walEntryHeaderSize) || size > end {
return 0, walEntry{}, false
}
start := end - size
record := make([]byte, size)
if _, err := fd.ReadAt(record, int64(walOffset+start)); err != nil {
return 0, walEntry{}, false
}
entry, err := decodeWALEntry(record)
if err != nil {
return 0, walEntry{}, false
}
switch entry.Type {
case walEntryWrite, walEntryWriteBatch, walEntryTrim,
walEntryBarrier, walEntryPadding:
return start, entry, true
default:
return 0, walEntry{}, false
}
}
// recoveryScanRange is a physical [start, end) span of the WAL region.
type recoveryScanRange struct {
start, end uint64
}
func allZeroBytes(b []byte) bool {
for _, c := range b {
if c != 0 {
return false
}
}
return true
}
// laterValidEntry looks, from pos in ranges[ri] through the later ranges,
// for an offset holding a valid WAL entry (it decodes, CRC included) whose
// LSN is above minLSN. It runs only after a bad entry, so a linear resync
// over the remaining WAL is acceptable; a cheap header prefilter keeps the
// full decodes to plausible candidates.
func laterValidEntry(fd *os.File, walOffset uint64, ranges []recoveryScanRange, ri int, pos, minLSN uint64, blockSize uint32) (bool, uint64, error) {
const window = 1 << 20
hdr := uint64(walEntryHeaderSize)
for i := ri; i < len(ranges); i++ {
start, end := ranges[i].start, ranges[i].end
if i == ri {
start = pos
}
for p := start; p+hdr <= end; p += window {
n := min(window+hdr, end-p)
buf := make([]byte, n)
if _, err := fd.ReadAt(buf, int64(walOffset+p)); err != nil {
return false, 0, fmt.Errorf("storage: recovery resync read at %d: %w", p, err)
}
for q := uint64(0); q+hdr <= n && q < window; q++ {
size, ok := plausibleEntryHeader(buf[q:q+hdr], minLSN, end-(p+q), blockSize)
if !ok {
continue
}
full := make([]byte, size)
if _, err := fd.ReadAt(full, int64(walOffset+p+q)); err != nil {
return false, 0, fmt.Errorf("storage: recovery resync read entry at %d: %w", p+q, err)
}
if _, err := decodeWALEntry(full); err == nil {
return true, p + q, nil
}
}
}
}
return false, 0, nil
}
// plausibleEntryHeader is the resync prefilter: a known record type, an
// LSN above minLSN, and a length that fits in what remains.
func plausibleEntryHeader(h []byte, minLSN, remaining uint64, blockSize uint32) (uint64, bool) {
lsn := binary.LittleEndian.Uint64(h[0:8])
if lsn <= minLSN {
return 0, false
}
length := uint64(parseLengthFromHeader(h))
size := uint64(walEntryHeaderSize)
switch h[16] {
case walEntryWrite, walEntryWriteBatch:
if length == 0 || blockSize == 0 || length%uint64(blockSize) != 0 {
return 0, false
}
size += length
case walEntryTrim, walEntryBarrier:
default:
return 0, false
}
if size > remaining {
return 0, false
}
return size, true
}
// detectHole notes a suspected WAL hole at a bad entry (issue #51;
// detection only). An all-zero
// header is just the end of what was written. Otherwise, if a valid entry
// with an LSN above minLSN (the highest decoded so far, or the checkpoint)
// follows it, the hole is recorded as the typed warning
// WarningWALHoleSuspected and logged. Nothing about the replay changes:
// the caller stops this range exactly as before. A torn tail and a
// corrupted record cannot be told apart without a synced watermark, hence
// "suspected".
func detectHole(result *recoveryResult, fd *os.File, walOffset uint64, ranges []recoveryScanRange, ri int, pos uint64, header []byte, minLSN uint64, blockSize uint32, cause error) error {
if allZeroBytes(header) || result.HoleSuspected {
return nil
}
found, at, err := laterValidEntry(fd, walOffset, ranges, ri, pos+1, minLSN, blockSize)
if err != nil {
// Detection never changes the outcome: a failed look-ahead read
// is logged, and recovery goes on exactly as before.
log.Printf("storage: recovery hole detection at offset=%d skipped: %v", pos, err)
return nil
}
if !found {
return nil
}
result.HoleSuspected = true
result.HoleDetail = fmt.Sprintf("WAL entry at offset=%d fails its check and a valid later entry (LSN > %d) follows at offset=%d", pos, minLSN, at)
if cause != nil {
result.HoleDetail += " (" + cause.Error() + ")"
}
log.Printf("storage: recovery %s: %s", WarningWALHoleSuspected, result.HoleDetail)
return nil
}
+3 -228
View File
@@ -1,244 +1,19 @@
package storage
import (
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"time"
)
import "errors"
// WAL entry kinds.
const (
walEntryWrite = 0x01
walEntryTrim = 0x02
walEntryBarrier = 0x03
walEntryWriteBatch = 0x04
walEntryPadding = 0xFF
// walEntryHeaderSize is the TOTAL fixed overhead per record. Layout:
// prefix (30 bytes):
// LSN(8) + Reserved(8) + Type(1) + Flags(1) + LBA(8) + Length(4)
// variable-length data
// trailer (8 bytes):
// CRC32(4) + EntrySize(4)
// Total = 30 + len(Data) + 8. The constant captures the 30+8=38 of
// fixed overhead so callers can compute total_size = header + data.
//
// Reserved holds 0 today. It exists to keep the on-disk layout
// stable if a future implementation needs to attach an
// implementation-private uint64 (e.g. a fencing token from the
// engine) without a format version bump.
walEntryHeaderSize = 38
// walEntryPrefixSize is the offset where data starts inside a
// serialized record. Distinct from walEntryHeaderSize because the
// 8-byte trailer (CRC + EntrySize) lives AFTER the data, not
// before it. Readers fetching data slice from absOff +
// walEntryPrefixSize, NOT walEntryHeaderSize.
walEntryPrefixSize = 30
)
var (
errCRCMismatch = errors.New("storage: WAL entry CRC mismatch")
errInvalidEntry = errors.New("storage: invalid WAL entry")
errEntryTruncated = errors.New("storage: WAL entry truncated")
errWALFull = errors.New("storage: WAL region full")
errWALPwrite = errors.New("storage: WAL pwrite failed")
)
// walEntry is one variable-size record in the WAL region of a store
// file. Stored bytes are exactly walEntryHeaderSize + Length when Type
// is Write/Padding, or walEntryHeaderSize when Type is Trim/Barrier.
type walEntry struct {
LSN uint64
Reserved uint64 // see walEntryHeaderSize comment
Type uint8
Flags uint8
LBA uint64 // in blocks
Length uint32 // bytes — data length for Write/Padding, trim extent for Trim
Data []byte // present only for Write
}
// encode serializes the entry into a fresh byte slice. CRC32 covers
// every byte from offset 0 through Data inclusive. The trailing 8
// bytes are CRC32 + EntrySize so a reader can detect torn writes by
// verifying both fields.
func (e *walEntry) encode() ([]byte, error) {
return e.encodeWithInstrumentation(nil)
}
func (e *walEntry) encodeWithInstrumentation(instr *writeInstrumentation) ([]byte, error) {
totalSize, err := e.encodedSize()
if err != nil {
return nil, err
}
buf := make([]byte, totalSize)
if err := e.encodeInto(buf, instr); err != nil {
return nil, err
}
return buf, nil
}
func (e *walEntry) appendEncoded(dst []byte, instr *writeInstrumentation) ([]byte, error) {
totalSize, err := e.encodedSize()
if err != nil {
return nil, err
}
start := len(dst)
dst = growWALRecordBuffer(dst, totalSize)
if err := e.encodeInto(dst[start:], instr); err != nil {
return nil, err
}
return dst, nil
}
func growWALRecordBuffer(dst []byte, n int) []byte {
newLen := len(dst) + n
if newLen <= cap(dst) {
return dst[:newLen]
}
newCap := cap(dst) * 2
if newCap < newLen {
newCap = newLen
}
next := make([]byte, newLen, newCap)
copy(next, dst)
return next
}
func (e *walEntry) encodedSize() (int, error) {
switch e.Type {
case walEntryWrite:
if len(e.Data) == 0 {
return 0, fmt.Errorf("%w: write entry with no data", errInvalidEntry)
}
if uint32(len(e.Data)) != e.Length {
return 0, fmt.Errorf("%w: data len %d != Length %d", errInvalidEntry, len(e.Data), e.Length)
}
case walEntryWriteBatch:
if e.Reserved == 0 {
return 0, fmt.Errorf("%w: batch write entry with zero block count", errInvalidEntry)
}
if len(e.Data) == 0 {
return 0, fmt.Errorf("%w: batch write entry with no data", errInvalidEntry)
}
if uint32(len(e.Data)) != e.Length {
return 0, fmt.Errorf("%w: batch data len %d != Length %d", errInvalidEntry, len(e.Data), e.Length)
}
case walEntryTrim:
if len(e.Data) != 0 {
return 0, fmt.Errorf("%w: trim entry must have no data payload", errInvalidEntry)
}
case walEntryBarrier:
if e.Length != 0 || len(e.Data) != 0 {
return 0, fmt.Errorf("%w: barrier entry must have no data", errInvalidEntry)
}
}
return walEntryHeaderSize + len(e.Data), nil
}
func (e *walEntry) encodeInto(buf []byte, instr *writeInstrumentation) error {
start := time.Now()
totalSize, err := e.encodedSize()
if err != nil {
return err
}
if len(buf) < totalSize {
return fmt.Errorf("%w: encode buffer size %d < entry size %d", errInvalidEntry, len(buf), totalSize)
}
buf = buf[:totalSize]
le := binary.LittleEndian
off := 0
le.PutUint64(buf[off:], e.LSN)
off += 8
le.PutUint64(buf[off:], e.Reserved)
off += 8
buf[off] = e.Type
off++
buf[off] = e.Flags
off++
le.PutUint64(buf[off:], e.LBA)
off += 8
le.PutUint32(buf[off:], e.Length)
off += 4
if len(e.Data) > 0 {
copyStart := time.Now()
copy(buf[off:], e.Data)
if instr != nil {
instr.recordWALCopy(len(e.Data), time.Since(copyStart))
}
off += len(e.Data)
}
checksumStart := time.Now()
checksum := crc32.ChecksumIEEE(buf[:off])
if instr != nil {
instr.recordWALChecksum(off, time.Since(checksumStart))
}
le.PutUint32(buf[off:], checksum)
off += 4
le.PutUint32(buf[off:], uint32(totalSize))
if instr != nil {
instr.recordWALEncode(len(buf), time.Since(start))
}
return nil
}
// decodeWALEntry parses a record from buf and verifies its CRC and
// declared size. Returns errEntryTruncated if buf is too short to
// hold the declared entry, errCRCMismatch if the stored CRC does
// not match the recomputed one.
func decodeWALEntry(buf []byte) (walEntry, error) {
if len(buf) < walEntryHeaderSize {
return walEntry{}, fmt.Errorf("%w: need %d bytes, have %d",
errEntryTruncated, walEntryHeaderSize, len(buf))
}
le := binary.LittleEndian
var e walEntry
off := 0
e.LSN = le.Uint64(buf[off:])
off += 8
e.Reserved = le.Uint64(buf[off:])
off += 8
e.Type = buf[off]
off++
e.Flags = buf[off]
off++
e.LBA = le.Uint64(buf[off:])
off += 8
e.Length = le.Uint32(buf[off:])
off += 4
var dataLen int
if e.Type == walEntryWrite || e.Type == walEntryWriteBatch || e.Type == walEntryPadding {
dataLen = int(e.Length)
}
dataEnd := off + dataLen
if dataEnd+8 > len(buf) {
return walEntry{}, fmt.Errorf("%w: need %d, have %d", errEntryTruncated, dataEnd+8, len(buf))
}
if dataLen > 0 {
e.Data = make([]byte, dataLen)
copy(e.Data, buf[off:dataEnd])
}
storedCRC := le.Uint32(buf[dataEnd:])
storedSize := le.Uint32(buf[dataEnd+4:])
expectedCRC := crc32.ChecksumIEEE(buf[:dataEnd])
if storedCRC != expectedCRC {
return walEntry{}, fmt.Errorf("%w: stored=%08x computed=%08x",
errCRCMismatch, storedCRC, expectedCRC)
}
expectedSize := uint32(walEntryHeaderSize + dataLen)
if storedSize != expectedSize {
return walEntry{}, fmt.Errorf("%w: EntrySize=%d, expected=%d",
errInvalidEntry, storedSize, expectedSize)
}
return e, nil
}
// parseLengthFromHeader reads the Length field from a header-only
// buffer. Used by the recovery scanner to compute the full record
// size before reading the rest. Length is at offset
// 8(LSN) + 8(Reserved) + 1(Type) + 1(Flags) + 8(LBA) = 26.
func parseLengthFromHeader(headerBuf []byte) uint32 {
return binary.LittleEndian.Uint32(headerBuf[26:])
}
+21 -214
View File
@@ -2,230 +2,37 @@ package storage
import (
"bytes"
"encoding/binary"
"hash/crc32"
"reflect"
"testing"
)
// walEntryFuzzSeeds are well-formed records of every kind the writers
// produce, plus truncated and corrupted variants. Under `go test` (no
// -fuzz) the fuzz targets below run exactly these seeds.
func walEntryFuzzSeeds(t testing.TB) [][]byte {
t.Helper()
enc := func(e walEntry) []byte {
b, err := e.encode()
func FuzzDecodeWALEntryV3(f *testing.F) {
for _, e := range []walEntryV3{
{LSN: 1, Type: walEntryWrite, LBA: 2, Length: 4096, Data: bytes.Repeat([]byte{0x41}, 4096)},
{LSN: 1, Type: walEntryWriteBatch, LBA: 2, BatchCount: 2, Length: 8192, Data: bytes.Repeat([]byte{0x42}, 8192)},
{LSN: 1, Type: walEntryTrim, LBA: 2, Length: 8192},
{LSN: 1, Type: walEntryBarrier},
{Type: walEntryPadding, Length: 32, Data: make([]byte, 32)},
} {
e.Nonce[0] = 1
b, err := encodeWALEntryV3(e, 4096, 64)
if err != nil {
t.Fatalf("seed %+v: %v", e, err)
f.Fatal(err)
}
return b
f.Add(b)
f.Add(append(append([]byte(nil), b...), 0xA5))
}
pad, err := encodeWALPadding(walEntryHeaderSize + 16)
if err != nil {
t.Fatal(err)
}
block := bytes.Repeat([]byte{0xA5}, 512)
seeds := [][]byte{
enc(walEntry{LSN: 1, Type: walEntryWrite, LBA: 7, Length: uint32(len(block)), Data: block}),
enc(walEntry{LSN: 9, Reserved: 2, Type: walEntryWriteBatch, LBA: 3, Length: 1024, Data: bytes.Repeat([]byte{0x5A}, 1024)}),
enc(walEntry{LSN: 4, Type: walEntryTrim, LBA: 10, Length: 8192}),
enc(walEntry{LSN: 5, Type: walEntryBarrier}),
pad,
{},
make([]byte, walEntryHeaderSize),
}
good := seeds[0]
seeds = append(seeds,
good[:walEntryHeaderSize-1], // short header
good[:len(good)-1], // short trailer
append(append([]byte{}, good...), 0xFF), // trailing byte
)
flipped := append([]byte{}, good...)
flipped[40] ^= 0x01 // data byte: CRC mismatch
seeds = append(seeds, flipped)
huge := append([]byte{}, good[:walEntryHeaderSize]...)
binary.LittleEndian.PutUint32(huge[26:], ^uint32(0)) // Length claims 4 GiB
seeds = append(seeds, huge)
return seeds
}
// FuzzDecodeWALEntry: decodeWALEntry never panics; an error comes with the
// zero value; an accepted record is self-consistent and re-encodes to
// exactly the bytes it was decoded from.
func FuzzDecodeWALEntry(f *testing.F) {
for _, s := range walEntryFuzzSeeds(f) {
f.Add(s)
}
f.Fuzz(func(t *testing.T, data []byte) {
e, err := decodeWALEntry(data)
if err != nil {
if !reflect.DeepEqual(e, walEntry{}) {
t.Fatalf("error %v with a partial value %+v", err, e)
}
return
f.Add([]byte{})
f.Fuzz(func(t *testing.T, b []byte) {
if len(b) > 1<<20 {
t.Skip()
}
size := walEntryHeaderSize + len(e.Data)
if size > len(data) {
t.Fatalf("decoded %d bytes from a %d-byte buffer", size, len(data))
}
if got := binary.LittleEndian.Uint32(data[size-4:]); got != uint32(size) {
t.Fatalf("EntrySize field %d, record is %d bytes", got, size)
}
switch e.Type {
case walEntryWrite, walEntryWriteBatch, walEntryPadding:
if uint32(len(e.Data)) != e.Length {
t.Fatalf("type %d: %d data bytes, Length %d", e.Type, len(e.Data), e.Length)
}
default:
if e.Data != nil {
t.Fatalf("type %d decoded with a payload", e.Type)
}
}
if gap := knownWALDecodeGap(e); gap != "" {
return // pinned below; see knownWALDecodeGap
}
if reason := walEntryEncoderRefuses(e); reason != "" {
t.Fatalf("decoder accepted a record the encoder refuses (%s): %+v", reason, e)
}
re, err := e.encode()
if err != nil {
t.Fatalf("re-encode of an accepted record: %v", err)
}
if !bytes.Equal(re, data[:size]) {
t.Fatalf("re-encode differs from the decoded bytes")
}
})
}
// FuzzWALEntryRoundTrip: every entry the encoder accepts decodes back to
// itself.
func FuzzWALEntryRoundTrip(f *testing.F) {
f.Add(uint64(1), uint64(0), uint8(walEntryWrite), uint8(0), uint64(7), uint32(4), []byte("abcd"))
f.Add(uint64(9), uint64(2), uint8(walEntryWriteBatch), uint8(0), uint64(3), uint32(2), []byte("xy"))
f.Add(uint64(4), uint64(0), uint8(walEntryTrim), uint8(0), uint64(10), uint32(8192), []byte(nil))
f.Add(uint64(5), uint64(0), uint8(walEntryBarrier), uint8(0), uint64(0), uint32(0), []byte(nil))
f.Add(uint64(6), uint64(0), uint8(walEntryPadding), uint8(0), uint64(0), uint32(3), []byte{0, 0, 0})
f.Fuzz(func(t *testing.T, lsn, reserved uint64, typ, flags uint8, lba uint64, length uint32, data []byte) {
e := walEntry{LSN: lsn, Reserved: reserved, Type: typ, Flags: flags, LBA: lba, Length: length, Data: data}
if len(e.Data) == 0 {
e.Data = nil
}
buf, err := e.encode()
e, err := decodeWALEntryV3(b, 4096, 64)
if err != nil {
return
}
if gap := knownWALEncodeGap(e); gap != "" {
return // pinned below; see knownWALEncodeGap
}
got, err := decodeWALEntry(buf)
if err != nil {
t.Fatalf("encoder accepted %+v but its bytes do not decode: %v", e, err)
}
if !reflect.DeepEqual(got, e) {
t.Fatalf("round trip: got %+v, want %+v", got, e)
encoded, err := encodeWALEntryV3(e, 4096, 64)
if err != nil || len(encoded) > len(b) || !bytes.Equal(encoded, b[:len(encoded)]) {
t.Fatalf("accepted native record does not roundtrip: %v", err)
}
})
}
// walEntryEncoderRefuses mirrors encodedSize's checks for a decoded entry
// ("" when the encoder accepts it).
func walEntryEncoderRefuses(e walEntry) string {
if _, err := e.encodedSize(); err != nil {
return err.Error()
}
return ""
}
// rawWALEntry lays out header fields, payload and a valid CRC/EntrySize
// exactly as the on-disk format does, without the encoder's checks, so the
// fuzzer reaches the decoder's acceptance rules instead of the CRC.
func rawWALEntry(lsn, reserved uint64, typ, flags uint8, lba uint64, length uint32, payload []byte) []byte {
le := binary.LittleEndian
buf := make([]byte, 30+len(payload)+8)
le.PutUint64(buf[0:], lsn)
le.PutUint64(buf[8:], reserved)
buf[16] = typ
buf[17] = flags
le.PutUint64(buf[18:], lba)
le.PutUint32(buf[26:], length)
copy(buf[30:], payload)
end := 30 + len(payload)
le.PutUint32(buf[end:], crc32.ChecksumIEEE(buf[:end]))
le.PutUint32(buf[end+4:], uint32(len(buf)))
return buf
}
// FuzzDecodeWALEntryFields: records with a valid CRC and EntrySize but
// arbitrary field values; the decoder must accept only what the encoder
// can produce.
func FuzzDecodeWALEntryFields(f *testing.F) {
f.Add(uint64(1), uint64(0), uint8(walEntryWrite), uint8(0), uint64(7), uint32(4), []byte("abcd"))
f.Add(uint64(9), uint64(2), uint8(walEntryWriteBatch), uint8(0), uint64(3), uint32(2), []byte("xy"))
f.Add(uint64(4), uint64(0), uint8(walEntryTrim), uint8(0), uint64(10), uint32(8192), []byte(nil))
f.Add(uint64(5), uint64(0), uint8(walEntryBarrier), uint8(0), uint64(0), uint32(0), []byte(nil))
f.Add(uint64(6), uint64(0), uint8(walEntryPadding), uint8(0), uint64(0), uint32(3), []byte{0, 0, 0})
f.Fuzz(func(t *testing.T, lsn, reserved uint64, typ, flags uint8, lba uint64, length uint32, payload []byte) {
buf := rawWALEntry(lsn, reserved, typ, flags, lba, length, payload)
e, err := decodeWALEntry(buf)
if err != nil {
if !reflect.DeepEqual(e, walEntry{}) {
t.Fatalf("error %v with a partial value %+v", err, e)
}
return
}
if gap := knownWALDecodeGap(e); gap != "" {
return // pinned below; see knownWALDecodeGap
}
if reason := walEntryEncoderRefuses(e); reason != "" {
t.Fatalf("decoder accepted a record the encoder refuses (%s): %+v", reason, e)
}
re, err := e.encode()
if err != nil || !bytes.Equal(re, buf[:walEntryHeaderSize+len(e.Data)]) {
t.Fatalf("accepted record does not re-encode to its bytes (err %v): %+v", err, e)
}
})
}
// knownWALDecodeGap names the record shapes decodeWALEntry accepts although
// the encoder never produces them (found by FuzzDecodeWALEntryFields;
// reported, not fixed here). Recovery already fails closed on an invalid
// batch (WALIntegrity), so a decoder-level rejection is not a drop-in
// change: it would turn that into a torn-entry stop. Any shape not listed
// here fails the fuzz targets.
func knownWALDecodeGap(e walEntry) string {
switch e.Type {
case walEntryWrite:
if e.Length == 0 {
return "write with no data"
}
case walEntryWriteBatch:
if e.Reserved == 0 || e.Length == 0 {
return "batch shape (checked by recovery, not by the decoder)"
}
case walEntryBarrier:
if e.Length != 0 {
return "barrier with a non-zero Length"
}
case walEntryTrim, walEntryPadding:
default:
return "unknown entry type"
}
return ""
}
// knownWALEncodeGap names the entries walEntry.encode accepts but whose
// bytes do not decode back (found by FuzzWALEntryRoundTrip; no writer
// builds them).
func knownWALEncodeGap(e walEntry) string {
switch e.Type {
case walEntryWrite, walEntryWriteBatch, walEntryTrim, walEntryBarrier:
return ""
case walEntryPadding:
if uint32(len(e.Data)) != e.Length {
return "padding whose Length differs from its payload"
}
return ""
default:
return "unknown entry type"
}
}
-500
View File
@@ -1,500 +0,0 @@
package storage
import (
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"os"
"sync"
"time"
)
var (
// errWALFull is returned when an Append request would overflow the
// circular WAL region. The caller is expected to either wait for
// the flusher to advance the tail, or escalate.
errWALFull = errors.New("storage: WAL region full")
)
// errWALPwrite marks an append that failed while writing to the file:
// part or all of its bytes may be on disk (see WALStore.noteAppendFailure).
var errWALPwrite = errors.New("storage: WAL pwrite failed")
// walWriter appends entries to the circular WAL region of a store
// file. It tracks position with monotonically-increasing logical
// counters so head==tail unambiguously means empty (used = head-tail).
//
// The writer performs ONLY pwrite — fsync is the caller's
// responsibility, typically batched through a group committer for
// throughput.
type walWriter struct {
mu sync.Mutex
fd *os.File
walOffset uint64 // absolute file offset where WAL region starts
walSize uint64 // size of the WAL region in bytes
logicalHead uint64 // monotonic write position
logicalTail uint64 // monotonic flush position
// durableTail is the tail in the last fsynced superblock. The writer
// overwrites only bytes released by it: bytes the on-disk superblock
// still declares retained
// are never reused, so a torn new record cannot land inside the
// persisted [tail, head) and hide a record recovery needs.
// durablePending: the bounds were rebuilt by recovery and are not yet
// persisted; nothing is reusable until they are.
durableTail uint64
durablePending bool
instr *writeInstrumentation
// Optional batch pwrite fault seam; nil uses the real file.
batchWriteAt func([]byte, int64) (int, error)
}
// newWALWriter constructs a writer over an open file. logicalHead and
// logicalTail come from the superblock when reopening; both 0 for a
// fresh store.
func newWALWriter(fd *os.File, walOffset, walSize, head, tail uint64, instr *writeInstrumentation) *walWriter {
return &walWriter{
fd: fd,
walOffset: walOffset,
walSize: walSize,
logicalHead: head,
logicalTail: tail,
durableTail: tail,
instr: instr,
}
}
func (w *walWriter) physicalPos(logical uint64) uint64 { return logical % w.walSize }
func (w *walWriter) used() uint64 { return w.logicalHead - w.logicalTail }
// spaceUsed is what the space checks count: everything from the durable
// tail on. Bytes released only in memory are not reusable yet.
func (w *walWriter) spaceUsed() uint64 {
if w.durablePending || w.durableTail > w.logicalHead {
return w.walSize
}
return w.logicalHead - w.durableTail
}
// append writes one entry and returns the WAL-relative offset where
// it was placed. If the entry would straddle the end of the WAL
// region, a padding entry is written first and the real entry starts
// at physical offset 0.
//
// Returns errWALFull when even the padding+entry would not fit.
func (w *walWriter) append(entry *walEntry) (walRelOffset uint64, err error) {
buf, err := entry.encodeWithInstrumentation(w.instr)
if err != nil {
return 0, fmt.Errorf("walWriter.append: encode: %w", err)
}
lockStart := time.Now()
w.mu.Lock()
if w.instr != nil {
w.instr.recordWALAppendLockWait(time.Since(lockStart))
}
defer w.mu.Unlock()
entryLen := uint64(len(buf))
if entryLen > w.walSize {
return 0, fmt.Errorf("%w: entry size %d exceeds WAL size %d", errWALFull, entryLen, w.walSize)
}
physHead := w.physicalPos(w.logicalHead)
remaining := w.walSize - physHead
if remaining < entryLen {
// Pad to end of region and wrap.
if w.spaceUsed()+remaining+entryLen > w.walSize {
return 0, errWALFull
}
if err := w.writePadding(remaining, physHead); err != nil {
return 0, fmt.Errorf("%w: walWriter.append: padding: %w", errWALPwrite, err)
}
if w.instr != nil {
w.instr.recordWALAppendWrap(remaining)
}
w.logicalHead += remaining
physHead = 0
}
if w.spaceUsed()+entryLen > w.walSize {
return 0, errWALFull
}
absOffset := int64(w.walOffset + physHead)
writeStart := time.Now()
if _, err := w.fd.WriteAt(buf, absOffset); err != nil {
return 0, fmt.Errorf("%w: walWriter.append: pwrite at %d: %w", errWALPwrite, absOffset, err)
}
if w.instr != nil {
w.instr.recordWALAppend(len(buf), time.Since(writeStart))
}
writeOffset := physHead
w.logicalHead += entryLen
return writeOffset, nil
}
// appendBatch writes entries under one WAL-writer critical section. Each entry
// remains independently encoded/recoverable; the batch only coalesces adjacent
// bytes into fewer pwrite calls when the circular WAL layout allows it.
func (w *walWriter) appendBatch(entries []walEntry) ([]uint64, error) {
if len(entries) == 0 {
return nil, nil
}
lengths := make([]uint64, len(entries))
for i := range entries {
entryLen, err := entries[i].encodedSize()
if err != nil {
return nil, fmt.Errorf("walWriter.appendBatch: validate entry %d: %w", i, err)
}
if uint64(entryLen) > w.walSize {
return nil, fmt.Errorf("%w: entry size %d exceeds WAL size %d", errWALFull, entryLen, w.walSize)
}
lengths[i] = uint64(entryLen)
}
pendingCapacity := boundedPendingCapacity(lengths)
lockStart := time.Now()
w.mu.Lock()
if w.instr != nil {
w.instr.recordWALAppendLockWait(time.Since(lockStart))
}
defer w.mu.Unlock()
offsets, finalHead, err := w.planAppendBatchLengths(lengths)
if err != nil {
return offsets, err
}
localHead := w.logicalHead
var pending []byte
var pendingStart uint64
flushPending := func() error {
if len(pending) == 0 {
return nil
}
writeStart := time.Now()
writeAt := w.fd.WriteAt
if w.batchWriteAt != nil {
writeAt = w.batchWriteAt
}
if _, err := writeAt(pending, int64(w.walOffset+pendingStart)); err != nil {
return fmt.Errorf("%w: walWriter.appendBatch: pwrite at %d: %w", errWALPwrite, w.walOffset+pendingStart, err)
}
if w.instr != nil {
w.instr.recordWALAppend(len(pending), time.Since(writeStart))
}
pending = nil
return nil
}
appendPendingBytes := func(phys uint64, buf []byte) error {
if len(buf) == 0 {
return nil
}
if len(pending) == 0 {
pendingStart = phys
pending = append(pending, buf...)
return nil
}
if pendingStart+uint64(len(pending)) != phys {
if err := flushPending(); err != nil {
return err
}
pendingStart = phys
}
pending = append(pending, buf...)
return nil
}
appendPendingEntry := func(phys uint64, entry *walEntry, entryLen uint64) error {
if len(pending) == 0 {
pendingStart = phys
pending = make([]byte, 0, pendingCapacity)
} else if pendingStart+uint64(len(pending)) != phys {
if err := flushPending(); err != nil {
return err
}
pendingStart = phys
pending = make([]byte, 0, pendingCapacity)
}
next, err := entry.appendEncoded(pending, w.instr)
if err != nil {
return err
}
pending = next
return nil
}
for i := range entries {
entry := &entries[i]
entryLen := lengths[i]
physHead := w.physicalPos(localHead)
remaining := w.walSize - physHead
if remaining < entryLen {
padding, err := encodeWALPadding(remaining)
if err != nil {
return offsets, fmt.Errorf("walWriter.appendBatch: padding: %w", err)
}
if err := appendPendingBytes(physHead, padding); err != nil {
return offsets, err
}
if w.instr != nil {
w.instr.recordWALAppendWrap(remaining)
}
localHead += remaining
physHead = 0
}
if err := appendPendingEntry(physHead, entry, entryLen); err != nil {
return offsets, err
}
localHead += entryLen
}
if err := flushPending(); err != nil {
return offsets, err
}
w.logicalHead = finalHead
return offsets, nil
}
func boundedPendingCapacity(lengths []uint64) int {
const maxPendingCapacity = 1 << 20
total := 0
for _, length := range lengths {
if length > uint64(maxPendingCapacity) {
return maxPendingCapacity
}
total += int(length)
if total >= maxPendingCapacity {
return maxPendingCapacity
}
}
if total == 0 {
return 0
}
return total
}
func (w *walWriter) planAppendBatchLengths(lengths []uint64) ([]uint64, uint64, error) {
localHead := w.logicalHead
offsets := make([]uint64, 0, len(lengths))
used := func() uint64 {
if w.durablePending || w.durableTail > localHead {
return w.walSize
}
return localHead - w.durableTail
}
for _, entryLen := range lengths {
physHead := w.physicalPos(localHead)
remaining := w.walSize - physHead
if remaining < entryLen {
if used()+remaining+entryLen > w.walSize {
return offsets, localHead, errWALFull
}
localHead += remaining
physHead = 0
}
if used()+entryLen > w.walSize {
return offsets, localHead, errWALFull
}
offsets = append(offsets, physHead)
localHead += entryLen
}
return offsets, localHead, nil
}
// writePadding fills [physPos, physPos+size) with a padding entry so
// the next write starts at a clean offset. If size is too small for a
// real header, just zeros the bytes — the recovery scanner skips
// header-too-short tails.
func (w *walWriter) writePadding(size, physPos uint64) error {
buf, err := encodeWALPadding(size)
if err != nil {
return err
}
if len(buf) == 0 {
return nil
}
if _, err := w.fd.WriteAt(buf, int64(w.walOffset+physPos)); err != nil {
return err
}
if w.instr != nil {
w.instr.recordWALAppendWriteAt(len(buf))
}
return nil
}
func encodeWALPadding(size uint64) ([]byte, error) {
if size < walEntryHeaderSize {
return make([]byte, size), nil
}
buf := make([]byte, size)
le := binary.LittleEndian
off := 0
le.PutUint64(buf[off:], 0) // LSN
off += 8
le.PutUint64(buf[off:], 0) // Reserved
off += 8
buf[off] = walEntryPadding
off++
buf[off] = 0 // Flags
off++
le.PutUint64(buf[off:], 0) // LBA
off += 8
paddingDataLen := uint32(size) - uint32(walEntryHeaderSize)
le.PutUint32(buf[off:], paddingDataLen)
off += 4
dataEnd := off + int(paddingDataLen)
crc := crc32.ChecksumIEEE(buf[:dataEnd])
le.PutUint32(buf[dataEnd:], crc)
le.PutUint32(buf[dataEnd+4:], uint32(size))
return buf, nil
}
// advanceTail moves the tail forward by (newPhysTail - currentPhysTail
// modulo walSize), freeing space. Called by the flusher after entries
// have been applied to the extent region.
func (w *walWriter) advanceTail(newPhysTail uint64) {
w.mu.Lock()
defer w.mu.Unlock()
physTail := w.physicalPos(w.logicalTail)
var advance uint64
if newPhysTail >= physTail {
advance = newPhysTail - physTail
} else {
advance = w.walSize - physTail + newPhysTail
}
w.logicalTail += advance
}
// advanceTailPastEntry frees WAL bytes through the entry at entryPhys
// with entryLen bytes. It advances in logical space, so entries that
// end at the same physical offset as the current tail still release a
// wrapped span.
func (w *walWriter) advanceTailPastEntry(entryPhys, entryLen uint64) {
w.mu.Lock()
defer w.mu.Unlock()
physTail := w.physicalPos(w.logicalTail)
var distanceToEntry uint64
if entryPhys >= physTail {
distanceToEntry = entryPhys - physTail
} else {
distanceToEntry = w.walSize - physTail + entryPhys
}
advance := distanceToEntry + entryLen
if advance > w.used() {
// The entry is no longer within the live WAL window. This
// makes repeated flush/checkpoint cycles idempotent instead
// of wrapping around and releasing unflushed entries.
return
}
w.logicalTail += advance
}
// reset truncates the writer to empty. Used after recovery decides
// the WAL region should start fresh.
func (w *walWriter) reset() {
w.mu.Lock()
defer w.mu.Unlock()
w.logicalHead = 0
w.logicalTail = 0
w.durableTail = 0
w.durablePending = false
}
func (w *walWriter) restoreRecoveredBounds(head, tail uint64) error {
w.mu.Lock()
defer w.mu.Unlock()
if head < tail || head-tail > w.walSize {
return fmt.Errorf(
"walWriter: invalid recovered bounds tail=%d head=%d size=%d",
tail, head, w.walSize,
)
}
w.logicalHead = head
w.logicalTail = tail
w.durablePending = true // until the caller persists these bounds
return nil
}
// bounds returns head and tail from one snapshot.
func (w *walWriter) bounds() (head, tail uint64) {
w.mu.Lock()
defer w.mu.Unlock()
return w.logicalHead, w.logicalTail
}
// tailPastEntry is the tail that advanceTailPastEntry would set, without
// moving it (the caller persists it first).
func (w *walWriter) tailPastEntry(entryPhys, entryLen uint64) uint64 {
w.mu.Lock()
defer w.mu.Unlock()
physTail := w.physicalPos(w.logicalTail)
var distanceToEntry uint64
if entryPhys >= physTail {
distanceToEntry = entryPhys - physTail
} else {
distanceToEntry = w.walSize - physTail + entryPhys
}
advance := distanceToEntry + entryLen
if advance > w.used() {
return w.logicalTail
}
return w.logicalTail + advance
}
// tailPersisted records that a superblock with WAL tail = tail is fsynced:
// the writer's tail moves there (never backward) and the bytes before it
// become reusable.
func (w *walWriter) tailPersisted(tail uint64) {
w.mu.Lock()
defer w.mu.Unlock()
if tail > w.logicalTail {
w.logicalTail = tail
}
w.durableTail = tail
w.durablePending = false
}
func (w *walWriter) head() uint64 {
w.mu.Lock()
defer w.mu.Unlock()
return w.physicalPos(w.logicalHead)
}
func (w *walWriter) tail() uint64 {
w.mu.Lock()
defer w.mu.Unlock()
return w.physicalPos(w.logicalTail)
}
func (w *walWriter) logicalHeadValue() uint64 {
w.mu.Lock()
defer w.mu.Unlock()
return w.logicalHead
}
func (w *walWriter) logicalTailValue() uint64 {
w.mu.Lock()
defer w.mu.Unlock()
return w.logicalTail
}
// fsync forces buffered data to durable storage.
func (w *walWriter) fsync() error {
sync, err := newDataFileSync(w.fd)
if err != nil {
return err
}
return sync()
}
// usedFraction returns the fraction of the WAL region currently in
// use, in the range [0, 1]. Used by the admission controller to
// decide whether to throttle or block writers.
func (w *walWriter) usedFraction() float64 {
w.mu.Lock()
defer w.mu.Unlock()
if w.walSize == 0 {
return 0
}
return float64(w.spaceUsed()) / float64(w.walSize)
}
File diff suppressed because it is too large. Load diff
@@ -2,8 +2,7 @@ package storage
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"testing"
@@ -90,45 +89,6 @@ func TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy(t *testing.T)
}
}
func TestWALStoreProductionRefusesLegacyWithoutMutation(t *testing.T) {
for _, version := range []uint32{1, 2} {
t.Run(fmt.Sprint(version), func(t *testing.T) {
path := filepath.Join(t.TempDir(), "legacy")
opts := WALStoreOptions{}
if version == 2 {
opts = recordingOptions(&recordingMetadata{}, 2)
}
s, err := createLegacyWALStoreWithOptions(path, 16, 4096, opts)
if err != nil {
t.Fatal(err)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
before, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if r, err := OpenWALStore(path); !errors.Is(err, ErrUnsupportedLegacyFormat) {
if r != nil {
_ = r.Close()
}
t.Fatalf("legacy writable open: %v", err)
}
if r, err := OpenReadOnly(path); !errors.Is(err, ErrUnsupportedLegacyFormat) {
if r != nil {
_ = r.Close()
}
t.Fatalf("legacy readonly open: %v", err)
}
after, err := os.ReadFile(path)
if err != nil || !bytes.Equal(before, after) {
t.Fatal("legacy refusal changed bytes", err)
}
})
}
}
func TestWALStoreProductionCreateOptions(t *testing.T) {
s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "volume"), 64, 4096, WALStoreOptions{ChunkBlocks: 4, WMode: WModeStrict})
if err != nil {
@@ -31,7 +31,7 @@ func TestWALStoreV3AdmissionUsesNativeOccupancy(t *testing.T) {
}
want := float64(32*4096+70) / float64(64*1024*1024)
if got := s.admission.walUsed(); got != want {
t.Fatalf("native occupancy=%g want%g; legacy=%g", got, want, s.wal.usedFraction())
t.Fatalf("native occupancy=%g want%g", got, want)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
@@ -484,14 +484,16 @@ func preparePhase173FileLayoutScratch(t *testing.T, dir string) *phase173FileLay
}
for index := 0; index < phase173ScratchBlocks; index++ {
entry := walEntry{
LSN: uint64(index + 1),
Type: walEntryWrite,
LBA: uint64(index),
Length: phase173FixedWorkBlockSize,
Data: scratch.logicalData,
entry := walEntryV3{
LSN: uint64(index + 1),
Type: walEntryWrite,
LBA: uint64(index),
Length: phase173FixedWorkBlockSize,
Data: scratch.logicalData,
Nonce: [16]byte{1},
LogicalStart: uint64(index * (walEntryHeaderSizeV3 + phase173FixedWorkBlockSize)),
}
encoded, err := entry.encodeWithInstrumentation(nil)
encoded, err := encodeWALEntryV3(entry, phase173FixedWorkBlockSize, phase173ScratchBlocks)
if err != nil {
t.Fatal(err)
}
@@ -537,7 +539,7 @@ func (s *phase173FileLayoutScratch) run(t *testing.T, split bool, run int) phase
for pass := 0; pass < phase173ScratchPasses; pass++ {
for index := 0; index < phase173ScratchBlocks; index++ {
offset := s.walBase + int64(index*s.recordSize)
header := make([]byte, walEntryHeaderSize)
header := make([]byte, walEntryHeaderSizeV3)
if _, err := walFile.ReadAt(header, offset); err != nil {
t.Fatal(err)
}
@@ -545,7 +547,7 @@ func (s *phase173FileLayoutScratch) run(t *testing.T, split bool, run int) phase
if _, err := walFile.ReadAt(full, offset); err != nil {
t.Fatal(err)
}
entry, err := decodeWALEntry(full)
entry, err := decodeWALEntryV3(full, phase173FixedWorkBlockSize, phase173ScratchBlocks)
if err != nil {
t.Fatal(err)
}
@@ -1,92 +0,0 @@
package storage
import (
"errors"
"path/filepath"
"testing"
)
// B5 (independent review): a batch append whose pwrite lands every record
// and then reports an error left nextLSN and the head unchanged, so the next
// write reused the batch's first LSN and offset while the batch's later
// record (a higher LSN) stayed on disk past it; after that write's Sync was
// acknowledged and the process crashed, recovery served the failed batch's
// stale record. A failed append is now sticky for the open store: no further
// append (so no LSN reuse) until a reopen. Recovery of the reopen may replay
// the failed, never-acknowledged records; an acknowledged write is never
// replaced by one of them.
func TestWALStoreFailedBatchAppendDoesNotRevertALaterAckedWrite(t *testing.T) {
const blockSize = 4096
path := filepath.Join(t.TempDir(), "store.bin")
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 64*1024)
s.DisableAutoFlushForRecoveryTest()
crashed := false
t.Cleanup(func() {
if !crashed {
_ = s.Close()
}
})
eio := errors.New("injected EIO after the batch bytes were written")
s.wal.batchWriteAt = func(b []byte, off int64) (int, error) {
n, _ := s.fd.WriteAt(b, off) // the bytes reach the file...
return n, eio // ...but the call reports failure
}
stale := makeBlock(blockSize, 0x5A)
if _, err := s.WriteBatch(10, [][]byte{makeBlock(blockSize, 0x5B), stale}); !errors.Is(err, eio) {
t.Fatalf("WriteBatch with a failing pwrite: %v", err)
}
s.wal.batchWriteAt = nil
// The failed append is sticky: no write reuses its LSNs, nothing is acked.
acked := makeBlock(blockSize, 0xAC)
if _, err := s.Write(11, acked); !errors.Is(err, ErrAppendFailed) {
t.Fatalf("write after a failed append: %v; want the sticky ErrAppendFailed", err)
} else {
var rf *RecoveryFailure
if !errors.As(err, &rf) || rf.Kind != StorageRecoveryFailureSubstrateIO {
t.Fatalf("write after a failed append: %v; want a SubstrateIO RecoveryFailure (io_error)", err)
}
}
if _, err := s.Sync(); !errors.Is(err, ErrAppendFailed) {
t.Fatalf("Sync after a failed append: %v; want ErrAppendFailed", err)
}
crashRecoveryHardeningStore(t, s)
crashed = true
// Reopen: recovery may replay the failed batch (never acked). A write
// acknowledged now must survive the next crash.
r := reopenForB5(t, path)
lsn, err := r.Write(11, acked)
if err != nil {
t.Fatal(err)
}
if _, err := r.Sync(); err != nil {
t.Fatal(err)
}
t.Logf("acked write of LBA 11 after the reopen got LSN %d", lsn)
crashRecoveryHardeningStore(t, r)
q := reopenForB5(t, path)
t.Cleanup(func() { _ = q.Close() })
got, err := q.Read(11)
if err != nil {
t.Fatal(err)
}
if got[0] != acked[0] {
t.Fatalf("LBA 11 after recovery = %02x; want the acknowledged %02x (the failed batch's stale record is %02x)", got[0], acked[0], stale[0])
}
}
func reopenForB5(t *testing.T, path string) *WALStore {
t.Helper()
r, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
if _, err := r.Recover(); err != nil {
t.Fatalf("Recover: %v", err)
}
return r
}
@@ -2,120 +2,7 @@
package storage
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"testing"
)
const (
checkpointCrashHelperEnv = "SW_BLOCK_CHECKPOINT_CRASH_HELPER"
checkpointCrashPathEnv = "SW_BLOCK_CHECKPOINT_CRASH_PATH"
)
func TestWALStoreCheckpointSIGKILLCrashWindows(t *testing.T) {
if crashWindow := os.Getenv(checkpointCrashHelperEnv); crashWindow != "" {
runCheckpointCrashHelper(crashWindow, os.Getenv(checkpointCrashPathEnv))
return
}
tests := []struct {
name string
checkpointMin uint64
checkpointMax uint64
}{
{name: "after_extent_sync", checkpointMin: 0, checkpointMax: 0},
{name: "after_checkpoint_pwrite", checkpointMin: 0, checkpointMax: 1},
{name: "after_checkpoint_sync", checkpointMin: 1, checkpointMax: 1},
{name: "after_tail_publish", checkpointMin: 1, checkpointMax: 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
cmd := exec.Command(os.Args[0], "-test.run=^TestWALStoreCheckpointSIGKILLCrashWindows$")
cmd.Env = append(os.Environ(),
checkpointCrashHelperEnv+"="+tt.name,
checkpointCrashPathEnv+"="+path,
)
if output, err := cmd.CombinedOutput(); err == nil {
t.Fatalf("crash helper returned normally: %s", output)
}
reopened, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = reopened.Close() })
checkpoint := reopened.CheckpointLSN()
if checkpoint < tt.checkpointMin || checkpoint > tt.checkpointMax {
t.Fatalf("checkpoint=%d want in [%d,%d]",
checkpoint, tt.checkpointMin, tt.checkpointMax)
}
if _, err := reopened.Recover(); err != nil {
t.Fatal(err)
}
got, err := reopened.Read(3)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, makeBlock(4096, 0x7c)) {
t.Fatal("acknowledged bytes did not survive checkpoint crash window")
}
})
}
}
func runCheckpointCrashHelper(window, path string) {
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
panic(err)
}
s.flusher.Stop()
if _, err := s.Write(3, makeBlock(4096, 0x7c)); err != nil {
panic(err)
}
if _, err := s.Sync(); err != nil {
panic(err)
}
kill := func() error {
process, err := os.FindProcess(os.Getpid())
if err != nil {
return err
}
return process.Kill()
}
switch window {
case "after_extent_sync":
s.writeSuperblockMetadata = func([]byte) error {
return kill()
}
case "after_checkpoint_pwrite":
s.writeSuperblockMetadata = func(data []byte) error {
_, err := s.fd.WriteAt(data, 0)
return err
}
s.syncSuperblockMetadata = kill
case "after_checkpoint_sync":
s.syncSuperblockMetadata = func() error {
if err := s.fd.Sync(); err != nil {
return err
}
return kill()
}
case "after_tail_publish":
default:
panic(fmt.Sprintf("unknown checkpoint crash window %q", window))
}
if err := s.flusher.flushOnce(); err != nil {
panic(err)
}
if err := kill(); err != nil {
panic(err)
}
panic("SIGKILL returned")
}
@@ -1,639 +1,9 @@
package storage
import (
"bytes"
"errors"
"path/filepath"
"strings"
"testing"
"time"
)
func TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle(t *testing.T) {
tests := []struct {
name string
inject func(*WALStore)
}{
{
name: "write",
inject: func(s *WALStore) {
s.writeSuperblockMetadata = func([]byte) error {
return errors.New("injected checkpoint write failure")
}
},
},
{
name: "sync",
inject: func(s *WALStore) {
s.syncSuperblockMetadata = func() error {
return errors.New("injected checkpoint sync failure")
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.flusher.Stop()
want := makeBlock(4096, 0x71)
lsn, err := s.Write(3, want)
if err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
tailBefore := s.wal.logicalTailValue()
savedWrite := s.writeSuperblockMetadata
savedSync := s.syncSuperblockMetadata
tt.inject(s)
if err := s.flusher.flushOnce(); err == nil {
t.Fatal("flush with injected checkpoint failure succeeded")
}
if got := s.CheckpointLSN(); got != 0 {
t.Fatalf("checkpoint after failed metadata publication=%d want 0", got)
}
if got := s.sb.WALCheckpointLSN; got != 0 {
t.Fatalf("superblock checkpoint after failed metadata publication=%d want 0", got)
}
if got := s.wal.logicalTailValue(); got != tailBefore {
t.Fatalf("WAL tail after failed metadata publication=%d want %d", got, tailBefore)
}
if got := s.dm.len(); got != 1 {
t.Fatalf("dirty entries after failed metadata publication=%d want 1", got)
}
s.writeSuperblockMetadata = savedWrite
s.syncSuperblockMetadata = savedSync
if tt.name == "sync" {
// A failed fsync is sticky (ErrFsyncFailed): no checkpoint
// retry on this open store.
if err := s.flusher.flushOnce(); !errors.Is(err, ErrFsyncFailed) {
t.Fatalf("retry flush after a failed fsync: %v; want ErrFsyncFailed", err)
}
if got := s.CheckpointLSN(); got != 0 {
t.Fatalf("checkpoint after a refused retry=%d want 0", got)
}
return
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatalf("retry flush: %v", err)
}
if got := s.CheckpointLSN(); got != lsn {
t.Fatalf("checkpoint after retry=%d want %d", got, lsn)
}
if got := s.dm.len(); got != 0 {
t.Fatalf("dirty entries after retry=%d want 0", got)
}
got, err := s.Read(3)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, want) {
t.Fatal("extent bytes changed across checkpoint retry")
}
})
}
}
func TestCheckpointPublicationCrashWindowsRemainRecoverable(t *testing.T) {
tests := []struct {
name string
inject func(*WALStore)
wantFlushError bool
wantCheckpointMin uint64
wantCheckpointMax uint64
}{
{
name: "checkpoint_write_failed",
inject: func(s *WALStore) {
s.writeSuperblockMetadata = func([]byte) error {
return errors.New("injected checkpoint write failure")
}
},
wantFlushError: true,
wantCheckpointMin: 0,
wantCheckpointMax: 0,
},
{
name: "checkpoint_sync_failed",
inject: func(s *WALStore) {
s.syncSuperblockMetadata = func() error {
return errors.New("injected checkpoint sync failure")
}
},
wantFlushError: true,
wantCheckpointMin: 0,
wantCheckpointMax: 1,
},
{
name: "checkpoint_synced",
inject: func(*WALStore) {},
wantCheckpointMin: 1,
wantCheckpointMax: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
s.flusher.Stop()
want := makeBlock(4096, 0x73)
if _, err := s.Write(3, want); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
tt.inject(s)
flushErr := s.flusher.flushOnce()
if tt.wantFlushError && flushErr == nil {
t.Fatal("flush succeeded despite injected checkpoint failure")
}
if !tt.wantFlushError && flushErr != nil {
t.Fatal(flushErr)
}
// Simulate process loss without the WALStore Close metadata path.
s.committer.Stop()
if err := s.fd.Close(); err != nil {
t.Fatal(err)
}
s.fd = nil
reopened, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = reopened.Close() })
checkpoint := reopened.CheckpointLSN()
if checkpoint < tt.wantCheckpointMin || checkpoint > tt.wantCheckpointMax {
t.Fatalf("reopened checkpoint=%d want in [%d,%d]",
checkpoint, tt.wantCheckpointMin, tt.wantCheckpointMax)
}
if _, err := reopened.Recover(); err != nil {
t.Fatal(err)
}
got, err := reopened.Read(3)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, want) {
t.Fatal("checkpoint crash window lost the acknowledged block")
}
})
}
}
func TestFlusherWALSlotMismatchFailsClosed(t *testing.T) {
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.flusher.Stop()
if _, err := s.Write(4, makeBlock(4096, 0x44)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
walOffset, _, lsn, _, ok := s.dm.get(4)
if !ok {
t.Fatal("dirty entry missing")
}
header := make([]byte, walEntryHeaderSize)
absoluteOffset := int64(s.sb.WALOffset + walOffset)
if _, err := s.fd.ReadAt(header, absoluteOffset); err != nil {
t.Fatal(err)
}
mutated := append([]byte(nil), header...)
mutated[0] ^= 0x7f
if _, err := s.fd.WriteAt(mutated, absoluteOffset); err != nil {
t.Fatal(err)
}
err = s.flusher.flushOnce()
if err == nil || !strings.Contains(err.Error(), "WAL slot mismatch") {
t.Fatalf("flush error=%v want WAL slot mismatch", err)
}
if got := s.CheckpointLSN(); got != 0 {
t.Fatalf("checkpoint after WAL slot mismatch=%d want 0", got)
}
if got := s.dm.len(); got != 1 {
t.Fatalf("dirty entries after WAL slot mismatch=%d want 1", got)
}
instr := s.FlusherInstrumentation()
if instr.ValidationFailures != 1 || instr.ValidatedRecords != 0 ||
instr.CyclesFailed != 1 {
t.Fatalf("validation failures/validated/cycles failed=%d/%d/%d want 1/0/1",
instr.ValidationFailures, instr.ValidatedRecords, instr.CyclesFailed)
}
_, _, currentLSN, _, ok := s.dm.get(4)
if !ok || currentLSN != lsn {
t.Fatalf("dirty entry after mismatch ok=%t lsn=%d want true/%d", ok, currentLSN, lsn)
}
if _, err := s.fd.WriteAt(header, absoluteOffset); err != nil {
t.Fatal(err)
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatalf("flush after restoring WAL header: %v", err)
}
}
func TestFlusherRejectsCorruptOrUnsupportedDirtyRecord(t *testing.T) {
tests := []struct {
name string
mutate func([]byte)
wantErr string
}{
{
name: "crc",
mutate: func(record []byte) {
record[walEntryPrefixSize] ^= 0x7f
},
wantErr: "CRC mismatch",
},
{
name: "unsupported_type",
mutate: func(record []byte) {
record[16] = walEntryBarrier
},
wantErr: "invalid dirty WAL record",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.flusher.Stop()
if _, err := s.Write(2, makeBlock(4096, 0x22)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
walOffset, _, _, length, ok := s.dm.get(2)
if !ok {
t.Fatal("dirty entry missing")
}
record := make([]byte, walEntryHeaderSize+length)
absoluteOffset := int64(s.sb.WALOffset + walOffset)
if _, err := s.fd.ReadAt(record, absoluteOffset); err != nil {
t.Fatal(err)
}
original := append([]byte(nil), record...)
tt.mutate(record)
if _, err := s.fd.WriteAt(record, absoluteOffset); err != nil {
t.Fatal(err)
}
err = s.flusher.flushOnce()
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("flush error=%v want substring %q", err, tt.wantErr)
}
if got := s.CheckpointLSN(); got != 0 {
t.Fatalf("checkpoint after invalid record=%d want 0", got)
}
if got := s.dm.len(); got != 1 {
t.Fatalf("dirty entries after invalid record=%d want 1", got)
}
instr := s.FlusherInstrumentation()
if instr.ValidationFailures != 1 || instr.ValidatedRecords != 0 ||
instr.CyclesFailed != 1 {
t.Fatalf("validation failures/validated/cycles failed=%d/%d/%d want 1/0/1",
instr.ValidationFailures, instr.ValidatedRecords, instr.CyclesFailed)
}
if _, err := s.fd.WriteAt(original, absoluteOffset); err != nil {
t.Fatal(err)
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatalf("flush after restoring record: %v", err)
}
})
}
}
func TestWALStoreClosePerformsFinalFlush(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
replaceFlusherForTest(s, time.Hour)
want := makeBlock(4096, 0xa5)
lsn, err := s.Write(7, want)
if err != nil {
t.Fatal(err)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
reopened, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = reopened.Close() })
if got := reopened.CheckpointLSN(); got != lsn {
t.Fatalf("checkpoint after close=%d want final-flushed LSN %d", got, lsn)
}
if _, err := reopened.Recover(); err != nil {
t.Fatal(err)
}
got, err := reopened.Read(7)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, want) {
t.Fatal("final-flushed bytes did not survive reopen")
}
}
func TestWALStoreCloseWaitsForInflightSync(t *testing.T) {
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
replaceFlusherForTest(s, time.Hour)
if _, err := s.Write(1, makeBlock(4096, 0x61)); err != nil {
t.Fatal(err)
}
syncStarted := make(chan struct{})
releaseSync := make(chan struct{})
s.syncCache = func() error {
close(syncStarted)
<-releaseSync
return nil
}
syncDone := make(chan error, 1)
go func() {
_, err := s.Sync()
syncDone <- err
}()
<-syncStarted
closeDone := make(chan error, 1)
go func() { closeDone <- s.Close() }()
select {
case err := <-closeDone:
t.Fatalf("Close returned before in-flight Sync completed: %v", err)
case <-time.After(20 * time.Millisecond):
}
close(releaseSync)
if err := <-syncDone; err != nil {
t.Fatal(err)
}
if err := <-closeDone; err != nil {
t.Fatal(err)
}
}
func TestWALStoreMutationAPIsRejectAfterClose(t *testing.T) {
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
if err := s.ApplyEntry(1, makeBlock(4096, 0x11), 1); err == nil {
t.Fatal("ApplyEntry after Close succeeded")
}
if err := s.WriteExtentDirect(1, makeBlock(4096, 0x22)); err == nil {
t.Fatal("WriteExtentDirect after Close succeeded")
}
}
func TestWALStoreCloseReturnsFinalMetadataFailure(t *testing.T) {
tests := []struct {
name string
inject func(*WALStore)
}{
{
name: "write",
inject: func(s *WALStore) {
s.writeSuperblockMetadata = func([]byte) error {
return errors.New("injected final metadata write failure")
}
},
},
{
name: "sync",
inject: func(s *WALStore) {
s.syncSuperblockMetadata = func() error {
return errors.New("injected final metadata sync failure")
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
replaceFlusherForTest(s, time.Hour)
if _, err := s.Write(1, makeBlock(4096, 0x51)); err != nil {
t.Fatal(err)
}
tt.inject(s)
err = s.Close()
if err == nil || !strings.Contains(err.Error(), "injected final metadata") {
t.Fatalf("Close error=%v want injected final metadata failure", err)
}
if s.fd != nil {
t.Fatal("Close metadata failure left file open")
}
})
}
}
func TestWriteExtentDirectSupersedesPriorDirtyWAL(t *testing.T) {
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.flusher.Stop()
if _, err := s.Write(5, makeBlock(4096, 0x55)); err != nil {
t.Fatal(err)
}
base := makeBlock(4096, 0xb5)
if err := s.WriteExtentDirect(5, base); err != nil {
t.Fatal(err)
}
if _, _, _, _, ok := s.dm.get(5); ok {
t.Fatal("direct BASE install left the superseded dirty WAL mapping visible")
}
got, err := s.Read(5)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, base) {
t.Fatal("read after direct BASE install returned superseded WAL bytes")
}
}
func TestWriteExtentDirectSupersededWALDoesNotReappearAfterRestart(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
s.flusher.Stop()
if _, err := s.Write(9, makeBlock(4096, 0x39)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
base := makeBlock(4096, 0xb9)
if err := s.WriteExtentDirect(9, base); err != nil {
t.Fatal(err)
}
s.AdvanceFrontier(10)
if frontier, err := s.Sync(); err != nil || frontier != 10 {
t.Fatalf("Sync frontier=%d err=%v want 10/nil", frontier, err)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
reopened, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = reopened.Close() })
if _, err := reopened.Recover(); err != nil {
t.Fatal(err)
}
got, err := reopened.Read(9)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, base) {
t.Fatal("superseded WAL bytes reappeared after direct BASE restart")
}
}
func TestRunningFlusherCannotOverwriteDirectBase(t *testing.T) {
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
for iteration := 0; iteration < 50; iteration++ {
if _, err := s.Write(10, makeBlock(4096, byte(iteration))); err != nil {
t.Fatal(err)
}
s.flusher.Notify()
base := makeBlock(4096, byte(0x80+iteration))
if err := s.WriteExtentDirect(10, base); err != nil {
t.Fatal(err)
}
time.Sleep(time.Millisecond)
got, err := s.Read(10)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, base) {
t.Fatalf("iteration %d: running flusher overwrote direct BASE", iteration)
}
}
}
func TestFlusherSnapshotCannotOverwriteLaterDirectBase(t *testing.T) {
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.flusher.Stop()
old := makeBlock(4096, 0x31)
if _, err := s.Write(6, old); err != nil {
t.Fatal(err)
}
snapshot := s.dm.snapshot()
if len(snapshot) != 1 {
t.Fatalf("dirty snapshot entries=%d want 1", len(snapshot))
}
base := makeBlock(4096, 0xb6)
if err := s.WriteExtentDirect(6, base); err != nil {
t.Fatal(err)
}
written, err := s.writeExtentIfCurrent(snapshot[0].LBA, snapshot[0].LSN, old)
if err != nil {
t.Fatal(err)
}
if written {
t.Fatal("stale flusher snapshot overwrote a later direct BASE block")
}
got, err := s.readFromExtent(6)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, base) {
t.Fatal("extent does not contain the direct BASE bytes")
}
}
func TestWriteExtentDirectFailureRetainsDirtyWAL(t *testing.T) {
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
s.flusher.Stop()
if _, err := s.Write(8, makeBlock(4096, 0x48)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
s.committer.Stop()
if err := s.fd.Close(); err != nil {
t.Fatal(err)
}
if err := s.WriteExtentDirect(8, makeBlock(4096, 0xb8)); err == nil {
t.Fatal("direct BASE write on closed file succeeded")
}
if _, _, _, _, ok := s.dm.get(8); !ok {
t.Fatal("failed direct BASE write removed the recoverable dirty WAL mapping")
}
}
func replaceFlusherForTest(s *WALStore, interval time.Duration) {
s.flusher.Stop()
s.flusher = newFlusher(s, flusherConfig{Interval: interval})
@@ -2,7 +2,6 @@ package storage
import (
"bytes"
"errors"
"os"
"path/filepath"
"testing"
@@ -62,26 +61,6 @@ func TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW(t *testing.T) {
}
}
// The other legacy offset-0 writers (the checkpoint/recovery superblock
// writer and the direct-frontier writer behind SeedChunkFrontier and Sync's
// direct frontier) refuse on a v3 store and leave slot A untouched.
func TestWALStoreV3LegacySuperblockWritersRefuse(t *testing.T) {
s, path := newStoreV3(t, WModeStrict)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
writeSynced(t, s, 1, 1)
rawA := readSlotRawV3(t, path, slotAOffsetV3)
junk := bytes.Repeat([]byte{0xEE}, 4096)
if err := s.writeSuperblockMetadata(junk); !errors.Is(err, errV3LegacySuperblockWrite) {
t.Fatalf("writeSuperblockMetadata: err = %v, want errV3LegacySuperblockWrite", err)
}
if err := s.syncDirectFrontierMetadata(junk); !errors.Is(err, errV3LegacySuperblockWrite) {
t.Fatalf("syncDirectFrontierMetadata: err = %v, want errV3LegacySuperblockWrite", err)
}
if got := readSlotRawV3(t, path, slotAOffsetV3); !bytes.Equal(got, rawA) {
t.Fatal("a refused legacy writer changed descriptor slot A")
}
}
func readSlotRawV3(t *testing.T, path string, off int64) []byte {
t.Helper()
f, err := os.Open(path)
@@ -1,44 +0,0 @@
package storage
import (
"os"
"path/filepath"
"testing"
)
func TestWALStore_UnknownFormatWithoutFactoryRefused(t *testing.T) {
path := filepath.Join(t.TempDir(), "store")
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
if err = s.Close(); err != nil {
t.Fatal(err)
}
f, err := os.OpenFile(path, os.O_RDWR, 0)
if err != nil {
t.Fatal(err)
}
sb, err := readSuperblock(f)
if err != nil {
t.Fatal(err)
}
sb.ImplVersion = 77
if _, err = f.Seek(0, 0); err != nil {
t.Fatal(err)
}
if _, err = sb.writeTo(f); err != nil {
t.Fatal(err)
}
if err = f.Close(); err != nil {
t.Fatal(err)
}
if x, err := openLegacyWALStoreForTest(path); err == nil {
x.Close()
t.Fatal("unknown format opened without accepting factory")
}
if x, err := openLegacyReadOnlyForTest(path); err == nil {
x.Close()
t.Fatal("unknown format readonly opened without accepting factory")
}
}
@@ -1,118 +0,0 @@
package storage
import (
"bytes"
"path/filepath"
"testing"
)
func TestWALStoreRecoverReplaysLegacyRangeTrim(t *testing.T) {
const (
blockSize = 4096
trimBlocks = 3
)
path := filepath.Join(t.TempDir(), "store.bin")
func() {
s, err := createLegacyWALStoreForTest(path, 16, blockSize)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
for lba := uint32(3); lba < 3+trimBlocks; lba++ {
if err := s.WriteExtentDirect(lba, makeBlock(blockSize, 0xA5)); err != nil {
t.Fatal(err)
}
}
if stable, err := s.Sync(); err != nil || stable != 0 {
t.Fatalf("base Sync stable=%d err=%v want 0,nil", stable, err)
}
trim := &walEntry{
LSN: 1,
Type: walEntryTrim,
LBA: 3,
Length: trimBlocks * blockSize,
}
if _, err := s.wal.append(trim); err != nil {
t.Fatal(err)
}
s.mu.Lock()
s.nextLSN = 2
s.walHead = 1
s.walTail = 1
s.mu.Unlock()
if stable, err := s.Sync(); err != nil || stable != 1 {
t.Fatalf("Sync stable=%d err=%v want 1,nil", stable, err)
}
crashRecoveryHardeningStore(t, s)
}()
reader, err := openLegacyReadOnlyForTest(path)
if err != nil {
t.Fatal(err)
}
for lba := uint32(3); lba < 3+trimBlocks; lba++ {
got, err := reader.Read(lba)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, make([]byte, blockSize)) {
t.Fatalf("read-only trim LBA %d did not return zeros", lba)
}
}
if err := reader.Close(); err != nil {
t.Fatal(err)
}
s, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
if recovered, err := s.Recover(); err != nil || recovered != 1 {
t.Fatalf("Recover=%d err=%v want 1,nil", recovered, err)
}
entries := recoverySnapshotEntriesByLBA(s.dm.snapshot())
if len(entries) != trimBlocks {
t.Fatalf("trim dirty entries=%d want %d", len(entries), trimBlocks)
}
wantOffset := entries[3].WALOffset
for index, lba := range []uint64{3, 4, 5} {
entry := entries[lba]
if entry.WALOffset != wantOffset ||
entry.DataOffset != uint32(index*blockSize) {
t.Fatalf("trim LBA %d identity=(%d,%d) want=(%d,%d)",
lba, entry.WALOffset, entry.DataOffset,
wantOffset, index*blockSize)
}
got, err := s.Read(uint32(lba))
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, make([]byte, blockSize)) {
t.Fatalf("dirty trim LBA %d did not return zeros", lba)
}
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
if got := s.dm.len(); got != 0 {
t.Fatalf("trim dirty entries after flush=%d want 0", got)
}
if got := s.CheckpointLSN(); got != 1 {
t.Fatalf("trim checkpoint=%d want 1", got)
}
for lba := uint32(3); lba < 3+trimBlocks; lba++ {
got, err := s.readFromExtent(lba)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, make([]byte, blockSize)) {
t.Fatalf("flushed trim LBA %d did not zero extent", lba)
}
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
}
@@ -1,39 +1,9 @@
package storage
import (
"path/filepath"
"strings"
"testing"
)
// Issue #51, walstore: pure
// detection. A WAL hole followed by valid records is logged, counted and
// reported as the typed warning wal_hole_suspected; nothing about what is
// replayed, where replay stops, or whether the volume opens changes.
// writeSyncedEntries writes one block to each of lbas (in order), syncs,
// and returns the store with auto-flush off (nothing checkpointed) and
// each LBA's WAL offset.
func writeSyncedEntries(t *testing.T, lbas []uint32) (*WALStore, string, map[uint64]uint64) {
t.Helper()
const blockSize = 4096
path := filepath.Join(t.TempDir(), "store.bin")
s, err := createLegacyWALStoreForTest(path, 16, blockSize)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
for i, lba := range lbas {
if _, err := s.Write(lba, makeBlock(blockSize, byte(0xB0+i))); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
return s, path, walOffsetsByLBA(s)
}
func walOffsetsByLBA(s *WALStore) map[uint64]uint64 {
offs := map[uint64]uint64{}
for _, e := range s.dm.snapshot() {
@@ -42,34 +12,6 @@ func walOffsetsByLBA(s *WALStore) map[uint64]uint64 {
return offs
}
// flipDataByte corrupts one payload byte of the entry at walOffset without
// fixing its CRC.
func flipDataByte(t *testing.T, s *WALStore, walOffset uint64) {
t.Helper()
off := int64(s.sb.WALOffset+walOffset) + int64(walEntryHeaderSize) + 100
b := make([]byte, 1)
if _, err := s.fd.ReadAt(b, off); err != nil {
t.Fatal(err)
}
b[0] ^= 0xFF
if _, err := s.fd.WriteAt(b, off); err != nil {
t.Fatal(err)
}
}
func reopenAfterCrash(t *testing.T, s *WALStore, path string) (*WALStore, uint64, error) {
t.Helper()
crashRecoveryHardeningStore(t, s)
r, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = r.Close() })
lsn, rerr := r.Recover()
return r, lsn, rerr
}
func holeWarning(s *WALStore) bool {
for _, w := range s.RecoveryWarnings() {
if strings.HasPrefix(w, WarningWALHoleSuspected+":") {
@@ -78,131 +20,3 @@ func holeWarning(s *WALStore) bool {
}
return false
}
// (a) A corrupted mid-history synced record: recovery opens as before
// (this range stops at it), and warns (typed, counted).
func TestWALStoreRecoverWarnsOnMidHistoryHole(t *testing.T) {
s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2, 3})
flipDataByte(t, s, offs[1])
r, lsn, err := reopenAfterCrash(t, s, path)
if err != nil || lsn != 1 {
t.Fatalf("Recover after a mid-history hole = %d, %v; want 1, nil (no outage)", lsn, err)
}
if !holeWarning(r) || r.HolesSuspected() != 1 {
t.Fatalf("warnings %v holes %d; want %s, counted once", r.RecoveryWarnings(), r.HolesSuspected(), WarningWALHoleSuspected)
}
if got := r.dm.len(); got != 1 {
t.Fatalf("dirty entries replayed = %d; want 1 (nothing after the hole)", got)
}
assertRecoveryHardeningBlock(t, r, 0, makeBlock(4096, 0xB0))
}
// (b) A power loss with an unsynced, out-of-order tail: an earlier
// unsynced record torn, a later one written back. No outage: recovery
// succeeds with the synced prefix intact.
func TestWALStoreRecoverSurvivesAnOutOfOrderUnsyncedTail(t *testing.T) {
s, path, _ := writeSyncedEntries(t, []uint32{0, 1}) // synced
for i, lba := range []uint32{2, 3} { // unsynced
if _, err := s.Write(lba, makeBlock(4096, byte(0xC0+i))); err != nil {
t.Fatal(err)
}
}
offs := walOffsetsByLBA(s)
flipDataByte(t, s, offs[2]) // LBA 2 torn, LBA 3 reached the disk
r, lsn, err := reopenAfterCrash(t, s, path)
if err != nil || lsn != 2 {
t.Fatalf("Recover after an out-of-order unsynced tail = %d, %v; want 2, nil", lsn, err)
}
for i, lba := range []uint32{0, 1} {
assertRecoveryHardeningBlock(t, r, lba, makeBlock(4096, byte(0xB0+i)))
}
}
// A torn tail (nothing valid after it) recovers without a warning.
func TestWALStoreRecoverKeepsATornTail(t *testing.T) {
s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2, 3})
flipDataByte(t, s, offs[3])
r, lsn, err := reopenAfterCrash(t, s, path)
if err != nil || lsn != 3 || holeWarning(r) {
t.Fatalf("Recover with a torn tail = %d, %v, warnings %v; want 3, nil, none", lsn, err, r.RecoveryWarnings())
}
for i, lba := range []uint32{0, 1, 2} {
assertRecoveryHardeningBlock(t, r, lba, makeBlock(4096, byte(0xB0+i)))
}
}
// (c) A hole across wrapped ranges (the older record at the high end
// corrupted, the newer batch wrapped to offset 0) is no outage. Detection
// here is per range: when the newer entries were scanned first there is
// nothing "later" left to find, and telling generations apart across
// ranges (like not replaying past such a hole) is the post-M4 watermark
// work.
func TestWALStoreRecoverWrappedHoleIsNoOutage(t *testing.T) {
const (
blockSize = 4096
walSize = 24 * 1024
)
path := filepath.Join(t.TempDir(), "store.bin")
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
s.DisableAutoFlushForRecoveryTest()
for lba := uint32(0); lba < 3; lba++ {
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); 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 := s.Write(20, makeBlock(blockSize, 0xA4)); err != nil {
t.Fatal(err)
}
s.enableMultiBlockRecordsForTest(true)
if _, err := s.WriteBatch(24, [][]byte{makeBlock(blockSize, 0xB5), makeBlock(blockSize, 0xB6)}); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
offs := walOffsetsByLBA(s)
flipDataByte(t, s, offs[20])
r, _, err := reopenAfterCrash(t, s, path)
if err != nil {
t.Fatalf("Recover = %v; want no outage", err)
}
_ = r
}
// Review finding: a damaged STALE record in a released range (below the
// checkpoint, outside the retained window) must not cost retained data.
// Layout: checkpoint 2, persisted tail at S, head at 3S; LSN 1 (released)
// at 0 damaged, LSN 2 checkpointed at S, LSN 3 synced and unflushed at 2S.
// LSN 3 must be replayed with its exact bytes.
func TestWALStoreRecoverStaleReleasedGarbageKeepsRetainedData(t *testing.T) {
const blockSize = 4096
s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2})
S := uint64(walEntryHeaderSize + blockSize)
if offs[0] != 0 || offs[1] != S || offs[2] != 2*S {
t.Fatalf("offsets %v; want 0, S, 2S", offs)
}
sb := *s.sb
sb.WALCheckpointLSN, sb.WALTail, sb.WALHead = 2, S, 3*S
buf := newSimpleByteBuf()
if _, err := sb.writeTo(buf); err != nil {
t.Fatal(err)
}
if _, err := s.fd.WriteAt(buf.bytes(), 0); err != nil {
t.Fatal(err)
}
if err := s.fd.Sync(); err != nil {
t.Fatal(err)
}
flipDataByte(t, s, offs[0]) // the released LSN 1
r, _, err := reopenAfterCrash(t, s, path)
if err != nil {
t.Fatalf("Recover: %v", err)
}
assertRecoveryHardeningBlock(t, r, 2, makeBlock(blockSize, 0xB2)) // LSN 3, exact bytes
}
@@ -1,82 +0,0 @@
package storage
import (
"bytes"
"path/filepath"
"testing"
)
func TestWALStore_MultiBlockProfile_RecordCountReduction(t *testing.T) {
const (
numBlocks = 4096
blockSize = 4096
batches = 128
blocksPerBatch = 16
)
type profile struct {
instr WriteInstrumentationStatus
}
run := func(t *testing.T, multiblock bool) profile {
t.Helper()
path := filepath.Join(t.TempDir(), "store.bin")
s, err := createLegacyWALStoreForTest(path, numBlocks, blockSize)
if err != nil {
t.Fatalf("CreateWALStore: %v", err)
}
defer s.Close()
s.flusher.Stop()
s.enableMultiBlockRecordsForTest(multiblock)
var lastBlocks [][]byte
var lastStart uint32
for b := 0; b < batches; b++ {
start := uint32(b * blocksPerBatch)
blocks := make([][]byte, blocksPerBatch)
for i := range blocks {
blocks[i] = makeBlock(blockSize, byte((b+i)%251+1))
}
if _, err := s.WriteBatch(start, blocks); err != nil {
t.Fatalf("WriteBatch multiblock=%v batch=%d: %v", multiblock, b, err)
}
lastBlocks = blocks
lastStart = start
}
for i, want := range lastBlocks {
got, err := s.Read(lastStart + uint32(i))
if err != nil {
t.Fatalf("Read multiblock=%v block=%d: %v", multiblock, i, err)
}
if !bytes.Equal(got, want) {
t.Fatalf("Read multiblock=%v block=%d mismatch", multiblock, i)
}
}
return profile{instr: s.WriteInstrumentation()}
}
single := run(t, false)
multi := run(t, true)
t.Logf("phase149_single_block_wal_encode_ops=%d", single.instr.WALEncodeOps)
t.Logf("phase149_multiblock_wal_encode_ops=%d", multi.instr.WALEncodeOps)
t.Logf("phase149_single_block_wal_append_ops=%d", single.instr.WALAppendOps)
t.Logf("phase149_multiblock_wal_append_ops=%d", multi.instr.WALAppendOps)
t.Logf("phase149_single_block_wal_writeat_calls=%d", single.instr.WALAppendWriteAtCalls)
t.Logf("phase149_multiblock_wal_writeat_calls=%d", multi.instr.WALAppendWriteAtCalls)
if single.instr.WALEncodeOps == 0 || multi.instr.WALEncodeOps == 0 {
t.Fatalf("missing encode ops: single=%d multi=%d", single.instr.WALEncodeOps, multi.instr.WALEncodeOps)
}
if multi.instr.WALEncodeOps >= single.instr.WALEncodeOps {
t.Fatalf("multi-block encode ops=%d, want < single=%d", multi.instr.WALEncodeOps, single.instr.WALEncodeOps)
}
expectedMulti := uint64(batches)
if multi.instr.WALEncodeOps != expectedMulti {
t.Fatalf("multi-block encode ops=%d want %d", multi.instr.WALEncodeOps, expectedMulti)
}
expectedSingle := uint64(batches * blocksPerBatch)
if single.instr.WALEncodeOps != expectedSingle {
t.Fatalf("single-block encode ops=%d want %d", single.instr.WALEncodeOps, expectedSingle)
}
}
@@ -1,381 +0,0 @@
package storage
import (
"bytes"
"encoding/binary"
"path/filepath"
"testing"
"time"
)
func TestWALMultiBlock_EncodeDecode(t *testing.T) {
block0 := makeBlock(4096, 0xA0)
block1 := makeBlock(4096, 0xB0)
data := append(append([]byte{}, block0...), block1...)
entry := walEntry{
LSN: 10,
Reserved: 2,
Type: walEntryWriteBatch,
LBA: 7,
Length: uint32(len(data)),
Data: data,
}
encoded, err := entry.encode()
if err != nil {
t.Fatalf("encode: %v", err)
}
decoded, err := decodeWALEntry(encoded)
if err != nil {
t.Fatalf("decode: %v", err)
}
if decoded.Type != walEntryWriteBatch {
t.Fatalf("type=%d want %d", decoded.Type, walEntryWriteBatch)
}
if decoded.LSN != 10 || decoded.Reserved != 2 || decoded.LBA != 7 {
t.Fatalf("identity mismatch: %+v", decoded)
}
if !bytes.Equal(decoded.Data[:4096], block0) || !bytes.Equal(decoded.Data[4096:], block1) {
t.Fatal("decoded batch payload mismatch")
}
}
func TestWALStore_MultiBlockFeatureDisabledByDefault(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
defer s.Close()
s.flusher.Stop()
if _, err := s.WriteBatch(2, [][]byte{
makeBlock(4096, 0xA1),
makeBlock(4096, 0xA2),
makeBlock(4096, 0xA3),
}); err != nil {
t.Fatalf("WriteBatch: %v", err)
}
entries := s.dm.snapshot()
if len(entries) != 3 {
t.Fatalf("dirty entries=%d want 3", len(entries))
}
seenOffsets := map[uint64]bool{}
header := make([]byte, walEntryHeaderSize)
for _, e := range entries {
seenOffsets[e.WALOffset] = true
if e.DataOffset != 0 {
t.Fatalf("default dirty data offset=%d want 0", e.DataOffset)
}
if _, err := s.fd.ReadAt(header, int64(s.sb.WALOffset+e.WALOffset)); err != nil {
t.Fatalf("read header: %v", err)
}
if typ := header[16]; typ != walEntryWrite {
t.Fatalf("default entry type=%d want walEntryWrite", typ)
}
}
if len(seenOffsets) != 3 {
t.Fatalf("default WriteBatch offsets=%d want 3 independent records", len(seenOffsets))
}
}
func TestWALStore_MultiBlockDirtyRead(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
defer s.Close()
s.flusher.Stop()
s.enableMultiBlockRecordsForTest(true)
blocks := [][]byte{
makeBlock(4096, 0xB1),
makeBlock(4096, 0xB2),
makeBlock(4096, 0xB3),
}
lsns, err := s.WriteBatch(4, blocks)
if err != nil {
t.Fatalf("WriteBatch: %v", err)
}
for i, lsn := range lsns {
if want := uint64(i + 1); lsn != want {
t.Fatalf("lsn[%d]=%d want %d", i, lsn, want)
}
}
entries := s.dm.snapshot()
if len(entries) != 3 {
t.Fatalf("dirty entries=%d want 3", len(entries))
}
offset := entries[0].WALOffset
for _, e := range entries {
if e.WALOffset != offset {
t.Fatalf("batch dirty offset changed: %d vs %d", e.WALOffset, offset)
}
}
for i, want := range blocks {
got, err := s.Read(uint32(4 + i))
if err != nil {
t.Fatalf("Read %d: %v", i, err)
}
if !bytes.Equal(got, want) {
t.Fatalf("Read %d returned wrong block", i)
}
}
}
func TestWALStore_MultiBlockRecoverSplitsPerBlock(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
func() {
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
s.flusher.Stop()
s.enableMultiBlockRecordsForTest(true)
if _, err := s.WriteBatch(1, [][]byte{
makeBlock(4096, 0xC1),
makeBlock(4096, 0xC2),
makeBlock(4096, 0xC3),
}); err != nil {
t.Fatalf("WriteBatch: %v", err)
}
if stable, err := s.Sync(); err != nil || stable != 3 {
t.Fatalf("Sync stable=%d err=%v, want stable=3", stable, err)
}
s.committer.Stop()
_ = s.fd.Close()
}()
s, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
defer s.Close()
if recovered, err := s.Recover(); err != nil || recovered != 3 {
t.Fatalf("Recover=%d err=%v, want 3", recovered, err)
}
for i, marker := range []byte{0xC1, 0xC2, 0xC3} {
got, err := s.Read(uint32(1 + i))
if err != nil {
t.Fatalf("Read %d: %v", i, err)
}
if got[0] != marker {
t.Fatalf("Read %d marker=%02x want %02x", i, got[0], marker)
}
}
}
func TestWALStore_DisableAutoFlushForRecoveryTestPreservesReplayAfterCrash(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
blocks := [][]byte{
makeBlock(4096, 0xD1),
makeBlock(4096, 0xD2),
makeBlock(4096, 0xD3),
makeBlock(4096, 0xD4),
}
func() {
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
s.enableMultiBlockRecordsForTest(true)
if _, err := s.WriteBatch(2, blocks); err != nil {
t.Fatalf("WriteBatch: %v", err)
}
if stable, err := s.Sync(); err != nil || stable != 4 {
t.Fatalf("Sync stable=%d err=%v, want stable=4", stable, err)
}
if got := s.CheckpointLSN(); got != 0 {
t.Fatalf("checkpoint=%d want 0 before crash", got)
}
s.committer.Stop()
if err := s.fd.Close(); err != nil {
t.Fatalf("close fd: %v", err)
}
}()
s, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
defer s.Close()
if recovered, err := s.Recover(); err != nil || recovered != 4 {
t.Fatalf("Recover=%d err=%v, want 4", recovered, err)
}
if got := s.CheckpointLSN(); got != 0 {
t.Fatalf("checkpoint after recovery=%d want 0", got)
}
for i, want := range blocks {
got, err := s.Read(uint32(2 + i))
if err != nil {
t.Fatalf("Read %d: %v", i, err)
}
if !bytes.Equal(got, want) {
t.Fatalf("Read %d returned wrong block", i)
}
}
}
func TestWALStore_MultiBlockRecoveryHeadLSNUsesRecoveredFrontier(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
blocks := [][]byte{
makeBlock(4096, 0xE1),
makeBlock(4096, 0xE2),
makeBlock(4096, 0xE3),
makeBlock(4096, 0xE4),
}
var persistedWALHeadBytes uint64
func() {
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
s.enableMultiBlockRecordsForTest(true)
if _, err := s.WriteBatch(2, blocks); err != nil {
t.Fatalf("WriteBatch: %v", err)
}
if stable, err := s.Sync(); err != nil || stable != 4 {
t.Fatalf("Sync stable=%d err=%v, want stable=4", stable, err)
}
_, _, headLSN := s.Boundaries()
if headLSN != 4 {
t.Fatalf("pre-close HeadLSN=%d want 4", headLSN)
}
persistedWALHeadBytes = s.wal.logicalHeadValue()
if persistedWALHeadBytes <= headLSN {
t.Fatalf("test setup did not create distinct WAL byte head: walHeadBytes=%d headLSN=%d", persistedWALHeadBytes, headLSN)
}
if err := s.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
}()
s, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
defer s.Close()
recovered, err := s.Recover()
if err != nil {
t.Fatalf("Recover: %v", err)
}
if recovered != 4 {
t.Fatalf("Recover=%d want 4", recovered)
}
_, _, headLSN := s.Boundaries()
if headLSN != recovered {
t.Fatalf("HeadLSN=%d want recovered frontier %d, not WAL byte offset %d", headLSN, recovered, persistedWALHeadBytes)
}
if next := s.NextLSN(); next != recovered+1 {
t.Fatalf("NextLSN=%d want %d", next, recovered+1)
}
}
func TestWALStore_MultiBlockFlusherSplitsPerBlock(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
defer s.Close()
s.enableMultiBlockRecordsForTest(true)
blocks := [][]byte{
makeBlock(4096, 0xD1),
makeBlock(4096, 0xD2),
makeBlock(4096, 0xD3),
}
if _, err := s.WriteBatch(6, blocks); err != nil {
t.Fatalf("WriteBatch: %v", err)
}
if stable, err := s.Sync(); err != nil || stable != 3 {
t.Fatalf("Sync stable=%d err=%v, want stable=3", stable, err)
}
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if s.CheckpointLSN() >= 3 && s.dm.len() == 0 {
break
}
time.Sleep(20 * time.Millisecond)
}
if s.CheckpointLSN() < 3 {
t.Fatalf("checkpoint=%d want >=3", s.CheckpointLSN())
}
if got := s.dm.len(); got != 0 {
t.Fatalf("dirty map len=%d want 0 after flush", got)
}
for i, want := range blocks {
got, err := s.readFromExtent(uint32(6 + i))
if err != nil {
t.Fatalf("read extent %d: %v", i, err)
}
if !bytes.Equal(got, want) {
t.Fatalf("extent block %d mismatch", i)
}
}
}
func TestWALStore_MultiBlockScanLBAsSplitsPerLSN(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
defer s.Close()
s.flusher.Stop()
s.enableMultiBlockRecordsForTest(true)
if _, err := s.WriteBatch(8, [][]byte{
makeBlock(4096, 0xE1),
makeBlock(4096, 0xE2),
makeBlock(4096, 0xE3),
}); err != nil {
t.Fatalf("WriteBatch: %v", err)
}
if _, err := s.Sync(); err != nil {
t.Fatalf("Sync: %v", err)
}
var got []RecoveryEntry
if err := s.ScanLBAs(1, func(e RecoveryEntry) error {
dup := append([]byte(nil), e.Data...)
e.Data = dup
got = append(got, e)
return nil
}); err != nil {
t.Fatalf("ScanLBAs: %v", err)
}
if len(got) != 3 {
t.Fatalf("entries=%d want 3", len(got))
}
for i, e := range got {
if wantLSN := uint64(i + 1); e.LSN != wantLSN {
t.Fatalf("entry %d LSN=%d want %d", i, e.LSN, wantLSN)
}
if wantLBA := uint32(8 + i); e.LBA != wantLBA {
t.Fatalf("entry %d LBA=%d want %d", i, e.LBA, wantLBA)
}
if wantMarker := byte(0xE1 + i); e.Data[0] != wantMarker {
t.Fatalf("entry %d marker=%02x want %02x", i, e.Data[0], wantMarker)
}
}
header := make([]byte, walEntryHeaderSize)
entries := s.dm.snapshot()
if len(entries) == 0 {
t.Fatal("dirty map empty")
}
if _, err := s.fd.ReadAt(header, int64(s.sb.WALOffset+entries[0].WALOffset)); err != nil {
t.Fatalf("read header: %v", err)
}
if gotType := header[16]; gotType != walEntryWriteBatch {
t.Fatalf("entry type=%d want walEntryWriteBatch", gotType)
}
if count := binary.LittleEndian.Uint64(header[8:16]); count != 3 {
t.Fatalf("batch count=%d want 3", count)
}
}
@@ -1,482 +0,0 @@
package storage
import (
"bytes"
"errors"
"os"
"path/filepath"
"testing"
"time"
)
// The WAL writer may only overwrite bytes that the PERSISTED superblock tail
// has released (the torn-wrap finding). Otherwise a torn new record can
// land inside the persisted
// [tail, head) and stop recovery's scan before a synced record behind it.
func diskSuperblockForTest(t *testing.T, path string) superblock {
t.Helper()
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
sb, err := readSuperblock(f)
if err != nil {
t.Fatal(err)
}
return sb
}
// The S3 trace, deterministic: LSN 2 is appended (and synced) while the
// flush of LSN 1 runs, so the checkpoint covers LSN 1 and the persisted head
// covers LSN 2. Synced LSN 3..5 follow; an unsynced LSN 6 wraps to offset 0
// over the released LSN 1. The crash leaves LSN 6 torn and its end padding
// not on disk (both unsynced pages: a plain crash, no corruption). Synced
// LSN 2..5 must all be recovered.
func TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords(t *testing.T) {
const (
blockSize = 4096
walSize = 24 * 1024
)
S := uint64(walEntryHeaderSize + blockSize)
path := filepath.Join(t.TempDir(), "store.bin")
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
s.DisableAutoFlushForRecoveryTest()
if _, err := s.Write(0, makeBlock(blockSize, 0x10)); err != nil { // LSN 1
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
s.flusher.afterSnapshotForTest = func() {
s.flusher.afterSnapshotForTest = nil
if _, err := s.Write(1, makeBlock(blockSize, 0x11)); err != nil { // LSN 2, not in this flush
t.Error(err)
}
if _, err := s.Sync(); err != nil {
t.Error(err)
}
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
if sb := diskSuperblockForTest(t, path); sb.WALCheckpointLSN != 1 || sb.WALHead != 2*S {
t.Fatalf("persisted ckpt=%d head=%d; want the flush of LSN 1 to cover LSN 2 in its head (2S=%d)", sb.WALCheckpointLSN, sb.WALHead, 2*S)
}
for lba := uint32(2); lba <= 4; lba++ { // LSN 3..5, synced
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if _, err := s.Write(5, makeBlock(blockSize, 0x66)); err != nil { // LSN 6, unsynced, wraps
t.Fatal(err)
}
ents := recoverySnapshotEntriesByLBA(s.dm.snapshot())
if ents[5].WALOffset != 0 || ents[1].WALOffset != S {
t.Fatalf("layout: LSN 6 at %d, LSN 2 at %d; want 0 and S", ents[5].WALOffset, ents[1].WALOffset)
}
walOff := s.sb.WALOffset
if _, err := s.fd.WriteAt(make([]byte, walSize-5*S), int64(walOff+5*S)); err != nil { // padding not on disk
t.Fatal(err)
}
if _, err := s.fd.WriteAt(make([]byte, blockSize/2), int64(walOff+S-blockSize/2)); err != nil { // LSN 6 torn
t.Fatal(err)
}
crashRecoveryHardeningStore(t, s)
r, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = r.Close() })
if _, err := r.Recover(); err != nil {
t.Fatalf("Recover: %v", err)
}
for lba := uint32(1); lba <= 4; lba++ {
assertRecoveryHardeningBlock(t, r, lba, makeBlock(blockSize, byte(0x10+lba)))
}
}
// A flush persists the tail it releases: the on-disk tail equals the
// writer's tail after every checkpoint, and head/tail come from one snapshot.
func TestWALStoreFlushPersistsTheReleasedTail(t *testing.T) {
const blockSize = 4096
path := filepath.Join(t.TempDir(), "store.bin")
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024)
s.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = s.Close() })
for round := 0; round < 3; round++ {
for lba := uint32(0); lba < 2; lba++ {
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x20+round))); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
sb := diskSuperblockForTest(t, path)
if tail, head := s.wal.logicalTailValue(), s.wal.logicalHeadValue(); sb.WALTail != tail || sb.WALHead != head {
t.Fatalf("round %d: persisted tail=%d head=%d, writer tail=%d head=%d; the writer may reuse bytes the persisted tail still retains", round, sb.WALTail, sb.WALHead, tail, head)
}
}
}
// Recovery that moves the writer's bounds persists them before any append,
// so the writer never reuses bytes the on-disk superblock still declares
// retained.
func TestWALStoreRecoverPersistsTheRecoveredBounds(t *testing.T) {
const blockSize = 4096
path := filepath.Join(t.TempDir(), "store.bin")
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024)
s.DisableAutoFlushForRecoveryTest()
if _, err := s.Write(0, makeBlock(blockSize, 0x30)); err != nil { // LSN 1
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
if _, err := s.Write(1, makeBlock(blockSize, 0x31)); err != nil { // LSN 2, synced, unflushed
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
// the superblock as an older flush left it: ckpt 1, tail before LSN 1
sb := *s.sb
sb.WALCheckpointLSN, sb.WALTail, sb.WALHead = 1, 0, uint64(walEntryHeaderSize+blockSize)
buf := newSimpleByteBuf()
if _, err := sb.writeTo(buf); err != nil {
t.Fatal(err)
}
if _, err := s.fd.WriteAt(buf.bytes(), 0); err != nil {
t.Fatal(err)
}
crashRecoveryHardeningStore(t, s)
r, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = r.Close() })
if _, err := r.Recover(); err != nil {
t.Fatal(err)
}
disk := diskSuperblockForTest(t, path)
if tail, head := r.wal.logicalTailValue(), r.wal.logicalHeadValue(); disk.WALTail != tail || disk.WALHead != head {
t.Fatalf("after Recover: persisted tail=%d head=%d, writer tail=%d head=%d; want the recovered bounds persisted", disk.WALTail, disk.WALHead, tail, head)
}
assertRecoveryHardeningBlock(t, r, 1, makeBlock(blockSize, 0x31))
}
// The writer's space check uses the durable tail: an in-memory release that
// is not yet persisted does not make its bytes reusable.
func TestWALWriterReuseIsBoundedByTheDurableTail(t *testing.T) {
f, err := os.CreateTemp(t.TempDir(), "wal")
if err != nil {
t.Fatal(err)
}
defer f.Close()
const walSize = 4096
entry := func() *walEntry {
return &walEntry{LSN: 1, Type: walEntryWrite, LBA: 0, Length: 64, Data: make([]byte, 64)}
}
size, err := entry().encodedSize()
if err != nil {
t.Fatal(err)
}
n := uint64(walSize) / uint64(size)
w := newWALWriter(f, 0, walSize, 0, 0, nil)
for i := uint64(0); i < n; i++ {
if _, err := w.append(entry()); err != nil {
t.Fatalf("append %d of %d: %v", i, n, err)
}
}
w.advanceTailPastEntry(0, uint64(size)) // released in memory only
if _, err := w.append(entry()); !errors.Is(err, errWALFull) {
t.Fatalf("append into bytes released only in memory: err=%v; want errWALFull until the tail is persisted", err)
}
}
// A full flush persists head == tail (an empty WAL at that position). Sync
// does not persist the head, so synced appends follow it there; recovery must
// scan from the persisted position, not from offset 0 (a torn unsynced
// record wrapped to 0 must not hide the synced run).
func TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords(t *testing.T) {
const (
blockSize = 4096
walSize = 24 * 1024
)
S := uint64(walEntryHeaderSize + blockSize)
path := filepath.Join(t.TempDir(), "store.bin")
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
s.DisableAutoFlushForRecoveryTest()
if _, err := s.Write(0, makeBlock(blockSize, 0x10)); err != nil { // LSN 1
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
for lba := uint32(1); lba <= 4; lba++ { // LSN 2..5, synced
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if _, err := s.Write(5, makeBlock(blockSize, 0x66)); err != nil { // LSN 6, unsynced, wraps
t.Fatal(err)
}
ents := recoverySnapshotEntriesByLBA(s.dm.snapshot())
if ents[5].WALOffset != 0 || ents[1].WALOffset != S {
t.Fatalf("layout: LSN 6 at %d, LSN 2 at %d; want 0 and S", ents[5].WALOffset, ents[1].WALOffset)
}
walOff := s.sb.WALOffset
if _, err := s.fd.WriteAt(make([]byte, walSize-5*S), int64(walOff+5*S)); err != nil { // padding not on disk
t.Fatal(err)
}
if _, err := s.fd.WriteAt(make([]byte, blockSize/2), int64(walOff+S-blockSize/2)); err != nil { // LSN 6 torn
t.Fatal(err)
}
crashRecoveryHardeningStore(t, s)
r, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = r.Close() })
if _, err := r.Recover(); err != nil {
t.Fatalf("Recover: %v", err)
}
for lba := uint32(1); lba <= 4; lba++ {
assertRecoveryHardeningBlock(t, r, lba, makeBlock(blockSize, byte(0x10+lba)))
}
}
// Review of #159: the batch planner (with a padding wrap) counts from the
// durable tail too: refused while the release is only in memory or the
// bounds are recovery-pending, accepted once the tail is persisted.
func TestWALWriterBatchReuseIsBoundedByTheDurableTail(t *testing.T) {
const walSize = 4096
mk := func(lsn uint64) walEntry {
return walEntry{LSN: lsn, Type: walEntryWrite, LBA: lsn, Length: 64, Data: make([]byte, 64)}
}
e0 := mk(0)
size, err := e0.encodedSize()
if err != nil {
t.Fatal(err)
}
sz := uint64(size)
n := uint64(walSize) / sz // the last walSize%sz bytes force a padding wrap
fill := func(t *testing.T) (*walWriter, *os.File) {
f, err := os.CreateTemp(t.TempDir(), "wal")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = f.Close() })
if err := f.Truncate(walSize); err != nil {
t.Fatal(err)
}
w := newWALWriter(f, 0, walSize, 0, 0, nil)
for i := uint64(0); i < n; i++ {
e := mk(i + 1)
if _, err := w.append(&e); err != nil {
t.Fatalf("fill %d: %v", i, err)
}
}
return w, f
}
batch := func() []walEntry { return []walEntry{mk(n + 1), mk(n + 2)} }
refused := func(t *testing.T, w *walWriter, f *os.File, why string) {
t.Helper()
head := w.logicalHeadValue()
tailBytes := make([]byte, walSize-n*sz)
if _, err := f.ReadAt(tailBytes, int64(n*sz)); err != nil {
t.Fatal(err)
}
if _, err := w.appendBatch(batch()); !errors.Is(err, errWALFull) {
t.Fatalf("%s: appendBatch err=%v; want errWALFull", why, err)
}
after := make([]byte, len(tailBytes))
if _, err := f.ReadAt(after, int64(n*sz)); err != nil {
t.Fatal(err)
}
if w.logicalHeadValue() != head || !bytes.Equal(after, tailBytes) {
t.Fatalf("%s: a refused batch moved the head or wrote padding", why)
}
}
accepted := func(t *testing.T, w *walWriter) {
t.Helper()
offs, err := w.appendBatch(batch())
if err != nil {
t.Fatalf("after the tail is persisted: appendBatch: %v", err)
}
if len(offs) != 2 || offs[0] != 0 || offs[1] != sz {
t.Fatalf("offsets %v; want the batch wrapped to [0 %d]", offs, sz)
}
}
t.Run("released in memory only", func(t *testing.T) {
w, f := fill(t)
w.advanceTailPastEntry(0, 2*sz)
refused(t, w, f, "in-memory release")
w.tailPersisted(2 * sz)
accepted(t, w)
})
t.Run("recovered bounds pending", func(t *testing.T) {
w, f := fill(t)
w.tailPersisted(2 * sz) // the space is free on disk; only the pending flag refuses it
if err := w.restoreRecoveredBounds(n*sz, 2*sz); err != nil {
t.Fatal(err)
}
refused(t, w, f, "durablePending")
single := mk(n + 1)
if _, err := w.append(&single); !errors.Is(err, errWALFull) {
t.Fatalf("durablePending: append err=%v; want errWALFull", err)
}
w.tailPersisted(2 * sz)
accepted(t, w)
})
}
// Review of #159: when Recover cannot persist the rebuilt bounds (the
// superblock write or its fsync fails), it fails, admits no append, and a
// same-instance retry persists them; later writes survive a reopen exactly.
func TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry(t *testing.T) {
const blockSize = 4096
S := uint64(walEntryHeaderSize + blockSize)
errInjected := errors.New("injected superblock failure")
for _, seam := range []string{"write", "sync"} {
t.Run(seam, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024)
s.DisableAutoFlushForRecoveryTest()
crashed := false
t.Cleanup(func() {
if !crashed {
_ = s.Close()
}
})
if _, err := s.Write(0, makeBlock(blockSize, 0x30)); err != nil { // LSN 1
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
if _, err := s.Write(1, makeBlock(blockSize, 0x31)); err != nil { // LSN 2, synced, unflushed
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
sb := *s.sb // an older flush's superblock: the bounds Recover must rebuild and persist
sb.WALCheckpointLSN, sb.WALTail, sb.WALHead = 1, 0, S
buf := newSimpleByteBuf()
if _, err := sb.writeTo(buf); err != nil {
t.Fatal(err)
}
if _, err := s.fd.WriteAt(buf.bytes(), 0); err != nil {
t.Fatal(err)
}
crashRecoveryHardeningStore(t, s)
crashed = true
r, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
rClosed := false
t.Cleanup(func() {
if !rClosed {
_ = r.Close()
}
})
realWrite, realSync := r.writeSuperblockMetadata, r.syncSuperblockMetadata
if seam == "write" {
r.writeSuperblockMetadata = func([]byte) error { return errInjected }
} else {
r.syncSuperblockMetadata = func() error { return errInjected }
}
if _, err := r.Recover(); !errors.Is(err, errInjected) {
t.Fatalf("Recover with a failing superblock %s: err=%v; want the injected failure", seam, err)
}
head := r.wal.logicalHeadValue()
r.admissionTimeout = 200 * time.Millisecond
if _, err := r.Write(5, makeBlock(blockSize, 0x55)); err == nil {
t.Fatal("Write after a failed Recover succeeded; want it refused until the bounds are persisted")
}
if r.wal.logicalHeadValue() != head {
t.Fatalf("refused Write moved the WAL head %d -> %d", head, r.wal.logicalHeadValue())
}
r.writeSuperblockMetadata, r.syncSuperblockMetadata = realWrite, realSync
live := r
if seam == "sync" {
// A failed fsync is sticky (ErrFsyncFailed): no same-instance
// retry; the bounds are persisted by the recovery of a reopen.
if _, err := r.Recover(); !errors.Is(err, ErrFsyncFailed) {
t.Fatalf("same-instance Recover after a failed fsync: %v; want ErrFsyncFailed", err)
}
crashRecoveryHardeningStore(t, r)
rClosed = true
r2, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
r2.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() {
if live == r2 && !rClosed {
_ = r2.Close()
}
})
rClosed = false
live = r2
}
if _, err := live.Recover(); err != nil {
t.Fatalf("Recover retry: %v", err)
}
disk := diskSuperblockForTest(t, path)
if tail, h := live.wal.logicalTailValue(), live.wal.logicalHeadValue(); disk.WALTail != tail || disk.WALHead != h {
t.Fatalf("after the retry: persisted tail=%d head=%d, writer tail=%d head=%d", disk.WALTail, disk.WALHead, tail, h)
}
live.admissionTimeout = 30 * time.Second
if _, err := live.Write(5, makeBlock(blockSize, 0x55)); err != nil {
t.Fatal(err)
}
if _, err := live.Sync(); err != nil {
t.Fatal(err)
}
crashRecoveryHardeningStore(t, live)
rClosed = true
q, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
q.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = q.Close() })
if _, err := q.Recover(); err != nil {
t.Fatalf("reopen Recover: %v", err)
}
assertRecoveryHardeningBlock(t, q, 1, makeBlock(blockSize, 0x31))
assertRecoveryHardeningBlock(t, q, 5, makeBlock(blockSize, 0x55))
})
}
}
@@ -67,39 +67,6 @@ func OpenReadOnlyWithOptions(path string, opts WALStoreOptions) (*WALStoreReader
return openReadOnlyV3(path, opts)
}
func openLegacyReadOnlyWithOptions(path string, opts WALStoreOptions) (*WALStoreReader, error) {
f, err := os.OpenFile(path, os.O_RDONLY, 0)
if err != nil {
return nil, fmt.Errorf("storage: OpenReadOnly %s: %w", path, err)
}
if _, err := f.Seek(0, 0); err != nil {
_ = f.Close()
return nil, fmt.Errorf("storage: seek superblock: %w", err)
}
sb, err := readSuperblock(f)
if err != nil {
_ = f.Close()
return nil, err
}
if err := sb.validate(); err != nil {
_ = f.Close()
return nil, err
}
metadata, _, err := bindBlockMetadata(f, &sb, opts, false, true)
if err != nil {
_ = f.Close()
return nil, err
}
dm := newDirtyMap(64)
// Replay WAL into the dirty map. recoverWAL is a pure read pass
// over the WAL frames — no writes back to the fd.
if _, err := recoverWAL(f, &sb, dm); err != nil {
_ = f.Close()
return nil, fmt.Errorf("storage: OpenReadOnly recover: %w", err)
}
return &WALStoreReader{metadata: metadata, fd: f, sb: &sb, dm: dm}, nil
}
// Read returns the current bytes at lba — same merge logic the
// daemon uses (WAL-recent over extent). No mutation; safe to call
// concurrently from multiple goroutines.
@@ -109,46 +76,10 @@ func (r *WALStoreReader) Read(lba uint32) ([]byte, error) {
r.mu.Unlock()
return nil, errors.New("storage: WALStoreReader.Read after Close")
}
if r.v3 != nil {
defer r.mu.Unlock()
return r.readV3(lba)
}
r.mu.Unlock()
maxLBA := uint32(r.sb.VolumeSize / uint64(r.sb.BlockSize))
if lba >= maxLBA {
return nil, fmt.Errorf("storage: LBA %d out of range", lba)
}
// WAL-recent first. Inline the same logic as WALStore.readFromWAL
// + readFromExtent, but operating against the read-only fd.
if walRelOff, dataOffset, _, _, ok := r.dm.get(uint64(lba)); ok {
return r.readFromWAL(walRelOff, dataOffset)
}
return r.readFromExtent(lba)
}
defer r.mu.Unlock()
return r.readV3(lba)
func (r *WALStoreReader) readFromWAL(walRelOff uint64, dataOffset uint32) ([]byte, error) {
headerBuf := make([]byte, walEntryHeaderSize)
absOff := int64(r.sb.WALOffset + walRelOff)
if _, err := r.fd.ReadAt(headerBuf, absOff); err != nil {
return nil, fmt.Errorf("storage: OpenReadOnly WAL header: %w", err)
}
if headerBuf[16] == walEntryTrim {
return make([]byte, r.sb.BlockSize), nil
}
length := parseLengthFromHeader(headerBuf)
if dataOffset >= length {
return nil, fmt.Errorf("storage: OpenReadOnly WAL data offset %d >= length %d", dataOffset, length)
}
readLen := r.sb.BlockSize
if remaining := length - dataOffset; remaining < readLen {
readLen = remaining
}
data := make([]byte, readLen)
if _, err := r.fd.ReadAt(data, absOff+int64(walEntryPrefixSize)+int64(dataOffset)); err != nil {
return nil, fmt.Errorf("storage: OpenReadOnly WAL data: %w", err)
}
return data, nil
}
func (r *WALStoreReader) readFromExtent(lba uint32) ([]byte, error) {
+2 -192
View File
@@ -44,201 +44,11 @@ func (s *WALStore) ScanLBAs(fromLSN uint64, fn func(RecoveryEntry) error) error
s.mu.RUnlock()
return errors.New("storage: walstore ScanLBAs after Close")
}
checkpointLSN := s.checkpointLSN
headLSN := s.nextLSN
retentionLSNs := s.recoveryRetentionLSNs
s.mu.RUnlock()
if s.v3 != nil {
// The v3 source-state gate must precede even an empty scan.
return s.scanLBAsV3(fromLSN, fn)
}
// Retention gate: by default the recycle threshold is
// checkpointLSN; an operator-tunable retention window lets a
// slow replica keep a recovery scan path while it lags within
// the configured envelope.
//
// Effective recycle floor:
// floor = checkpointLSN - retentionLSNs (saturating to 0)
//
// fromLSN is recycled when fromLSN <= floor (strict <= — an LSN
// equal to the floor IS recycled). retentionLSNs == 0 reduces
// to the simple 'fromLSN <= checkpointLSN' gate.
//
// Pinned by: INV-G6-CATCHUP-CONVERGES-WITHIN-RETENTION (positive)
// + INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE (the knob itself).
floor := checkpointLSN
if retentionLSNs >= floor {
floor = 0
} else {
floor = checkpointLSN - retentionLSNs
}
if fromLSN <= floor && checkpointLSN > 0 {
// Wrap in typed RecoveryFailure so transport can extract
// the kind via errors.As. errors.Is(err, ErrWALRecycled)
// still works via Unwrap.
return NewWALRecycledFailure(
ErrWALRecycled,
fmt.Sprintf("fromLSN=%d checkpointLSN=%d headLSN=%d retentionLSNs=%d floor=%d",
fromLSN, checkpointLSN, headLSN, retentionLSNs, floor),
)
}
if fromLSN >= headLSN {
return nil // caller is at-or-ahead of head; nothing to ship
}
// The v3 source-state gate must precede even an empty scan.
return s.scanLBAsV3(fromLSN, fn)
// Snapshot WAL writer's logical head/tail under its own lock,
// then walk the active region. Wraparound handled the same way
// recovery.go:recoverWAL does it.
logicalHead := s.wal.logicalHeadValue()
logicalTail := s.wal.logicalTailValue()
walSize := s.sb.WALSize
walOffset := s.sb.WALOffset
if logicalHead == logicalTail {
return nil // WAL is empty
}
physHead := logicalHead % walSize
physTail := logicalTail % walSize
type scanRange struct{ start, end uint64 }
var ranges []scanRange
if physHead > physTail {
ranges = append(ranges, scanRange{physTail, physHead})
} else {
ranges = append(ranges, scanRange{physTail, walSize})
if physHead > 0 {
ranges = append(ranges, scanRange{0, physHead})
}
}
blockSize := s.sb.BlockSize
for _, r := range ranges {
pos := r.start
for pos < r.end {
remaining := r.end - pos
if remaining < uint64(walEntryHeaderSize) {
break
}
headerBuf := make([]byte, walEntryHeaderSize)
absOff := int64(walOffset + pos)
if _, err := s.fd.ReadAt(headerBuf, absOff); err != nil {
return fmt.Errorf("storage: walstore ScanLBAs read header at %d: %w", pos, err)
}
entryType := headerBuf[16]
lengthField := parseLengthFromHeader(headerBuf)
if entryType == walEntryPadding {
pos += uint64(walEntryHeaderSize) + uint64(lengthField)
continue
}
var payloadLen uint64
if entryType == walEntryWrite || entryType == walEntryWriteBatch {
payloadLen = uint64(lengthField)
}
entrySize := uint64(walEntryHeaderSize) + payloadLen
if entrySize > remaining {
// Torn / partial entry; stop this range.
break
}
fullBuf := make([]byte, entrySize)
if _, err := s.fd.ReadAt(fullBuf, absOff); err != nil {
return fmt.Errorf("storage: walstore ScanLBAs read entry at %d: %w", pos, err)
}
entry, err := decodeWALEntry(fullBuf)
if err != nil {
// Torn or trailing-zero region — stop scanning.
break
}
pos += entrySize
// LSN filter: skip entries below fromLSN; stop walking
// is NOT correct here because LSN order in the WAL is
// monotonic only WITHIN A RANGE — we may need to keep
// scanning past entries below fromLSN in the wraparound
// case. Filter inline rather than break.
highestEntryLSN := entry.LSN
if entry.Type == walEntryWriteBatch && entry.Reserved > 0 {
highestEntryLSN = entry.LSN + entry.Reserved - 1
}
if highestEntryLSN < fromLSN {
continue
}
if entry.LSN >= headLSN {
continue
}
// Build RecoveryEntry. Walstore stores full data in
// the WAL — emit byte-for-byte.
switch entry.Type {
case walEntryWrite:
blocks := entry.Length / blockSize
if blocks == 0 {
blocks = 1
}
// One WAL entry may cover multiple consecutive LBAs
// (entry.Length spans multiple block-sized chunks).
// Emit one RecoveryEntry per block, all carrying the
// same LSN — V2-faithful since each LSN labels the
// full multi-block write atomically.
for i := uint32(0); i < blocks; i++ {
blockData := entry.Data[i*blockSize : (i+1)*blockSize]
emit := RecoveryEntry{
LSN: entry.LSN,
LBA: uint32(entry.LBA) + i,
Flags: walEntryWrite,
Data: blockData,
}
if err := fn(emit); err != nil {
return err
}
}
case walEntryWriteBatch:
blocks := uint32(entry.Reserved)
if blocks == 0 || entry.Length != blocks*blockSize {
return fmt.Errorf("storage: walstore ScanLBAs invalid batch record at %d", pos-entrySize)
}
for i := uint32(0); i < blocks; i++ {
lsn := entry.LSN + uint64(i)
if lsn < fromLSN || lsn >= headLSN {
continue
}
blockData := entry.Data[i*blockSize : (i+1)*blockSize]
emit := RecoveryEntry{
LSN: lsn,
LBA: uint32(entry.LBA) + i,
Flags: walEntryWrite,
Data: blockData,
}
if err := fn(emit); err != nil {
return err
}
}
case walEntryTrim:
blocks := entry.Length / blockSize
if blocks == 0 {
blocks = 1
}
for i := uint32(0); i < blocks; i++ {
emit := RecoveryEntry{
LSN: entry.LSN,
LBA: uint32(entry.LBA) + i,
Flags: walEntryTrim,
Data: nil, // trim has no data
}
if err := fn(emit); err != nil {
return err
}
}
case walEntryBarrier:
// barrier entries don't carry data; skip emission
// (they're an internal marker, not a recovery payload)
}
}
}
return nil
}
// WALCapacityBytes exposes the WAL region size for POC retention
@@ -1,77 +0,0 @@
package storage
import (
"os"
"path/filepath"
"testing"
)
// Condition (1) for any prefix-cut recovery rule: an intentional LSN gap
// must not drop synced entries above it. A
// rebuild installs BASE through WriteExtentDirect (no LSN) and applies
// WAL-lane entries with their real LSNs through ApplyEntry; the frontier
// jump (AdvanceFrontier at MarkBaseComplete) is not persisted before them.
// So a replica can hold a synced LSN 101 with a persisted checkpoint of 0 and
// no LSN 1..100 anywhere. Recovery must keep it (a rule that replays only the
// contiguous LSN prefix above the checkpoint keeps nothing here).
func TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump(t *testing.T) {
const blockSize = 4096
path := filepath.Join(t.TempDir(), "store.bin")
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024)
s.DisableAutoFlushForRecoveryTest()
crashed := false
t.Cleanup(func() {
if !crashed {
_ = s.Close()
}
})
if err := s.WriteExtentDirect(0, makeBlock(blockSize, 0xBA)); err != nil { // BASE, no LSN
t.Fatal(err)
}
live := makeBlock(blockSize, 0x65)
if err := s.ApplyEntry(3, live, 101); err != nil { // session-live entry above the BASE hint
t.Fatal(err)
}
if err := s.ApplyEntry(4, makeBlock(blockSize, 0x66), 102); err != nil {
t.Fatal(err)
}
synced, err := s.Sync()
if err != nil {
t.Fatal(err)
}
if synced < 102 {
t.Fatalf("Sync frontier %d; want 102 (the applied entries are synced)", synced)
}
crashRecoveryHardeningStore(t, s)
crashed = true
if sb := diskSuperblockForGapTest(t, path); sb.WALCheckpointLSN != 0 {
t.Fatalf("persisted checkpoint %d; want 0 (the frontier jump is not persisted)", sb.WALCheckpointLSN)
}
r, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = r.Close() })
if _, err := r.Recover(); err != nil {
t.Fatalf("Recover: %v", err)
}
assertRecoveryHardeningBlock(t, r, 3, live)
assertRecoveryHardeningBlock(t, r, 4, makeBlock(blockSize, 0x66))
}
// diskSuperblockForGapTest reads the on-disk superblock with a plain file
// read: no store, no flusher or committer.
func diskSuperblockForGapTest(t *testing.T, path string) superblock {
t.Helper()
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
sb, err := readSuperblock(f)
if err != nil {
t.Fatal(err)
}
return sb
}
@@ -3,283 +3,12 @@ package storage
import (
"bytes"
"encoding/binary"
"errors"
"hash/crc32"
"path/filepath"
"testing"
)
func TestWALStoreRecoverRetainsMultiBlockSuffixAcrossRestart(t *testing.T) {
const blockSize = 4096
path := filepath.Join(t.TempDir(), "store.bin")
s, err := createLegacyWALStoreForTest(path, 32, blockSize)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
s.enableMultiBlockRecordsForTest(true)
blocks := make([][]byte, 16)
for index := range blocks {
blocks[index] = makeBlock(blockSize, byte(0x60+index))
}
if _, err := s.WriteBatch(0, blocks); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 8, anyActive: true})
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
if got := s.CheckpointLSN(); got != 8 {
t.Fatalf("pinned checkpoint=%d want 8", got)
}
if got := s.wal.logicalTailValue(); got != 0 {
t.Fatalf("physical WAL tail under pin=%d want 0", got)
}
_, tail, head := s.Boundaries()
if tail != 1 || head != 16 {
t.Fatalf("logical tail/head under pin=%d/%d want 1/16", tail, head)
}
var retained []RecoveryEntry
if err := s.ScanLBAs(9, func(entry RecoveryEntry) error {
retained = append(retained, entry)
return nil
}); err != nil {
t.Fatal(err)
}
if len(retained) != 8 {
t.Fatalf("retained entries above pin=%d want 8", len(retained))
}
crashRecoveryHardeningStore(t, s)
reopened, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
reopened.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = reopened.Close() })
if recovered, err := reopened.Recover(); err != nil || recovered != 16 {
t.Fatalf("Recover=%d err=%v want 16,nil", recovered, err)
}
wantRecoveredHead := uint64(walEntryHeaderSize + 16*blockSize)
if tail, head := reopened.wal.logicalTailValue(), reopened.wal.logicalHeadValue(); tail != 0 || head != wantRecoveredHead {
t.Fatalf("recovered physical tail/head=%d/%d want 0/%d",
tail, head, wantRecoveredHead)
}
newBlock := makeBlock(blockSize, 0xF1)
newLSN, err := reopened.Write(20, newBlock)
if err != nil {
t.Fatal(err)
}
newEntry := recoverySnapshotEntriesByLBA(reopened.dm.snapshot())[20]
if newEntry.WALOffset != wantRecoveredHead {
t.Fatalf("post-recovery append offset=%d want %d",
newEntry.WALOffset, wantRecoveredHead)
}
if _, err := reopened.Sync(); err != nil {
t.Fatal(err)
}
if err := reopened.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
if got := reopened.CheckpointLSN(); got != newLSN {
t.Fatalf("checkpoint after recovery=%d want %d", got, newLSN)
}
for index, want := range blocks {
assertRecoveryHardeningBlock(t, reopened, uint32(index), want)
}
assertRecoveryHardeningBlock(t, reopened, 20, newBlock)
}
func TestWALStoreRecoverRejectsOverflowingBatchGeometry(t *testing.T) {
tests := []struct {
name string
mutate func([]byte)
}{
{
name: "reserved multiplication overflow",
mutate: func(record []byte) {
binary.LittleEndian.PutUint64(record[8:16], (uint64(1)<<52)+3)
},
},
{
name: "LSN range overflow",
mutate: func(record []byte) {
binary.LittleEndian.PutUint64(record[0:8], ^uint64(0)-1)
},
},
{
name: "reserved length mismatch",
mutate: func(record []byte) {
binary.LittleEndian.PutUint64(record[8:16], 2)
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
const (
blockSize = 4096
blocks = 3
)
path := filepath.Join(t.TempDir(), "store.bin")
s, err := createLegacyWALStoreForTest(path, 16, blockSize)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
s.enableMultiBlockRecordsForTest(true)
if _, err := s.WriteBatch(4, [][]byte{
makeBlock(blockSize, 0xA1),
makeBlock(blockSize, 0xA2),
makeBlock(blockSize, 0xA3),
}); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
entry := recoverySnapshotEntriesByLBA(s.dm.snapshot())[4]
rewriteRecoveryRecordForTest(
t, s, uint64(walEntryHeaderSize+blocks*blockSize),
int64(s.sb.WALOffset+entry.WALOffset), tt.mutate,
)
crashRecoveryHardeningStore(t, s)
reopened, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
reopened.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = reopened.Close() })
recovered, recoverErr := reopened.Recover()
if recovered != 0 || !errors.Is(recoverErr, ErrWALIntegrityFault) {
t.Fatalf("Recover=%d err=%v want 0,WALIntegrity", recovered, recoverErr)
}
if got := reopened.dm.len(); got != 0 {
t.Fatalf("dirty entries from malformed batch=%d want 0", got)
}
if got := reopened.NextLSN(); got != 1 {
t.Fatalf("next LSN after malformed batch=%d want 1", got)
}
})
}
}
func TestWALStoreRecoverReconstructsLegacyWrappedRetainedWindow(t *testing.T) {
const (
blockSize = 4096
walSize = 24 * 1024
lowRecordSize = uint64(walEntryHeaderSize + 2*blockSize)
)
path := filepath.Join(t.TempDir(), "store.bin")
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
s.DisableAutoFlushForRecoveryTest()
for lba := uint32(0); lba < 3; lba++ {
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
high := makeBlock(blockSize, 0xA4)
if _, err := s.Write(20, high); err != nil {
t.Fatal(err)
}
s.enableMultiBlockRecordsForTest(true)
low := [][]byte{
makeBlock(blockSize, 0xB5),
makeBlock(blockSize, 0xB6),
}
if _, err := s.WriteBatch(24, low); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
entries := recoverySnapshotEntriesByLBA(s.dm.snapshot())
if entries[20].WALOffset != uint64(3*(walEntryHeaderSize+blockSize)) ||
entries[24].WALOffset != 0 {
t.Fatalf("high/low offsets=%d/%d want %d/0",
entries[20].WALOffset, entries[24].WALOffset,
3*(walEntryHeaderSize+blockSize))
}
legacy := *s.sb
legacy.WALHead = 0
legacy.WALTail = 0
buf := newSimpleByteBuf()
if _, err := legacy.writeTo(buf); err != nil {
t.Fatal(err)
}
if _, err := s.fd.WriteAt(buf.bytes(), 0); err != nil {
t.Fatal(err)
}
if err := s.fd.Sync(); err != nil {
t.Fatal(err)
}
crashRecoveryHardeningStore(t, s)
reopened, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
reopened.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = reopened.Close() })
if recovered, err := reopened.Recover(); err != nil || recovered != 6 {
t.Fatalf("Recover=%d err=%v want 6,nil", recovered, err)
}
wantTail := entries[20].WALOffset
wantHead := walSize + lowRecordSize
if tail, head := reopened.wal.logicalTailValue(), reopened.wal.logicalHeadValue(); tail != wantTail || head != wantHead {
t.Fatalf("recovered wrapped tail/head=%d/%d want %d/%d",
tail, head, wantTail, wantHead)
}
assertRecoveryHardeningBlock(t, reopened, 20, high)
assertRecoveryHardeningBlock(t, reopened, 24, low[0])
assertRecoveryHardeningBlock(t, reopened, 25, low[1])
postRecovery := makeBlock(blockSize, 0xC7)
finalLSN, err := reopened.Write(30, postRecovery)
if err != nil {
t.Fatal(err)
}
postEntry := recoverySnapshotEntriesByLBA(reopened.dm.snapshot())[30]
if postEntry.WALOffset != lowRecordSize {
t.Fatalf("post-recovery append offset=%d want %d",
postEntry.WALOffset, lowRecordSize)
}
if _, err := reopened.Sync(); err != nil {
t.Fatal(err)
}
if err := reopened.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
if got := reopened.CheckpointLSN(); got != finalLSN {
t.Fatalf("checkpoint=%d want %d", got, finalLSN)
}
if got := reopened.dm.len(); got != 0 {
t.Fatalf("dirty entries after wrapped flush=%d want 0", got)
}
wantFinalBoundary := wantHead + uint64(walEntryHeaderSize+blockSize)
if tail, head := reopened.wal.logicalTailValue(), reopened.wal.logicalHeadValue(); tail != wantFinalBoundary || head != wantFinalBoundary {
t.Fatalf("final wrapped tail/head=%d/%d want %d/%d",
tail, head, wantFinalBoundary, wantFinalBoundary)
}
assertRecoveryHardeningBlock(t, reopened, 20, high)
assertRecoveryHardeningBlock(t, reopened, 24, low[0])
assertRecoveryHardeningBlock(t, reopened, 25, low[1])
assertRecoveryHardeningBlock(t, reopened, 30, postRecovery)
}
func crashRecoveryHardeningStore(t *testing.T, s *WALStore) {
t.Helper()
s.committer.Stop()
@@ -1,64 +0,0 @@
package storage
import (
"path/filepath"
"testing"
)
// Recovery is last-writer-wins by LSN. Two valid versions of one LBA
// survive in the WAL; the persisted
// head/tail predate the wrap, so the range scanned first holds the newer
// version (wrapped to offset 0) and the range scanned later the older one.
// Recovery must still serve the newer bytes.
func TestWALStoreRecoverLastWriterWinsAcrossScanOrder(t *testing.T) {
const (
blockSize = 4096
walSize = 24 * 1024
)
path := filepath.Join(t.TempDir(), "store.bin")
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
s.DisableAutoFlushForRecoveryTest()
for lba := uint32(0); lba < 3; lba++ {
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.flusher.flushOnce(); err != nil { // checkpoint 3: head/tail persisted here
t.Fatal(err)
}
older := makeBlock(blockSize, 0xA4)
if _, err := s.Write(20, older); err != nil { // LSN 4, at the high end
t.Fatal(err)
}
newer := makeBlock(blockSize, 0xB5)
s.enableMultiBlockRecordsForTest(true)
if _, err := s.WriteBatch(20, [][]byte{newer, makeBlock(blockSize, 0xB6)}); err != nil { // LSN 5-6, wraps to 0
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if e := recoverySnapshotEntriesByLBA(s.dm.snapshot())[20]; e.WALOffset != 0 || e.LSN != 5 {
t.Fatalf("newest LBA 20 entry at offset %d LSN %d; want the wrapped batch at 0, LSN 5", e.WALOffset, e.LSN)
}
crashRecoveryHardeningStore(t, s)
r, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = r.Close() })
if _, err := r.Recover(); err != nil {
t.Fatal(err)
}
got, err := r.Read(20)
if err != nil {
t.Fatal(err)
}
if got[0] != newer[0] {
t.Fatalf("LBA 20 after recovery = %02x; want the newer version %02x (LSN 5), not the older %02x (LSN 4)", got[0], newer[0], older[0])
}
}
@@ -1,9 +1,5 @@
package storage
import (
"testing"
)
// G7-redo priority 2.5 — WAL recycle path consumes
// `MinPinAcrossActiveSessions()` from an external coordinator (today
// `core/recovery.PeerShipCoordinator`). These tests pin the substrate
@@ -29,139 +25,3 @@ type fakeRecycleFloorSource struct {
func (f *fakeRecycleFloorSource) MinPinAcrossActiveSessions() (uint64, bool) {
return f.floor, f.anyActive
}
// TestWALStore_RecycleGate_NilSource_LegacyBehavior pins fallback:
// when no source is installed (the daemon is in legacy mode, or
// dual-lane wiring opted out for this volume), persistCheckpoint
// advances exactly as it did before priority 2.5 landed.
func TestWALStore_RecycleGate_NilSource_LegacyBehavior(t *testing.T) {
ws := freshWALStore(t)
advanceCheckpointForTest(t, ws, 50) // start at checkpoint=50
// No source set → checkpoint advances to 100 unmodified.
if err := ws.persistCheckpoint(100); err != nil {
t.Fatalf("persistCheckpoint(100): %v", err)
}
if got := ws.CheckpointLSN(); got != 100 {
t.Errorf("CheckpointLSN = %d, want 100 (nil source = no clamp)", got)
}
}
// TestWALStore_RecycleGate_SourceInactive_LegacyBehavior pins the
// `(_, false)` branch: a source that reports "no active session"
// MUST NOT clamp. This is the steady-state (no rebuild in flight)
// path; legacy behavior is preserved.
func TestWALStore_RecycleGate_SourceInactive_LegacyBehavior(t *testing.T) {
ws := freshWALStore(t)
advanceCheckpointForTest(t, ws, 50)
src := &fakeRecycleFloorSource{floor: 60, anyActive: false}
ws.SetRecycleFloorSource(src)
// Even though src.floor=60 (< 100), anyActive=false → no clamp.
if err := ws.persistCheckpoint(100); err != nil {
t.Fatalf("persistCheckpoint(100): %v", err)
}
if got := ws.CheckpointLSN(); got != 100 {
t.Errorf("CheckpointLSN = %d, want 100 (anyActive=false bypasses gate)", got)
}
}
// TestWALStore_RecycleGate_SourceActive_ClampsAtFloor pins the
// headline behavior: an active session with floor=70 forces the
// effective checkpoint to 70 even though the flusher proposed 100.
// This is what holds the WAL retained for a replica that has
// committed pin_floor=70 in its rebuild session.
func TestWALStore_RecycleGate_SourceActive_ClampsAtFloor(t *testing.T) {
ws := freshWALStore(t)
advanceCheckpointForTest(t, ws, 50)
src := &fakeRecycleFloorSource{floor: 70, anyActive: true}
ws.SetRecycleFloorSource(src)
// Flusher proposes 100; gate clamps to 70.
if err := ws.persistCheckpoint(100); err != nil {
t.Fatalf("persistCheckpoint(100): %v", err)
}
if got := ws.CheckpointLSN(); got != 70 {
t.Errorf("CheckpointLSN = %d, want 70 (clamped to active pin floor)", got)
}
}
// TestWALStore_RecycleGate_FloorAboveProposed_NoClamp pins the
// "floor doesn't pull checkpoint forward" rule: when the source
// reports floor=200 but the flusher only has 100 ready, the
// effective checkpoint is the proposed 100 — the floor is an
// upper-bound gate, not a target.
func TestWALStore_RecycleGate_FloorAboveProposed_NoClamp(t *testing.T) {
ws := freshWALStore(t)
advanceCheckpointForTest(t, ws, 50)
src := &fakeRecycleFloorSource{floor: 200, anyActive: true}
ws.SetRecycleFloorSource(src)
// floor=200 >= proposed=100 → no clamp; checkpoint advances to 100.
if err := ws.persistCheckpoint(100); err != nil {
t.Fatalf("persistCheckpoint(100): %v", err)
}
if got := ws.CheckpointLSN(); got != 100 {
t.Errorf("CheckpointLSN = %d, want 100 (floor >= proposed → no clamp)", got)
}
}
// TestWALStore_RecycleGate_FloorBelowCurrentCheckpoint_NoRegress pins
// the monotonic invariant: even if the source reports a floor BELOW
// the current checkpoint (e.g., transient race during session
// install), persistCheckpoint must not regress checkpointLSN. The
// `if highestLSN <= s.checkpointLSN { return nil }` guard handles
// this — the post-clamp value just becomes a no-op rather than a
// rollback.
func TestWALStore_RecycleGate_FloorBelowCurrentCheckpoint_NoRegress(t *testing.T) {
ws := freshWALStore(t)
advanceCheckpointForTest(t, ws, 80) // current checkpoint = 80
// Active session reports floor=30 (below current). The clamp
// would set highestLSN=30, but the no-regress guard returns
// without changing checkpointLSN.
src := &fakeRecycleFloorSource{floor: 30, anyActive: true}
ws.SetRecycleFloorSource(src)
if err := ws.persistCheckpoint(100); err != nil {
t.Fatalf("persistCheckpoint(100): %v", err)
}
if got := ws.CheckpointLSN(); got != 80 {
t.Errorf("CheckpointLSN = %d, want 80 (must not regress under floor)", got)
}
}
// TestWALStore_RecycleGate_SetRecycleFloorSourceNil_Disables pins the
// disable path: passing nil to SetRecycleFloorSource removes the gate
// (used when the daemon transitions back to legacy mode, or when a
// volume is closing down a coordinator). After Set(nil), behavior
// matches the nil-source default.
func TestWALStore_RecycleGate_SetRecycleFloorSourceNil_Disables(t *testing.T) {
ws := freshWALStore(t)
advanceCheckpointForTest(t, ws, 50)
src := &fakeRecycleFloorSource{floor: 70, anyActive: true}
ws.SetRecycleFloorSource(src)
// First call clamps to 70.
if err := ws.persistCheckpoint(100); err != nil {
t.Fatalf("persistCheckpoint(100) [gated]: %v", err)
}
if got := ws.CheckpointLSN(); got != 70 {
t.Fatalf("CheckpointLSN = %d, want 70 (gated)", got)
}
// Disable the gate.
ws.SetRecycleFloorSource(nil)
// Second call advances unmodified.
if err := ws.persistCheckpoint(150); err != nil {
t.Fatalf("persistCheckpoint(150) [ungated]: %v", err)
}
if got := ws.CheckpointLSN(); got != 150 {
t.Errorf("CheckpointLSN = %d, want 150 (gate disabled)", got)
}
}
@@ -1,41 +1,9 @@
package storage
import (
"errors"
"path/filepath"
"testing"
)
// G6 §1.A α + §2 substrate retention-gate tests:
//
// Pre-G6: walstore's recovery scan rejects fromLSN <= checkpointLSN
// (strict gate; G5-5C scenario D evidence).
//
// G6: WALRetentionLSNs widens the window so fromLSN > (checkpointLSN
// - retention) is still scannable. This buys a slow replica room to
// catch up before the engine has to escalate to rebuild.
//
// Pinned by:
// - INV-G6-CATCHUP-CONVERGES-WITHIN-RETENTION (positive: within window
// scan succeeds)
// - INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE (the knob is a real
// operator-tunable plumbed from --wal-retention-lsns)
// freshWALStore creates a walstore in a temp dir and returns it.
// Uses small block geometry — the tests exercise scan-gate semantics,
// not block-IO performance.
func freshWALStore(t *testing.T) *WALStore {
t.Helper()
dir := t.TempDir()
path := filepath.Join(dir, "v.bin")
ws, err := createLegacyWALStoreForTest(path, 64, 4096)
if err != nil {
t.Fatalf("CreateWALStore: %v", err)
}
t.Cleanup(func() { _ = ws.Close() })
return ws
}
// advanceCheckpointForTest writes data to grow nextLSN, then forces
// the in-memory checkpointLSN to a chosen value so the test can
// exercise the retention gate at a known boundary. Test-only path —
@@ -62,122 +30,3 @@ func (c *recoveryEntryCounter) onEntry(RecoveryEntry) error {
c.count++
return nil
}
// TestWALStore_RecoveryRetention_Default_StrictRecycle pins pre-G6
// behavior under the new code: when WALRetentionLSNs is 0 (default),
// the gate behaves exactly as before — fromLSN <= checkpointLSN is
// rejected with WALRecycled.
func TestWALStore_RecoveryRetention_Default_StrictRecycle(t *testing.T) {
ws := freshWALStore(t)
advanceCheckpointForTest(t, ws, 100)
if got := ws.RecoveryRetentionLSNs(); got != 0 {
t.Fatalf("default retention = %d, want 0", got)
}
// fromLSN = 50 (well under checkpoint=100) must be recycled.
c := &recoveryEntryCounter{}
err := ws.ScanLBAs(50, c.onEntry)
if err == nil {
t.Fatal("fromLSN=50 with checkpoint=100 + retention=0 should be recycled")
}
if !errors.Is(err, ErrWALRecycled) {
t.Errorf("expected ErrWALRecycled (or unwrap chain match), got %v", err)
}
// fromLSN = 100 is at-or-below checkpoint → still recycled
// (boundary preserved: <= is rejected, > is accepted).
err = ws.ScanLBAs(100, c.onEntry)
if !errors.Is(err, ErrWALRecycled) {
t.Errorf("fromLSN=100 (== checkpoint) with retention=0 should be recycled, got %v", err)
}
}
// TestWALStore_RecoveryRetention_NonZero_WidensWindow verifies the
// G6 α path: setting retention=N accepts fromLSN as low as
// checkpointLSN - N (exclusive: at floor still rejected; above floor
// accepted).
func TestWALStore_RecoveryRetention_NonZero_WidensWindow(t *testing.T) {
ws := freshWALStore(t)
advanceCheckpointForTest(t, ws, 100)
ws.SetRecoveryRetentionLSNs(20)
if got := ws.RecoveryRetentionLSNs(); got != 20 {
t.Fatalf("retention after Set: got %d, want 20", got)
}
// floor = 100 - 20 = 80; fromLSN > 80 is accepted, fromLSN <= 80
// is rejected.
c := &recoveryEntryCounter{}
// fromLSN = 90: above floor → accepted (no error). The scan
// itself may produce no entries because we haven't written
// anything in the window; that's fine — this test only pins the
// gate decision, not scan content.
if err := ws.ScanLBAs(90, c.onEntry); err != nil {
t.Errorf("fromLSN=90 with checkpoint=100 + retention=20 should be accepted, got %v", err)
}
// fromLSN = 81: above floor (80) → accepted.
if err := ws.ScanLBAs(81, c.onEntry); err != nil {
t.Errorf("fromLSN=81 with checkpoint=100 + retention=20 should be accepted (floor=80), got %v", err)
}
// fromLSN = 80: at floor → rejected (<= floor recycles).
err := ws.ScanLBAs(80, c.onEntry)
if !errors.Is(err, ErrWALRecycled) {
t.Errorf("fromLSN=80 (==floor) should be recycled, got %v", err)
}
// fromLSN = 50: well below floor → rejected.
err = ws.ScanLBAs(50, c.onEntry)
if !errors.Is(err, ErrWALRecycled) {
t.Errorf("fromLSN=50 (<floor) should be recycled, got %v", err)
}
}
// TestWALStore_RecoveryRetention_LargerThanCheckpoint_ClampsToZero
// verifies the saturating-subtraction guard: if retention >=
// checkpoint, the floor saturates to 0 and any fromLSN > 0 is
// accepted.
func TestWALStore_RecoveryRetention_LargerThanCheckpoint_ClampsToZero(t *testing.T) {
ws := freshWALStore(t)
advanceCheckpointForTest(t, ws, 100)
ws.SetRecoveryRetentionLSNs(1_000_000) // way larger than checkpoint
c := &recoveryEntryCounter{}
// fromLSN = 1: floor saturates to 0; 1 > 0 → accepted.
if err := ws.ScanLBAs(1, c.onEntry); err != nil {
t.Errorf("fromLSN=1 with retention >> checkpoint should be accepted (floor saturates to 0), got %v", err)
}
}
// TestWALStore_RecoveryRetention_TypedFailureKind verifies that the
// recycle-rejection error is the typed RecoveryFailure envelope (so
// the transport layer can extract via errors.As). This pins the
// substrate side of INV-G6-WALRECYCLE-DISPATCHES-REBUILD: if the
// substrate returned a bare sentinel here, transport's
// classifyRecoveryFailure would fall through to RecoveryFailureTransport
// and the engine wouldn't escalate to rebuild.
func TestWALStore_RecoveryRetention_TypedFailureKind(t *testing.T) {
ws := freshWALStore(t)
advanceCheckpointForTest(t, ws, 100)
ws.SetRecoveryRetentionLSNs(20)
c := &recoveryEntryCounter{}
err := ws.ScanLBAs(50, c.onEntry) // below floor 80 → rejected
if err == nil {
t.Fatal("expected recycle error")
}
var rf *RecoveryFailure
if !errors.As(err, &rf) {
t.Fatalf("expected typed *RecoveryFailure (so transport can map kind via errors.As), got %T (%v)", err, err)
}
if rf.Kind != StorageRecoveryFailureWALRecycled {
t.Errorf("RecoveryFailure.Kind = %v, want StorageRecoveryFailureWALRecycled", rf.Kind)
}
// errors.Is chain still works for legacy callers.
if !errors.Is(err, ErrWALRecycled) {
t.Error("errors.Is(err, ErrWALRecycled) should still hold via Unwrap chain")
}
}
@@ -2,7 +2,7 @@ package storage
import (
"errors"
"path/filepath"
"testing"
)
@@ -24,107 +24,3 @@ func assertStickyFsync(t *testing.T, err error) {
t.Fatalf("err %v; want a SubstrateIO RecoveryFailure (io_error)", err)
}
}
func stickyStore(t *testing.T) (*WALStore, string) {
t.Helper()
path := filepath.Join(t.TempDir(), "store.bin")
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, 4096, 64*1024)
s.DisableAutoFlushForRecoveryTest()
if _, err := s.Write(0, makeBlock(4096, 0x10)); err != nil { // acked before the fault
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
return s, path
}
// assertRefusesAfterFault: no Sync ack (and no physical WAL fsync), no write,
// no checkpoint; a reopen clears it and keeps the data acked before the fault.
func assertRefusesAfterFault(t *testing.T, s *WALStore, path string) {
t.Helper()
before := s.WALSyncCount()
_, err := s.Sync()
assertStickyFsync(t, err)
if n := s.WALSyncCount() - before; n != 0 {
t.Fatalf("a Sync after the fault fsynced again (%d); it must refuse without retrying", n)
}
if _, err := s.Write(2, makeBlock(4096, 0x22)); err == nil {
t.Fatal("a write after an fsync failure was accepted")
} else {
assertStickyFsync(t, err)
}
if _, err := s.WriteBatch(3, [][]byte{makeBlock(4096, 0x33)}); err == nil {
t.Fatal("a batch write after an fsync failure was accepted")
}
ckpt := s.CheckpointLSN()
_ = s.flusher.flushOnce()
if got := s.CheckpointLSN(); got != ckpt {
t.Fatalf("the flusher advanced the checkpoint %d -> %d after an fsync failure", ckpt, got)
}
_ = s.Close()
r, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = r.Close() })
if _, err := r.Recover(); err != nil {
t.Fatalf("reopen after an fsync failure: %v", err)
}
assertRecoveryHardeningBlock(t, r, 0, makeBlock(4096, 0x10))
if _, err := r.Write(4, makeBlock(4096, 0x44)); err != nil {
t.Fatalf("write after a reopen: %v", err)
}
if _, err := r.Sync(); err != nil {
t.Fatalf("Sync after a reopen: %v", err)
}
}
func TestWALStoreWALFsyncFailureIsSticky(t *testing.T) {
s, path := stickyStore(t)
if _, err := s.Write(1, makeBlock(4096, 0x11)); err != nil {
t.Fatal(err)
}
real := s.syncWALFile
s.syncWALFile = func() error { return errInjectedFsync }
if _, err := s.Sync(); !errors.Is(err, errInjectedFsync) {
t.Fatalf("Sync with a failing fsync: %v", err)
}
s.syncWALFile = real // the disk "recovers": the next fsync would succeed
assertRefusesAfterFault(t, s, path)
}
func TestWALStoreExtentFsyncFailureIsSticky(t *testing.T) {
s, path := stickyStore(t)
if _, err := s.Write(1, makeBlock(4096, 0x11)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
real := s.syncExtentFile
s.syncExtentFile = func() error { return errInjectedFsync }
if err := s.flusher.flushOnce(); !errors.Is(err, errInjectedFsync) {
t.Fatalf("flush with a failing extent fsync: %v", err)
}
s.syncExtentFile = real
assertRefusesAfterFault(t, s, path)
}
func TestWALStoreCheckpointFsyncFailureIsSticky(t *testing.T) {
s, path := stickyStore(t)
if _, err := s.Write(1, makeBlock(4096, 0x11)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
real := s.syncSuperblockMetadata
s.syncSuperblockMetadata = func() error { return errInjectedFsync }
if err := s.flusher.flushOnce(); !errors.Is(err, errInjectedFsync) {
t.Fatalf("flush with a failing checkpoint fsync: %v", err)
}
s.syncSuperblockMetadata = real
assertRefusesAfterFault(t, s, path)
}
@@ -1,10 +1,8 @@
package storage
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
@@ -114,82 +112,6 @@ func startWorker(t workerTB, fn func() error, gates ...*gate) <-chan error {
return res
}
func heldStore(t *testing.T) (*WALStore, string) {
t.Helper()
path := filepath.Join(t.TempDir(), "store.bin")
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, 4096, 64*1024)
s.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { // runs after the workers' and gates' cleanups (LIFO)
if _, leaked := leakedStores.LoadAndDelete(t); leaked {
return // a worker is still inside the store: never close under it
}
_ = s.Close()
})
return s, path
}
func diskCheckpoint(t *testing.T, path string) uint64 {
t.Helper()
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
sb, err := readSuperblock(f)
if err != nil {
t.Fatal(err)
}
return sb.WALCheckpointLSN
}
// A Sync queued behind an fsync that then fails must not be acknowledged by
// a second fsync of the same batch run.
func TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused(t *testing.T) {
s, _ := heldStore(t)
if _, err := s.Write(0, makeBlock(4096, 0x10)); err != nil {
t.Fatal(err)
}
g := newGate(t)
real := s.syncWALFile
var calls atomic.Int32
fault := errors.New("injected fsync failure")
s.syncWALFile = func() error {
if calls.Add(1) == 1 {
g.block()
return fault
}
return real() // a later fsync would "succeed"
}
errA := startWorker(t, func() error {
_, err := s.Sync()
return err
}, g)
g.waitEntered(t, "Sync A's fsync")
if _, err := s.Write(1, makeBlock(4096, 0x11)); err != nil {
t.Fatal(err)
}
errB := startWorker(t, func() error {
_, err := s.Sync()
return err
}, g)
waitQueuedSync(t, s, 1) // B passed the entry check and waits in the committer
g.open()
if err := recvErr(t, errA, "Sync A"); !errors.Is(err, fault) {
t.Fatalf("Sync A: %v; want the injected fault", err)
}
if err := recvErr(t, errB, "Sync B"); !errors.Is(err, ErrFsyncFailed) {
t.Fatalf("queued Sync B after the failed fsync: %v; want ErrFsyncFailed", err)
}
if n := calls.Load(); n != 1 {
t.Fatalf("physical fsyncs=%d; want 1 (no fsync after the fault)", n)
}
if r, _, _ := s.Boundaries(); r != 0 {
t.Fatalf("published R=%d after the fault", r)
}
}
func waitQueuedSync(t *testing.T, s *WALStore, n int) {
t.Helper()
deadline := time.Now().Add(holdBound)
@@ -205,80 +127,6 @@ func waitQueuedSync(t *testing.T, s *WALStore, n int) {
t.Fatalf("no queued Sync after %v", holdBound)
}
// A writer admitted (past its entry check) while an append fails, and then
// waiting for the append lock, must not reuse the failed append's LSNs or
// offsets. One subtest per write path, each with its own oracle.
func TestWALStoreWritersQueuedBehindAFailedAppendAreRefused(t *testing.T) {
paths := []struct {
name string
run func(s *WALStore, lsn uint64) error
}{
{"Write", func(s *WALStore, _ uint64) error { _, err := s.Write(11, makeBlock(4096, 0xAC)); return err }},
{"WriteBatch", func(s *WALStore, _ uint64) error {
_, err := s.WriteBatch(20, [][]byte{makeBlock(4096, 0xAD)})
return err
}},
{"ApplyEntry", func(s *WALStore, lsn uint64) error { return s.ApplyEntry(21, makeBlock(4096, 0xAE), lsn) }},
}
for _, p := range paths {
t.Run(p.name, func(t *testing.T) {
s, _ := heldStore(t)
// WAL admission reads usage under the WAL writer's lock, which the
// held append owns; without it the queued writer reaches its
// admission point (and then the append lock) deterministically.
s.admission = nil
appendGate := newGate(t)
eio := errors.New("injected EIO after the batch bytes were written")
var batchCalls atomic.Int32
s.wal.batchWriteAt = func(b []byte, off int64) (int, error) {
if batchCalls.Add(1) == 1 {
appendGate.block()
}
n, _ := s.fd.WriteAt(b, off)
return n, eio
}
nextBefore := s.NextLSN()
headBefore := s.wal.logicalHeadValue()
errA := startWorker(t, func() error {
_, err := s.WriteBatch(10, [][]byte{makeBlock(4096, 0x5B), makeBlock(4096, 0x5A)})
return err
}, appendGate)
appendGate.waitEntered(t, "the failing batch append")
// The queued writer acknowledges that it passed its entry check
// before the fault exists, then waits for the append lock.
admitted := make(chan struct{})
var admitOnce sync.Once
s.testAfterAdmit = func() { admitOnce.Do(func() { close(admitted) }) }
errB := startWorker(t, func() error { return p.run(s, nextBefore) }, appendGate)
select {
case <-admitted:
case <-time.After(holdBound):
t.Fatalf("%s was never admitted", p.name)
}
appendGate.open()
if err := recvErr(t, errA, "the failing batch"); !errors.Is(err, eio) {
t.Fatalf("failing batch: %v", err)
}
if err := recvErr(t, errB, p.name); !errors.Is(err, ErrAppendFailed) {
t.Fatalf("%s admitted before the fault: %v; want ErrAppendFailed", p.name, err)
}
s.testAfterAdmit = nil
if n := batchCalls.Load(); n != 1 {
t.Fatalf("batch pwrites=%d; want 1 (no append after the fault)", n)
}
if got := s.NextLSN(); got != nextBefore {
t.Fatalf("NextLSN %d -> %d after a refused %s", nextBefore, got, p.name)
}
if got := s.wal.logicalHeadValue(); got != headBefore {
t.Fatalf("WAL head %d -> %d after a refused %s", headBefore, got, p.name)
}
})
}
}
// heldMetadata blocks BeforeCheckpointAdvance once armed.
type heldMetadata struct {
armed atomic.Bool
@@ -294,100 +142,6 @@ func (m *heldMetadata) BeforeCheckpointAdvance(uint64) error {
return nil
}
// A direct-frontier publication must not complete after the flusher's
// extent fsync failed, even when that failure lands while the publication
// is past its fault check (in its metadata barrier).
func TestWALStoreExtentFsyncFaultDuringDirectFrontierPublication(t *testing.T) {
s, path := heldStore(t)
meta := &heldMetadata{g: newGate(t)}
s.metadata = meta
if _, err := s.Write(0, makeBlock(4096, 0x10)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
ckptBefore, diskBefore := s.CheckpointLSN(), diskCheckpoint(t, path)
extentGate := newGate(t)
eio := errors.New("injected extent fsync failure")
s.syncExtentFile = func() error { extentGate.block(); return eio }
errFlush := startWorker(t, func() error { return s.flusher.flushOnce() }, extentGate, meta.g)
extentGate.waitEntered(t, "the flusher's extent fsync")
meta.armed.Store(true)
s.AdvanceFrontier(10)
errSync := startWorker(t, func() error {
_, err := s.Sync()
return err
}, extentGate, meta.g)
inBarrier := meta.g.enteredWithin(300 * time.Millisecond)
extentGate.open() // the extent fsync fails and latches the fault
if err := recvErr(t, errFlush, "the flush"); !errors.Is(err, eio) {
t.Fatalf("flush: %v; want the injected extent fault", err)
}
meta.g.open()
err := recvErr(t, errSync, "the direct-frontier Sync")
t.Logf("Sync reached its metadata barrier before the fault: %t", inBarrier)
if !errors.Is(err, ErrFsyncFailed) {
t.Fatalf("direct-frontier Sync after the extent fsync failed: %v; want ErrFsyncFailed", err)
}
if got := s.CheckpointLSN(); got != ckptBefore {
t.Fatalf("checkpoint %d -> %d after the fault", ckptBefore, got)
}
if got := diskCheckpoint(t, path); got != diskBefore {
t.Fatalf("superblock checkpoint %d -> %d after the fault", diskBefore, got)
}
}
// A checkpoint publication must not complete after a WAL fsync failed, even
// when that failure lands while the flusher is past its fault check (in its
// metadata barrier).
func TestWALStoreWALFsyncFaultDuringCheckpointPublication(t *testing.T) {
s, path := heldStore(t)
meta := &heldMetadata{g: newGate(t)}
s.metadata = meta
if _, err := s.Write(0, makeBlock(4096, 0x10)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if _, err := s.Write(1, makeBlock(4096, 0x11)); err != nil { // dirty WAL
t.Fatal(err)
}
ckptBefore, diskBefore := s.CheckpointLSN(), diskCheckpoint(t, path)
walGate := newGate(t)
fault := errors.New("injected WAL fsync failure")
s.syncWALFile = func() error { walGate.block(); return fault }
errSync := startWorker(t, func() error {
_, err := s.Sync()
return err
}, walGate, meta.g)
walGate.waitEntered(t, "the WAL fsync")
meta.armed.Store(true)
errFlush := startWorker(t, func() error { return s.flusher.flushOnce() }, walGate, meta.g)
inBarrier := meta.g.enteredWithin(300 * time.Millisecond)
walGate.open() // the WAL fsync fails and latches the fault
if err := recvErr(t, errSync, "the Sync"); !errors.Is(err, fault) {
t.Fatalf("Sync: %v; want the injected WAL fault", err)
}
meta.g.open()
err := recvErr(t, errFlush, "the flush")
t.Logf("the flusher reached its metadata barrier before the fault: %t", inBarrier)
if !errors.Is(err, ErrFsyncFailed) {
t.Fatalf("flush after the WAL fsync failed: %v; want ErrFsyncFailed", err)
}
if got := s.CheckpointLSN(); got != ckptBefore {
t.Fatalf("checkpoint %d -> %d after the fault", ckptBefore, got)
}
if got := diskCheckpoint(t, path); got != diskBefore {
t.Fatalf("superblock checkpoint %d -> %d after the fault", diskBefore, got)
}
}
// extentHeldMetadata blocks the first OnExtentWrite (the flusher after its
// snapshot, before its extent fsync) and, once armed, BeforeCheckpointAdvance.
type extentHeldMetadata struct {
@@ -411,135 +165,6 @@ func (m *extentHeldMetadata) BeforeCheckpointAdvance(uint64) error {
return nil
}
// The fault check at the publication's own superblock fsync: a direct-
// frontier Sync is already in its metadata barrier (past every earlier
// check) when the flusher's extent fsync fails; its superblock publication
// must be refused.
func TestWALStoreExtentFsyncFaultAfterThePublicationCheck(t *testing.T) {
s, path := heldStore(t)
meta := &extentHeldMetadata{extent: newGate(t), barrier: newGate(t)}
s.metadata = meta
if _, err := s.Write(1, makeBlock(4096, 0x11)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
ckptBefore, diskBefore := s.CheckpointLSN(), diskCheckpoint(t, path)
errFlush := startWorker(t, func() error { return s.flusher.flushOnce() }, meta.extent, meta.barrier)
meta.extent.waitEntered(t, "the flusher's extent write") // before its extent fsync
meta.armed.Store(true)
s.AdvanceFrontier(10)
errSync := startWorker(t, func() error {
_, err := s.Sync()
return err
}, meta.extent, meta.barrier)
meta.barrier.waitEntered(t, "the Sync's metadata barrier") // past the store-lock check
eio := errors.New("injected extent fsync failure")
s.syncExtentFile = func() error { return eio }
meta.extent.open()
if err := recvErr(t, errFlush, "the flush"); !errors.Is(err, eio) {
t.Fatalf("flush: %v; want the injected extent fault", err)
}
meta.barrier.open()
if err := recvErr(t, errSync, "the direct-frontier Sync"); !errors.Is(err, ErrFsyncFailed) {
t.Fatalf("Sync whose barrier outlived the extent fault: %v; want ErrFsyncFailed", err)
}
if got := s.CheckpointLSN(); got != ckptBefore {
t.Fatalf("checkpoint %d -> %d after the fault", ckptBefore, got)
}
if got := diskCheckpoint(t, path); got != diskBefore {
t.Fatalf("superblock checkpoint %d -> %d after the fault", diskBefore, got)
}
}
// No two fsyncs of the store's file overlap: an extent fsync waits for a
// WAL fsync in flight (so a failure of either is latched before the other
// can complete as a success).
func TestWALStoreFsyncsOfTheFileAreSerialized(t *testing.T) {
s, _ := heldStore(t)
if _, err := s.Write(0, makeBlock(4096, 0x10)); err != nil {
t.Fatal(err)
}
walGate := newGate(t)
real := s.syncWALFile
s.syncWALFile = func() error { walGate.block(); return real() }
errSync := startWorker(t, func() error {
_, err := s.Sync()
return err
}, walGate)
walGate.waitEntered(t, "the WAL fsync")
extentEntered := make(chan struct{})
var once sync.Once
realExtent := s.syncExtentFile
s.syncExtentFile = func() error { once.Do(func() { close(extentEntered) }); return realExtent() }
arrived := make(chan struct{})
var arriveOnce sync.Once
s.testBeforeFileSync = func() { arriveOnce.Do(func() { close(arrived) }) } // the next syncFile caller: the flusher
errFlush := startWorker(t, func() error { return s.flusher.flushOnce() }, walGate)
select { // the flusher reached the serialization boundary...
case <-arrived:
case <-time.After(holdBound):
t.Fatal("the flusher never reached the file sync boundary")
}
select { // ...and does not pass it while the WAL fsync is in flight
case <-extentEntered:
t.Fatal("the extent fsync ran while a WAL fsync of the same file was in flight")
case <-time.After(100 * time.Millisecond):
}
walGate.open()
if err := recvErr(t, errSync, "the Sync"); err != nil {
t.Fatal(err)
}
if err := recvErr(t, errFlush, "the flush"); err != nil {
t.Fatal(err)
}
select {
case <-extentEntered:
default:
t.Fatal("the extent fsync never ran")
}
}
// The failure path's cleanup settles: a test that stops (here SkipNow, which
// ends the test the same way as Fatal) while a worker is held inside the
// store still opens the gate, joins the worker and then closes the store.
func TestWALStoreHeldWorkersSettleOnAFailurePath(t *testing.T) {
var s *WALStore
var res <-chan error
t.Run("stops-while-held", func(t *testing.T) {
s, _ = heldStore(t)
if _, err := s.Write(0, makeBlock(4096, 0x10)); err != nil {
t.Fatal(err)
}
g := newGate(t)
// After its gate opens the flush still takes a while, so only a
// cleanup that joins it (not one that just opens the gate) sees it end.
s.syncExtentFile = func() error { g.block(); time.Sleep(200 * time.Millisecond); return nil }
res = startWorker(t, func() error { return s.flusher.flushOnce() }, g)
g.waitEntered(t, "the held flush")
t.SkipNow() // leaves the flush held inside the store
})
select {
case err := <-res:
if err != nil {
t.Fatalf("held flush after cleanup: %v", err)
}
default:
t.Fatal("cleanup returned while the held flush was still running")
}
s.mu.RLock()
closed := s.closed
s.mu.RUnlock()
if !closed {
t.Fatal("cleanup did not close the store")
}
}
// leakRecorder records cleanups and errors in place of a *testing.T.
type leakRecorder struct {
mu sync.Mutex
@@ -1,9 +1,8 @@
package storage
import (
"bytes"
"errors"
"io"
"path/filepath"
"sync/atomic"
"testing"
@@ -178,43 +177,6 @@ func TestWALGenerationSyncFailureAndShutdown(t *testing.T) {
}
}
func TestWALGenerationBypassesUntrackedMutationPaths(t *testing.T) {
for _, kind := range []string{"old LSN apply", "direct extent", "direct frontier", "chunk layer"} {
t.Run(kind, func(t *testing.T) {
s := newLegacyGenerationStore(t)
if _, err := s.Write(0, makeBlock(4096, 0x81)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
before := s.WALSyncCount()
switch kind {
case "old LSN apply":
if err := s.ApplyEntry(0, makeBlock(4096, 0x82), 1); err != nil {
t.Fatal(err)
}
case "direct extent":
if err := s.WriteExtentDirect(1, makeBlock(4096, 0x83)); err != nil {
t.Fatal(err)
}
case "direct frontier":
s.AdvanceFrontier(5)
case "chunk layer":
mustAttach(t, s, newFakeChunkRemote(), ctConfig(1))
}
for i := 0; i < 2; i++ {
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
}
if n := s.WALSyncCount() - before; n != 2 {
t.Fatalf("bypass physical syncs=%d want 2", n)
}
})
}
}
func TestWALGenerationBatchPublication(t *testing.T) {
for _, multi := range []bool{false, true} {
t.Run(map[bool]string{false: "normal records", true: "multiblock record"}[multi], func(t *testing.T) {
@@ -241,78 +203,6 @@ func TestWALGenerationBatchPublication(t *testing.T) {
}
}
// An actual partial pwrite leaves a valid first record and a torn second record,
// but appendBatch returns before publishing its planned head. Same-open Recover
// must not let the prefix reuse the pre-failure durable generation.
func TestWALGenerationPartialAppendRecoverySync(t *testing.T) {
for _, recoverFirst := range []bool{false, true} {
t.Run(map[bool]string{false: "failed append without recovery", true: "same-open recovery"}[recoverFirst], func(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, 4096, 1<<20)
s.DisableAutoFlushForRecoveryTest()
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
beforeHead := s.wal.logicalHeadValue()
want := makeBlock(4096, 0xa7)
pwriteCalls := 0
s.wal.batchWriteAt = func(data []byte, off int64) (int, error) {
pwriteCalls++
limit := walEntryHeaderSize + 4096 + walEntryHeaderSize + 17
if len(data) <= limit {
return 0, errors.New("fixture needs two whole records")
}
n, err := s.fd.WriteAt(data[:limit], off)
if err != nil {
return n, err
}
return n, io.ErrShortWrite
}
_, err := s.WriteBatch(0, [][]byte{want, makeBlock(4096, 0xb8)})
s.wal.batchWriteAt = nil
if !errors.Is(err, io.ErrShortWrite) || pwriteCalls != 1 {
t.Fatalf("partial batch err=%v pwrite calls=%d", err, pwriteCalls)
}
if got := s.wal.logicalHeadValue(); got != beforeHead {
t.Fatalf("failed batch published head=%d want %d", got, beforeHead)
}
// The failed append is sticky (ErrAppendFailed): no same-open
// recovery, and no Sync acknowledges anything, without an fsync.
if recoverFirst {
if _, err := s.Recover(); !errors.Is(err, ErrAppendFailed) {
t.Fatalf("same-open Recover after a failed append: %v; want ErrAppendFailed", err)
}
}
before := s.WALSyncCount()
if _, err := s.Sync(); !errors.Is(err, ErrAppendFailed) {
t.Fatalf("Sync after a failed append: %v; want ErrAppendFailed", err)
}
if n := s.WALSyncCount() - before; n != 0 {
t.Fatalf("a refused Sync fsynced %d times", n)
}
crashRecoveryHardeningStore(t, s)
// A reopen may republish the failed batch's complete prefix (it
// was never acknowledged) and serves normally again.
r, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
r.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = r.Close() })
if n, err := r.Recover(); err != nil || n != 1 {
t.Fatalf("reopen Recover=%d err=%v want 1,nil", n, err)
}
if got, err := r.Read(0); err != nil || !bytes.Equal(got, want) {
t.Fatalf("valid prefix not recovered: err=%v", err)
}
if _, err := r.Sync(); err != nil {
t.Fatalf("Sync after a reopen: %v", err)
}
})
}
}
// Even unchanged recovery must invalidate the prior open-instance coverage;
// its next successful sync may then be reused normally, not permanently bypassed.
func TestWALGenerationSameOpenRecoverInvalidatesCoverage(t *testing.T) {
@@ -360,17 +250,3 @@ func TestWALGenerationSameOpenRecoverInvalidatesCoverage(t *testing.T) {
t.Fatalf("Recover permanently disabled dedup: syncs=%d want1", n)
}
}
// TODO(format-v3 row 14a): v2 callback-cache / direct-mutation controls only.
func newLegacyGenerationStore(t *testing.T) *WALStore {
t.Helper()
// This control holds the standalone WAL fsync seam. Mode A retains
// that phase; mode C combines WAL durability with descriptor publication.
s, err := createLegacyWALStoreWithOptions(filepath.Join(t.TempDir(), "store.bin"), 32, 4096, WALStoreOptions{WMode: WModeStrict})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.DisableAutoFlushForRecoveryTest()
return s
}
+1 -142
View File
@@ -2,70 +2,13 @@ package storage
import (
"bytes"
"errors"
"os"
"path/filepath"
"sync"
"testing"
)
func TestWALStore_FailedAppendDoesNotConsumeLSN(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
bad, err := os.CreateTemp(t.TempDir(), "closed-wal")
if err != nil {
t.Fatal(err)
}
if err := bad.Close(); err != nil {
t.Fatal(err)
}
s.wal.fd = bad
if _, err := s.Write(0, makeBlock(4096, 0xA1)); err == nil {
t.Fatal("Write with closed WAL fd succeeded")
}
if got := s.NextLSN(); got != 1 {
t.Fatalf("NextLSN after failed append=%d want 1", got)
}
// A failed append is sticky (ErrAppendFailed): no later write reuses
// its LSN on this open store, single or batch.
s.wal.fd = s.fd
if _, err := s.Write(0, makeBlock(4096, 0xA2)); !errors.Is(err, ErrAppendFailed) {
t.Fatalf("Write after a failed append: %v; want ErrAppendFailed", err)
}
if _, err := s.WriteBatch(1, [][]byte{makeBlock(4096, 0xC1), makeBlock(4096, 0xC2)}); !errors.Is(err, ErrAppendFailed) {
t.Fatalf("WriteBatch after a failed append: %v; want ErrAppendFailed", err)
}
if got := s.NextLSN(); got != 1 {
t.Fatalf("NextLSN after refused appends=%d want 1", got)
}
_ = s.Close()
// A reopen starts from what is on disk (nothing of the failed append):
// the first write gets LSN 1, the next batch LSNs 2 and 3.
r, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = r.Close() })
if _, err := r.Recover(); err != nil {
t.Fatal(err)
}
lsn, err := r.Write(0, makeBlock(4096, 0xA2))
if err != nil || lsn != 1 {
t.Fatalf("first write after a reopen LSN=%d err=%v want 1", lsn, err)
}
lsns, err := r.WriteBatch(1, [][]byte{makeBlock(4096, 0xC1), makeBlock(4096, 0xC2)})
if err != nil || len(lsns) != 2 || lsns[0] != 2 || lsns[1] != 3 {
t.Fatalf("batch after a reopen LSNs=%v err=%v want [2 3]", lsns, err)
}
}
func TestWALStore_SyncDoesNotClaimConcurrentWrite(t *testing.T) {
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
@@ -111,90 +54,6 @@ func TestWALStore_SyncDoesNotClaimConcurrentWrite(t *testing.T) {
}
}
func TestWALStore_DirectFrontierMetadataFailureRetainsRetryState(t *testing.T) {
path := filepath.Join(t.TempDir(), "store.bin")
s, err := createLegacyWALStoreForTest(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.DisableAutoFlushForRecoveryTest()
if _, err := s.Write(0, makeBlock(4096, 0xA1)); err != nil {
t.Fatal(err)
}
s.AdvanceFrontier(10)
savedSync := s.syncDirectFrontierMetadata
s.syncDirectFrontierMetadata = func([]byte) error {
return errors.New("injected superblock sync failure")
}
if _, err := s.Sync(); err == nil {
t.Fatal("Sync with injected metadata failure succeeded")
}
if s.checkpointLSN != 0 {
t.Fatalf("checkpointLSN=%d want 0 after failed metadata sync", s.checkpointLSN)
}
if s.pendingDirectFrontierLSN != 10 {
t.Fatalf("pendingDirectFrontierLSN=%d want retry target 10", s.pendingDirectFrontierLSN)
}
if R, _, _ := s.Boundaries(); R != 0 {
t.Fatalf("durable frontier=%d want 0 after failed metadata sync", R)
}
// The failed fsync is sticky (ErrFsyncFailed): the retry is refused, the
// in-memory frontier is never published, and a reopen starts from what
// is on disk.
s.syncDirectFrontierMetadata = savedSync
if _, err := s.Sync(); !errors.Is(err, ErrFsyncFailed) {
t.Fatalf("retry after a failed metadata fsync: %v; want ErrFsyncFailed", err)
}
if s.checkpointLSN != 0 {
t.Fatalf("refused retry published checkpoint %d", s.checkpointLSN)
}
_ = s.Close()
reopened, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
reopenedOpen := true
t.Cleanup(func() {
if reopenedOpen {
_ = reopened.Close()
}
})
if _, err := reopened.Recover(); err != nil {
t.Fatal(err)
}
if got := reopened.CheckpointLSN(); got != 0 {
t.Fatalf("reopened checkpointLSN=%d want 0 (the frontier was never durable)", got)
}
if reopened.wal.logicalHeadValue() == 0 {
t.Fatal("recovery did not reconstruct the WAL head of the LSN 1 record")
}
reopened.AdvanceFrontier(10)
frontier, err := reopened.Sync()
if err != nil || frontier != 10 || reopened.CheckpointLSN() != 10 {
t.Fatalf("frontier after a reopen=%d checkpoint=%d err=%v want 10/10", frontier, reopened.CheckpointLSN(), err)
}
if got, want := reopened.sb.WALHead, reopened.wal.logicalHeadValue(); got != want || got == 0 {
t.Fatalf("superblock WALHead byte cursor=%d want %d (nonzero)", got, want)
}
reopened.committer.Stop()
_ = reopened.fd.Close() // crash
reopenedOpen = false
again, err := openLegacyWALStoreForTest(path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = again.Close() })
if _, err := again.Recover(); err != nil {
t.Fatal(err)
}
if got := again.CheckpointLSN(); got != 10 {
t.Fatalf("checkpoint after a crash=%d want the durable frontier 10", got)
}
}
// TestWALStore_WriteSyncCloseReopenRead is the headline acceptance:
// a clean Sync → Close → Open → Recover round-trip preserves every
// acked block.
+3 -8
View File
@@ -136,15 +136,10 @@ type walStoreV3State struct {
// of its target and its completion; nothing is acknowledged.
var errV3RecoveredMeanwhile = errors.New("storage: v3 recovery ran meanwhile; the Sync is not acknowledged")
// errV3LegacySuperblockWrite: a legacy superblock write (offset 0, which is
// descriptor slot A on a v3 file) was attempted on a v3 store.
var errV3LegacySuperblockWrite = errors.New("storage: legacy superblock write refused on a v3 store (offset 0 is descriptor slot A)")
var errV3NotYet = errors.New("storage: operation not yet supported on a v3 store (later plan row)")
// ErrUnsupportedLegacyFormat requires offline migration or workspace restore;
// a production open never interprets a v2 volume as v3.
var ErrUnsupportedLegacyFormat = errors.New("storage: unsupported legacy walstore format; migrate offline or restore into a new volume")
// ErrUnsupportedLegacyFormat refuses v2 files without an in-place upgrade.
var ErrUnsupportedLegacyFormat = errors.New("storage: unsupported legacy walstore format; restore into a new volume")
func refuseLegacyWALStore(f *os.File) error {
if sb, err := readSuperblock(io.NewSectionReader(f, 0, superblockSize)); err == nil && sb.Version == 2 && sb.validate() == nil {
@@ -412,7 +407,7 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO
return nil, err
}
}
s, err := openInitializedInternal(path, f, &sb, metadata, func(s *WALStore) error {
s, err := openInitializedV3(path, f, &sb, metadata, func(s *WALStore) error {
v := &walStoreV3State{}
v.pub = newDescriptorPublisherV3(d, id, other, descriptorIOV3{
writeSlot: func(off int64, buf []byte) error {
+30 -30
View File
@@ -13,7 +13,7 @@ The design is described in three documents, and this one collects their machines
- Status:
- `ACTIVE`: a Go test in this repository asserts the statement.
- `STUB`: the code enforces the statement (by reading), but no test asserts it yet. A release note must not claim behaviour backed only by a `STUB` row.
- `ARCHIVED`: a retired row, kept with its reason. There are none yet.
- `ARCHIVED`: a retired row, kept with its reason. The retired v2 converter is archived.
- The rule carried over from the internal ledger still applies: an invariant without a test is a wish, not an invariant.
## Contents
@@ -55,17 +55,17 @@ stateDiagram-v2
|---|---|---|---|---|
| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` |
| Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` |
| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` |
| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` |
| Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` |
| Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001` |
| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse (C11 bitmap/superblock path remains legacy-fixture-only) | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001` |
| Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `noteAppendFailure`, `syncFile` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` |
| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001` |
| Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`; `core/storage/walstore_v3.go` `appendWriteV3` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` |
| FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` |
| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — |
Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestCheckpointDiagnostics_RefusalThenSuccess`, `TestCheckpointDiagnostics_PrepareRefusalAndIOFailure`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged.
The v2 writer, scanner, checkpoint path, C11 codec/reconciler and in-place converter are retired. Native map and descriptor rules remain enforced; v2 inputs refuse open without mutation. `TestNativeReplacementLegacyBytesRefusedWithoutMutation` and `TestChunkAttachRefusesAnUnmappedNativeStore` cover these admission boundaries. The receiver session bitmap is separate and unchanged.
Public walstore Create now selects mapped format v3/impl3 (mode C by default, mode A by create option). Open and offline readonly use A/B slot and owned-map validation; valid legacy formats are refused with `ErrUnsupportedLegacyFormat`, rather than silently retrofitted. The temporary old-engine/raw-codec test scope and every named native replacement are recorded in [the legacy inventory](format-v3-legacy-test-inventory.md). Native recovery validates nonce/cursor binding and a contiguous physical LSN prefix before applying the mode-specific W rule; an acknowledged-range integrity failure blocks startup. The provider's create geometry, auto probe, capture, HEAD restore and readonly/status controls exercise the public selector (`INV-WAL-V3-ACTIVATION-001`). Before reading v3 slots, both read/write and offline read-only open acquire an exclusive nonblocking file lock; the offline migration CLI acquires the same lock before any descriptor read or mutation (`INV-WAL-V3-OWNER-001`). Contention refuses open/migration without changing bytes; descriptor close or process exit releases ownership. This implements the existing offline-migration precondition, not a new serving state. The mapped v3 checkpoint also carries a complete-record physical tail through the covered LSN minus the configured retention window; partial batches remain retained. The existing sole publisher then performs metadata-only rollover when the fallback still pins that prefix. Reuse still requires both valid same-nonce slot tails and retirement of checkpointed dirty references under writer exclusion; idle, unchanged-checkpoint and admission paths also settle a pinned fallback. An unlocked catch-up scan revalidates the coherent checkpoint and tail before emitting anything. A failed rollover latches and grants no reuse (`INV-WAL-V3-RECLAIM-001`).
Public walstore Create now selects mapped format v3/impl3 (mode C by default, mode A by create option). Open and offline readonly use A/B slot and owned-map validation; valid legacy formats are refused with `ErrUnsupportedLegacyFormat`, rather than silently retrofitted. The temporary old-engine/raw-codec test scope and every named native replacement are recorded in [the legacy inventory](format-v3-legacy-test-inventory.md). Native recovery validates nonce/cursor binding and a contiguous physical LSN prefix before applying the mode-specific W rule; an acknowledged-range integrity failure blocks startup. The provider's create geometry, auto probe, capture, HEAD restore and readonly/status controls exercise the public selector (`INV-WAL-V3-ACTIVATION-001`). Before reading v3 slots, both read/write and offline read-only open acquire an exclusive nonblocking file lock (`INV-WAL-V3-OWNER-001`). Contention refuses open without changing bytes; descriptor close or process exit releases ownership. The offline converter is retired; legacy volumes refuse open unchanged. The mapped v3 checkpoint also carries a complete-record physical tail through the covered LSN minus the configured retention window; partial batches remain retained. The existing sole publisher then performs metadata-only rollover when the fallback still pins that prefix. Reuse still requires both valid same-nonce slot tails and retirement of checkpointed dirty references under writer exclusion; idle, unchanged-checkpoint and admission paths also settle a pinned fallback. An unlocked catch-up scan revalidates the coherent checkpoint and tail before emitting anything. A failed rollover latches and grants no reuse (`INV-WAL-V3-RECLAIM-001`).
Recovery warnings such as `wal_hole_suspected` are recorded in Serving without changing health (`INV-WAL-WARN-NO-HEALTH-001`). The open gaps of this machine (a corrupted synced record mid-history only warns; forged records in user data) are listed in the [core known issues](block-design.md#24-known-issues-and-work-in-progress) and are not ledger rows.
@@ -205,7 +205,7 @@ A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. Th
```mermaid
stateDiagram-v2
[*] --> Admit
Admit --> Refused: budget refused, closed, fenced, detached, base install, reconciling, or lineage or lease invalid
Admit --> Refused: budget refused, closed, fenced, detached, base install, or lineage or lease invalid
Admit --> Stage: budget admitted, earlier unknown CAS settled
Stage --> Quiesce: spill-budget remainder reached or no shrink
Quiesce --> OpenWindow: Sync H and D fixed under barrier
@@ -230,18 +230,18 @@ stateDiagram-v2
| Step | Guard | Enforced in | Protects |
|---|---|---|---|
| Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease); no cut while reconciling | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-CUT-RECONCILING-001`, `INV-WS-LEASE-001` |
| Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease) | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-WS-LEASE-001` |
| Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` |
| Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001` |
| Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` |
| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` |
| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` |
| LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` |
| Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after one durable intent per cut or staging round names all candidate keys; an immutable slot retries through transient failures until cancellation or its object deadline | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` |
| Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` |
| No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001` |
| Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-WS-HEAD-CAS-001` |
| CAS | conditional update on `{gen, epoch}`, with `RemoteLSN = H`; refused for a lower epoch, a lower `RemoteLSN`, or a HEAD in a delete state | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001`, `INV-HEAD-DELETE-FROZEN-001` |
| Settled | drop the intents; reset the bitmap to the cut, keeping chunks dirtied after it; a refused current-lineage point retains intent-rooted completed uploads until reuse, supersession or clean Close (unresolved CAS roots excluded) | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` |
| Settled | drop the intents; settle native map capture tokens, keeping chunks dirtied after the cut; a refused current-lineage point retains intent-rooted completed uploads until reuse, supersession or clean Close (unresolved CAS roots excluded) | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` |
| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` |
### M6 Chunk lifecycle
@@ -342,20 +342,20 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status |
|---|---|---|---|---|---|---|
| `INV-REBUILD-SNAPSHOT-COMPLETE-001` | A rebuild snapshot returns all readable nonzero blocks or an error, never a partial success. The sender propagates snapshot failure before shipping blocks or RebuildDone. | M3 NeedsRebuild (base enumeration) | `core/storage/logical_storage.go` `AllBlocks`; storage implementations; `core/transport/rebuild_sender.go` `doRebuild` | `TestChunkHydration_SnapshotFailsOnReadError`, `TestRebuildSnapshotErrorNeverShipsPartialImage` | Existing fail-closed recovery contract; error propagation only | ACTIVE |
| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE |
| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `TestNativeReplacementTornWrapKeepsAcknowledgedSuffix` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE |
| `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE |
| `INV-FE-NVME-READY-001` | Reads and writes on successfully recovered chunk volumes awaiting attachment wait up to 3s (or an earlier caller deadline) for attachment readiness before storage admission; NVMe readiness timeout/refusal returns Namespace Not Ready (SC0x82), DNR=0, without reading or mutating storage; closed/stale lineage retain their ANA errors and physical I/O faults retain Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable`; `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` | — | ACTIVE |
| `INV-WAL-REPLAY-LWW-001` | Replay applies the highest LSN per LBA, independent of the physical scan order. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALStoreRecoverLastWriterWinsAcrossScanOrder` (`core/storage/walstore_recovery_lww_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE |
| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the on-disk superblock has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_writer.go` `spaceUsed`, `tailPersisted`; `core/storage/walstore.go` `persistCheckpointReleasing` | `TestWALWriterReuseIsBoundedByTheDurableTail`, `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE |
| `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherSnapshotCutPreservesSyncedWrites` (`core/storage/flusher_snapshot_cut_test.go`); `TestWALStoreCheckpointSIGKILLCrashWindows` (`core/storage/walstore_checkpoint_crash_linux_test.go`) | `WALRecovery` `I1` | ACTIVE |
| `INV-WAL-FRONTIER-GAP-001` | Synced entries above an intentional LSN gap (a rebuild's frontier jump) are kept by recovery. | M1 Recovering | `core/storage/recovery.go` `recoverWAL` | `TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump` (`core/storage/walstore_recovery_frontier_gap_test.go`) | `WALRecovery` `I1` | ACTIVE |
| `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore.go` `persistCheckpointReleasing` | `TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle` (`core/storage/walstore_checkpoint_safety_test.go`) | — | ACTIVE |
| `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent or superblock), the open store refuses every later `Sync`, write and checkpoint without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestWALStoreWALFsyncFailureIsSticky`, `TestWALStoreExtentFsyncFailureIsSticky`, `TestWALStoreCheckpointFsyncFailureIsSticky` (`core/storage/walstore_sticky_fsync_test.go`); `TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE |
| `INV-WAL-APPEND-STICKY-001` | A WAL append whose write failed latches the store fault; writers already queued behind it are refused. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteAppendFailure`, `WALStore.Write` | `TestWALStoreWritersQueuedBehindAFailedAppendAreRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE |
| `INV-WAL-SYNC-FRONTIER-001` | `Sync` never reports an uncovered write durable: it returns the global synced frontier, which is at least the caller's own write and is covered by a completed `fsync`. It may include later writes whose covering `fsync` completed before the caller resumed. | M1 write lifecycle: Appended → Synced | `core/storage/walstore.go` `WALStore.Sync` | `TestWALStore_SyncDoesNotClaimConcurrentWrite` (`core/storage/walstore_test.go`); `TestWALGenerationFirstCallerReturnOrdering` (`core/storage/walstore_sync_frontier_order_test.go`) | — | ACTIVE |
| `INV-WAL-REPLAY-LWW-001` | Replay of the validated native prefix retains the highest admitted LSN per LBA; invalid cursor, nonce or LSN order is refused. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALLSNOrderV3_RefusesDuplicateAndLower` (`core/storage/wal_lsn_order_v3_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE |
| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the both durable descriptor slots has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_io_v3.go` `append`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE |
| `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`); `TestNativeReplacementCheckpointSIGKILL` (`core/storage/legacy_checkpoint_replacement_v3_linux_test.go`) | `WALRecovery` `I1` | ACTIVE |
| `INV-WAL-FRONTIER-GAP-001` | A durable BASE anchor and its contiguous synced install-lane suffix survive recovery; an unpersisted frontier jump is not admitted. | M1 Recovering | `core/storage/walstore_v3.go` `recoverV3` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`) | `WALRecovery` `I1` | ACTIVE |
| `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | — | ACTIVE |
| `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent or superblock), the open store refuses every later `Sync`, write and checkpoint without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestNativeReplacementDataFsyncFailureIsSticky` (`core/storage/legacy_replacement_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`) | — | ACTIVE |
| `INV-WAL-APPEND-STICKY-001` | A WAL append whose write failed latches the store fault; writers already queued behind it are refused. | M1 Serving → FaultLatched | `core/storage/walstore_v3.go` `latchV3`, `appendWriteV3` | `TestNativeReplacementQueuedApplyAfterFailedAppend` (`core/storage/legacy_replacement_v3_test.go`) | — | ACTIVE |
| `INV-WAL-SYNC-FRONTIER-001` | `Sync` never reports an uncovered write durable: it returns the global synced frontier, which is at least the caller's own write and is covered by a completed `fsync`. It may include later writes whose covering `fsync` completed before the caller resumed. | M1 write lifecycle: Appended → Synced | `core/storage/walstore.go` `WALStore.Sync` | `TestWALStore_SyncDoesNotClaimConcurrentWrite` (`core/storage/walstore_test.go`); `TestNativeReplacementSyncCallerReturnOrdering` (`core/storage/legacy_sync_replacement_v3_test.go`) | — | ACTIVE |
| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt` (`cmd/blockvolume/durable_startup_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE |
| `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE |
| `INV-WAL-V3-ACTIVATION-001` | Public create produces an owned mapped v3/impl3 volume with the requested chunk geometry and C default/A option. Writable/readonly open validate A/B dependencies, reject actual legacy headers without mutation, and can select a valid fallback when A is damaged. Production provider capture/HEAD restore/status use those selectors. Legacy fixture constructors cannot be called by default production code or enter its transitive storage import closure. | M1 open/create/readonly | `walstore.go` public selectors; `walstore_v3.go` `refuseLegacyWALStore`, `ProbeWALStoreV3`; `provider.go` | `TestWALStoreProductionSelectorCreatesMappedV3`, `TestWALStoreProductionRefusesLegacyWithoutMutation`, `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy`, `TestWALStoreProductionCreateOptions`, `TestLegacyFixtureIsolation`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE |
| `INV-WAL-V3-ACTIVATION-001` | Public create produces an owned mapped v3/impl3 volume with the requested chunk geometry and C default/A option. Writable/readonly open validate A/B dependencies, reject actual legacy headers without mutation, and can select a valid fallback when A is damaged. Production provider capture/HEAD restore/status use those selectors. Legacy fixture constructors cannot be called by default production code or enter its transitive storage import closure. | M1 open/create/readonly | `walstore.go` public selectors; `walstore_v3.go` `refuseLegacyWALStore`, `ProbeWALStoreV3`; `provider.go` | `TestWALStoreProductionSelectorCreatesMappedV3` (`core/storage/walstore_activation_test.go`); `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy` (`core/storage/walstore_activation_test.go`); `TestWALStoreProductionCreateOptions` (`core/storage/walstore_activation_test.go`); `TestLegacyFixtureIsolation` (`core/storage/legacy_fixture_isolation_test.go`); `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN` (`core/frontend/durable/provider_format_v3_test.go`); `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` (`core/frontend/durable/provider_format_v3_test.go`); `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE |
| `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE |
| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE |
| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB |
@@ -363,20 +363,20 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB |
| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. One earliest command deadline spans adapter batches and the long store admission waits (capture, lifecycle); short locks (store, descriptor, WAL writer) are taken blocking and keep RWMutex writer preference, with the deadline checked once held. The deadline is checked again after a checkpoint rollover and inside the WAL writer after its descriptor snapshot, lock wait and encoding, before the first payload write: an expired command starts no new payload WAL I/O, and expiry before append preserves the WAL/nextLSN/dirty state. A batch that returns a committed prefix with a storage error keeps that error in the classified error set. Issued WAL I/O retains its existing lifecycle ownership. Pure caller expiry stays retryable through required-observer classification and NVMe; a provided physical cause remains terminal. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire`; `write_command_budget.go`; `StorageBackend.Write`; NVMe `handleWrite` | `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestSessionWriteBudgetIncludesDispatchQueue`, `TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait`, `TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders`, `TestWALStoreV3WriteBudgetRefusesNewPayloadAfterRollover`, `TestWALStoreV3WriteBudgetRechecksAfterRollover`, `TestWALStoreV3WriteBudgetRefusesAfterDescriptorWaitBehindSync`, `TestStorageBackendPartialBatchPhysicalFaultSurvivesObserverDeadline`, `TestWALStoreV3WritePressureSampleMatchesOccupancy`, `TestStorageBackendExpiredWriteDoesNotAppend`, `TestStorageBackendRequiredObserverDeadlineStaysRetryable`; `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE |
| `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint releases only complete validated record ends covered by the checkpoint and outside the retention window; an installing BASE retains its install suffix. Physical recovery rebuilds the volatile boundary index only from the trusted kept scan, without restoring a disconnect cursor. Tail/head/map/checkpoint/W publish together, followed by metadata-only rollover; both slot tails still pin reuse. Failure grants no reuse and retains exact dirty retry identity. Checkpoint publication excludes writer admission through both-slot rollover and dirty-reference retirement. Idle, unchanged-checkpoint and admission settle pending rollover; catch-up revalidates tail/checkpoint before delivering its buffered scan. | M1 checkpoint / existing two-slot retirement | `wal_io_v3.go` `reclaimThroughV3`, `rememberReclaimScanV3`; `walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `descriptor_v3.go` `rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse`, `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint`, tagged `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB |
| `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-OWNER-001` | v3 read/write open and offline readonly open 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 | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go` | `TestWALStoreV3CreatorKeepsOwnershipThroughPublication` (`core/storage/volume_lock_v3_test.go`); `TestWALStoreV3OwnerExcludesOpenAndReadOnly` (`core/storage/volume_lock_v3_test.go`); `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | 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`, `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 |
| `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-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` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshAndSetWModeCloseTheWindow` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3AppendWriteErrorLatchesTheStore` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeWaitsForAHeldBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3InstallingScanErrorIsTypedNotReady` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision` (`core/storage/recovery_v3_test.go`); `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 |
| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB |
| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB |
| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB |
| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB |
| `INV-WAL-V3-MIGRATE-001` | `sw-block migrate-v3` rewrites only the descriptor of a cleanly closed v2/impl1 volume whose WAL the exhaustive scan proves flushed; the scan and the geometry check run before any write, and a refusal leaves the volume and every sidecar byte-identical. It keeps the extent base (WALSize = old - 4096), writes an atomic operator backup, an all-UNKNOWN initial map (covered = the v2 checkpoint), the prepared slot B, slot A at phase 0 (the commit point), slot B at phase 0, and only then retires the v2 chunk bitmap; each step is durable before the next. A rerun decides from the slot bytes alone: before the commit it restarts with a full rescan; after it, it only finishes the rollover and the retirement; a prepared B with an invalid A refuses with `ErrMigrationIncomplete`, as v3 open does; it never reads or restores the backup. | offline tool | `cmd/sw-block/migrate.go`; `cmd/sw-block/internal/v2legacy`; `core/storage/migrate_v3.go` | `TestMigrateV3CleanVolume`, `TestMigrateV3RefusalsChangeNothing`, `TestMigrateV3CrashAfterEachStepIsResumable`, `TestMigrateV3OldBinaryAfterPreparation`, `TestMigrateV3OldWALOverwritesThePreparedSlot`, `TestMigrateV3NeverRestoresTheBackup` (`cmd/sw-block/migrate_test.go`); tagged `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | none (tool) | STUB |
| `INV-WAL-V3-MIGRATE-001` | ARCHIVED: the in-place v2 converter is removed. Public opens refuse v2 bytes without mutation; no upgrade path is provided. | M1 open refusal | `core/storage/walstore_v3.go` `openWALStoreV3WithOptions` | `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | none (retired tool) | ARCHIVED |
| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA` (expiry and joined physical-fault wire status); `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE |
| `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE |
| `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE |
@@ -394,7 +394,7 @@ Notes:
- `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.
- `INV-WAL-V3-RESET-001`: Format bump v3, plan row 8 (DESIGN 8.6). Dark: no production path calls the reset, and it must not be activated before the reset model (r4.5) passes. No v3 tail release exists yet, so the precondition is CheckpointLSN >= W rather than an empty retained range: retained old-incarnation bytes at or below the checkpoint are preserved in the extent. The map root is unchanged by a reset, so no map page is retired.
- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). Until the chunk layer's side of the v3 install protocol lands (codex03), a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until codex03's v3 FreshFromHead restore lands; since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from (codex01 row 11b P1); it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge).
- `INV-WAL-V3-MIGRATE-001`: Format bump v3, plan rows 13a and 13b (DESIGN 10.1). Not yet in this row: the exclusive advisory lock that v3 open will share (precondition 1; it lands with the 12b open path), and raw v2 fixtures committed under testdata (today's controls build v2 volumes with the v2 code that row 14 deletes). The minimum migrated WAL size (64 KiB and two single-block records) is provisional.
- `INV-WAL-V3-MIGRATE-001`: Archived with the converter and its legacy fixtures; v2 inputs refuse open without mutation.
- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model (claude05), not by these tests. Installing recovery is row 11.
- `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). It is a STUB until the v3 store is wired in (rows 4 and 5) and activated (row 12b). The v2 checkpoint path (`persistCheckpointReleasing`) is unchanged and is retired in row 14a. The map coverage predicates against the root are added by row 7, and the conditions on BASE edges by rows 9 to 11.
- `INV-WAL-V3-DESCRIPTOR-001`: Format bump v3, plan row 1 (DESIGN r15 section 2). It is a STUB until the activation commit (plan row 12b): no production open or create path reaches the v3 codec before then. The map-dependency checks (root and pages present and hash-valid) are added by plan row 7. The tests decode vectors from an independent generator (`core/storage/testdata/format_v3/slot/gen_slot_vectors.py`).
@@ -448,7 +448,7 @@ Notes:
|---|---|---|---|---|---|---|
| `INV-WS-HEAD-BELT-001` | A takeover confirms its exact HEAD before serving. The supported single-serialization-point mode has W=0; explicit experimental cooling requires W >= the 2 s HEAD operation deadline plus 100 ms settling. Each CAS and confirmation has its own 2 s deadline. A successful cut CAS requires readback before remoteLSN/map settlement and intent cleanup. Unconfirmed roots remain protected through Close; an observed different publication owner fences without retry, even after epoch regression or when the original HEAD was empty. | M4 Claiming → Cooling → Holder; M5 CAS → Confirmed or Pending/Fenced | `core/storage/chunk_head_belt.go`; `chunk_restore.go` `ClaimChunkHead`; `chunk_layer.go` `captureLocked`, `resolvePending`, `SettleDetach`, `dropIntents`, `Close` | `TestHeadBeltTakeoverRefusesLateOldCAS`; `TestHeadBeltTakeoverWaitsBeforeConfirmation`; `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`; `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`; `TestHeadBeltEmptyBaseForeignPublicationFences`; `TestHeadBeltSinglePointHasNoCoolingDelay`; `TestHeadBeltOperationsHaveOwnDeadline`; `TestHeadBeltCoolingWindowCoversCASAndSettle` (`core/storage/chunk_head_belt_test.go`) | `WorkspaceTakeover` belt extension pending | ACTIVE |
| `INV-WS-HEAD-CAS-001` | Every HEAD publish is conditional on `{gen, epoch}` at one serialization point. A conflicting observed owner fences the publisher. Multiple independent filer serialization points are not made atomic by readback. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE |
| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE |
| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`); `TestNativeReplacementCutBehindHEADRefuses` (`core/storage/legacy_replacement_v3_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE |
| `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE |
| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE |
| `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE |
@@ -474,10 +474,10 @@ Notes:
| `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE |
| `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE |
| `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE |
| `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window (legacy fixtures retain the full-copy barrier). | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy`, `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`), `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
| `INV-CUT-BITMAP-001` | The dirty bitmap never under-reports: it is durable before the checkpoint passes its WAL entries, and it is reset only after a successful CAS, keeping chunks dirtied after the cut. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/chunk_layer.go` `BeforeCheckpointAdvance`, `finishCut` | `TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle`, `TestChunkLayer_C11_RolloverKeepsPostCutDirt` (`core/storage/chunk_layer_c11_test.go`) | `CutCapture` `HeadImage` | ACTIVE |
| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE |
| `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED |
| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
| `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE |
| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE |
| `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE |
| `INV-CUT-NO-WAL-PIN` | A cut window pins no WAL space and does not defer the flusher. Logical readers validate their resolved record and retry against the dirty map/extent after retirement and reuse. | M1 Checkpoint / M5 Copy | `walstore_v3.go` `readDirtyV3`; `flusher.go` `flushOnceInternal` | `TestCutCOWV3_CaptureDoesNotPinWAL` (`core/storage/chunk_cut_alignment_test.go`) | CutFlush refinement; native real ring-reuse control | ACTIVE |
| `INV-CUT-HOOK-BEFORE-APPEND` | The COW hook owns/saves the at-H image before a read-visible WAL mutation, under shared capture admission. | M1 Write / M5 Save | `walstore.go` `Write`, `WriteBatch`; `chunk_cut_cow.go` `beforeChunkMutation` | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 SaveStart before Write | ACTIVE |
@@ -586,5 +586,5 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a
### Dark v3 chunk/BASE integration (row12a)
- `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for dark mapped v3): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu.
- The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging/reconciliation generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission.
- The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission.
- Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Both installed local presence and the provider durable attach point are required before retirement. The provider removes its fresh marker and fsyncs its directory under the store installMu-exclusive commit, then records per-open owner readiness; the callback never re-enters the store. Layer attach alone never allows retirement. Later completed transitions require owner readiness plus saved full presence before allowing; the next ordinary publication still checks existing retirement coverage. The provider keeps the constructed layer private as chunkPending until this commit succeeds; explicit publication cannot resolve it and the scheduler starts only after commit. Failed commits retain the private layer for retry without reattaching. Held pre-marker controls require Capture/Cut/MakeRemoteDurable to return ErrNotChunkVolume with no new remote writes, intents or HEAD changes, then crash/reopen exact local bytes. Actual subprocess controls crash after presence but before marker removal (both pre-existing installed BASE and attached completion), retaining the installed discriminator and recovering exact local data. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam.