mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
storage: run the v3 format inside the real WALStore; fold codex01 row 5 review (format bump row 5b)
Integration seam ruling (Claude01, hub 10:22Z): v3 lives inside the real
*WALStore with version-dispatched internals, selected only through a
test-only create/open; production Create/Open stay v2 until row 12b.
The parallel walStoreV3 type from row 5 is removed; its logic is now the
store's v3 internals.
- walstore.go: a v3 field, set before the committer and flusher start
(openInitializedInternal init hook). Dispatch at the v2-coupled points:
Write appends through walWriterV3 with DurableLSN = Wack; Read uses the
v3 record layout; Recover runs recoverV3 (R < W*, replay <= R into the
dirty map, the exact fence, head = E, writer restored to E);
syncWALBatch runs the C/A modes through the row-3 publisher under the
v3 leader role; persistCheckpointReleasing publishes through it.
WriteBatch, ApplyEntry, WriteExtentDirect refuse (errV3NotYet) and
AdvanceFrontier is a no-op on v3 until their rows.
- flusher.go: readDirtyRecord decodes and validates v3 records.
- The v3 checkpoint/tail publication takes a map candidate hook for row
7; without it the checkpoint and tail do not move (no fabricated
coverage; the WAL stays retained).
codex01 row 5 review (40b7614f, AMEND):
- P1: the batch acknowledgement rechecks the store fault under s.mu
before advancing Wack, closing the window where a queued append latches
after the publisher's check. Held control in both modes.
- P1 (LSN order): recovery keeps the physical-prefix rule, which DESIGN
r16 makes canonical (the WAL is LSN-strictly-increasing); a
contradictory chain while installing is wrapped as ErrBaseIncomplete.
The ErrWALLSNOrder writer refusal is codex03's row-4 change.
- P2: fence ranges use interval length, never floor+WALSize; a history
ending at the last representable cursor recovers.
- P2: SetWMode evidence: a held C batch acks under C before the mode
changes; no batch acks under a stale mode; crash cases.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2a658d5dcf
commit
b8950a262f
7 files changed
+710
-332
No files matched your search
@@ -256,6 +256,9 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
|
||||
}
|
||||
|
||||
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() {
|
||||
|
||||
@@ -107,7 +107,13 @@ func decideRecoveryV3(d descriptorV3, recs []trustedRecordV3, maxDurable uint64)
|
||||
o := recoveryOutcomeV3{Start: scanStartV3(d), F: replayFloorV3(d)}
|
||||
R, E, err := contiguousPrefixV3(o.Start, o.F, recs)
|
||||
if err != nil {
|
||||
return o, NewWALIntegrityFailure(err, err.Error())
|
||||
ierr := NewWALIntegrityFailure(err, err.Error())
|
||||
if d.BaseState == BaseInstalling {
|
||||
// Installing keeps its outer not-ready outcome (DESIGN 8.3).
|
||||
o.Installing, o.Damaged = true, true
|
||||
return o, fmt.Errorf("%w: %w: %w", ErrBaseIncomplete, ErrInstallSuffixDamaged, ierr)
|
||||
}
|
||||
return o, ierr
|
||||
}
|
||||
o.R, o.E = R, E
|
||||
o.WStar = max(d.W, maxDurable)
|
||||
@@ -154,14 +160,15 @@ func fenceRangesV3(E, floor, walSize uint64, sameNonce bool) ([]fenceRangeV3, er
|
||||
if E < floor {
|
||||
return nil, fmt.Errorf("storage: v3 fence: head %d below the reuse floor %d", E, floor)
|
||||
}
|
||||
end, ok := checkedAddV3(floor, walSize)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: fence end %d+%d", ErrCounterExhausted, floor, walSize)
|
||||
}
|
||||
if E >= end {
|
||||
// Interval-length arithmetic: floor+walSize is never formed, so a
|
||||
// history ending at the last representable cursor still recovers
|
||||
// (codex01 row 5 P2). The logical end may exceed 2^64-2; only the
|
||||
// physical bytes matter.
|
||||
used := E - floor
|
||||
if used >= walSize {
|
||||
return nil, nil
|
||||
}
|
||||
n := end - E // at most walSize
|
||||
n := walSize - used // at most walSize
|
||||
start := E % walSize
|
||||
if start+n <= walSize {
|
||||
return []fenceRangeV3{{Off: start, Len: n}}, nil
|
||||
|
||||
@@ -98,6 +98,12 @@ func TestRecoveryV3Decision(t *testing.T) {
|
||||
if !errors.Is(installingErrorV3(o), ErrBaseIncomplete) || errors.Is(installingErrorV3(o), ErrInstallSuffixDamaged) {
|
||||
t.Fatal("intact installing error is not a plain ErrBaseIncomplete")
|
||||
}
|
||||
// A contradictory chain while installing keeps the outer not-ready
|
||||
// outcome (codex01 row 5).
|
||||
bad := []trustedRecordV3{rec(11, 11, 1100), rec(11, 11, 1200)}
|
||||
if _, err := decideRecoveryV3(inst, bad, 11); !errors.Is(err, ErrBaseIncomplete) || !errors.Is(err, ErrInstallSuffixDamaged) {
|
||||
t.Fatalf("contradictory installing chain: err = %v, want ErrBaseIncomplete wrapping ErrInstallSuffixDamaged", err)
|
||||
}
|
||||
o, err = decideRecoveryV3(inst, recs[:1], 12)
|
||||
if err != nil || !o.Installing || !o.Damaged {
|
||||
t.Fatalf("installing damaged: %+v %v (the check runs while installing)", o, err)
|
||||
@@ -152,7 +158,13 @@ func TestRecoveryV3FenceRangesAreExact(t *testing.T) {
|
||||
if _, err := fenceRangesV3(50, 100, 256, true); err == nil {
|
||||
t.Fatal("a head below the floor was accepted")
|
||||
}
|
||||
if _, err := fenceRangesV3(counterMaxV3, counterMaxV3, 256, true); !errors.Is(err, ErrCounterExhausted) {
|
||||
t.Fatalf("fence end overflow: err = %v, want ErrCounterExhausted", err)
|
||||
// codex01 row 5 P2: a history ending at the last representable cursor
|
||||
// still fences exactly; floor+WALSize is never formed.
|
||||
got, err := fenceRangesV3(counterMaxV3, counterMaxV3-100, 256, true)
|
||||
if err != nil {
|
||||
t.Fatalf("terminal-cursor fence: %v", err)
|
||||
}
|
||||
if want := []fenceRangeV3{{254, 2}, {0, 154}}; !reflect.DeepEqual(got, want) { // 2^64-2 mod 256 = 254: wraps
|
||||
t.Fatalf("terminal-cursor fence %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
@@ -135,6 +135,10 @@ type WALStore struct {
|
||||
// gates and mounted NVMe/TCP profiling pass.
|
||||
multiBlockRecords bool
|
||||
|
||||
// v3 is non-nil for a format-v3 store (walstore_v3.go). Dark until
|
||||
// activation: only createWALStoreV3ForTest/openWALStoreV3ForTest set it.
|
||||
v3 *walStoreV3State
|
||||
|
||||
// Physical WAL sync attempts exclude the separate metadata/checkpoint syncs.
|
||||
syncWALFile func() error
|
||||
walSyncCalls atomic.Uint64
|
||||
@@ -263,6 +267,13 @@ func openInitialized(path string, f *os.File, sb *superblock) (*WALStore, error)
|
||||
}
|
||||
|
||||
func openInitializedWithMetadata(path string, f *os.File, sb *superblock, metadata BlockMetadata) (*WALStore, error) {
|
||||
return openInitializedInternal(path, f, sb, metadata, nil)
|
||||
}
|
||||
|
||||
// openInitializedInternal is openInitializedWithMetadata with an optional
|
||||
// init hook that runs before the committer and flusher goroutines start
|
||||
// (the v3 store attaches its state there).
|
||||
func openInitializedInternal(path string, f *os.File, sb *superblock, metadata BlockMetadata, init func(*WALStore)) (*WALStore, error) {
|
||||
dm := newDirtyMap(64) // 64 shards is plenty for Phase 07 demo workloads
|
||||
|
||||
s := &WALStore{
|
||||
@@ -290,6 +301,9 @@ func openInitializedWithMetadata(path string, f *os.File, sb *superblock, metada
|
||||
return f.Sync()
|
||||
}
|
||||
s.syncExtentFile = f.Sync
|
||||
if init != nil {
|
||||
init(s)
|
||||
}
|
||||
committer := NewGroupCommitter(GroupCommitterConfig{
|
||||
SyncFunc: s.syncWALBatch,
|
||||
MaxDelay: 1 * time.Millisecond,
|
||||
@@ -407,6 +421,9 @@ func (s *WALStore) persistCheckpointAndRelease(highestLSN, entryPhys, entryLen u
|
||||
}
|
||||
|
||||
func (s *WALStore) persistCheckpointReleasing(highestLSN, entryPhys, entryLen uint64, release bool) error {
|
||||
if s.v3 != nil {
|
||||
return s.persistCheckpointV3(highestLSN)
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := s.stickyIOFault(); err != nil {
|
||||
@@ -578,6 +595,9 @@ func (s *WALStore) Recover() (uint64, error) {
|
||||
// are never reused across it), also on a failed or partial scan. Runs
|
||||
// before s.mu is released, so no read sees recovered bytes first.
|
||||
defer s.noteChunkRecovery()
|
||||
if s.v3 != nil {
|
||||
return s.recoverV3()
|
||||
}
|
||||
s.dm.clear()
|
||||
res, err := recoverWAL(s.fd, s.sb, s.dm)
|
||||
if err != nil {
|
||||
@@ -695,12 +715,20 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) {
|
||||
Data: data,
|
||||
}
|
||||
appendStart := time.Now()
|
||||
walRelOff, err := s.wal.append(entry)
|
||||
var walRelOff uint64
|
||||
var err error
|
||||
if s.v3 != nil {
|
||||
walRelOff, err = s.appendWriteV3(lba, data, lsn)
|
||||
} else {
|
||||
walRelOff, err = s.wal.append(entry)
|
||||
}
|
||||
s.instr.appendLatency.Observe(time.Since(appendStart))
|
||||
// A failed pwrite may still leave complete records or padding in the file.
|
||||
s.walMutation.Add(1)
|
||||
if err != nil {
|
||||
s.noteAppendFailure(err)
|
||||
if s.v3 == nil {
|
||||
s.noteAppendFailure(err)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
return 0, fmt.Errorf("storage: WAL append: %w", err)
|
||||
}
|
||||
@@ -721,6 +749,9 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) {
|
||||
}
|
||||
|
||||
func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error) {
|
||||
if s.v3 != nil {
|
||||
return nil, errV3NotYet
|
||||
}
|
||||
s.captureMu.RLock()
|
||||
defer s.captureMu.RUnlock()
|
||||
s.lifecycleMu.RLock()
|
||||
@@ -888,6 +919,9 @@ func (s *WALStore) Read(lba uint32) ([]byte, error) {
|
||||
s.mu.RUnlock()
|
||||
|
||||
if walRelOff, dataOffset, _, _, ok := s.dm.get(uint64(lba)); ok {
|
||||
if s.v3 != nil {
|
||||
return s.readFromWALV3(walRelOff)
|
||||
}
|
||||
return s.readFromWAL(walRelOff, dataOffset)
|
||||
}
|
||||
return s.readFromExtent(lba)
|
||||
@@ -1135,6 +1169,9 @@ func (s *WALStore) RecoveryRetentionLSNs() uint64 {
|
||||
// Used by the rebuild server to declare the replica's frontier
|
||||
// matches the primary's head once base blocks are installed.
|
||||
func (s *WALStore) AdvanceFrontier(lsn uint64) {
|
||||
if s.v3 != nil {
|
||||
return // v3 frontier jumps happen only inside MarkBaseComplete (rows 9 to 11)
|
||||
}
|
||||
s.bypassSyncDedup.Store(true)
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
@@ -1183,6 +1220,9 @@ func (s *WALStore) AdvanceWALTail(newTail uint64) {
|
||||
// Durability follows the same rule as Write: bytes become durable
|
||||
// only on the next successful Sync (the extent fsync covers them).
|
||||
func (s *WALStore) WriteExtentDirect(lba uint32, data []byte) error {
|
||||
if s.v3 != nil {
|
||||
return errV3NotYet // v3 BASE writes go through an install handle (rows 9 to 11)
|
||||
}
|
||||
s.bypassSyncDedup.Store(true)
|
||||
s.captureMu.RLock()
|
||||
defer s.captureMu.RUnlock()
|
||||
@@ -1240,6 +1280,9 @@ func (s *WALStore) noteChunkMutation(lba uint64) {
|
||||
}
|
||||
|
||||
func (s *WALStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error {
|
||||
if s.v3 != nil {
|
||||
return errV3NotYet // the install-lane apply is plan rows 9 to 11
|
||||
}
|
||||
s.bypassSyncDedup.Store(true)
|
||||
s.captureMu.RLock()
|
||||
defer s.captureMu.RUnlock()
|
||||
@@ -1467,6 +1510,9 @@ func (s *WALStore) walSyncCovered() bool {
|
||||
// Requests queued during a sync can reuse it only if their mutations predate its
|
||||
// captured cut. Failure leaves the previous durable generation unchanged.
|
||||
func (s *WALStore) syncWALBatch() error {
|
||||
if s.v3 != nil {
|
||||
return s.syncWALBatchV3()
|
||||
}
|
||||
// A batch queued behind a failed fsync must not fsync again (or report
|
||||
// a covered cut as durable): the failed fsync may have dropped pages.
|
||||
if err := s.stickyIOFault(); err != nil {
|
||||
|
||||
@@ -2,126 +2,91 @@ package storage
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
// walStoreV3 is the dark impl-3 store core (format bump v3, DESIGN r15
|
||||
// section 6; plan row 5). It composes the row-3 descriptor publisher, the
|
||||
// row-4 WAL writer and scan, and the row-5 recovery decisions:
|
||||
// Impl-3 internals of the real WALStore (format bump v3, DESIGN r15
|
||||
// section 6; plan rows 5 and 5b). A *WALStore whose v3 field is set runs
|
||||
// the v3 format: its descriptor publisher (row 3), its WAL writer and scan
|
||||
// (row 4), and the row-5 recovery (R < W*, the exact drop fence, head = E,
|
||||
// admission). Every other piece of the store is shared with v2: the group
|
||||
// committer, the dirty map, the flusher's extent writes, the syncFile leaf,
|
||||
// fileSyncMu and the sticky fault.
|
||||
//
|
||||
// - open: select a slot, scan, decide R < W*, replay records <= R, fence
|
||||
// [E, floor+WALSize) exactly, publish retainedHead = E, restore the
|
||||
// writer to E, and only then admit appends;
|
||||
// - Sync in mode C (default: the slot carries the previous batch's W and
|
||||
// one fsync covers the WAL and the slot) or mode A (WAL fsync, then a
|
||||
// slot publication with W = H and its own fsync);
|
||||
// - the idle refresh, SetWMode, and the store-global fault latch for
|
||||
// append and publication failures.
|
||||
// Dark until activation (plan row 12b): only createWALStoreV3ForTest and
|
||||
// openWALStoreV3ForTest build a v3 store; Create and Open stay v2.
|
||||
//
|
||||
// It is reachable only from tests until activation (plan row 12b). The
|
||||
// map, checkpoint and extent flush are later rows: this core keeps the
|
||||
// replayed and written blocks in memory for its read path.
|
||||
type walStoreV3 struct {
|
||||
fd *os.File
|
||||
|
||||
fileSyncMu sync.Mutex
|
||||
ioFault atomic.Pointer[error] // store-global sticky fault
|
||||
|
||||
mu sync.Mutex // the WALStore.mu analogue
|
||||
nextLSN uint64
|
||||
appended uint64 // highest LSN appended
|
||||
wack uint64 // highest acknowledged LSN
|
||||
data map[uint64][]byte
|
||||
admitted bool
|
||||
|
||||
syncMu sync.Mutex // group-commit leader role; SetWMode takes it too
|
||||
|
||||
// Not yet v3 (refused with errV3NotYet until their rows): WriteBatch, the
|
||||
// install paths (ApplyEntry, WriteExtentDirect, AdvanceFrontier; rows 9 to
|
||||
// 11) and the checkpoint/tail advance, which needs the row-7 map candidate.
|
||||
type walStoreV3State struct {
|
||||
pub *descriptorPublisherV3
|
||||
w *walWriterV3
|
||||
|
||||
// testBeforeFence, when set, runs just before the drop fence writes.
|
||||
testBeforeFence func()
|
||||
appended atomic.Uint64 // highest LSN pwritten to the WAL
|
||||
wack atomic.Uint64 // highest acknowledged LSN (Sync completed)
|
||||
|
||||
// syncMu is the group-commit leader role for the v3-only publications
|
||||
// that run outside the committer (refreshW, SetWMode).
|
||||
syncMu sync.Mutex
|
||||
|
||||
// mapCandidate, when set by plan row 7, prepares the map candidate a
|
||||
// checkpoint advance needs (DESIGN 9.1). Until then the v3 checkpoint
|
||||
// and tail do not move: coverage is never fabricated.
|
||||
mapCandidate func(checkpoint uint64) (func(next *descriptorV3) error, error)
|
||||
|
||||
// Test hooks (never set in production). testBeforeSlotWrite runs inside
|
||||
// the leaf just before a descriptor slot pwrite; a non-nil error fails
|
||||
// that write. testLeaderWaiting runs in a committer batch just before it
|
||||
// takes the leader role.
|
||||
testBeforeSlotWrite func() error
|
||||
testLeaderWaiting func()
|
||||
// testSetWModeHoldingRole runs in SetWMode after it has taken the leader
|
||||
// role and before it publishes the new mode.
|
||||
testSetWModeHoldingRole func()
|
||||
}
|
||||
|
||||
var errV3NotYet = errors.New("storage: operation not yet supported on a v3 store (later plan row)")
|
||||
|
||||
// testSkipFenceOnRecoverV3 is a test-only mutant switch for the G1 control
|
||||
// (it proves the schedule resurrects without the fence). Never set outside
|
||||
// tests.
|
||||
var testSkipFenceOnRecoverV3 bool
|
||||
|
||||
var errStoreNotAdmittedV3 = errors.New("storage: v3 store not admitted (recovery incomplete)")
|
||||
|
||||
func (s *walStoreV3) sticky() error {
|
||||
if e := s.ioFault.Load(); e != nil {
|
||||
return *e
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *walStoreV3) latch(err error) {
|
||||
func (s *WALStore) latchV3(err error) {
|
||||
if err != nil {
|
||||
s.ioFault.CompareAndSwap(nil, &err)
|
||||
s.ioFault.CompareAndSwap(nil, NewSubstrateIOFailure(err,
|
||||
"v3 WAL append or descriptor publication failed; the open store refuses further Syncs, writes and checkpoints"))
|
||||
}
|
||||
}
|
||||
|
||||
// syncFile is the leaf: one optional pwrite and one fsync under fileSyncMu,
|
||||
// refused when a fault is latched; an fsync failure latches before unlock.
|
||||
func (s *walStoreV3) syncFile(write, sync func() error) error {
|
||||
s.fileSyncMu.Lock()
|
||||
defer s.fileSyncMu.Unlock()
|
||||
if err := s.sticky(); err != nil {
|
||||
return err
|
||||
}
|
||||
if write != nil {
|
||||
if err := write(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := sync(); err != nil {
|
||||
err = fmt.Errorf("%w: %w", ErrFsyncFailed, err)
|
||||
s.latch(err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
// createWALStoreV3ForTest creates a v3 file (slot A at generation 1) and
|
||||
// returns it opened and recovered. It is the only v3 creator before
|
||||
// activation.
|
||||
func createWALStoreV3ForTest(path string, numBlocks uint32, blockSize uint32, walSize uint64, mode WMode) (*WALStore, error) {
|
||||
return createWALStoreV3AtCursorForTest(path, numBlocks, blockSize, walSize, mode, 0)
|
||||
}
|
||||
|
||||
func (s *walStoreV3) descriptorIO() descriptorIOV3 {
|
||||
return descriptorIOV3{
|
||||
writeSlot: func(off int64, b []byte) error {
|
||||
n, err := s.fd.WriteAt(b, off)
|
||||
if err == nil && n != len(b) {
|
||||
err = io.ErrShortWrite
|
||||
}
|
||||
return err
|
||||
},
|
||||
fsync: s.fd.Sync,
|
||||
syncFile: s.syncFile,
|
||||
sticky: s.sticky,
|
||||
latch: s.latch,
|
||||
}
|
||||
}
|
||||
|
||||
// createWALStoreV3ForTest creates a v3 file with slot A at generation 1 and
|
||||
// opens it. It is the only constructor of a v3 store before activation.
|
||||
func createWALStoreV3ForTest(path string, numBlocks uint32, blockSize uint32, walSize uint64, mode WMode) (*walStoreV3, error) {
|
||||
// createWALStoreV3AtCursorForTest is createWALStoreV3ForTest with the WAL's
|
||||
// logical cursor (tail = head) starting at cursor, to exercise the last
|
||||
// representable cursors.
|
||||
func createWALStoreV3AtCursorForTest(path string, numBlocks uint32, blockSize uint32, walSize uint64, mode WMode, cursor uint64) (*WALStore, error) {
|
||||
d := descriptorV3{
|
||||
ImplKind: ImplKindWALStore, ImplVersion: walStoreImplVersion3,
|
||||
VolumeSize: uint64(numBlocks) * uint64(blockSize), ExtentSize: 64 * 1024, BlockSize: blockSize,
|
||||
WALOffset: walOffsetV3, WALSize: walSize, CreatedAt: 1, SlotGen: 1,
|
||||
MapFormatID: mapFormatIDV1, MapGeneration: 1, WMode: mode,
|
||||
RetainedTail: cursor, RetainedHead: cursor,
|
||||
}
|
||||
if _, err := rand.Read(d.UUID[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := rand.Read(d.Nonce[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := rand.Read(d.MapLineage[:]); err != nil {
|
||||
return nil, err
|
||||
for _, b := range [][]byte{d.UUID[:], d.Nonce[:], d.MapLineage[:]} {
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := d.validate(nil); err != nil {
|
||||
return nil, err
|
||||
@@ -143,36 +108,35 @@ func createWALStoreV3ForTest(path string, numBlocks uint32, blockSize uint32, wa
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return openWALStoreV3(path)
|
||||
}
|
||||
|
||||
// openWALStoreV3 opens and recovers a v3 file (DESIGN 6.5, 6.6). An
|
||||
// installing descriptor returns the typed not-ready error (rows 9 to 11
|
||||
// own the install paths).
|
||||
func openWALStoreV3(path string) (*walStoreV3, error) {
|
||||
fd, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
s, err := openWALStoreV3ForTest(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s, err := recoverWALStoreV3(fd)
|
||||
if err != nil {
|
||||
_ = fd.Close()
|
||||
if _, err := s.Recover(); err != nil {
|
||||
_ = s.Close()
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func recoverWALStoreV3(fd *os.File) (*walStoreV3, error) {
|
||||
// openWALStoreV3ForTest opens a v3 file WITHOUT recovering it, like
|
||||
// OpenWALStore: call Recover before any Read or Write.
|
||||
func openWALStoreV3ForTest(path string) (*WALStore, error) {
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0o644)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("storage: open %s: %w", path, err)
|
||||
}
|
||||
a := make([]byte, slotSizeV3)
|
||||
b := make([]byte, slotSizeV3)
|
||||
if _, err := fd.ReadAt(a, slotAOffsetV3); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := fd.ReadAt(b, slotBOffsetV3); err != nil {
|
||||
_, errA := f.ReadAt(a, slotAOffsetV3)
|
||||
_, errB := f.ReadAt(b, slotBOffsetV3)
|
||||
if err := errors.Join(errA, errB); err != nil {
|
||||
_ = f.Close()
|
||||
return nil, err
|
||||
}
|
||||
d, id, err := selectSlotV3(a, b, nil)
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
return nil, err
|
||||
}
|
||||
var other *descriptorV3
|
||||
@@ -183,13 +147,66 @@ func recoverWALStoreV3(fd *os.File) (*walStoreV3, error) {
|
||||
if od, oerr := decodeSlotV3(otherRaw, nil); oerr == nil && od.MigrationPhase == MigrationNormal {
|
||||
other = &od
|
||||
}
|
||||
s := &walStoreV3{fd: fd, data: make(map[uint64][]byte)}
|
||||
s.pub = newDescriptorPublisherV3(d, id, other, s.descriptorIO())
|
||||
|
||||
scan, err := scanWALV3(fd, d)
|
||||
// The shared store reads its geometry from sb; WAL bounds and the
|
||||
// checkpoint come from the selected descriptor.
|
||||
sb := superblock{
|
||||
Version: superblockVersionV3, UUID: d.UUID, VolumeSize: d.VolumeSize,
|
||||
ExtentSize: d.ExtentSize, BlockSize: d.BlockSize, WALOffset: d.WALOffset, WALSize: d.WALSize,
|
||||
WALHead: d.RetainedHead, WALTail: d.RetainedTail, WALCheckpointLSN: d.CheckpointLSN,
|
||||
CreatedAt: d.CreatedAt, ImplKind: d.ImplKind, ImplVersion: d.ImplVersion,
|
||||
}
|
||||
copy(sb.Magic[:], superblockMagic)
|
||||
var initErr error
|
||||
s, err := openInitializedInternal(path, f, &sb, nil, func(s *WALStore) {
|
||||
v := &walStoreV3State{}
|
||||
v.pub = newDescriptorPublisherV3(d, id, other, descriptorIOV3{
|
||||
writeSlot: func(off int64, buf []byte) error {
|
||||
if h := s.v3.testBeforeSlotWrite; h != nil {
|
||||
if err := h(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
n, err := f.WriteAt(buf, off)
|
||||
if err == nil && n != len(buf) {
|
||||
err = fmt.Errorf("storage: v3 slot short write %d of %d", n, len(buf))
|
||||
}
|
||||
return err
|
||||
},
|
||||
fsync: f.Sync,
|
||||
syncFile: s.syncFile,
|
||||
sticky: s.stickyIOFault,
|
||||
latch: s.latchV3,
|
||||
})
|
||||
w, err := newWALWriterV3(f, v.pub)
|
||||
if err != nil {
|
||||
initErr = err
|
||||
return
|
||||
}
|
||||
v.w = w
|
||||
v.wack.Store(d.W)
|
||||
s.v3 = v
|
||||
})
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
return nil, err
|
||||
}
|
||||
if initErr != nil {
|
||||
_ = s.Close()
|
||||
return nil, initErr
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// recoverV3 is Recover for a v3 store (DESIGN 6.5, 6.6). The caller holds
|
||||
// captureMu, lifecycleMu and s.mu, as v2 Recover does.
|
||||
func (s *WALStore) recoverV3() (uint64, error) {
|
||||
v := s.v3
|
||||
d := v.pub.current()
|
||||
s.dm.clear()
|
||||
scan, err := scanWALV3(s.fd, d)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
recs := make([]trustedRecordV3, 0, len(scan.Records))
|
||||
for _, r := range scan.Records {
|
||||
last := r.Entry.LSN
|
||||
@@ -200,72 +217,59 @@ func recoverWALStoreV3(fd *os.File) (*walStoreV3, error) {
|
||||
}
|
||||
o, err := decideRecoveryV3(d, recs, scan.MaxDurableLSN)
|
||||
if err != nil {
|
||||
return nil, err // R < W*: fail closed (wal_corrupt)
|
||||
return 0, err // R < W*: fail closed (wal_corrupt)
|
||||
}
|
||||
if o.Installing {
|
||||
return nil, installingErrorV3(o)
|
||||
return 0, installingErrorV3(o)
|
||||
}
|
||||
// Replay the records <= R by LSN (last writer wins); drop the rest.
|
||||
lsnOf := make(map[uint64]uint64)
|
||||
// Replay the records <= R into the dirty map (last writer wins); the
|
||||
// rest are dropped and fenced below.
|
||||
for _, r := range scan.Records {
|
||||
e := r.Entry
|
||||
if e.LSN > o.R {
|
||||
break
|
||||
}
|
||||
s.replayV3(e, d.BlockSize, lsnOf)
|
||||
if e.Type != walEntryWrite {
|
||||
s.dm.clear()
|
||||
return 0, fmt.Errorf("%w: replay of v3 record type %#x", errV3NotYet, e.Type)
|
||||
}
|
||||
size := uint64(walEntryHeaderSizeV3 + len(e.Data))
|
||||
phys := (r.End - size) % d.WALSize
|
||||
s.dm.putAtIfNewer(e.LBA, phys, 0, e.LSN, d.BlockSize)
|
||||
}
|
||||
// The drop fence (6.6), then the recovered head, then admission.
|
||||
floor, sameNonce := s.pub.reuseFloor()
|
||||
// The drop fence, then the recovered head, then the writer and admission.
|
||||
floor, sameNonce := v.pub.reuseFloor()
|
||||
if err := s.fenceV3(o.E, floor, d.WALSize, sameNonce, d.WALOffset); err != nil {
|
||||
return nil, err
|
||||
s.dm.clear()
|
||||
return 0, err
|
||||
}
|
||||
if _, err := s.pub.publish(&s.mu, nil, func(n *descriptorV3) error {
|
||||
if _, err := v.pub.publish(nil, nil, func(n *descriptorV3) error {
|
||||
n.RetainedHead = o.E
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w, err := newWALWriterV3(fd, s.pub)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
s.dm.clear()
|
||||
return 0, err
|
||||
}
|
||||
restore := scan
|
||||
restore.End = o.E
|
||||
if err := w.restoreScanV3(restore); err != nil {
|
||||
return nil, err
|
||||
if err := v.w.restoreScanV3(restore); err != nil {
|
||||
s.dm.clear()
|
||||
return 0, err
|
||||
}
|
||||
s.w = w
|
||||
s.checkpointLSN = d.CheckpointLSN
|
||||
s.nextLSN = o.R + 1
|
||||
s.appended, s.wack = o.R, o.R
|
||||
s.admitted = true
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *walStoreV3) replayV3(e walEntryV3, blockSize uint32, lsnOf map[uint64]uint64) {
|
||||
put := func(lba, lsn uint64, b []byte) {
|
||||
if prev, ok := lsnOf[lba]; ok && prev > lsn {
|
||||
return
|
||||
}
|
||||
lsnOf[lba] = lsn
|
||||
s.data[lba] = b
|
||||
}
|
||||
switch e.Type {
|
||||
case walEntryWrite:
|
||||
put(e.LBA, e.LSN, append([]byte(nil), e.Data...))
|
||||
case walEntryWriteBatch:
|
||||
for i := uint64(0); i < e.BatchCount; i++ {
|
||||
put(e.LBA+i, e.LSN+i, append([]byte(nil), e.Data[i*uint64(blockSize):(i+1)*uint64(blockSize)]...))
|
||||
}
|
||||
case walEntryTrim:
|
||||
for i := uint64(0); i < uint64(e.Length)/uint64(blockSize); i++ {
|
||||
put(e.LBA+i, e.LSN, nil)
|
||||
}
|
||||
s.walHead, s.syncedLSN = o.R, o.R
|
||||
if s.walTail == 0 && o.R > 0 {
|
||||
s.walTail = 1
|
||||
}
|
||||
v.appended.Store(o.R)
|
||||
v.wack.Store(max(v.wack.Load(), o.R))
|
||||
return s.syncedLSN, nil
|
||||
}
|
||||
|
||||
// fenceV3 zeroes exactly the fence ranges and fsyncs them through the leaf
|
||||
// before any admission (DESIGN 6.6).
|
||||
func (s *walStoreV3) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset uint64) error {
|
||||
// before any admission (DESIGN 6.6). A write error latches inside the leaf.
|
||||
func (s *WALStore) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset uint64) error {
|
||||
ranges, err := fenceRangesV3(E, floor, walSize, sameNonce)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -273,9 +277,6 @@ func (s *walStoreV3) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset
|
||||
if len(ranges) == 0 || testSkipFenceOnRecoverV3 {
|
||||
return nil
|
||||
}
|
||||
if s.testBeforeFence != nil {
|
||||
s.testBeforeFence()
|
||||
}
|
||||
return s.syncFile(func() error {
|
||||
const chunk = 64 * 1024
|
||||
zero := make([]byte, chunk)
|
||||
@@ -284,7 +285,7 @@ func (s *walStoreV3) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset
|
||||
n := min(r.Len-done, chunk)
|
||||
if _, err := s.fd.WriteAt(zero[:n], int64(walOffset+r.Off+done)); err != nil {
|
||||
err = fmt.Errorf("storage: v3 drop fence: %w", err)
|
||||
s.latch(err) // inside the leaf, before fileSyncMu unlocks
|
||||
s.latchV3(err)
|
||||
return err
|
||||
}
|
||||
done += n
|
||||
@@ -294,107 +295,182 @@ func (s *walStoreV3) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset
|
||||
}, s.fd.Sync)
|
||||
}
|
||||
|
||||
// Write appends one single-block record. DurableLSN is the acknowledged W
|
||||
// at append time. A pwrite failure latches the store-global fault.
|
||||
func (s *walStoreV3) Write(lba uint32, data []byte) (uint64, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if !s.admitted {
|
||||
return 0, errStoreNotAdmittedV3
|
||||
}
|
||||
if err := s.sticky(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
lsn := s.nextLSN
|
||||
// appendWriteV3 is the v3 body of Write's append, under s.mu. DurableLSN is
|
||||
// the acknowledged W at append time; a pwrite failure latches the store.
|
||||
func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, error) {
|
||||
e := walEntryV3{LSN: lsn, Type: walEntryWrite, LBA: uint64(lba), Length: uint32(len(data)), Data: data}
|
||||
if _, err := s.w.append(e, s.wack); err != nil {
|
||||
phys, err := s.v3.w.append(e, s.v3.wack.Load())
|
||||
if err != nil {
|
||||
if errors.Is(err, errWALPwrite) {
|
||||
s.latch(err)
|
||||
s.latchV3(err)
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
s.nextLSN++
|
||||
s.appended = lsn
|
||||
s.data[uint64(lba)] = append([]byte(nil), data...)
|
||||
return lsn, nil
|
||||
s.v3.appended.Store(lsn)
|
||||
return phys, nil
|
||||
}
|
||||
|
||||
// Read returns the current block (dark read path for tests).
|
||||
func (s *walStoreV3) Read(lba uint32) []byte {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.data[uint64(lba)]
|
||||
}
|
||||
|
||||
// Sync acknowledges every write appended before it was called (DESIGN 6.1
|
||||
// to 6.3). It returns the acknowledged W.
|
||||
func (s *walStoreV3) Sync() (uint64, error) {
|
||||
s.syncMu.Lock()
|
||||
defer s.syncMu.Unlock()
|
||||
s.mu.Lock()
|
||||
H, prev := s.appended, s.wack
|
||||
err := s.sticky()
|
||||
s.mu.Unlock()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
// syncWALBatchV3 is the committer leader's batch for a v3 store (DESIGN 6.2,
|
||||
// 6.3). The cut H is every record pwritten before the leader starts.
|
||||
func (s *WALStore) syncWALBatchV3() error {
|
||||
if err := s.stickyIOFault(); err != nil {
|
||||
return err
|
||||
}
|
||||
if H <= prev {
|
||||
return prev, nil
|
||||
cut := s.walMutation.Load()
|
||||
if !s.bypassSyncDedup.Load() && s.chunk.Load() == nil && cut <= s.durableMutation.Load() {
|
||||
return nil
|
||||
}
|
||||
switch s.pub.current().WMode {
|
||||
v := s.v3
|
||||
// The leader role: SetWMode holds it while it changes the mode, so no
|
||||
// batch acknowledges under a stale mode selection (the mode is read
|
||||
// only after the role is taken).
|
||||
if h := v.testLeaderWaiting; h != nil {
|
||||
h()
|
||||
}
|
||||
v.syncMu.Lock()
|
||||
defer v.syncMu.Unlock()
|
||||
H, prev := v.appended.Load(), v.wack.Load()
|
||||
switch v.pub.current().WMode {
|
||||
case WModeStrict:
|
||||
// A: fsync the WAL, then publish W = H with its own fsync.
|
||||
if err := s.syncFile(nil, s.fd.Sync); err != nil {
|
||||
return 0, err
|
||||
if err := s.syncFile(nil, func() error { return s.syncWALFile() }); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := s.pub.publish(&s.mu, nil, func(n *descriptorV3) error { n.W = H; return nil }); err != nil {
|
||||
return 0, err
|
||||
if _, err := v.pub.publish(nil, nil, func(n *descriptorV3) error { n.W = H; return nil }); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
// C: the fallback slot carries the PREVIOUS batch's acknowledged W;
|
||||
// the publication's one fsync covers this batch's records and the
|
||||
// slot. The slot never names an LSN beyond a completed fsync.
|
||||
if _, err := s.pub.publish(&s.mu, nil, func(n *descriptorV3) error { n.W = prev; return nil }); err != nil {
|
||||
return 0, err
|
||||
// C: the fallback slot carries the PREVIOUS batch's acknowledged
|
||||
// W, and the publication's one fsync covers this batch's records
|
||||
// and the slot. The slot never names an LSN beyond a completed fsync.
|
||||
s.walSyncCalls.Add(1)
|
||||
if _, err := v.pub.publish(nil, nil, func(n *descriptorV3) error { n.W = prev; return nil }); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// The acknowledgement boundary (codex01 row 5 P1): a queued append may
|
||||
// have failed and latched the store fault while this batch's slot I/O
|
||||
// was in flight. Recheck under the store lock, which that append holds
|
||||
// until it has latched, before acknowledging anything.
|
||||
s.mu.Lock()
|
||||
s.wack = max(s.wack, H)
|
||||
s.mu.Unlock()
|
||||
return H, nil
|
||||
defer s.mu.Unlock()
|
||||
if err := s.stickyIOFault(); err != nil {
|
||||
return err
|
||||
}
|
||||
if H > prev {
|
||||
v.wack.Store(H)
|
||||
}
|
||||
s.durableMutation.Store(cut)
|
||||
return nil
|
||||
}
|
||||
|
||||
// refreshW is the mode-C idle refresh (DESIGN 6.2): publish W = the
|
||||
// acknowledged W when the slot lags it. The flusher calls it after the
|
||||
// refresh interval; tests call it directly (no timing oracle).
|
||||
func (s *walStoreV3) refreshW() error {
|
||||
s.syncMu.Lock()
|
||||
defer s.syncMu.Unlock()
|
||||
s.mu.Lock()
|
||||
wack := s.wack
|
||||
s.mu.Unlock()
|
||||
if wack <= s.pub.current().W {
|
||||
// acknowledged W when the slot lags it.
|
||||
func (s *WALStore) refreshW() error {
|
||||
v := s.v3
|
||||
if v == nil {
|
||||
return errV3NotYet
|
||||
}
|
||||
v.syncMu.Lock()
|
||||
defer v.syncMu.Unlock()
|
||||
wack := v.wack.Load()
|
||||
if wack <= v.pub.current().W {
|
||||
return nil
|
||||
}
|
||||
_, err := s.pub.publish(&s.mu, nil, func(n *descriptorV3) error { n.W = wack; return nil })
|
||||
_, err := v.pub.publish(nil, nil, func(n *descriptorV3) error { n.W = wack; return nil })
|
||||
return err
|
||||
}
|
||||
|
||||
// SetWMode changes the W mode (DESIGN 6.4). It takes the group-commit
|
||||
// leader role, so every batch admitted before it has been acknowledged
|
||||
// under the old mode, and publishes the new mode with W = the actual
|
||||
// acknowledged W. Every later batch uses the new mode.
|
||||
func (s *walStoreV3) SetWMode(m WMode) error {
|
||||
s.syncMu.Lock()
|
||||
defer s.syncMu.Unlock()
|
||||
s.mu.Lock()
|
||||
wack := s.wack
|
||||
s.mu.Unlock()
|
||||
_, err := s.pub.publish(&s.mu, nil, func(n *descriptorV3) error {
|
||||
// SetWMode changes the W mode (DESIGN 6.4). It runs a Sync first, so every
|
||||
// write admitted before it is acknowledged under the old mode, then
|
||||
// publishes the new mode with W = the actual acknowledged W while holding
|
||||
// the v3 leader role. Every later batch uses the new mode.
|
||||
func (s *WALStore) SetWMode(m WMode) error {
|
||||
v := s.v3
|
||||
if v == nil {
|
||||
return errV3NotYet
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
v.syncMu.Lock()
|
||||
defer v.syncMu.Unlock()
|
||||
if h := v.testSetWModeHoldingRole; h != nil {
|
||||
h()
|
||||
}
|
||||
wack := v.wack.Load()
|
||||
_, err := v.pub.publish(nil, nil, func(n *descriptorV3) error {
|
||||
n.WMode, n.W = m, wack
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *walStoreV3) Close() error { return s.fd.Close() }
|
||||
// readFromWALV3 reads one block of a v3 write record at a WAL offset.
|
||||
func (s *WALStore) readFromWALV3(walRelOff uint64) ([]byte, error) {
|
||||
absOff := int64(s.sb.WALOffset + walRelOff)
|
||||
header := make([]byte, walEntryPrefixSizeV3)
|
||||
if _, err := s.fd.ReadAt(header, absOff); err != nil {
|
||||
return nil, fmt.Errorf("storage: v3 WAL read header: %w", err)
|
||||
}
|
||||
if header[16] != walEntryWrite || binary.LittleEndian.Uint32(header[26:30]) != s.sb.BlockSize {
|
||||
return nil, fmt.Errorf("storage: v3 WAL read: unexpected record type %#x", header[16])
|
||||
}
|
||||
data := make([]byte, s.sb.BlockSize)
|
||||
if _, err := s.fd.ReadAt(data, absOff+int64(walEntryPrefixSizeV3)); err != nil {
|
||||
return nil, fmt.Errorf("storage: v3 WAL read data: %w", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// readDirtyRecordV3 is the flusher's record read for a v3 store: it decodes
|
||||
// and validates the whole record before its data may reach the extent.
|
||||
func (f *flusher) readDirtyRecordV3(e snapshotEntry) ([]byte, uint64, error) {
|
||||
store := f.store
|
||||
d := store.v3.pub.current()
|
||||
absOff := int64(store.sb.WALOffset + e.WALOffset)
|
||||
size := uint64(walEntryHeaderSizeV3) + uint64(store.sb.BlockSize)
|
||||
if e.WALOffset+size > store.sb.WALSize {
|
||||
return nil, 0, fmt.Errorf("flusher: v3 record LBA %d offset %d crosses the ring end", e.LBA, e.WALOffset)
|
||||
}
|
||||
full := make([]byte, size)
|
||||
if _, err := store.fd.ReadAt(full, absOff); err != nil {
|
||||
return nil, 0, fmt.Errorf("flusher: read v3 WAL record at %d: %w", e.WALOffset, err)
|
||||
}
|
||||
entry, err := decodeWALEntryV3(full, d.BlockSize, d.VolumeSize/uint64(d.BlockSize))
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("flusher: invalid v3 WAL record LBA %d offset %d: %w", e.LBA, e.WALOffset, err)
|
||||
}
|
||||
if entry.Type != walEntryWrite || entry.LSN != e.LSN || entry.LBA != e.LBA || entry.Nonce != d.Nonce ||
|
||||
e.DataOffset != 0 || e.Length != store.sb.BlockSize {
|
||||
return nil, 0, fmt.Errorf("flusher: v3 WAL slot mismatch LBA %d offset %d dirty LSN %d record LSN %d",
|
||||
e.LBA, e.WALOffset, e.LSN, entry.LSN)
|
||||
}
|
||||
return entry.Data, size, nil
|
||||
}
|
||||
|
||||
// persistCheckpointV3 is the v3 checkpoint/tail publication. It goes
|
||||
// through the row-3 publisher with the row-7 map candidate; without one,
|
||||
// the checkpoint and tail do not move (no coverage is fabricated) and the
|
||||
// flushed bytes stay retained in the WAL.
|
||||
func (s *WALStore) persistCheckpointV3(highestLSN uint64) error {
|
||||
v := s.v3
|
||||
if v.mapCandidate == nil {
|
||||
return nil
|
||||
}
|
||||
mutateMap, err := v.mapCandidate(highestLSN)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := v.pub.publish(&s.mu, nil, func(n *descriptorV3) error {
|
||||
n.CheckpointLSN = highestLSN
|
||||
return mutateMap(n)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.checkpointLSN = d.CheckpointLSN
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
@@ -5,31 +5,68 @@ import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Row 5 store-level controls (DESIGN r15 6.1 to 6.6, section 11 item 5 and
|
||||
// the G1 fence). "Crash" here closes the file without any further write, so
|
||||
// every pwritten byte is still visible on reopen; damage is injected into
|
||||
// the file directly.
|
||||
// Row 5/5b store-level controls on the REAL *WALStore in its v3 mode
|
||||
// (DESIGN r15 6.1 to 6.6, section 11 item 5 and the G1 fence). A "crash"
|
||||
// stops the committer and closes the file without any flush or further
|
||||
// write (crashRecoveryHardeningStore), so every pwritten byte is still
|
||||
// visible on reopen; damage is injected into the file directly.
|
||||
|
||||
const v3TestBlock = 4096
|
||||
const v3TestWAL = 64 * 1024
|
||||
|
||||
func newStoreV3(t *testing.T, mode WMode) (*walStoreV3, string) {
|
||||
func newStoreV3(t *testing.T, mode WMode) (*WALStore, string) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "store.v3")
|
||||
s, err := createWALStoreV3ForTest(path, 64, v3TestBlock, v3TestWAL, mode)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
return s, path
|
||||
}
|
||||
|
||||
// reopenV3 opens and recovers, as a restart would.
|
||||
func reopenV3(t *testing.T, path string) (*WALStore, error) {
|
||||
t.Helper()
|
||||
s, err := openWALStoreV3ForTest(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err := s.Recover(); err != nil {
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func mustReopenV3(t *testing.T, path string) *WALStore {
|
||||
t.Helper()
|
||||
s, err := reopenV3(t, path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func blk(b byte) []byte { return bytes.Repeat([]byte{b}, v3TestBlock) }
|
||||
|
||||
func readV3(t *testing.T, s *WALStore, lba uint32) []byte {
|
||||
t.Helper()
|
||||
b, err := s.Read(lba)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// writeSynced writes one block per LSN, each in its own Sync (batch).
|
||||
func writeSynced(t *testing.T, s *walStoreV3, from, to uint32) {
|
||||
func writeSynced(t *testing.T, s *WALStore, from, to uint32) {
|
||||
t.Helper()
|
||||
for lba := from; lba <= to; lba++ {
|
||||
if _, err := s.Write(lba, blk(byte(lba))); err != nil {
|
||||
@@ -102,26 +139,18 @@ func TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes(t *testing.T) {
|
||||
for _, mode := range []WMode{WModeLagged, WModeStrict} {
|
||||
s, path := newStoreV3(t, mode)
|
||||
writeSynced(t, s, 1, 5)
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := openWALStoreV3(path)
|
||||
if err != nil {
|
||||
t.Fatalf("mode %d: reopen: %v", mode, err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r := mustReopenV3(t, path)
|
||||
for lba := uint32(1); lba <= 5; lba++ {
|
||||
if !bytes.Equal(r.Read(lba), blk(byte(lba))) {
|
||||
if !bytes.Equal(readV3(t, r, lba), blk(byte(lba))) {
|
||||
t.Fatalf("mode %d: acknowledged LBA %d lost", mode, lba)
|
||||
}
|
||||
}
|
||||
// Writes continue after recovery and survive another reopen.
|
||||
// Writes continue after recovery and survive another crash.
|
||||
writeSynced(t, r, 6, 7)
|
||||
_ = r.Close()
|
||||
r2, err := openWALStoreV3(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(r2.Read(7), blk(7)) || !bytes.Equal(r2.Read(1), blk(1)) {
|
||||
crashRecoveryHardeningStore(t, r)
|
||||
r2 := mustReopenV3(t, path)
|
||||
if !bytes.Equal(readV3(t, r2, 7), blk(7)) || !bytes.Equal(readV3(t, r2, 1), blk(1)) {
|
||||
t.Fatalf("mode %d: writes after recovery lost", mode)
|
||||
}
|
||||
_ = r2.Close()
|
||||
@@ -129,17 +158,18 @@ func TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch(t *testing.T) {
|
||||
// Newest acknowledged batch corrupted before any later Sync or refresh:
|
||||
// mode C truncates it silently (the documented window); mode A refuses.
|
||||
// The newest acknowledged batch corrupted before any later Sync or
|
||||
// refresh: mode C truncates it silently (the documented window); mode A
|
||||
// refuses.
|
||||
for _, c := range []struct {
|
||||
mode WMode
|
||||
corrupt bool
|
||||
}{{WModeLagged, false}, {WModeStrict, true}} {
|
||||
s, path := newStoreV3(t, c.mode)
|
||||
writeSynced(t, s, 1, 3)
|
||||
_ = s.Close()
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
damageRecord(t, path, 3)
|
||||
r, err := openWALStoreV3(path)
|
||||
r, err := reopenV3(t, path)
|
||||
if c.corrupt {
|
||||
if !isWALCorrupt(err) {
|
||||
t.Fatalf("mode A, newest batch corrupt: err = %v, want wal_corrupt", err)
|
||||
@@ -149,7 +179,7 @@ func TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("mode C, newest batch corrupt: err = %v, want the documented silent truncation", err)
|
||||
}
|
||||
if !bytes.Equal(r.Read(2), blk(2)) || r.Read(3) != nil {
|
||||
if !bytes.Equal(readV3(t, r, 2), blk(2)) || bytes.Equal(readV3(t, r, 3), blk(3)) {
|
||||
t.Fatal("mode C: want LSN 1-2 kept and the newest batch (3) truncated")
|
||||
}
|
||||
_ = r.Close()
|
||||
@@ -158,9 +188,9 @@ func TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch(t *testing.T) {
|
||||
for _, mode := range []WMode{WModeLagged, WModeStrict} {
|
||||
s, path := newStoreV3(t, mode)
|
||||
writeSynced(t, s, 1, 3)
|
||||
_ = s.Close()
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
damageRecord(t, path, 2)
|
||||
if _, err := openWALStoreV3(path); !isWALCorrupt(err) {
|
||||
if _, err := reopenV3(t, path); !isWALCorrupt(err) {
|
||||
t.Fatalf("mode %d, second-newest batch corrupt: err = %v, want wal_corrupt", mode, err)
|
||||
}
|
||||
}
|
||||
@@ -172,9 +202,9 @@ func TestWALStoreV3RefreshAndSetWModeCloseTheWindow(t *testing.T) {
|
||||
if err := s.refreshW(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = s.Close()
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
damageRecord(t, path, 3)
|
||||
if _, err := openWALStoreV3(path); !isWALCorrupt(err) {
|
||||
if _, err := reopenV3(t, path); !isWALCorrupt(err) {
|
||||
t.Fatalf("after the idle refresh: err = %v, want wal_corrupt", err)
|
||||
}
|
||||
|
||||
@@ -183,12 +213,12 @@ func TestWALStoreV3RefreshAndSetWModeCloseTheWindow(t *testing.T) {
|
||||
if err := s2.SetWMode(WModeStrict); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s2.pub.current().WMode != WModeStrict {
|
||||
if s2.v3.pub.current().WMode != WModeStrict {
|
||||
t.Fatal("SetWMode did not publish the new mode")
|
||||
}
|
||||
_ = s2.Close()
|
||||
crashRecoveryHardeningStore(t, s2)
|
||||
damageRecord(t, path2, 3)
|
||||
if _, err := openWALStoreV3(path2); !isWALCorrupt(err) {
|
||||
if _, err := reopenV3(t, path2); !isWALCorrupt(err) {
|
||||
t.Fatalf("after SetWMode(A): err = %v, want wal_corrupt (C -> A closes the window)", err)
|
||||
}
|
||||
}
|
||||
@@ -200,36 +230,41 @@ func TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt(t *testing.T) {
|
||||
if _, err := s.Write(4, blk(4)); err != nil { // appended, never synced
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = s.Close()
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
damageRecord(t, path, 4) // a torn unsynced record
|
||||
r, err := openWALStoreV3(path)
|
||||
r, err := reopenV3(t, path)
|
||||
if err != nil {
|
||||
t.Fatalf("mode %d, torn unsynced tail: err = %v, want recovery", mode, err)
|
||||
}
|
||||
if !bytes.Equal(r.Read(3), blk(3)) || r.Read(4) != nil {
|
||||
if !bytes.Equal(readV3(t, r, 3), blk(3)) || bytes.Equal(readV3(t, r, 4), blk(4)) {
|
||||
t.Fatalf("mode %d: want 1-3 kept and the unsynced 4 dropped", mode)
|
||||
}
|
||||
_ = r.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// G1 (DESIGN 6.6): records dropped by one recovery must not resurface after
|
||||
// a second crash. Without the fence, re-filling the gap with a record of the
|
||||
// same size re-chains the old record behind it.
|
||||
// resurrectionSchedule is the G1 schedule (DESIGN 6.6): records dropped by
|
||||
// one recovery must not resurface after a second crash. Without the fence,
|
||||
// re-filling the gap with a record of the same size re-chains the old
|
||||
// record behind it.
|
||||
func resurrectionSchedule(t *testing.T, mode WMode, skipFence bool) (resurrected bool) {
|
||||
t.Helper()
|
||||
s, path := newStoreV3(t, mode)
|
||||
writeSynced(t, s, 1, 3)
|
||||
if _, err := s.Write(4, blk(4)); err != nil { // unsynced
|
||||
t.Fatal(err)
|
||||
for _, lba := range []uint32{4, 5} { // unsynced
|
||||
if _, err := s.Write(lba, blk(byte(lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Write(5, blk(5)); err != nil { // unsynced
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = s.Close()
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
damageRecord(t, path, 4) // a torn LSN 4: recovery keeps 1-3 and drops the trusted 5
|
||||
r := openV3WithFence(t, path, skipFence)
|
||||
if r.Read(5) != nil {
|
||||
testSkipFenceOnRecoverV3 = skipFence
|
||||
r, err := reopenV3(t, path)
|
||||
testSkipFenceOnRecoverV3 = false
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bytes.Equal(readV3(t, r, 5), blk(5)) {
|
||||
t.Fatal("first recovery kept LSN 5 above the gap")
|
||||
}
|
||||
if _, err := r.Write(9, blk(0x99)); err != nil { // re-fills LSN 4's place, same size
|
||||
@@ -238,37 +273,10 @@ func resurrectionSchedule(t *testing.T, mode WMode, skipFence bool) (resurrected
|
||||
if _, err := r.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = r.Close()
|
||||
r2, err := openWALStoreV3(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, r)
|
||||
r2 := mustReopenV3(t, path)
|
||||
defer r2.Close()
|
||||
return r2.Read(5) != nil
|
||||
}
|
||||
|
||||
// openV3WithFence opens with the fence optionally disabled (mutant switch),
|
||||
// by re-running recovery on a store whose test switch is set first.
|
||||
func openV3WithFence(t *testing.T, path string, skipFence bool) *walStoreV3 {
|
||||
t.Helper()
|
||||
if !skipFence {
|
||||
r, err := openWALStoreV3(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r
|
||||
}
|
||||
fd, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
testSkipFenceOnRecoverV3 = true
|
||||
defer func() { testSkipFenceOnRecoverV3 = false }()
|
||||
r, err := recoverWALStoreV3(fd)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r
|
||||
return bytes.Equal(readV3(t, r2, 5), blk(5))
|
||||
}
|
||||
|
||||
func TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash(t *testing.T) {
|
||||
@@ -295,18 +303,15 @@ func TestWALStoreV3FenceTouchesNoByteBeforeTheHead(t *testing.T) {
|
||||
if _, err := s.Write(4, blk(4)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = s.Close()
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
damageRecord(t, path, 4)
|
||||
before, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e := uint64(recordOffset(t, path, 3)) + walEntryHeaderSizeV3 + v3TestBlock // end of LSN 3
|
||||
r, err := openWALStoreV3(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = r.Close()
|
||||
r := mustReopenV3(t, path)
|
||||
crashRecoveryHardeningStore(t, r)
|
||||
after, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -317,8 +322,6 @@ func TestWALStoreV3FenceTouchesNoByteBeforeTheHead(t *testing.T) {
|
||||
if !bytes.Equal(after[e:walOffsetV3+v3TestWAL], make([]byte, walOffsetV3+v3TestWAL-e)) {
|
||||
t.Fatal("the fence left a nonzero byte in [E, floor+WALSize)")
|
||||
}
|
||||
// E = 3 x 4166 = 12498 is not page-aligned; the byte just before it
|
||||
// belongs to LSN 3 and is unchanged (checked above), so nothing rounded down.
|
||||
if e%4096 == 0 {
|
||||
t.Fatal("test setup: E is page-aligned; it should exercise an unaligned head")
|
||||
}
|
||||
@@ -329,17 +332,248 @@ func TestWALStoreV3AppendWriteErrorLatchesTheStore(t *testing.T) {
|
||||
defer s.Close()
|
||||
writeSynced(t, s, 1, 1)
|
||||
boom := errors.New("injected WAL pwrite error")
|
||||
s.w.writeAt = func([]byte, int64) (int, error) { return 0, boom }
|
||||
s.v3.w.writeAt = func([]byte, int64) (int, error) { return 0, boom }
|
||||
if _, err := s.Write(2, blk(2)); !errors.Is(err, boom) {
|
||||
t.Fatalf("append: err = %v, want the pwrite error", err)
|
||||
}
|
||||
if s.sticky() == nil {
|
||||
if s.stickyIOFault() == nil {
|
||||
t.Fatal("an append pwrite error did not latch the store-global fault")
|
||||
}
|
||||
if _, err := s.Sync(); err == nil {
|
||||
t.Fatal("Sync acknowledged after an append write error")
|
||||
}
|
||||
if _, err := s.pub.publish(&s.mu, nil, nil); err == nil {
|
||||
t.Fatal("a descriptor publication succeeded after an append write error")
|
||||
if _, err := s.Write(3, blk(3)); err == nil {
|
||||
t.Fatal("a later Write was admitted after an append write error")
|
||||
}
|
||||
}
|
||||
|
||||
// Row 5b: the v3 store uses the real flusher. Its extent writes happen,
|
||||
// but without the row-7 map candidate the checkpoint and tail do not move
|
||||
// (no fabricated coverage), and the flushed records stay retained.
|
||||
func TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.v3")
|
||||
s, err := createWALStoreV3ForTest(path, 64, v3TestBlock, v3TestWAL, WModeLagged)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeSynced(t, s, 1, 3)
|
||||
before := s.v3.pub.current()
|
||||
if err := s.flusher.flushOnceInternal(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after := s.v3.pub.current()
|
||||
if after.CheckpointLSN != before.CheckpointLSN || after.RetainedTail != before.RetainedTail || s.CheckpointLSN() != 0 {
|
||||
t.Fatalf("checkpoint/tail advanced without a map candidate: %d/%d -> %d/%d",
|
||||
before.CheckpointLSN, before.RetainedTail, after.CheckpointLSN, after.RetainedTail)
|
||||
}
|
||||
// The data reads back (now from the extent) and survives a crash (from
|
||||
// the still-retained WAL).
|
||||
for lba := uint32(1); lba <= 3; lba++ {
|
||||
if !bytes.Equal(readV3(t, s, lba), blk(byte(lba))) {
|
||||
t.Fatalf("LBA %d unreadable after the v3 flush", lba)
|
||||
}
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r := mustReopenV3(t, path)
|
||||
defer r.Close()
|
||||
for lba := uint32(1); lba <= 3; lba++ {
|
||||
if !bytes.Equal(readV3(t, r, lba), blk(byte(lba))) {
|
||||
t.Fatalf("LBA %d lost after flush and crash", lba)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreV3RefusesPathsOfLaterRows(t *testing.T) {
|
||||
s, _ := newStoreV3(t, WModeLagged)
|
||||
defer s.Close()
|
||||
if _, err := s.WriteBatch(0, [][]byte{blk(1)}); !errors.Is(err, errV3NotYet) {
|
||||
t.Fatalf("WriteBatch: err = %v, want errV3NotYet", err)
|
||||
}
|
||||
if err := s.ApplyEntry(0, blk(1), 10); !errors.Is(err, errV3NotYet) {
|
||||
t.Fatalf("ApplyEntry: err = %v, want errV3NotYet", err)
|
||||
}
|
||||
if err := s.WriteExtentDirect(0, blk(1)); !errors.Is(err, errV3NotYet) {
|
||||
t.Fatalf("WriteExtentDirect: err = %v, want errV3NotYet", err)
|
||||
}
|
||||
}
|
||||
|
||||
// codex01 row 5 P1-1: a batch's acknowledgement rechecks the store fault
|
||||
// under the store lock. Schedule, in both modes: batch A's slot write is
|
||||
// parked (A holds descMu); B's Write takes s.mu and waits on descMu in the
|
||||
// writer's snapshot; A is released, B's pwrite fails and latches while B
|
||||
// still holds s.mu; A must then refuse without advancing the acknowledged W.
|
||||
func TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary(t *testing.T) {
|
||||
for _, mode := range []WMode{WModeLagged, WModeStrict} {
|
||||
s, _ := newStoreV3(t, mode)
|
||||
writeSynced(t, s, 1, 1)
|
||||
if _, err := s.Write(2, blk(2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prev := s.v3.wack.Load()
|
||||
parked, release := make(chan struct{}), make(chan struct{})
|
||||
var once sync.Once
|
||||
s.v3.testBeforeSlotWrite = func() error {
|
||||
once.Do(func() { close(parked); <-release })
|
||||
return nil
|
||||
}
|
||||
aErr := make(chan error, 1)
|
||||
go func() { _, err := s.Sync(); aErr <- err }()
|
||||
<-parked
|
||||
boom := errors.New("injected append write error")
|
||||
s.v3.w.writeAt = func([]byte, int64) (int, error) { return 0, boom }
|
||||
bErr := make(chan error, 1)
|
||||
go func() { _, err := s.Write(3, blk(3)); bErr <- err }()
|
||||
for s.mu.TryLock() { // wait until B holds s.mu (it then blocks on descMu)
|
||||
s.mu.Unlock()
|
||||
runtime.Gosched()
|
||||
}
|
||||
close(release)
|
||||
if err := <-bErr; !errors.Is(err, boom) {
|
||||
t.Fatalf("mode %d: B: err = %v, want the append write error", mode, err)
|
||||
}
|
||||
if err := <-aErr; err == nil {
|
||||
t.Fatalf("mode %d: A acknowledged after B latched the store fault", mode)
|
||||
}
|
||||
if got := s.v3.wack.Load(); got != prev {
|
||||
t.Fatalf("mode %d: acknowledged W advanced to %d after the fault (want %d)", mode, got, prev)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
}
|
||||
}
|
||||
|
||||
// codex01 row 5 P2: a history ending at the last representable cursor
|
||||
// recovers; only further appends are refused.
|
||||
func TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor(t *testing.T) {
|
||||
const recSize = uint64(walEntryHeaderSizeV3 + v3TestBlock)
|
||||
cursor := counterMaxV3 - 3*recSize // 3 records end exactly at 2^64-2, no ring-end crossing
|
||||
path := filepath.Join(t.TempDir(), "store.v3")
|
||||
s, err := createWALStoreV3AtCursorForTest(path, 64, v3TestBlock, v3TestWAL, WModeStrict, cursor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
writeSynced(t, s, 1, 3)
|
||||
if _, err := s.Write(4, blk(4)); !errors.Is(err, ErrCounterExhausted) {
|
||||
t.Fatalf("append past the last cursor: err = %v, want ErrCounterExhausted", err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r := mustReopenV3(t, path)
|
||||
defer r.Close()
|
||||
for lba := uint32(1); lba <= 3; lba++ {
|
||||
if !bytes.Equal(readV3(t, r, lba), blk(byte(lba))) {
|
||||
t.Fatalf("LBA %d of the terminal history lost", lba)
|
||||
}
|
||||
}
|
||||
if _, err := r.Write(5, blk(5)); !errors.Is(err, ErrCounterExhausted) {
|
||||
t.Fatalf("append after recovery at the last cursor: err = %v, want ErrCounterExhausted", err)
|
||||
}
|
||||
}
|
||||
|
||||
// codex01 row 5 P2 (SetWMode evidence): a held mode-C batch completes and
|
||||
// acknowledges under C before SetWMode(A) publishes the new mode.
|
||||
func TestWALStoreV3SetWModeWaitsForAHeldBatch(t *testing.T) {
|
||||
s, _ := newStoreV3(t, WModeLagged)
|
||||
defer crashRecoveryHardeningStore(t, s)
|
||||
writeSynced(t, s, 1, 1)
|
||||
if _, err := s.Write(2, blk(2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parked, release := make(chan struct{}), make(chan struct{})
|
||||
var once sync.Once
|
||||
s.v3.testBeforeSlotWrite = func() error {
|
||||
once.Do(func() { close(parked); <-release })
|
||||
return nil
|
||||
}
|
||||
aErr := make(chan error, 1)
|
||||
go func() { _, err := s.Sync(); aErr <- err }()
|
||||
<-parked
|
||||
setErr := make(chan error, 1)
|
||||
go func() { setErr <- s.SetWMode(WModeStrict) }()
|
||||
select {
|
||||
case err := <-setErr:
|
||||
t.Fatalf("SetWMode returned (%v) while a C batch was held", err)
|
||||
default:
|
||||
}
|
||||
close(release)
|
||||
if err := <-aErr; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-setErr; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cur := s.v3.pub.current()
|
||||
if cur.WMode != WModeStrict || cur.W != 2 {
|
||||
t.Fatalf("after SetWMode: mode %d W %d, want A and W 2", cur.WMode, cur.W)
|
||||
}
|
||||
// The held batch's own publication (now the fallback slot) was mode C
|
||||
// with the lagged W 1.
|
||||
if fb := s.v3.pub.other; fb.WMode != WModeLagged || fb.W != 1 || fb.SlotGen != cur.SlotGen-1 {
|
||||
t.Fatalf("held batch publication: mode %d W %d gen %d, want C, W 1, gen %d", fb.WMode, fb.W, fb.SlotGen, cur.SlotGen-1)
|
||||
}
|
||||
}
|
||||
|
||||
// No batch acknowledges under a stale mode: a batch that reaches the
|
||||
// leader role while SetWMode(A) holds it publishes with A's rule (W = H)
|
||||
// once SetWMode has committed.
|
||||
func TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode(t *testing.T) {
|
||||
s, _ := newStoreV3(t, WModeLagged)
|
||||
defer crashRecoveryHardeningStore(t, s)
|
||||
writeSynced(t, s, 1, 1)
|
||||
parked, release := make(chan struct{}), make(chan struct{})
|
||||
s.v3.testSetWModeHoldingRole = func() { close(parked); <-release }
|
||||
setErr := make(chan error, 1)
|
||||
go func() { setErr <- s.SetWMode(WModeStrict) }() // parks holding the leader role, before publishing
|
||||
<-parked
|
||||
if _, err := s.Write(2, blk(2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waiting := make(chan struct{})
|
||||
var wonce sync.Once
|
||||
s.v3.testLeaderWaiting = func() { wonce.Do(func() { close(waiting) }) }
|
||||
bErr := make(chan error, 1)
|
||||
go func() { _, err := s.Sync(); bErr <- err }()
|
||||
<-waiting // B is about to take the leader role SetWMode holds
|
||||
close(release)
|
||||
if err := <-setErr; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-bErr; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cur := s.v3.pub.current(); cur.WMode != WModeStrict || cur.W != 2 {
|
||||
t.Fatalf("batch after SetWMode(A): mode %d slot W %d, want A with W = H = 2 (a stale C ack would leave W 1)", cur.WMode, cur.W)
|
||||
}
|
||||
}
|
||||
|
||||
// SetWMode crash cases: a committed mode survives a crash; a failed mode
|
||||
// publication leaves the old mode on disk and latches the store.
|
||||
func TestWALStoreV3SetWModeCrashCases(t *testing.T) {
|
||||
s, path := newStoreV3(t, WModeLagged)
|
||||
writeSynced(t, s, 1, 2)
|
||||
if err := s.SetWMode(WModeStrict); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r := mustReopenV3(t, path)
|
||||
if m := r.v3.pub.current().WMode; m != WModeStrict {
|
||||
t.Fatalf("committed SetWMode lost across a crash: mode %d", m)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, r)
|
||||
|
||||
s2, path2 := newStoreV3(t, WModeLagged)
|
||||
writeSynced(t, s2, 1, 2)
|
||||
boom := errors.New("injected mode slot write error")
|
||||
s2.v3.testBeforeSlotWrite = func() error { return boom }
|
||||
if err := s2.SetWMode(WModeStrict); !errors.Is(err, boom) {
|
||||
t.Fatalf("SetWMode with a failing slot write: err = %v, want the write error", err)
|
||||
}
|
||||
if s2.stickyIOFault() == nil {
|
||||
t.Fatal("a failed mode publication did not latch the store")
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s2)
|
||||
r2 := mustReopenV3(t, path2)
|
||||
defer r2.Close()
|
||||
if m := r2.v3.pub.current().WMode; m != WModeLagged {
|
||||
t.Fatalf("a failed SetWMode changed the mode on disk: %d", m)
|
||||
}
|
||||
}
|
||||
@@ -283,8 +283,8 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
|
||||
| `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB |
|
||||
| `INV-WAL-V3-MAP-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; any failure yields no candidate and no retry I/O. Append-only retention preserves both slots and pending candidates. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords` | 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. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `Sync`, `refreshW`, `SetWMode`, `recoverWALStoreV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3` | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_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` `fenceV3`, `recoverWALStoreV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | 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. | 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` | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_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-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` | `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. | 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`); `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 |
|
||||
@@ -295,7 +295,7 @@ Notes:
|
||||
|
||||
- `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only.
|
||||
- `INV-FE-FLUSH-SYNC-001`: The failed-`Sync` case is asserted for ublk; for NVMe/TCP only the dispatch to `Sync` is asserted here.
|
||||
- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan row 5 (DESIGN r15 sections 6.1 to 6.6). 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-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`).
|
||||
|
||||
|
||||
Reference in new issue
Block a user