storage: v3 publisher latches slot write errors and pins the uncertain candidate (row 3 amend)

codex01 row 3 review (c9790ac4, AMEND):
- P1: a slot pwrite error (full or partial), like an fsync error, now
  latches a publisher failure (ErrDescriptorPublishUncertain) and the store
  fault through descriptorIOV3.latch, retains the uncertain candidate, and
  refuses every further publication, rollover and reuse with no further
  I/O until reopen reads the slots back (DESIGN 5 failure rule). The v2
  syncFile leaf is unchanged.
- P2: publication-side counter checks return ErrCounterExhausted before
  any write; installed -> installing is refused (not an 8.5 edge).
- Tests: full and partial slot write then error (refusals, no further
  writes, no reuse, store fault latched, reopen selects the previous gen
  after a torn write and the new gen after a complete one); counter
  exhaustion for W, checkpoint, head and map generation; the extra edge.
- invariants.md: INV-WAL-V3-PUBLISH-001 statement and tests updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-17 01:52:02 -08:00
1 parent c9790ac474
commit 092784eb80
3 files changed
+195 -9

No files matched your search

+80 -5
View File
@@ -35,15 +35,26 @@ var (
// descriptorIOV3 is the store I/O the publisher needs. writeSlot does one
// pwrite of a whole slot; syncFile runs the store's leaf (pwrite + fsync
// under fileSyncMu, latching the sticky fault on fsync failure); sticky
// reports a latched fault.
// under fileSyncMu); sticky reports a latched store fault; latch records a
// fault in the store so every other store path (appends, Sync, reuse) is
// refused too. The publisher latches on a slot write error as well as on an
// fsync error (DESIGN 5): the v2 leaf does not latch pwrite errors, so the
// v3 publisher does it itself.
type descriptorIOV3 struct {
writeSlot func(off int64, b []byte) error
fsync func() error
syncFile func(write, sync func() error) error
sticky func() error
latch func(err error)
}
// ErrDescriptorPublishUncertain: a descriptor slot write or fsync failed, so
// the slot on disk may hold the new generation, the old one, or a torn mix.
// The open store refuses every further publication and all reuse; only a
// reopen, which reads back and selects the actual slots, resolves it
// (DESIGN 5, failure rule).
var ErrDescriptorPublishUncertain = errors.New("storage: v3 descriptor publication outcome uncertain; reopen required")
// descriptorPublisherV3 holds the authoritative in-memory descriptor and
// the contents of the fallback slot, which pins reuse (DESIGN 5).
type descriptorPublisherV3 struct {
@@ -57,6 +68,12 @@ type descriptorPublisherV3 struct {
io descriptorIOV3
accept slotImplAcceptor
// failed is set by the first slot write or fsync failure. uncertain is
// the candidate that may be on disk: it stays pinned (its tail bounds
// reuse, and its map dependencies stay referenced) until reopen.
failed error
uncertain *descriptorV3
// trace, when set by a test, records lock acquisitions and releases
// in order (the section 11 item 9 lock recorder).
trace func(event string)
@@ -94,6 +111,9 @@ func (p *descriptorPublisherV3) reuseFloor() (floor uint64, ok bool) {
}
func (p *descriptorPublisherV3) reuseFloorLocked() (uint64, bool) {
if p.failed != nil {
return 0, false // an uncertain slot may reference anything: no reuse until reopen
}
if !p.otherValid {
return p.cur.RetainedTail, true
}
@@ -132,7 +152,22 @@ func (p *descriptorPublisherV3) publish(storeMu sync.Locker, snap func(), mutate
return p.publishLocked(mutate)
}
// uncertainCandidate returns the candidate whose publication failed, if
// any. Its dependencies (WAL bytes from its tail, its map root and pages)
// stay pinned until reopen.
func (p *descriptorPublisherV3) uncertainCandidate() (descriptorV3, bool) {
p.descMu.Lock()
defer p.descMu.Unlock()
if p.uncertain == nil {
return descriptorV3{}, false
}
return *p.uncertain, true
}
func (p *descriptorPublisherV3) publishLocked(mutate func(next *descriptorV3) error) (descriptorV3, error) {
if p.failed != nil {
return descriptorV3{}, p.failed
}
if err := p.io.sticky(); err != nil {
return descriptorV3{}, err
}
@@ -145,6 +180,9 @@ func (p *descriptorPublisherV3) publishLocked(mutate func(next *descriptorV3) er
if err := mergeDescriptorV3(&p.cur, &next); err != nil {
return descriptorV3{}, err
}
if err := checkCountersV3(&next); err != nil {
return descriptorV3{}, err
}
gen, err := nextSlotGenV3(p.cur.SlotGen)
if err != nil {
return descriptorV3{}, err
@@ -160,12 +198,26 @@ func (p *descriptorPublisherV3) publishLocked(mutate func(next *descriptorV3) er
target, off = slotA, slotAOffsetV3
}
buf := next.encode()
wrote := false
err = p.io.syncFile(func() error {
p.note("hold fileSyncMu")
wrote = true
return p.io.writeSlot(off, buf)
}, p.io.fsync)
if err != nil {
return descriptorV3{}, err
if wrote {
// The slot write or its fsync failed: the fallback slot may hold
// the new generation, the old one or a torn mix. Latch, keep the
// candidate pinned, and refuse everything until reopen.
uncertain := next
p.uncertain = &uncertain
p.failed = fmt.Errorf("%w: %w", ErrDescriptorPublishUncertain, err)
if p.io.latch != nil {
p.io.latch(p.failed)
}
return descriptorV3{}, p.failed
}
return descriptorV3{}, err // refused before any I/O (a latched fault)
}
// Success boundary: a fault latched by another path while this
// publication was in flight still refuses it (#172).
@@ -177,6 +229,26 @@ func (p *descriptorPublisherV3) publishLocked(mutate func(next *descriptorV3) er
return next, nil
}
// checkCountersV3 refuses a publication whose counters would exceed 2^64-2
// (DESIGN 2.4) with ErrCounterExhausted, before any write. Slot decoding of
// such a value stays errSuperblockInvalid.
func checkCountersV3(d *descriptorV3) error {
for _, c := range []struct {
name string
v uint64
}{
{"W", d.W}, {"CheckpointLSN", d.CheckpointLSN}, {"retainedTail", d.RetainedTail},
{"retainedHead", d.RetainedHead}, {"mapGeneration", d.MapGeneration},
{"mapCoveredCheckpoint", d.MapCoveredCheckpoint}, {"BaseLSN", d.BaseLSN},
{"BaseCursor", d.BaseCursor},
} {
if c.v > counterMaxV3 {
return fmt.Errorf("%w: %s %d", ErrCounterExhausted, c.name, c.v)
}
}
return nil
}
// mergeDescriptorV3 applies the monotonic merge and transition rules of
// DESIGN 5 and 8.5 to next, a mutated copy of cur.
func mergeDescriptorV3(cur, next *descriptorV3) error {
@@ -242,10 +314,10 @@ func baseTransitionAllowedV3(cur, next *descriptorV3) error {
// Retirement may clear BaseCursor below the tail; the ID and
// BaseLSN stay.
ok = next.BaseInstallID == cur.BaseInstallID && next.BaseLSN == cur.BaseLSN
case BaseInstalling:
ok = next.BaseInstallID != cur.BaseInstallID // a new install begins
case BaseNone:
ok = next.BaseLSN == 0 && next.CheckpointLSN >= cur.BaseLSN
// installed -> installing is not an 8.5 edge: a new install
// begins only after installed -> none (retire, then begin).
}
}
if !ok {
@@ -266,6 +338,9 @@ func (p *descriptorPublisherV3) rolloverIfPinned() (bool, error) {
p.note("unlock descMu")
p.descMu.Unlock()
}()
if p.failed != nil {
return false, p.failed
}
if !p.otherValid || p.other.Nonce != p.cur.Nonce || p.other.RetainedTail >= p.cur.RetainedTail {
return false, nil
}
@@ -20,8 +20,12 @@ type descHarnessV3 struct {
fault atomic.Pointer[error]
fsyncErr atomic.Pointer[error]
afterFsync func() // test hook inside the leaf, after a successful fsync
storeMu sync.Mutex
pub *descriptorPublisherV3
// writeHook, when set, replaces the slot pwrite (to inject a full or
// partial write followed by an error).
writeHook func(off int64, b []byte) error
writes atomic.Int64
storeMu sync.Mutex
pub *descriptorPublisherV3
}
func newDescHarnessV3(t *testing.T) *descHarnessV3 {
@@ -44,7 +48,15 @@ func newDescHarnessV3(t *testing.T) *descHarnessV3 {
}
h := &descHarnessV3{t: t, f: f}
h.pub = newDescriptorPublisherV3(d, slotA, nil, descriptorIOV3{
writeSlot: func(off int64, b []byte) error { _, err := f.WriteAt(b, off); return err },
writeSlot: func(off int64, b []byte) error {
h.writes.Add(1)
if h.writeHook != nil {
return h.writeHook(off, b)
}
_, err := f.WriteAt(b, off)
return err
},
latch: func(err error) { h.fault.CompareAndSwap(nil, &err) },
fsync: func() error {
if e := h.fsyncErr.Load(); e != nil {
return *e
@@ -366,6 +378,7 @@ func TestDescriptorV3BaseTransitionTable(t *testing.T) {
{"installing -> none (abort)", mk(BaseInstalling, 50, id1), mk(BaseNone, 0, [16]byte{}), true},
{"none -> installed", mk(BaseNone, 0, [16]byte{}), mk(BaseInstalled, 50, id1), false},
{"installed -> none needs checkpoint past BaseLSN", mk(BaseInstalled, 50, id1), mk(BaseNone, 0, [16]byte{}), false},
{"installed -> installing is not an 8.5 edge", mk(BaseInstalled, 50, id1), mk(BaseInstalling, 60, id2), false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
@@ -382,3 +395,101 @@ func TestDescriptorV3BaseTransitionTable(t *testing.T) {
t.Fatalf("installed -> none with the checkpoint at BaseLSN refused: %v", err)
}
}
// codex01 row 3 review P1: a slot write error (full or partial), like an
// fsync error, latches the store, keeps the candidate pinned and refuses
// every further publication, rollover and reuse with no further I/O.
// Reopen (read back and select) is the positive control.
func TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate(t *testing.T) {
for _, partial := range []bool{true, false} {
name := "full write then error"
if partial {
name = "partial write then error"
}
t.Run(name, func(t *testing.T) {
h := newDescHarnessV3(t)
// A checkpoint first, so the fallback pins tail 0 and a
// rollover would otherwise be due.
if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error {
n.RetainedTail, n.RetainedHead = 100, 100
return nil
}); err != nil {
t.Fatal(err)
}
before := h.pub.current()
boom := errors.New("injected slot write error")
h.writeHook = func(off int64, b []byte) error {
n := len(b)
if partial {
n = 1000
}
if _, err := h.f.WriteAt(b[:n], off); err != nil {
t.Fatal(err)
}
return boom
}
_, err := h.pub.publish(&h.storeMu, nil, setW(30))
if !errors.Is(err, ErrDescriptorPublishUncertain) || !errors.Is(err, boom) {
t.Fatalf("err = %v, want ErrDescriptorPublishUncertain wrapping the write error", err)
}
if h.pub.current() != before {
t.Fatal("a failed publication changed the authoritative descriptor")
}
if cand, ok := h.pub.uncertainCandidate(); !ok || cand.W != 30 || cand.SlotGen != before.SlotGen+1 {
t.Fatalf("uncertain candidate not retained: ok %v %+v", ok, cand)
}
if h.fault.Load() == nil {
t.Fatal("the store fault was not latched: other store paths could still acknowledge or reclaim")
}
h.writeHook = nil
writes := h.writes.Load()
if _, err := h.pub.publish(&h.storeMu, nil, setW(31)); !errors.Is(err, ErrDescriptorPublishUncertain) {
t.Fatalf("publication after the failure: err = %v, want ErrDescriptorPublishUncertain", err)
}
if _, err := h.pub.rolloverIfPinned(); !errors.Is(err, ErrDescriptorPublishUncertain) {
t.Fatalf("rollover after the failure: err = %v, want ErrDescriptorPublishUncertain", err)
}
if _, ok := h.pub.reuseFloor(); ok {
t.Fatal("reuse allowed while a publication outcome is uncertain")
}
if got := h.writes.Load(); got != writes {
t.Fatalf("%d further slot writes after the failure, want none", got-writes)
}
// Reopen resolves it: a torn slot fails its CRC and the
// previous generation is selected; a complete slot is the new one.
got, _ := h.onDisk()
if partial && got != before {
t.Fatalf("reopen after a torn write selected gen %d W %d, want the previous gen %d", got.SlotGen, got.W, before.SlotGen)
}
if !partial && (got.SlotGen != before.SlotGen+1 || got.W != 30) {
t.Fatalf("reopen after a complete write selected gen %d W %d, want gen %d W 30", got.SlotGen, got.W, before.SlotGen+1)
}
})
}
}
// codex01 row 3 review P2: counters beyond 2^64-2 are refused at
// publication with ErrCounterExhausted, before any write.
func TestDescriptorV3PublicationCounterExhaustion(t *testing.T) {
const over = counterMaxV3 + 1
for _, c := range []struct {
name string
set func(*descriptorV3)
}{
{"W", func(n *descriptorV3) { n.W = over }},
{"CheckpointLSN", func(n *descriptorV3) { n.CheckpointLSN = over }},
{"retainedHead", func(n *descriptorV3) { n.RetainedHead = over }},
{"mapGeneration", func(n *descriptorV3) { n.MapGeneration = over; n.MapRootHash[0] ^= 1 }},
} {
t.Run(c.name, func(t *testing.T) {
h := newDescHarnessV3(t)
writes := h.writes.Load()
if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { c.set(n); return nil }); !errors.Is(err, ErrCounterExhausted) {
t.Fatalf("err = %v, want ErrCounterExhausted", err)
}
if h.writes.Load() != writes {
t.Fatal("an exhausted publication wrote a slot")
}
})
}
}
+1 -1
View File
@@ -280,7 +280,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `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-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. A failed fsync or a fault latched mid-flight publishes nothing. 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` (`core/storage/descriptor_v3_test.go`) | — | 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, 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` (`core/storage/descriptor_v3_test.go`) | — | 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 |