storage: persist dark v3 chunk LSN maps as owned immutable COW generations

This commit is contained in:
pingqiu committed 2026-11-17 02:22:32 -08:00
1 parent 40b7614faf
commit d2a778f849
6 files changed
+721 -1

No files matched your search

@@ -0,0 +1,389 @@
package storage
// Dark impl-3 COW map, DESIGN r15 9.2-9.5. All bytes are append-only;
// neither fallback slots nor pending candidates can lose a dependency.
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"os"
"path/filepath"
"sync"
)
const mapPageDomainV3 = "swblock:chunk-map:page:v1\x00"
const mapRootDomainV3 = "swblock:chunk-map:root:v1\x00"
var ErrMapInvalid = errors.New("storage: v3 chunk map invalid")
type chunkLSNEntryV3 struct {
LSN uint64
Unknown bool
}
type mapPageRefV3 struct {
Offset uint64
Hash [32]byte
}
type mapShapeV3 struct{ chunks, pages, raw, aligned uint64 }
func mapShapeForV3(d descriptorV3, cb uint64) (mapShapeV3, error) {
var s mapShapeV3
if d.BlockSize == 0 || d.VolumeSize == 0 || d.VolumeSize%uint64(d.BlockSize) != 0 || cb == 0 {
return s, ErrMapInvalid
}
nb := d.VolumeSize / uint64(d.BlockSize)
s.chunks = nb / cb
if nb%cb != 0 {
s.chunks++
}
s.pages = s.chunks / 250
if s.chunks%250 != 0 {
s.pages++
}
if s.pages == 0 || s.pages > (counterMaxV3-120)/40 {
return s, ErrCounterExhausted
}
s.raw = 120 + 40*s.pages
if s.raw > uint64(math.MaxInt64)-4095 {
return s, ErrCounterExhausted
}
s.aligned = (s.raw + 4095) &^ uint64(4095)
if s.aligned > uint64(int(^uint(0)>>1)) {
return s, ErrCounterExhausted
}
return s, nil
}
func mapZeroV3(b []byte) bool { return firstNonZero(b) < 0 }
func mapDigestV3(domain string, b []byte) [32]byte {
h := sha256.New()
h.Write([]byte(domain))
h.Write(b)
var out [32]byte
copy(out[:], h.Sum(nil))
return out
}
func encodeMapPageV3(d descriptorV3, g, index uint64, es []chunkLSNEntryV3) ([]byte, error) {
if g == 0 || g > counterMaxV3 || len(es) == 0 || len(es) > 250 {
return nil, ErrMapInvalid
}
b := make([]byte, 4096)
copy(b, "CLM3")
le := binary.LittleEndian
le.PutUint16(b[4:], 1)
copy(b[8:], d.UUID[:])
copy(b[24:], d.MapLineage[:])
le.PutUint64(b[40:], g)
le.PutUint64(b[48:], index)
le.PutUint32(b[56:], uint32(len(es)))
for i, e := range es {
if e.LSN > counterMaxV3 {
return nil, ErrCounterExhausted
}
le.PutUint64(b[64+16*i:], e.LSN)
if e.Unknown {
b[72+16*i] = 1
}
}
hash := mapDigestV3(mapPageDomainV3, b[:4064])
copy(b[4064:], hash[:])
return b, nil
}
func encodeMapRootV3(d descriptorV3, g, cb, C uint64, refs []mapPageRefV3) ([]byte, error) {
s, e := mapShapeForV3(d, cb)
if e != nil {
return nil, e
}
if g == 0 || g > counterMaxV3 || C > counterMaxV3 || uint64(len(refs)) != s.pages {
return nil, ErrMapInvalid
}
b := make([]byte, int(s.aligned))
copy(b, "CLR3")
le := binary.LittleEndian
le.PutUint16(b[4:], 1)
copy(b[8:], d.UUID[:])
copy(b[24:], d.MapLineage[:])
le.PutUint64(b[40:], g)
le.PutUint64(b[48:], s.chunks)
le.PutUint64(b[56:], cb)
le.PutUint64(b[64:], C)
le.PutUint64(b[72:], s.pages)
le.PutUint64(b[80:], s.raw)
for i, r := range refs {
if r.Offset%4096 != 0 {
return nil, ErrMapInvalid
}
off := 88 + 40*i
le.PutUint64(b[off:], r.Offset)
copy(b[off+8:], r.Hash[:])
}
h := mapDigestV3(mapRootDomainV3, b[:s.raw-32])
copy(b[s.raw-32:], h[:])
return b, nil
}
func mapReadAtV3(f *os.File, off, n, size uint64) ([]byte, error) {
if off%4096 != 0 || off > size || n > size-off || off > math.MaxInt64 || n > uint64(int(^uint(0)>>1)) {
return nil, ErrMapInvalid
}
b := make([]byte, int(n))
if _, e := f.ReadAt(b, int64(off)); e != nil {
return nil, e
}
return b, nil
}
// readChunkLSNMapV3 checks the descriptor tuple and every immutable dependency
// before returning any entries. No corrupt root is treated as an empty map.
func readChunkLSNMapV3(f *os.File, d descriptorV3, cb uint64) ([]chunkLSNEntryV3, []mapPageRefV3, error) {
s, e := mapShapeForV3(d, cb)
if e != nil {
return nil, nil, e
}
if d.MapGeneration == 0 || d.MapGeneration > counterMaxV3 || d.MapCoveredCheckpoint > counterMaxV3 || d.UUID == [16]byte{} || d.MapLineage == [16]byte{} {
return nil, nil, ErrMapInvalid
}
info, e := f.Stat()
if e != nil {
return nil, nil, e
}
if info.Size() < 0 {
return nil, nil, ErrMapInvalid
}
size := uint64(info.Size())
b, e := mapReadAtV3(f, d.MapRootLocator, s.aligned, size)
if e != nil {
return nil, nil, e
}
le := binary.LittleEndian
if string(b[:4]) != "CLR3" || le.Uint16(b[4:]) != 1 || le.Uint16(b[6:]) != 0 || !bytes.Equal(b[8:24], d.UUID[:]) || !bytes.Equal(b[24:40], d.MapLineage[:]) || le.Uint64(b[40:]) != d.MapGeneration || d.MapGeneration == 0 || le.Uint64(b[48:]) != s.chunks || le.Uint64(b[56:]) != cb || le.Uint64(b[64:]) != d.MapCoveredCheckpoint || le.Uint64(b[72:]) != s.pages || le.Uint64(b[80:]) != s.raw || d.MapFormatID != 1 {
return nil, nil, ErrMapInvalid
}
hash := mapDigestV3(mapRootDomainV3, b[:s.raw-32])
if hash != d.MapRootHash || !bytes.Equal(hash[:], b[s.raw-32:s.raw]) || !mapZeroV3(b[s.raw:]) {
return nil, nil, ErrMapInvalid
}
// Root is file-bounded before page and entry allocations; every page needs
// 4096 distinct bytes. Reject impossible geometry before allocating entries.
if s.pages > size/4096 || s.chunks > uint64(int(^uint(0)>>1))/16 {
return nil, nil, ErrMapInvalid
}
entries := make([]chunkLSNEntryV3, 0, int(s.chunks))
refs := make([]mapPageRefV3, 0, int(s.pages))
seen := make(map[uint64]bool)
for j := uint64(0); j < s.pages; j++ {
pos := 88 + 40*j
r := mapPageRefV3{Offset: le.Uint64(b[pos:])}
copy(r.Hash[:], b[pos+8:pos+40])
if seen[r.Offset] || (r.Offset < d.MapRootLocator+s.aligned && r.Offset+4096 > d.MapRootLocator) {
return nil, nil, ErrMapInvalid
}
seen[r.Offset] = true
p, e := mapReadAtV3(f, r.Offset, 4096, size)
if e != nil {
return nil, nil, e
}
count := min(uint64(250), s.chunks-j*250)
pg := le.Uint64(p[40:])
ph := mapDigestV3(mapPageDomainV3, p[:4064])
if string(p[:4]) != "CLM3" || le.Uint16(p[4:]) != 1 || le.Uint16(p[6:]) != 0 || !bytes.Equal(p[8:24], d.UUID[:]) || !bytes.Equal(p[24:40], d.MapLineage[:]) || pg == 0 || pg > d.MapGeneration || le.Uint64(p[48:]) != j || uint64(le.Uint32(p[56:])) != count || !mapZeroV3(p[60:64]) || ph != r.Hash || !bytes.Equal(ph[:], p[4064:]) || !mapZeroV3(p[64+16*count:4064]) {
return nil, nil, ErrMapInvalid
}
for i := uint64(0); i < count; i++ {
q := p[64+16*i : 80+16*i]
lsn := le.Uint64(q)
if lsn > counterMaxV3 || q[8]&^byte(1) != 0 || !mapZeroV3(q[9:]) {
return nil, nil, ErrMapInvalid
}
entries = append(entries, chunkLSNEntryV3{LSN: lsn, Unknown: q[8] == 1})
}
refs = append(refs, r)
}
return entries, refs, nil
}
type chunkMapCandidateV3 struct {
owner *chunkLSNMapV3
generation, covered, rootOffset uint64
hash [32]byte
refs []mapPageRefV3
entries []chunkLSNEntryV3
}
func (c *chunkMapCandidateV3) descriptor(d descriptorV3) descriptorV3 {
d.MapFormatID = 1
d.MapGeneration = c.generation
d.MapCoveredCheckpoint = c.covered
d.MapRootLocator = c.rootOffset
d.MapRootHash = c.hash
return d
}
type chunkLSNMapV3 struct {
mu sync.Mutex
fd *os.File
identity descriptorV3
chunkBlocks uint64
failed error
lastGeneration uint64
syncFile func() error
syncDirectory func() error
}
func createChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3, error) {
if _, e := mapShapeForV3(d, cb); e != nil {
return nil, e
}
if d.UUID == [16]byte{} || d.MapLineage == [16]byte{} {
return nil, ErrMapInvalid
}
f, e := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
if e != nil {
return nil, e
}
m := &chunkLSNMapV3{fd: f, identity: d, chunkBlocks: cb}
m.syncFile = f.Sync
m.syncDirectory = func() error { return syncDir(filepath.Dir(path)) }
if e = m.syncFile(); e == nil {
e = m.syncDirectory()
}
if e != nil {
f.Close()
return nil, e
}
return m, nil
}
// Open validates the selected generation before permitting any append. The
// caller must also validate the fallback descriptor before serving/retiring.
func openChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3, *chunkMapCandidateV3, error) {
f, e := os.OpenFile(path, os.O_RDWR, 0)
if e != nil {
return nil, nil, e
}
es, refs, e := readChunkLSNMapV3(f, d, cb)
if e != nil {
f.Close()
return nil, nil, e
}
m := &chunkLSNMapV3{fd: f, identity: d, chunkBlocks: cb, lastGeneration: d.MapGeneration}
m.syncFile = f.Sync
m.syncDirectory = func() error { return syncDir(filepath.Dir(path)) }
c := &chunkMapCandidateV3{owner: m, generation: d.MapGeneration, covered: d.MapCoveredCheckpoint, rootOffset: d.MapRootLocator, hash: d.MapRootHash, refs: refs, entries: es}
return m, c, nil
}
// Prepare persists pages -> page fsync -> root -> root fsync -> directory fsync.
// It returns a pinned tuple, never a descriptor publication or reuse authority.
// No pages are reclaimed in this append-only implementation.
func (m *chunkLSNMapV3) Prepare(g, C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (out *chunkMapCandidateV3, err error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.failed != nil {
return nil, m.failed
}
s, e := mapShapeForV3(m.identity, m.chunkBlocks)
if e != nil {
return nil, e
}
if uint64(len(entries)) != s.chunks || g == 0 || g <= m.lastGeneration || g > counterMaxV3 || C > counterMaxV3 {
return nil, ErrMapInvalid
}
if prior != nil && (prior.owner != m || prior.generation >= g) {
return nil, ErrMapInvalid
}
// Validate every entry before any I/O.
for _, v := range entries {
if v.LSN > counterMaxV3 {
return nil, ErrCounterExhausted
}
}
info, e := m.fd.Stat()
if e != nil {
return nil, e
}
if info.Size() < 0 {
return nil, ErrMapInvalid
}
off := uint64(info.Size())
if off > math.MaxInt64-4095 {
return nil, ErrCounterExhausted
}
off = (off + 4095) &^ uint64(4095)
defer func() {
if err != nil {
m.failed = err
}
}()
write := func(b []byte) (uint64, error) {
if uint64(len(b)) > math.MaxInt64-off {
return 0, ErrCounterExhausted
}
at := off
n, e := m.fd.WriteAt(b, int64(at))
if e == nil && n != len(b) {
e = io.ErrShortWrite
}
if e != nil {
return 0, e
}
off += uint64(len(b))
return at, nil
}
refs := make([]mapPageRefV3, s.pages)
for j := uint64(0); j < s.pages; j++ {
start := j * 250
end := min(start+250, s.chunks)
same := prior != nil && len(prior.entries) == len(entries)
if same {
for i := start; i < end; i++ {
if prior.entries[i] != entries[i] {
same = false
break
}
}
}
if same {
refs[j] = prior.refs[j]
continue
}
p, e := encodeMapPageV3(m.identity, g, j, entries[start:end])
if e != nil {
return nil, e
}
at, e := write(p)
if e != nil {
return nil, e
}
refs[j] = mapPageRefV3{Offset: at, Hash: mapDigestV3(mapPageDomainV3, p[:4064])}
}
if e = m.syncFile(); e != nil {
return nil, e
}
root, e := encodeMapRootV3(m.identity, g, m.chunkBlocks, C, refs)
if e != nil {
return nil, e
}
at, e := write(root)
if e != nil {
return nil, e
}
if e = m.syncFile(); e != nil {
return nil, e
}
if e = m.syncDirectory(); e != nil {
return nil, e
}
m.lastGeneration = g
out = &chunkMapCandidateV3{owner: m, generation: g, covered: C, rootOffset: at, hash: mapDigestV3(mapRootDomainV3, root[:s.raw-32]), refs: refs, entries: append([]chunkLSNEntryV3(nil), entries...)}
return out, nil
}
func (m *chunkLSNMapV3) Close() error {
m.mu.Lock()
defer m.mu.Unlock()
m.failed = fmt.Errorf("%w: closed", ErrMapInvalid)
return m.fd.Close()
}
@@ -0,0 +1,325 @@
package storage
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"os"
"path/filepath"
"testing"
)
func mapDescriptorV3(t *testing.T) descriptorV3 {
t.Helper()
d, e := decodeSlotV3(readSlotVector(t, "slot-ref"), nil)
if e != nil {
t.Fatal(e)
}
for i := range d.UUID {
d.UUID[i] = byte(i)
d.MapLineage[i] = byte(i + 16)
}
d.VolumeSize = 4096
d.BlockSize = 4096
d.MapGeneration = 1
d.MapCoveredCheckpoint = 7
d.W = 7
d.CheckpointLSN = 7
return d
}
func TestChunkLSNMapV3_CanonicalVectors(t *testing.T) {
d := mapDescriptorV3(t)
p, e := encodeMapPageV3(d, 1, 0, []chunkLSNEntryV3{{LSN: 7}})
if e != nil {
t.Fatal(e)
}
want, e := os.ReadFile("testdata/format_v3/reference-page.bin")
if e != nil {
t.Fatal(e)
}
if !bytes.Equal(p, want) {
t.Fatal("page differs from independent vector")
}
root, e := encodeMapRootV3(d, 1, 1, 7, []mapPageRefV3{{Offset: 4096, Hash: mapDigestV3(mapPageDomainV3, p[:4064])}})
if e != nil {
t.Fatal(e)
}
want, e = os.ReadFile("testdata/format_v3/reference-root.bin")
if e != nil {
t.Fatal(e)
}
if !bytes.Equal(root, want) {
t.Fatal("root differs from independent vector")
}
d.MapRootHash = mapDigestV3(mapRootDomainV3, root[:128])
d.MapRootLocator = 0
f, e := os.Create(filepath.Join(t.TempDir(), "map"))
if e != nil {
t.Fatal(e)
}
defer f.Close()
if _, e = f.WriteAt(root, 0); e != nil {
t.Fatal(e)
}
if _, e = f.WriteAt(p, 4096); e != nil {
t.Fatal(e)
}
entries, _, e := readChunkLSNMapV3(f, d, 1)
if e != nil || len(entries) != 1 || entries[0].LSN != 7 {
t.Fatalf("read=%v %v", entries, e)
}
}
func TestChunkLSNMapV3_PersistReloadAndReuse(t *testing.T) {
d := mapDescriptorV3(t)
d.VolumeSize = 251 * 4096
path := filepath.Join(t.TempDir(), "map")
m, e := createChunkLSNMapV3(path, d, 1)
if e != nil {
t.Fatal(e)
}
defer m.Close()
entries := make([]chunkLSNEntryV3, 251)
entries[0].LSN = 7
entries[250].Unknown = true
a, e := m.Prepare(1, 7, entries, nil)
if e != nil {
t.Fatal(e)
}
entries[250] = chunkLSNEntryV3{LSN: 8}
b, e := m.Prepare(2, 8, entries, a)
if e != nil {
t.Fatal(e)
}
if a.refs[0] != b.refs[0] || a.refs[1] == b.refs[1] {
t.Fatal("COW did not retain precisely the unchanged page")
}
next := b.descriptor(d)
next.W = 8
got, _, e := readChunkLSNMapV3(m.fd, next, 1)
if e != nil || len(got) != 251 || got[250].LSN != 8 {
t.Fatalf("reload=%v %v", got, e)
}
old, _, e := readChunkLSNMapV3(m.fd, a.descriptor(d), 1)
if e != nil || !old[250].Unknown {
t.Fatalf("old generation lost: %v", e)
}
foreign := next
foreign.UUID[0] ^= 1
if _, _, e := readChunkLSNMapV3(m.fd, foreign, 1); e == nil {
t.Fatal("foreign identity accepted")
}
}
func TestChunkLSNMapV3_CorruptionAndBounds(t *testing.T) {
for _, kind := range []string{"page", "coverage", "padding", "overlap", "count", "reserved"} {
t.Run(kind, func(t *testing.T) {
d := mapDescriptorV3(t)
m, e := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, 1)
if e != nil {
t.Fatal(e)
}
defer m.Close()
c, e := m.Prepare(1, 7, []chunkLSNEntryV3{{LSN: 7}}, nil)
if e != nil {
t.Fatal(e)
}
d = c.descriptor(d)
switch kind {
case "page":
_, e = m.fd.WriteAt([]byte{9}, int64(c.refs[0].Offset+64))
case "coverage":
d.MapCoveredCheckpoint = 6
case "padding":
_, e = m.fd.WriteAt([]byte{1}, int64(c.rootOffset+200))
case "overlap":
d.MapRootLocator = c.refs[0].Offset
case "count":
d.VolumeSize = 8192
case "reserved":
_, e = m.fd.WriteAt([]byte{1}, int64(c.refs[0].Offset+60))
}
if e != nil {
t.Fatal(e)
}
if _, _, e := readChunkLSNMapV3(m.fd, d, 1); e == nil {
t.Fatalf("%s accepted", kind)
}
})
}
}
func TestChunkLSNMapV3_FailureDoesNotPublishOrReuse(t *testing.T) {
for _, stage := range []string{"page_sync", "root_sync", "directory"} {
t.Run(stage, func(t *testing.T) {
d := mapDescriptorV3(t)
m, e := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, 1)
if e != nil {
t.Fatal(e)
}
defer m.Close()
boom := errors.New("injected durability failure")
calls := 0
m.syncFile = func() error {
calls++
if (stage == "page_sync" && calls == 1) || (stage == "root_sync" && calls == 2) {
return boom
}
return m.fd.Sync()
}
m.syncDirectory = func() error {
if stage == "directory" {
return boom
}
return nil
}
if c, e := m.Prepare(1, 7, []chunkLSNEntryV3{{Unknown: true}}, nil); !errors.Is(e, boom) || c != nil {
t.Fatalf("candidate escaped failed persistence: %v %v", c, e)
}
before, _ := m.fd.Stat()
if _, e := m.Prepare(2, 7, []chunkLSNEntryV3{{Unknown: true}}, nil); e == nil {
t.Fatal("failed sidecar reused")
}
after, _ := m.fd.Stat()
if before.Size() != after.Size() {
t.Fatal("retry wrote after failure")
}
})
}
}
func TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage(t *testing.T) {
d := mapDescriptorV3(t)
d.VolumeSize = 501 * 4096
path := filepath.Join(t.TempDir(), "map")
m, e := createChunkLSNMapV3(path, d, 2)
if e != nil {
t.Fatal(e)
}
if other, e := createChunkLSNMapV3(path, d, 2); e == nil {
other.Close()
t.Fatal("overwrote owned sidecar")
}
var stages []string
m.syncFile = func() error {
info, err := m.fd.Stat()
if err != nil {
return err
}
want := int64(8192)
if len(stages) == 1 {
want = 12288
}
if info.Size() != want {
t.Errorf("sync boundary file size=%d want %d", info.Size(), want)
}
stages = append(stages, "file")
return m.fd.Sync()
}
m.syncDirectory = func() error { stages = append(stages, "directory"); return nil }
es := make([]chunkLSNEntryV3, 251)
es[250] = chunkLSNEntryV3{LSN: 7, Unknown: true}
c, e := m.Prepare(1, 7, es, nil)
if e != nil {
t.Fatal(e)
}
if fmt.Sprint(stages) != "[file file directory]" {
t.Fatalf("durability order=%v", stages)
}
next := c.descriptor(d)
if e = m.Close(); e != nil {
t.Fatal(e)
}
reopened, loaded, e := openChunkLSNMapV3(path, next, 2)
if e != nil {
t.Fatal(e)
}
defer reopened.Close()
if len(loaded.entries) != 251 || !loaded.entries[250].Unknown {
t.Fatal("clipped final chunk lost")
}
// The last page has precisely one entry even though the last chunk is clipped.
if loaded.refs[1].Offset == loaded.refs[0].Offset {
t.Fatal("pages aliased")
}
if _, e := reopened.Prepare(1, 7, es, loaded); e == nil {
t.Fatal("generation reuse accepted")
}
foreign := next
foreign.MapLineage[0] ^= 1
if f, _, e := openChunkLSNMapV3(path, foreign, 2); e == nil {
f.Close()
t.Fatal("foreign lineage opened")
}
if f, _, e := openChunkLSNMapV3(path+"missing", next, 2); e == nil {
f.Close()
t.Fatal("missing metadata became clean")
}
}
func TestChunkLSNMapV3_RejectsRehashedMalformedRecords(t *testing.T) {
for _, kind := range []string{"page_generation", "state", "reserved", "unused", "page_domain", "root_domain", "root_padding", "overlap", "duplicate", "huge_count"} {
t.Run(kind, func(t *testing.T) {
d := mapDescriptorV3(t)
d.VolumeSize = 251 * 4096
m, e := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, 1)
if e != nil {
t.Fatal(e)
}
defer m.Close()
c, e := m.Prepare(1, 7, make([]chunkLSNEntryV3, 251), nil)
if e != nil {
t.Fatal(e)
}
d = c.descriptor(d)
shape, _ := mapShapeForV3(d, 1)
root := make([]byte, shape.aligned)
if _, e = m.fd.ReadAt(root, int64(c.rootOffset)); e != nil {
t.Fatal(e)
}
le := binary.LittleEndian
page := make([]byte, 4096)
if _, e = m.fd.ReadAt(page, int64(c.refs[1].Offset)); e != nil {
t.Fatal(e)
}
switch kind {
case "page_generation":
le.PutUint64(page[40:], 2)
case "state":
page[72] = 2
case "reserved":
page[60] = 1
case "unused":
page[80] = 1
case "page_domain":
case "root_domain":
case "root_padding":
root[shape.raw] = 1
case "overlap":
le.PutUint64(root[88:], c.rootOffset)
case "duplicate":
copy(root[128:168], root[88:128])
case "huge_count":
le.PutUint64(root[72:], ^uint64(0))
}
ph := mapDigestV3(mapPageDomainV3, page[:4064])
if kind == "page_domain" {
ph = mapDigestV3(mapRootDomainV3, page[:4064])
}
copy(page[4064:], ph[:])
copy(root[136:168], ph[:])
if _, e = m.fd.WriteAt(page, int64(c.refs[1].Offset)); e != nil {
t.Fatal(e)
}
rh := mapDigestV3(mapRootDomainV3, root[:shape.raw-32])
if kind == "root_domain" {
rh = mapDigestV3(mapPageDomainV3, root[:shape.raw-32])
}
copy(root[shape.raw-32:], rh[:])
d.MapRootHash = rh
if _, e = m.fd.WriteAt(root, int64(c.rootOffset)); e != nil {
t.Fatal(e)
}
if _, _, e := readChunkLSNMapV3(m.fd, d, 1); e == nil {
t.Fatalf("rehashed %s accepted", kind)
}
})
}
}
Binary file not shown.
Binary file not shown.
+4 -1
View File
@@ -258,7 +258,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th
## Part B. Invariant ledger
77 rows: 69 ACTIVE, 8 STUB; 15 kept from the internal ledger, 62 new.
78 rows: 69 ACTIVE, 9 STUB; 15 kept from the internal ledger, 63 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.
@@ -281,6 +281,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `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-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 |
@@ -290,6 +291,8 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
Notes:
- `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. No sidecar page reclamation is implemented, so fallback or uncertain generations remain pinned conservatively.
- `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.
+3
View File
@@ -1,4 +1,7 @@
----------------------------- MODULE WALRecovery -----------------------------
(* V3 row 6: COW map digest domains and pages/root/directory persistence are *)
(* code-test obligations. The composed WALFormatR5 model abstracts validated *)
(* map dependencies; this legacy model is not a proof of the byte codec. *)
(***************************************************************************)
(* S3, walstore layout: a ring WAL of K pages in front of an extent. *)
(* Records of 1 or 2 pages are appended to the page cache, written back to *)