fix(storage): v3 ScanLBAs is all or nothing (review P1s)

ScanLBAs on v3 now returns entries only when the trusted chain covers the
whole captured range [fromLSN, head): a chain that stops short is a WAL
integrity failure carrying the scanner's stop cause (CRC, binding,
truncation), a chain that starts after fromLSN is WALRecycled, and a
missing LSN mid-range is an integrity failure. Nothing is emitted before
the check.

An installing source is refused with ErrBaseInstalling before emitting.
The capture (recover generation, descriptor, head) is taken under s.mu
and revalidated after the scan, with no lock held across the callbacks;
a transition during the scan retries from a fresh capture, and a source
that began installing meanwhile is refused.

Controls: corrupt middle and first records (store), an installing
source, an install begun during a held scan, a Recover during a held
scan (retry), and a corrupt middle record through the actual catch-up
sender (the session does not close successfully).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-17 21:58:51 -08:00
1 parent 88d52b76c1
commit 3ecde2ccc9
5 files changed
+245 -32

No files matched your search

@@ -2,6 +2,11 @@
package storage
import (
"fmt"
"os"
)
// CreateMappedWALStoreV3Test is available only to tagged cross-package caller
// controls. Production Create/Open remain unchanged until the activation gate.
func CreateMappedWALStoreV3Test(path string, blocks, blockSize, chunkBlocks uint32) (*WALStore, error) {
@@ -72,3 +77,44 @@ func MapCoverageV3Test(s *WALStore) (covered uint64, allUnknown bool) {
}
return s.v3.pub.cur.MapCoveredCheckpoint, allUnknown
}
// DamageV3RecordTest flips one payload byte of the v3 WAL record carrying
// lsn in the closed or open file at path (a cross-package corrupt-record
// control).
func DamageV3RecordTest(path string, lsn uint64) error {
f, err := os.OpenFile(path, os.O_RDWR, 0)
if err != nil {
return err
}
defer f.Close()
a, b := make([]byte, slotSizeV3), make([]byte, slotSizeV3)
if _, err := f.ReadAt(a, 0); err != nil {
return err
}
if _, err := f.ReadAt(b, slotBOffsetV3); err != nil {
return err
}
d, _, err := selectSlotV3(a, b, nil)
if err != nil {
return err
}
r, err := scanWALV3(f, d)
if err != nil {
return err
}
for _, rec := range r.Records {
if rec.Entry.LSN != lsn {
continue
}
size := uint64(walEntryHeaderSizeV3 + len(rec.Entry.Data))
off := int64(d.WALOffset+(rec.End-size)%d.WALSize) + walEntryPrefixSizeV3 + 100
x := []byte{0}
if _, err := f.ReadAt(x, off); err != nil {
return err
}
x[0] ^= 0xFF
_, err = f.WriteAt(x, off)
return err
}
return fmt.Errorf("no v3 record with LSN %d", lsn)
}
@@ -328,3 +328,83 @@ func TestWALStoreV3ScanLBAs(t *testing.T) {
t.Fatalf("ScanLBAs below the checkpoint: err = %v, want ErrWALRecycled", err)
}
}
// codex01 4caac700 P1s: v3 ScanLBAs is all or nothing. A corrupt middle
// record makes the chain stop short of the head: a typed WAL integrity
// failure carrying the scanner's stop cause, with nothing emitted (never
// a short success, never WALRecycled). An installing
// source is refused before emitting; a source that begins installing
// during a held scan is refused at the revalidation; a Recover during a
// held scan retries from a fresh capture and returns the full range.
// Mutants: accepting a short prefix, ignoring the stop cause, no
// installing refusal, no revalidation.
func TestWALStoreV3ScanLBAsIsAllOrNothing(t *testing.T) {
count := func(s *WALStore, from uint64) (int, error) {
n := 0
err := s.ScanLBAs(from, func(RecoveryEntry) error { n++; return nil })
return n, err
}
t.Run("corrupt middle record", func(t *testing.T) {
s, path := newStoreV3(t, WModeStrict)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
writeSynced(t, s, 1, 3)
damageRecord(t, path, 2)
n, err := count(s, 1)
if !isWALCorrupt(err) || !errors.Is(err, errCRCMismatch) || n != 0 {
t.Fatalf("ScanLBAs over a corrupt LSN 2: emitted %d, err %v; want 0 and a CRC WAL integrity failure", n, err)
}
})
t.Run("corrupt first record", func(t *testing.T) {
// The scanner's stop cause decides the kind: a damaged first
// record is an integrity fault, never a recycled WAL.
s, path := newStoreV3(t, WModeStrict)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
writeSynced(t, s, 1, 3)
damageRecord(t, path, 1)
n, err := count(s, 1)
if !isWALCorrupt(err) || !errors.Is(err, errCRCMismatch) || n != 0 {
t.Fatalf("ScanLBAs over a corrupt LSN 1: emitted %d, err %v; want 0 and a CRC WAL integrity failure", n, err)
}
})
t.Run("installing source", func(t *testing.T) {
s, _ := newStoreV3(t, WModeStrict)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
writeSynced(t, s, 1, 2)
beginV3(t, s, 2, idA)
if n, err := count(s, 1); !errors.Is(err, ErrBaseInstalling) || n != 0 {
t.Fatalf("installing source: emitted %d, err %v", n, err)
}
})
t.Run("install begins during a held scan", func(t *testing.T) {
s, _ := newStoreV3(t, WModeStrict)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
writeSynced(t, s, 1, 2)
once := false
s.v3.testScanRead = func() {
if !once {
once = true
beginV3(t, s, 2, idA)
}
}
if n, err := count(s, 1); !errors.Is(err, ErrBaseInstalling) || n != 0 {
t.Fatalf("install during the scan: emitted %d, err %v", n, err)
}
})
t.Run("Recover during a held scan retries", func(t *testing.T) {
s, _ := newStoreV3(t, WModeStrict)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
writeSynced(t, s, 1, 3)
retried := 0
s.v3.testScanRead = func() {
retried++
if retried == 1 {
if _, err := s.Recover(); err != nil {
t.Error(err)
}
}
}
if n, err := count(s, 1); err != nil || n != 3 || retried < 2 {
t.Fatalf("Recover during the scan: emitted %d, err %v, scans %d; want 3 entries after a retry", n, err, retried)
}
})
}
+85 -32
View File
@@ -253,23 +253,79 @@ func (s *WALStore) CheckpointLSNForPOC() uint64 {
return s.CheckpointLSN()
}
// scanLBAsV3 is ScanLBAs on a v3 store (the primary's catch-up source):
// the trusted v3 chain from the selected descriptor's scan start, each write
// record as one entry and each batch record as one entry per block with
// consecutive LSNs, every LSN in [fromLSN, headLSN). Records are scanned in
// cursor (= LSN) order. If the WAL no longer holds fromLSN (checkpointed
// and its bytes released), the scan refuses with the typed WALRecycled
// failure, so the caller escalates to a rebuild instead of skipping a range.
// Callers hold lifecycleMu shared; nothing is mutated.
func (s *WALStore) scanLBAsV3(fromLSN, headLSN, checkpointLSN uint64, fn func(RecoveryEntry) error) error {
d := s.v3.pub.current()
scan, err := scanWALV3(s.fd, d)
if err != nil {
return fmt.Errorf("storage: walstore ScanLBAs (v3): %w", err)
// scanLBAsV3 is ScanLBAs on a v3 store (the primary's catch-up source).
// It is all or nothing (codex01 4caac700 P1s): it captures the recovery
// generation, the descriptor and the head, refuses an installing source
// (ErrBaseInstalling) before emitting anything, scans the trusted v3 chain
// into memory, revalidates the capture (a Recover, reset or BASE transition
// meanwhile retries the whole scan, or refuses if the source is now
// installing), and requires the trusted records to cover every LSN of
// [fromLSN, head): a chain that stops short (the scanner's CRC, binding or
// truncation stop cause) is a typed WAL integrity failure, and a WAL that
// no longer holds fromLSN a typed WALRecycled failure. Only then are the
// entries emitted, from memory, with no store lock held across the
// callbacks. A write record is one entry; a batch one entry per block.
func (s *WALStore) scanLBAsV3(fromLSN, _, _ uint64, fn func(RecoveryEntry) error) error {
v := s.v3
const attempts = 8
for attempt := 0; attempt < attempts; attempt++ {
s.mu.RLock()
gen := v.recoverGen.Load()
d := v.pub.current()
headLSN := s.nextLSN
s.mu.RUnlock()
if d.BaseState == BaseInstalling {
return fmt.Errorf("%w: catch-up from an installing source", ErrBaseInstalling)
}
if gen%2 != 0 {
continue // a recovery or reset is running; capture again
}
if fromLSN >= headLSN {
return nil
}
scan, err := scanWALV3(s.fd, d)
if err != nil {
return fmt.Errorf("storage: walstore ScanLBAs (v3): %w", err)
}
if h := v.testScanRead; h != nil {
h()
}
s.mu.RLock()
now := v.pub.current()
stable := v.recoverGen.Load() == gen && now.Nonce == d.Nonce && now.BaseState == d.BaseState &&
now.BaseInstallID == d.BaseInstallID
s.mu.RUnlock()
if !stable {
if now.BaseState == BaseInstalling {
return fmt.Errorf("%w: catch-up source began installing", ErrBaseInstalling)
}
continue // a transition ran meanwhile: scan again from a fresh capture
}
entries, err := v3CatchUpEntries(scan, d, fromLSN, headLSN)
if err != nil {
return err
}
for _, e := range entries {
if err := fn(e); err != nil {
return err
}
}
return nil
}
return fmt.Errorf("storage: walstore ScanLBAs (v3) did not get a stable capture in %d attempts", attempts)
}
// v3CatchUpEntries cuts [fromLSN, headLSN) out of a trusted scan, or fails:
// WALRecycled when the chain starts after fromLSN, WAL integrity (with the
// scanner's stop cause) when it ends before headLSN.
func v3CatchUpEntries(scan walScanResultV3, d descriptorV3, fromLSN, headLSN uint64) ([]RecoveryEntry, error) {
blockSize := uint64(d.BlockSize)
next := fromLSN // the next LSN the stream must carry
next := fromLSN
var out []RecoveryEntry
for _, r := range scan.Records {
if next >= headLSN {
break
}
e := r.Entry
count := uint64(1)
switch e.Type {
@@ -283,32 +339,29 @@ func (s *WALStore) scanLBAsV3(fromLSN, headLSN, checkpointLSN uint64, fn func(Re
continue
}
if e.LSN > next {
return NewWALRecycledFailure(ErrWALRecycled, fmt.Sprintf(
"v3 WAL starts at LSN %d, after the requested %d (checkpoint %d, head %d)", e.LSN, next, checkpointLSN, headLSN))
if next == fromLSN {
return nil, NewWALRecycledFailure(ErrWALRecycled, fmt.Sprintf(
"v3 WAL starts at LSN %d, after the requested %d (head %d)", e.LSN, fromLSN, headLSN))
}
return nil, NewWALIntegrityFailure(nil, fmt.Sprintf("v3 catch-up: LSN %d missing before %d", next, e.LSN))
}
for i := uint64(0); i < count; i++ {
lsn := e.LSN + i
if lsn < next || lsn >= headLSN {
continue
}
emit := RecoveryEntry{
LSN: lsn,
LBA: uint32(e.LBA + i),
Flags: RecoveryEntryWrite,
Data: e.Data[i*blockSize : (i+1)*blockSize],
}
if err := fn(emit); err != nil {
return err
}
out = append(out, RecoveryEntry{LSN: lsn, LBA: uint32(e.LBA + i), Flags: RecoveryEntryWrite,
Data: e.Data[i*blockSize : (i+1)*blockSize]})
next = lsn + 1
}
if next >= headLSN {
return nil
}
if next < headLSN {
if next == fromLSN && len(out) == 0 && scan.StopCause == nil {
return nil, NewWALRecycledFailure(ErrWALRecycled, fmt.Sprintf(
"v3 WAL holds no record at LSN %d (head %d)", fromLSN, headLSN))
}
return nil, NewWALIntegrityFailure(scan.StopCause, fmt.Sprintf(
"v3 catch-up stopped at LSN %d, short of the captured head %d", next, headLSN))
}
if next < headLSN && next == fromLSN {
return NewWALRecycledFailure(ErrWALRecycled, fmt.Sprintf(
"v3 WAL holds no record at LSN %d (checkpoint %d, head %d)", fromLSN, checkpointLSN, headLSN))
}
return nil
return out, nil
}
@@ -121,6 +121,9 @@ type walStoreV3State struct {
// testInstallLogBeforeAck runs in SyncInstallLog after its publication
// and before its final ack-boundary check.
testInstallLogBeforeAck func()
// testScanRead runs in a v3 ScanLBAs after its scan and before its
// revalidation.
testScanRead func()
}
// errV3RecoveredMeanwhile: a recovery ran between an outer Sync's capture
@@ -50,3 +50,34 @@ func TestCatchUpV3PrimaryToV3Replica(t *testing.T) {
}
}
}
// codex01 4caac700 P1: a corrupt middle record on the v3 primary must not
// let the actual catch-up sender complete at the prefix before it: the
// session closes unsuccessfully. Mutant: accepting a short prefix fails
// here.
func TestCatchUpV3CorruptMiddleRecordFails(t *testing.T) {
path := filepath.Join(t.TempDir(), "primary.v3")
primary, err := storage.CreateWALStoreV3Test(path, 64, v3RepBlock)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = primary.Close() })
for lba := uint32(0); lba < 3; lba++ {
if _, err := primary.Write(lba, v3RepBlk(0x10+byte(lba))); err != nil {
t.Fatal(err)
}
}
if _, err := primary.Sync(); err != nil {
t.Fatal(err)
}
if err := storage.DamageV3RecordTest(path, 2); err != nil {
t.Fatal(err)
}
_, _, head := primary.Boundaries()
replica := v3Rep(t)
l := v3Listen(t, replica)
exec := NewBlockExecutor(primary, l.Addr())
if r := runCatchUp(t, exec, head); r.Success {
t.Fatalf("catch-up over a corrupt LSN 2 closed successfully: %+v", r)
}
}