storage: add dark impl-3 record codec and byte contract tests

This commit is contained in:
pingqiu committed 2026-11-17 01:33:31 -08:00
1 parent 1de78938a9
commit 26f4cb77eb
7 files changed
+410 -1

No files matched your search

@@ -0,0 +1,7 @@
# Format v3 test-only fixture custody
The barrier vector is a literal worked example of DESIGN r12 (SHA in barrier.json). It was constructed independently from the byte table, using reflected Castagnoli polynomial 0x82f63b78, initial/final XOR 0xffffffff. It does not use a production encoder. Nonce 00..0f is deliberately nonzero as a 128-bit value. Fixed prefix 62 bytes; no payload; CRC32C then EntrySize gives 70 bytes. Exact values and raw-file SHA are in barrier.json.
The custody test checks bytes against literals and the standard library CRC32C. It is new-format FIXTURE coverage only, not a parent behavioral RED, product codec acceptance, or v3 recovery PASS. After code GO, the real encoder/decoder must consume this same vector; mutating nonce/cursor/type/count/CRC/footer and lap-placement controls must exercise the product path, not this fixture checker.
Existing-caller REDs are in walstore_incarnation_red_test.go and chunk_lsn_map_red_test.go. They intentionally fail on the authorized base. Do not include those failing heads as a green integration claim.
Binary file not shown.
@@ -0,0 +1,13 @@
{
"design_sha256": "c9c652cbe846822dff5c08ce95081b0156e1df0582e6b9766b62e1742ddc1adf",
"kind": "barrier",
"lsn": 7,
"batch_count": 0,
"durable_lsn": 6,
"logical_start": 128,
"nonce_hex": "000102030405060708090a0b0c0d0e0f",
"prefix_bytes": 62,
"entry_size": 70,
"crc32c_hex": "5d1aabd6",
"sha256": "10056856c951fe00bc95a63ccfe021601fb36aaeb08806511066db438304f493"
}
+167
View File
@@ -0,0 +1,167 @@
package storage
import (
"encoding/binary"
"fmt"
"hash/crc32"
"math"
)
// The impl-3 codec is deliberately separate from the 38-byte impl-1 codec.
// No production writer, reader or recovery path selects it before activation.
const (
walEntryPrefixSizeV3 = 62
walEntryHeaderSizeV3 = 70 // prefix plus CRC32C and EntrySize
)
var walEntryCRC32CV3 = crc32.MakeTable(crc32.Castagnoli)
type walEntryV3 struct {
LSN uint64
BatchCount uint64
Type uint8
Flags uint8
LBA uint64
Length uint32
DurableLSN uint64
LogicalStart uint64
Nonce [16]byte
Data []byte
}
// payloadSizeV3 validates header arithmetic before reading or allocating the
// payload. The reader passes geometry from the selected, validated descriptor.
// Nonce equality, exact expected cursor and lap admission belong to the scanner;
// a valid CRC here alone never makes a record trustworthy for replay.
func (e walEntryV3) payloadSizeV3(blockSize uint32, numBlocks uint64) (uint64, error) {
invalid := func(why string) (uint64, error) { return 0, fmt.Errorf("%w: v3 %s", errInvalidEntry, why) }
if blockSize == 0 || numBlocks == 0 || numBlocks > counterMaxV3/uint64(blockSize) {
return invalid("invalid volume geometry")
}
if e.Nonce == ([16]byte{}) || e.Flags != 0 {
return invalid("nonce or flags")
}
if e.LSN > counterMaxV3 || e.DurableLSN > counterMaxV3 || e.LogicalStart > counterMaxV3 || e.LBA > counterMaxV3 || e.BatchCount > counterMaxV3 {
return 0, ErrCounterExhausted
}
if e.Type != walEntryPadding && e.LSN == 0 {
return invalid("zero record LSN")
}
var payload, blocks uint64
switch e.Type {
case walEntryWrite:
if e.BatchCount != 0 || e.Length != blockSize {
return invalid("single write geometry")
}
blocks = 1
payload = uint64(e.Length)
case walEntryWriteBatch:
if e.BatchCount == 0 {
return invalid("empty batch")
}
if e.BatchCount > counterMaxV3/uint64(blockSize) || e.BatchCount-1 > counterMaxV3-e.LSN {
return 0, ErrCounterExhausted
}
blocks = e.BatchCount
payload = blocks * uint64(blockSize)
if payload != uint64(e.Length) {
return invalid("batch payload length")
}
case walEntryTrim:
if e.BatchCount != 0 || e.Length == 0 || e.Length%blockSize != 0 {
return invalid("trim geometry")
}
blocks = uint64(e.Length / blockSize)
case walEntryBarrier:
if e.BatchCount != 0 || e.Length != 0 {
return invalid("barrier geometry")
}
case walEntryPadding:
if e.BatchCount != 0 || e.LSN != 0 || e.LBA != 0 || e.DurableLSN != 0 {
return invalid("padding header")
}
payload = uint64(e.Length)
default:
return invalid("unknown record type")
}
if blocks > 0 && (e.LBA >= numBlocks || blocks > numBlocks-e.LBA) {
return invalid("LBA span outside volume")
}
// EntrySize is a 32-bit wire field. Never truncate it or an allocation size.
if payload > math.MaxUint32-walEntryHeaderSizeV3 || payload > uint64(int(^uint(0)>>1))-walEntryHeaderSizeV3 {
return invalid("encoded record too large")
}
if uint64(walEntryHeaderSizeV3)+payload > counterMaxV3-e.LogicalStart {
return 0, ErrCounterExhausted
}
return payload, nil
}
func encodeWALEntryV3(e walEntryV3, blockSize uint32, numBlocks uint64) ([]byte, error) {
n, err := e.payloadSizeV3(blockSize, numBlocks)
if err != nil {
return nil, err
}
if uint64(len(e.Data)) != n {
return nil, fmt.Errorf("%w: v3 payload size", errInvalidEntry)
}
if e.Type == walEntryPadding {
for _, b := range e.Data {
if b != 0 {
return nil, fmt.Errorf("%w: v3 nonzero padding", errInvalidEntry)
}
}
}
buf := make([]byte, walEntryHeaderSizeV3+int(n))
le := binary.LittleEndian
le.PutUint64(buf[0:8], e.LSN)
le.PutUint64(buf[8:16], e.BatchCount)
buf[16] = e.Type
buf[17] = e.Flags
le.PutUint64(buf[18:26], e.LBA)
le.PutUint32(buf[26:30], e.Length)
le.PutUint64(buf[30:38], e.DurableLSN)
le.PutUint64(buf[38:46], e.LogicalStart)
copy(buf[46:62], e.Nonce[:])
end := walEntryPrefixSizeV3 + int(n)
copy(buf[walEntryPrefixSizeV3:end], e.Data)
le.PutUint32(buf[end:end+4], crc32.Checksum(buf[:end], walEntryCRC32CV3))
le.PutUint32(buf[end+4:end+8], uint32(len(buf)))
return buf, nil
}
func decodeWALEntryV3(buf []byte, blockSize uint32, numBlocks uint64) (walEntryV3, error) {
if len(buf) < walEntryHeaderSizeV3 {
return walEntryV3{}, errEntryTruncated
}
le := binary.LittleEndian
e := walEntryV3{LSN: le.Uint64(buf[0:8]), BatchCount: le.Uint64(buf[8:16]), Type: buf[16], Flags: buf[17], LBA: le.Uint64(buf[18:26]), Length: le.Uint32(buf[26:30]), DurableLSN: le.Uint64(buf[30:38]), LogicalStart: le.Uint64(buf[38:46])}
copy(e.Nonce[:], buf[46:62])
n, err := e.payloadSizeV3(blockSize, numBlocks)
if err != nil {
return walEntryV3{}, err
}
size := uint64(walEntryHeaderSizeV3) + n
if size > uint64(len(buf)) {
return walEntryV3{}, errEntryTruncated
}
end := walEntryPrefixSizeV3 + int(n)
if le.Uint32(buf[end+4:end+8]) != uint32(size) {
return walEntryV3{}, fmt.Errorf("%w: v3 EntrySize", errInvalidEntry)
}
if le.Uint32(buf[end:end+4]) != crc32.Checksum(buf[:end], walEntryCRC32CV3) {
return walEntryV3{}, errCRCMismatch
}
if e.Type == walEntryPadding {
for _, b := range buf[walEntryPrefixSizeV3:end] {
if b != 0 {
return walEntryV3{}, fmt.Errorf("%w: v3 nonzero padding", errInvalidEntry)
}
}
}
// Only copy after geometry, source bounds, CRC and footer all validate.
if n > 0 {
e.Data = append([]byte(nil), buf[walEntryPrefixSizeV3:end]...)
}
return e, nil
}
@@ -0,0 +1,215 @@
package storage
// Row 2 NEW-API contract coverage, prepared before the codec exists.
// Missing walEntryV3/encodeWALEntryV3/decodeWALEntryV3 is NOT a behavioral
// RED. These names are internal codec seams owned by row 2. Slot nonce and
// geometry are passed as values; this test does not invent a slot codec.
import (
"bytes"
"encoding/binary"
"hash/crc32"
"os"
"reflect"
"testing"
)
const v3TestBlockSize uint32 = 4096
const v3TestNumBlocks uint64 = 1024
func v3TestBarrier() walEntryV3 {
var nonce [16]byte
for i := range nonce {
nonce[i] = byte(i)
}
return walEntryV3{LSN: 7, Type: walEntryBarrier, DurableLSN: 6, LogicalStart: 128, Nonce: nonce}
}
func TestWALEntryV3_CanonicalBarrierBytes(t *testing.T) {
want, err := os.ReadFile("testdata/format_v3/barrier.bin")
if err != nil {
t.Fatal(err)
}
entry := v3TestBarrier()
got, err := encodeWALEntryV3(entry, v3TestBlockSize, v3TestNumBlocks)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, want) {
t.Fatalf("encoded barrier differs from independent signed-layout vector: %x", got)
}
decoded, err := decodeWALEntryV3(want, v3TestBlockSize, v3TestNumBlocks)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(decoded, entry) {
t.Fatalf("decoded barrier=%+v want %+v", decoded, entry)
}
}
func TestWALEntryV3_TypeFootprints(t *testing.T) {
for _, tc := range []struct {
name string
kind uint8
count uint64
length uint32
data []byte
size int
}{
{"single block", walEntryWrite, 0, 4096, bytes.Repeat([]byte{0x91}, 4096), 4166},
{"batch", walEntryWriteBatch, 2, 8192, bytes.Repeat([]byte{0x72}, 8192), 8262},
{"large trim no payload", walEntryTrim, 0, 65536, nil, 70},
{"barrier", walEntryBarrier, 0, 0, nil, 70},
{"padding", walEntryPadding, 0, 12, make([]byte, 12), 82},
} {
t.Run(tc.name, func(t *testing.T) {
e := v3TestBarrier()
e.Type = tc.kind
e.BatchCount = tc.count
e.Length = tc.length
e.Data = tc.data
if tc.kind == walEntryPadding {
e.LSN = 0
e.DurableLSN = 0
}
b, err := encodeWALEntryV3(e, v3TestBlockSize, v3TestNumBlocks)
if err != nil {
t.Fatal(err)
}
if len(b) != tc.size {
t.Fatalf("footprint=%d want %d", len(b), tc.size)
}
if binary.LittleEndian.Uint32(b[len(b)-4:]) != uint32(tc.size) {
t.Fatal("incorrect EntrySize footer")
}
// Return every logical field, not merely an equal CRC or payload.
got, err := decodeWALEntryV3(b, v3TestBlockSize, v3TestNumBlocks)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got, e) {
t.Fatalf("decoded=%+v want %+v", got, e)
}
})
}
}
func TestWALEntryV3_RefusesInvalidEncode(t *testing.T) {
for _, tc := range []struct {
name string
edit func(*walEntryV3)
}{
{"unknown type", func(e *walEntryV3) { e.Type = 0x55 }},
{"flags", func(e *walEntryV3) { e.Flags = 1 }},
{"zero nonce", func(e *walEntryV3) { e.Nonce = [16]byte{} }},
{"barrier payload", func(e *walEntryV3) { e.Data = []byte{1}; e.Length = 1 }},
{"nonbatch count", func(e *walEntryV3) { e.BatchCount = 1 }},
{"write short", func(e *walEntryV3) { e.Type = walEntryWrite; e.Length = 1; e.Data = []byte{1} }},
{"write long", func(e *walEntryV3) { e.Type = walEntryWrite; e.Length = 8192; e.Data = make([]byte, 8192) }},
{"batch zero count", func(e *walEntryV3) { e.Type = walEntryWriteBatch; e.Length = 4096; e.Data = make([]byte, 4096) }},
{"batch length mismatch", func(e *walEntryV3) {
e.Type = walEntryWriteBatch
e.BatchCount = 2
e.Length = 4096
e.Data = make([]byte, 4096)
}},
{"batch count overflow", func(e *walEntryV3) {
e.Type = walEntryWriteBatch
e.BatchCount = ^uint64(0)
e.Length = 4096
e.Data = make([]byte, 4096)
}},
{"batch LSN overflow", func(e *walEntryV3) {
e.Type = walEntryWriteBatch
e.LSN = ^uint64(0) - 1
e.BatchCount = 2
e.Length = 8192
e.Data = make([]byte, 8192)
}},
{"batch LBA span", func(e *walEntryV3) {
e.Type = walEntryWriteBatch
e.LBA = v3TestNumBlocks - 1
e.BatchCount = 2
e.Length = 8192
e.Data = make([]byte, 8192)
}},
{"trim outside volume", func(e *walEntryV3) { e.Type = walEntryTrim; e.LBA = v3TestNumBlocks - 1; e.Length = 8192 }},
{"trim payload", func(e *walEntryV3) { e.Type = walEntryTrim; e.Length = 4096; e.Data = []byte{1} }},
{"padding data nonzero", func(e *walEntryV3) {
e.Type = walEntryPadding
e.LSN = 0
e.DurableLSN = 0
e.Length = 1
e.Data = []byte{1}
}},
{"padding LSN", func(e *walEntryV3) { e.Type = walEntryPadding; e.DurableLSN = 0 }},
{"padding DurableLSN", func(e *walEntryV3) { e.Type = walEntryPadding; e.LSN = 0 }},
{"padding LBA", func(e *walEntryV3) { e.Type = walEntryPadding; e.LSN = 0; e.DurableLSN = 0; e.LBA = 1 }},
{"zero normal LSN", func(e *walEntryV3) { e.LSN = 0 }},
{"LSN exhausted", func(e *walEntryV3) { e.LSN = ^uint64(0) }},
{"durable exhausted", func(e *walEntryV3) { e.DurableLSN = ^uint64(0) }},
{"cursor size overflow", func(e *walEntryV3) { e.LogicalStart = ^uint64(0) - 30 }},
} {
t.Run(tc.name, func(t *testing.T) {
e := v3TestBarrier()
tc.edit(&e)
if _, err := encodeWALEntryV3(e, v3TestBlockSize, v3TestNumBlocks); err == nil {
t.Fatal("invalid record admitted")
}
})
}
}
func TestWALEntryV3_RefusesMalformedWire(t *testing.T) {
original, err := os.ReadFile("testdata/format_v3/barrier.bin")
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
edit func([]byte)
repairCRC bool
}{
{"CRC", func(b []byte) { b[62] ^= 1 }, false},
{"footer", func(b []byte) { b[66] ^= 1 }, false},
{"unknown type valid CRC", func(b []byte) { b[16] = 0x55 }, true},
{"flags valid CRC", func(b []byte) { b[17] = 1 }, true},
{"count valid CRC", func(b []byte) { b[8] = 1 }, true},
{"zero nonce valid CRC", func(b []byte) { clear(b[46:62]) }, true},
{"huge length valid CRC", func(b []byte) { binary.LittleEndian.PutUint32(b[26:30], ^uint32(0)) }, true},
} {
t.Run(tc.name, func(t *testing.T) {
b := bytes.Clone(original)
tc.edit(b)
if tc.repairCRC {
binary.LittleEndian.PutUint32(b[62:66], crc32.Checksum(b[:62], crc32.MakeTable(crc32.Castagnoli)))
}
if _, err := decodeWALEntryV3(b, v3TestBlockSize, v3TestNumBlocks); err == nil {
t.Fatal("malformed wire record admitted")
}
})
}
for n := 0; n < len(original); n++ {
if _, err := decodeWALEntryV3(original[:n], v3TestBlockSize, v3TestNumBlocks); err == nil {
t.Fatalf("truncated size%d admitted", n)
}
}
}
// Native fuzzing runs later against the actual decoder. Seed execution belongs
// to the row-2 package tests; allocation bounds must precede copying payload.
func FuzzWALEntryV3_DecodeNeverPanics(f *testing.F) {
b, err := os.ReadFile("testdata/format_v3/barrier.bin")
if err != nil {
f.Fatal(err)
}
f.Add(b)
f.Add([]byte{})
f.Add(bytes.Repeat([]byte{0xff}, 70))
f.Fuzz(func(t *testing.T, b []byte) {
if len(b) > 16384 {
t.Skip()
}
_, _ = decodeWALEntryV3(b, v3TestBlockSize, v3TestNumBlocks)
})
}
+4 -1
View File
@@ -63,6 +63,8 @@ stateDiagram-v2
| FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` |
| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — |
The format-v3 record codec (plan row 2) is dark: no production M1 transition selects it yet. Its framing/validation boundary is tested separately (`INV-WAL-V3-RECORD-001`); writer/cursor/lap admission and production activation land in later ordered rows. Existing machine diagrams and ACTIVE recovery guards are unchanged.
Recovery warnings such as `wal_hole_suspected` are recorded in Serving without changing health (`INV-WAL-WARN-NO-HEALTH-001`). The open gaps of this machine (a corrupted synced record mid-history only warns; forged records in user data) are listed in the [core known issues](block-design.md#24-known-issues-and-work-in-progress) and are not ledger rows.
### M2 Authority: assignment, epoch, lease
@@ -256,7 +258,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th
## Part B. Invariant ledger
72 rows: 69 ACTIVE, 3 STUB; 15 kept from the internal ledger, 57 new.
73 rows: 69 ACTIVE, 4 STUB; 15 kept from the internal ledger, 58 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.
@@ -277,6 +279,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt` (`cmd/blockvolume/durable_startup_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE |
| `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE |
| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB |
| `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-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 |
+4
View File
@@ -25,6 +25,10 @@
(* "watermarkFull" watermarkSB, and recovery decodes every page position *)
(* instead of stopping a range at its first bad entry. *)
(***************************************************************************)
(* Impl-3 row 2 adds a DARK byte codec in wal_entry_v3.go. Its 62/70-byte *)
(* framing, CRC32C, type/size bounds and allocation order are code-test *)
(* obligations, abstracted as record validity here, NOT proved by this model.*)
(* No production state/transition or model action changes in codec row 2. *)
EXTENDS Integers, FiniteSets, Sequences, TLC
CONSTANTS K, MaxLSN, LBAs, Rule, CorruptOn, MaxCkpt,