mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
storage: v3 store core, W modes C/A, R<W* recovery and the drop fence (format bump row 5)
DESIGN r15 sections 6.1 to 6.6 (f2122d66), PLAN row 5 (b870a569). Dark: the only constructor is createWALStoreV3ForTest; the v2 path is unchanged. - recovery_v3.go (pure): scan start max(BaseCursor, retainedTail) (G2), floor F, contiguous prefix R and its end E over the row-4 trusted chain, the R < W* decision (wal_corrupt when serving; ErrBaseIncomplete, plus ErrInstallSuffixDamaged and WALIntegrity when damaged, while installing), and the exact fence ranges over [E, floor+WALSize), split at the wrap. - walstore_v3.go: open selects a slot, scans (row 4), decides, replays the records <= R last-writer-wins, fences and fsyncs the exact ranges through the leaf, publishes retainedHead = E, restores the writer to E, and only then admits. Sync mode C publishes the previous batch's W, so one fsync covers WAL and slot; mode A fsyncs the WAL, then publishes W = H. refreshW, and SetWMode under the group-commit leader role, publish W = Wack. An append pwrite error latches the store-global fault. - Tests: I1 across reopen in both modes; the C window (newest batch truncated in C, wal_corrupt in A; second-newest wal_corrupt in both); refresh and SetWMode(A) close it; a torn unsynced tail is never corrupt; the G1 resurrection schedule (and its no-fence counterexample); a byte-exact fence at an unaligned E; the append write-error latch. - invariants.md: INV-WAL-V3-W-001 and INV-WAL-V3-FENCE-001 (STUB). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f93e17d80a
commit
40b7614faf
5 files changed
+1078
-1
No files matched your search
@@ -0,0 +1,171 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Impl-3 recovery decisions (format bump v3, DESIGN r15 sections 6.5 and
|
||||
// 6.6; plan row 5). These are the pure parts: the scan start, the replay
|
||||
// floor F, the contiguous prefix R with its end E, the R < W* decision for
|
||||
// serving and installing descriptors, and the exact byte ranges of the drop
|
||||
// fence. The record scan itself (nonce, cursor, lap and CRC trust order) is
|
||||
// plan row 4; this file consumes its trusted records.
|
||||
|
||||
// ErrInstallSuffixDamaged: an installing volume's acknowledged install-log
|
||||
// suffix is missing or corrupt (R < W*). The volume stays not ready, the
|
||||
// install cannot be resumed, and only a covering superseding install (new
|
||||
// BaseLSN >= W) may proceed (DESIGN 6.5, 8.3).
|
||||
var ErrInstallSuffixDamaged = errors.New("storage: v3 install-log suffix damaged; resume refused")
|
||||
|
||||
// ErrBaseIncomplete: the descriptor is installing; the local image is not
|
||||
// ready (DESIGN 8.3). It wraps ErrInstallSuffixDamaged and a WALIntegrity
|
||||
// cause when the suffix is damaged.
|
||||
var ErrBaseIncomplete = errors.New("storage: v3 BASE install incomplete; not ready")
|
||||
|
||||
// scanStartV3 is where recovery starts reading (DESIGN 6.5 step 2): the
|
||||
// retained tail, or max(BaseCursor, retainedTail) when a BASE state is set
|
||||
// (G2: after installed the tail may have moved past BaseCursor).
|
||||
func scanStartV3(d descriptorV3) uint64 {
|
||||
if d.BaseState == BaseNone {
|
||||
return d.RetainedTail
|
||||
}
|
||||
return max(d.BaseCursor, d.RetainedTail)
|
||||
}
|
||||
|
||||
// replayFloorV3 is F (DESIGN 6.5 step 1): LSNs at or below it need not be
|
||||
// in this WAL.
|
||||
func replayFloorV3(d descriptorV3) uint64 {
|
||||
if d.BaseState == BaseNone {
|
||||
return d.CheckpointLSN
|
||||
}
|
||||
return max(d.CheckpointLSN, d.BaseLSN)
|
||||
}
|
||||
|
||||
// trustedRecordV3 is one record of the trusted chain, in cursor order, as
|
||||
// the row-4 scan returns it: its first and last LSN (a batch covers a
|
||||
// range; padding carries none) and the logical cursor just past it.
|
||||
type trustedRecordV3 struct {
|
||||
FirstLSN uint64 // 0 for padding
|
||||
LastLSN uint64
|
||||
End uint64 // logical cursor after this record
|
||||
Padding bool
|
||||
}
|
||||
|
||||
// contiguousPrefixV3 computes R, the contiguous LSN prefix above F, and E,
|
||||
// the logical cursor just past the last record that belongs to it (or to
|
||||
// the already-covered region at or below F). Records above R are dropped by
|
||||
// recovery. start is the scan start, used when no record qualifies. LSNs
|
||||
// in a trusted chain only increase; a decrease is a contradiction and is
|
||||
// refused.
|
||||
func contiguousPrefixV3(start, F uint64, recs []trustedRecordV3) (R, E uint64, err error) {
|
||||
R, E = F, start
|
||||
var prev uint64
|
||||
for _, r := range recs {
|
||||
if r.Padding {
|
||||
// The loop returns at the first gap, so any padding seen here
|
||||
// lies inside the kept run: E moves past it.
|
||||
E = r.End
|
||||
continue
|
||||
}
|
||||
if r.FirstLSN == 0 || r.LastLSN < r.FirstLSN {
|
||||
return 0, 0, fmt.Errorf("storage: v3 recovery: malformed record span %d..%d", r.FirstLSN, r.LastLSN)
|
||||
}
|
||||
if prev != 0 && r.FirstLSN <= prev {
|
||||
return 0, 0, fmt.Errorf("storage: v3 recovery: LSN %d after %d in one trusted chain", r.FirstLSN, prev)
|
||||
}
|
||||
prev = r.LastLSN
|
||||
switch {
|
||||
case r.LastLSN <= R:
|
||||
E = r.End // at or below the floor or already counted: part of the kept run
|
||||
case r.FirstLSN <= R+1:
|
||||
R, E = r.LastLSN, r.End
|
||||
default:
|
||||
return R, E, nil // a gap: everything from here on is dropped
|
||||
}
|
||||
}
|
||||
return R, E, nil
|
||||
}
|
||||
|
||||
// recoveryOutcomeV3 is what recovery does with the scan (DESIGN 6.5).
|
||||
type recoveryOutcomeV3 struct {
|
||||
Start, F, R, E, WStar uint64
|
||||
// Serve: replay records <= R, drop the rest, fence above E, publish
|
||||
// retainedHead = E, admit. Installing: not ready (ErrBaseIncomplete);
|
||||
// Damaged says whether resume is refused.
|
||||
Serve bool
|
||||
Installing bool
|
||||
Damaged bool
|
||||
}
|
||||
|
||||
// decideRecoveryV3 applies DESIGN 6.5 steps 3 to 7. maxDurable is the
|
||||
// highest DurableLSN among the trusted records. It returns an error only
|
||||
// for a serving descriptor with R < W* (WALIntegrity, wal_corrupt); the
|
||||
// installing outcomes are reported in the result, damaged or not, and the
|
||||
// caller wraps them in ErrBaseIncomplete.
|
||||
func decideRecoveryV3(d descriptorV3, recs []trustedRecordV3, maxDurable uint64) (recoveryOutcomeV3, error) {
|
||||
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())
|
||||
}
|
||||
o.R, o.E = R, E
|
||||
o.WStar = max(d.W, maxDurable)
|
||||
if d.BaseState == BaseInstalling {
|
||||
o.Installing = true
|
||||
o.Damaged = R < o.WStar
|
||||
return o, nil
|
||||
}
|
||||
if R < o.WStar {
|
||||
return o, NewWALIntegrityFailure(nil, fmt.Sprintf(
|
||||
"v3 recovery: synced LSN missing or corrupt: contiguous prefix R=%d below W*=%d (F=%d, start=%d)",
|
||||
R, o.WStar, o.F, o.Start))
|
||||
}
|
||||
o.Serve = true
|
||||
return o, nil
|
||||
}
|
||||
|
||||
// installingErrorV3 is the typed not-ready error for an installing outcome.
|
||||
func installingErrorV3(o recoveryOutcomeV3) error {
|
||||
if !o.Damaged {
|
||||
return ErrBaseIncomplete
|
||||
}
|
||||
return fmt.Errorf("%w: %w (R=%d < W*=%d): %w", ErrBaseIncomplete, ErrInstallSuffixDamaged, o.R, o.WStar,
|
||||
NewWALIntegrityFailure(nil, "acknowledged install-log record missing or corrupt"))
|
||||
}
|
||||
|
||||
// fenceRangeV3 is one physical byte range of the WAL region to zero,
|
||||
// relative to the region start (the caller adds the WAL offset).
|
||||
type fenceRangeV3 struct{ Off, Len uint64 }
|
||||
|
||||
// fenceRangesV3 returns the exact physical byte ranges of the drop fence
|
||||
// (DESIGN 6.6, r14): the logical interval [E, floor+walSize) mapped modulo
|
||||
// the ring, split at the physical wrap into at most two ranges. Nothing
|
||||
// outside it is touched: not [floor, E), and no rounding to pages. With
|
||||
// sameNonce false (a reset between its two publications) the interval is
|
||||
// empty, as it is when E >= floor+walSize.
|
||||
func fenceRangesV3(E, floor, walSize uint64, sameNonce bool) ([]fenceRangeV3, error) {
|
||||
if walSize == 0 {
|
||||
return nil, fmt.Errorf("storage: v3 fence: zero WAL size")
|
||||
}
|
||||
if !sameNonce {
|
||||
return nil, nil
|
||||
}
|
||||
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 {
|
||||
return nil, nil
|
||||
}
|
||||
n := end - E // at most walSize
|
||||
start := E % walSize
|
||||
if start+n <= walSize {
|
||||
return []fenceRangeV3{{Off: start, Len: n}}, nil
|
||||
}
|
||||
first := walSize - start
|
||||
return []fenceRangeV3{{Off: start, Len: first}, {Off: 0, Len: n - first}}, nil
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Row 5 pure recovery decisions (DESIGN r15 6.5, 6.6).
|
||||
|
||||
func rec(first, last, end uint64) trustedRecordV3 {
|
||||
return trustedRecordV3{FirstLSN: first, LastLSN: last, End: end}
|
||||
}
|
||||
|
||||
func TestRecoveryV3ScanStartAndFloor(t *testing.T) {
|
||||
d := descriptorV3{RetainedTail: 500, CheckpointLSN: 40}
|
||||
if scanStartV3(d) != 500 || replayFloorV3(d) != 40 {
|
||||
t.Fatalf("none: start %d floor %d, want 500 40", scanStartV3(d), replayFloorV3(d))
|
||||
}
|
||||
d.BaseState, d.BaseLSN, d.BaseCursor = BaseInstalling, 100, 600
|
||||
if scanStartV3(d) != 600 || replayFloorV3(d) != 100 {
|
||||
t.Fatalf("installing: start %d floor %d, want 600 100", scanStartV3(d), replayFloorV3(d))
|
||||
}
|
||||
// G2: after installed the tail moved past BaseCursor; start at the tail.
|
||||
d.BaseState, d.BaseCursor = BaseInstalled, 300
|
||||
if scanStartV3(d) != 500 {
|
||||
t.Fatalf("installed with tail past BaseCursor: start %d, want 500 (max)", scanStartV3(d))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoveryV3ContiguousPrefix(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
F uint64
|
||||
recs []trustedRecordV3
|
||||
R, E uint64
|
||||
isErr bool
|
||||
}{
|
||||
{"empty", 10, nil, 10, 1000, false},
|
||||
{"contiguous", 10, []trustedRecordV3{rec(11, 11, 1100), rec(12, 12, 1200)}, 12, 1200, false},
|
||||
{"gap drops the rest", 10, []trustedRecordV3{rec(11, 11, 1100), rec(13, 13, 1300)}, 11, 1100, false},
|
||||
{"first record above the floor is a gap", 10, []trustedRecordV3{rec(12, 12, 1200)}, 10, 1000, false},
|
||||
{"records at or below F are kept", 10, []trustedRecordV3{rec(9, 9, 1050), rec(10, 10, 1080), rec(11, 11, 1100)}, 11, 1100, false},
|
||||
{"batch counts as its whole range", 10, []trustedRecordV3{rec(11, 14, 1400), rec(15, 15, 1500)}, 15, 1500, false},
|
||||
{"batch straddling the floor", 10, []trustedRecordV3{rec(9, 12, 1200), rec(13, 13, 1300)}, 13, 1300, false},
|
||||
{"padding inside the run moves E", 10, []trustedRecordV3{rec(11, 11, 1100), {Padding: true, End: 1150}, rec(12, 12, 1250)}, 12, 1250, false},
|
||||
{"padding at the end of the run", 10, []trustedRecordV3{rec(11, 11, 1100), {Padding: true, End: 1150}}, 11, 1150, false},
|
||||
{"repeated or decreasing LSN inside the run is refused", 10, []trustedRecordV3{rec(11, 11, 1100), rec(11, 11, 1200)}, 0, 0, true},
|
||||
{"malformed span is refused", 10, []trustedRecordV3{rec(12, 11, 1200)}, 0, 0, true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
R, E, err := contiguousPrefixV3(1000, c.F, c.recs)
|
||||
if c.isErr {
|
||||
if err == nil {
|
||||
t.Fatal("want an error")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if R != c.R || E != c.E {
|
||||
t.Fatalf("R %d E %d, want R %d E %d", R, E, c.R, c.E)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoveryV3Decision(t *testing.T) {
|
||||
base := descriptorV3{RetainedTail: 1000, RetainedHead: 1000, CheckpointLSN: 10, W: 12}
|
||||
recs := []trustedRecordV3{rec(11, 11, 1100), rec(12, 12, 1200), rec(13, 13, 1300)}
|
||||
|
||||
o, err := decideRecoveryV3(base, recs, 12)
|
||||
if err != nil || !o.Serve || o.R != 13 || o.E != 1300 {
|
||||
t.Fatalf("serve: %+v %v, want serve R 13 E 1300", o, err)
|
||||
}
|
||||
// A synced record (12, W=12) corrupt: the chain stops at 11 < W*.
|
||||
_, err = decideRecoveryV3(base, recs[:1], 12)
|
||||
var rf *RecoveryFailure
|
||||
if !errors.As(err, &rf) || rf.Kind != StorageRecoveryFailureWALIntegrity {
|
||||
t.Fatalf("R < W: err = %v, want a WALIntegrity failure", err)
|
||||
}
|
||||
// W* takes the max DurableLSN of the trusted records.
|
||||
low := base
|
||||
low.W = 10
|
||||
if _, err := decideRecoveryV3(low, recs[:1], 12); err == nil {
|
||||
t.Fatal("max DurableLSN 12 above R 11 was not refused")
|
||||
}
|
||||
// Installing: intact and damaged, never a bare wal_corrupt.
|
||||
inst := base
|
||||
inst.BaseState, inst.BaseLSN, inst.BaseCursor = BaseInstalling, 10, 1000
|
||||
inst.BaseInstallID[0] = 1
|
||||
o, err = decideRecoveryV3(inst, recs, 12)
|
||||
if err != nil || !o.Installing || o.Damaged {
|
||||
t.Fatalf("installing intact: %+v %v", o, err)
|
||||
}
|
||||
if !errors.Is(installingErrorV3(o), ErrBaseIncomplete) || errors.Is(installingErrorV3(o), ErrInstallSuffixDamaged) {
|
||||
t.Fatal("intact installing error is not a plain ErrBaseIncomplete")
|
||||
}
|
||||
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)
|
||||
}
|
||||
ie := installingErrorV3(o)
|
||||
if !errors.Is(ie, ErrBaseIncomplete) || !errors.Is(ie, ErrInstallSuffixDamaged) || !errors.As(ie, &rf) ||
|
||||
rf.Kind != StorageRecoveryFailureWALIntegrity {
|
||||
t.Fatalf("damaged installing error %v must wrap ErrBaseIncomplete, ErrInstallSuffixDamaged and WALIntegrity", ie)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoveryV3FenceRangesAreExact(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
E, floor, walSize uint64
|
||||
sameNonce bool
|
||||
want []fenceRangeV3
|
||||
}{
|
||||
// codex03 r13 example: WALSize 256, fallback tail 0, selected 100,
|
||||
// E 120. The fence is exactly [120, 256): physical [0, 100), which
|
||||
// the fallback still references, is untouched.
|
||||
{"floor bound, not the selected tail", 120, 0, 256, true, []fenceRangeV3{{120, 136}}},
|
||||
// Unaligned E after a barrier (70) and a one-block write (4166):
|
||||
// never rounded to a page.
|
||||
{"unaligned E 70", 70, 0, 1 << 20, true, []fenceRangeV3{{70, 1<<20 - 70}}},
|
||||
{"unaligned E 4166", 4166, 0, 1 << 20, true, []fenceRangeV3{{4166, 1<<20 - 4166}}},
|
||||
// The interval wraps physically: two exact ranges.
|
||||
{"no wrap: logical [300,356) is physical [44,100)", 300, 100, 256, true, []fenceRangeV3{{44, 56}}},
|
||||
{"wrap: two exact ranges, [floor,E) untouched", 200, 100, 256, true, []fenceRangeV3{{200, 56}, {0, 100}}},
|
||||
{"unaligned end after a wrap", 5000, 4166, 4096, true, []fenceRangeV3{{904, 3192}, {0, 70}}},
|
||||
{"head at the end: nothing", 356, 100, 256, true, nil},
|
||||
{"mixed nonces: nothing", 120, 0, 256, false, nil},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got, err := fenceRangesV3(c.E, c.floor, c.walSize, c.sameNonce)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, c.want) {
|
||||
t.Fatalf("ranges %v, want %v", got, c.want)
|
||||
}
|
||||
var total uint64
|
||||
for _, r := range got {
|
||||
total += r.Len
|
||||
}
|
||||
if c.sameNonce && c.E < c.floor+c.walSize && total != c.floor+c.walSize-c.E {
|
||||
t.Fatalf("fenced %d bytes, want exactly %d", total, c.floor+c.walSize-c.E)
|
||||
}
|
||||
})
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"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:
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// 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
|
||||
|
||||
pub *descriptorPublisherV3
|
||||
w *walWriterV3
|
||||
|
||||
// testBeforeFence, when set, runs just before the drop fence writes.
|
||||
testBeforeFence func()
|
||||
}
|
||||
|
||||
// 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) {
|
||||
if err != nil {
|
||||
s.ioFault.CompareAndSwap(nil, &err)
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
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) {
|
||||
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,
|
||||
}
|
||||
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
|
||||
}
|
||||
if err := d.validate(nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fd, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o644)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = fd.Truncate(int64(d.WALOffset + d.WALSize + d.VolumeSize))
|
||||
if err == nil {
|
||||
_, err = fd.WriteAt(d.encode(), slotAOffsetV3)
|
||||
}
|
||||
if err == nil {
|
||||
err = fd.Sync()
|
||||
}
|
||||
if cerr := fd.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s, err := recoverWALStoreV3(fd)
|
||||
if err != nil {
|
||||
_ = fd.Close()
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func recoverWALStoreV3(fd *os.File) (*walStoreV3, error) {
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
d, id, err := selectSlotV3(a, b, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var other *descriptorV3
|
||||
otherRaw := b
|
||||
if id == slotB {
|
||||
otherRaw = a
|
||||
}
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
recs := make([]trustedRecordV3, 0, len(scan.Records))
|
||||
for _, r := range scan.Records {
|
||||
last := r.Entry.LSN
|
||||
if r.Entry.Type == walEntryWriteBatch {
|
||||
last += r.Entry.BatchCount - 1
|
||||
}
|
||||
recs = append(recs, trustedRecordV3{FirstLSN: r.Entry.LSN, LastLSN: last, End: r.End})
|
||||
}
|
||||
o, err := decideRecoveryV3(d, recs, scan.MaxDurableLSN)
|
||||
if err != nil {
|
||||
return nil, err // R < W*: fail closed (wal_corrupt)
|
||||
}
|
||||
if o.Installing {
|
||||
return nil, installingErrorV3(o)
|
||||
}
|
||||
// Replay the records <= R by LSN (last writer wins); drop the rest.
|
||||
lsnOf := make(map[uint64]uint64)
|
||||
for _, r := range scan.Records {
|
||||
e := r.Entry
|
||||
if e.LSN > o.R {
|
||||
break
|
||||
}
|
||||
s.replayV3(e, d.BlockSize, lsnOf)
|
||||
}
|
||||
// The drop fence (6.6), then the recovered head, then admission.
|
||||
floor, sameNonce := s.pub.reuseFloor()
|
||||
if err := s.fenceV3(o.E, floor, d.WALSize, sameNonce, d.WALOffset); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := s.pub.publish(&s.mu, 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
|
||||
}
|
||||
restore := scan
|
||||
restore.End = o.E
|
||||
if err := w.restoreScanV3(restore); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.w = w
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
ranges, err := fenceRangesV3(E, floor, walSize, sameNonce)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
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)
|
||||
for _, r := range ranges {
|
||||
for done := uint64(0); done < r.Len; {
|
||||
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
|
||||
return err
|
||||
}
|
||||
done += n
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}, 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
|
||||
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 {
|
||||
if errors.Is(err, errWALPwrite) {
|
||||
s.latch(err)
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
s.nextLSN++
|
||||
s.appended = lsn
|
||||
s.data[uint64(lba)] = append([]byte(nil), data...)
|
||||
return lsn, 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
|
||||
}
|
||||
if H <= prev {
|
||||
return prev, nil
|
||||
}
|
||||
switch s.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.pub.publish(&s.mu, nil, func(n *descriptorV3) error { n.W = H; return nil }); err != nil {
|
||||
return 0, 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
|
||||
}
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.wack = max(s.wack, H)
|
||||
s.mu.Unlock()
|
||||
return H, 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 {
|
||||
return nil
|
||||
}
|
||||
_, err := s.pub.publish(&s.mu, 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 {
|
||||
n.WMode, n.W = m, wack
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *walStoreV3) Close() error { return s.fd.Close() }
|
||||
@@ -0,0 +1,345 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"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.
|
||||
|
||||
const v3TestBlock = 4096
|
||||
const v3TestWAL = 64 * 1024
|
||||
|
||||
func newStoreV3(t *testing.T, mode WMode) (*walStoreV3, string) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "store.v3")
|
||||
s, err := createWALStoreV3ForTest(path, 64, v3TestBlock, v3TestWAL, mode)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s, path
|
||||
}
|
||||
|
||||
func blk(b byte) []byte { return bytes.Repeat([]byte{b}, v3TestBlock) }
|
||||
|
||||
// writeSynced writes one block per LSN, each in its own Sync (batch).
|
||||
func writeSynced(t *testing.T, s *walStoreV3, from, to uint32) {
|
||||
t.Helper()
|
||||
for lba := from; lba <= to; lba++ {
|
||||
if _, err := s.Write(lba, blk(byte(lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// recordOffset returns the absolute file offset of the record with lsn,
|
||||
// found by scanning the file as a reopen would.
|
||||
func recordOffset(t *testing.T, path string, lsn uint64) int64 {
|
||||
t.Helper()
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
a, b := make([]byte, slotSizeV3), make([]byte, slotSizeV3)
|
||||
if _, err := f.ReadAt(a, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.ReadAt(b, slotBOffsetV3); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d, _, err := selectSlotV3(a, b, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := scanWALV3(f, d)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, rec := range r.Records {
|
||||
if rec.Entry.LSN == lsn {
|
||||
size := uint64(walEntryHeaderSizeV3 + len(rec.Entry.Data))
|
||||
return int64(d.WALOffset + (rec.End-size)%d.WALSize)
|
||||
}
|
||||
}
|
||||
t.Fatalf("no record with LSN %d", lsn)
|
||||
return 0
|
||||
}
|
||||
|
||||
func damageRecord(t *testing.T, path string, lsn uint64) {
|
||||
t.Helper()
|
||||
off := recordOffset(t, path, lsn) + walEntryPrefixSizeV3 + 100 // a payload byte
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
b := []byte{0}
|
||||
if _, err := f.ReadAt(b, off); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b[0] ^= 0xFF
|
||||
if _, err := f.WriteAt(b, off); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func isWALCorrupt(err error) bool {
|
||||
var rf *RecoveryFailure
|
||||
return errors.As(err, &rf) && rf.Kind == StorageRecoveryFailureWALIntegrity
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
for lba := uint32(1); lba <= 5; lba++ {
|
||||
if !bytes.Equal(r.Read(lba), blk(byte(lba))) {
|
||||
t.Fatalf("mode %d: acknowledged LBA %d lost", mode, lba)
|
||||
}
|
||||
}
|
||||
// Writes continue after recovery and survive another reopen.
|
||||
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)) {
|
||||
t.Fatalf("mode %d: writes after recovery lost", mode)
|
||||
}
|
||||
_ = r2.Close()
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
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()
|
||||
damageRecord(t, path, 3)
|
||||
r, err := openWALStoreV3(path)
|
||||
if c.corrupt {
|
||||
if !isWALCorrupt(err) {
|
||||
t.Fatalf("mode A, newest batch corrupt: err = %v, want wal_corrupt", err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
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 {
|
||||
t.Fatal("mode C: want LSN 1-2 kept and the newest batch (3) truncated")
|
||||
}
|
||||
_ = r.Close()
|
||||
}
|
||||
// The second-newest batch is protected in both modes.
|
||||
for _, mode := range []WMode{WModeLagged, WModeStrict} {
|
||||
s, path := newStoreV3(t, mode)
|
||||
writeSynced(t, s, 1, 3)
|
||||
_ = s.Close()
|
||||
damageRecord(t, path, 2)
|
||||
if _, err := openWALStoreV3(path); !isWALCorrupt(err) {
|
||||
t.Fatalf("mode %d, second-newest batch corrupt: err = %v, want wal_corrupt", mode, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreV3RefreshAndSetWModeCloseTheWindow(t *testing.T) {
|
||||
s, path := newStoreV3(t, WModeLagged)
|
||||
writeSynced(t, s, 1, 3)
|
||||
if err := s.refreshW(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = s.Close()
|
||||
damageRecord(t, path, 3)
|
||||
if _, err := openWALStoreV3(path); !isWALCorrupt(err) {
|
||||
t.Fatalf("after the idle refresh: err = %v, want wal_corrupt", err)
|
||||
}
|
||||
|
||||
s2, path2 := newStoreV3(t, WModeLagged)
|
||||
writeSynced(t, s2, 1, 3)
|
||||
if err := s2.SetWMode(WModeStrict); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s2.pub.current().WMode != WModeStrict {
|
||||
t.Fatal("SetWMode did not publish the new mode")
|
||||
}
|
||||
_ = s2.Close()
|
||||
damageRecord(t, path2, 3)
|
||||
if _, err := openWALStoreV3(path2); !isWALCorrupt(err) {
|
||||
t.Fatalf("after SetWMode(A): err = %v, want wal_corrupt (C -> A closes the window)", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt(t *testing.T) {
|
||||
for _, mode := range []WMode{WModeLagged, WModeStrict} {
|
||||
s, path := newStoreV3(t, mode)
|
||||
writeSynced(t, s, 1, 3)
|
||||
if _, err := s.Write(4, blk(4)); err != nil { // appended, never synced
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = s.Close()
|
||||
damageRecord(t, path, 4) // a torn unsynced record
|
||||
r, err := openWALStoreV3(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 {
|
||||
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.
|
||||
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)
|
||||
}
|
||||
if _, err := s.Write(5, blk(5)); err != nil { // unsynced
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = s.Close()
|
||||
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 {
|
||||
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
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = r.Close()
|
||||
r2, err := openWALStoreV3(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
func TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash(t *testing.T) {
|
||||
for _, mode := range []WMode{WModeLagged, WModeStrict} {
|
||||
if resurrectionSchedule(t, mode, false) {
|
||||
t.Fatalf("mode %d: a record dropped by recovery resurfaced after the second crash (G1)", mode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreV3NoFenceResurrectsInBothModes(t *testing.T) {
|
||||
// The schedule is a real counterexample: with the fence skipped, the
|
||||
// dropped record comes back. This keeps the G1 control discriminating.
|
||||
for _, mode := range []WMode{WModeLagged, WModeStrict} {
|
||||
if !resurrectionSchedule(t, mode, true) {
|
||||
t.Fatalf("mode %d: the no-fence schedule did not resurrect; the G1 control is not discriminating", mode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreV3FenceTouchesNoByteBeforeTheHead(t *testing.T) {
|
||||
s, path := newStoreV3(t, WModeLagged)
|
||||
writeSynced(t, s, 1, 3)
|
||||
if _, err := s.Write(4, blk(4)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = s.Close()
|
||||
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()
|
||||
after, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(before[walOffsetV3:e], after[walOffsetV3:e]) {
|
||||
t.Fatal("the fence changed a byte before the recovered head E")
|
||||
}
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreV3AppendWriteErrorLatchesTheStore(t *testing.T) {
|
||||
s, _ := newStoreV3(t, WModeLagged)
|
||||
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 }
|
||||
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 {
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -258,7 +258,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th
|
||||
|
||||
## Part B. Invariant ledger
|
||||
|
||||
75 rows: 69 ACTIVE, 6 STUB; 15 kept from the internal ledger, 60 new.
|
||||
77 rows: 69 ACTIVE, 8 STUB; 15 kept from the internal ledger, 62 new.
|
||||
|
||||
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
|
||||
|
||||
@@ -282,6 +282,8 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
|
||||
| `INV-WAL-V3-RECORD-001` | A dark impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 (v3 codec only; no production transition yet) | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | 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-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-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 |
|
||||
@@ -290,6 +292,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-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