storage: invalidate bound map proofs at actual Recover start and end

This commit is contained in:
pingqiu committed 2026-11-17 03:17:19 -08:00
1 parent 3cf779490e
commit f3a2b35c94
4 files changed
+184 -3

No files matched your search

@@ -129,3 +129,16 @@ func (p *descriptorPublisherV3) publishMapV3(storeMu sync.Locker, snap func(), p
return nil
}, prepared)
}
// invalidateMapProofV3 is called under WALStore.mu at a lifecycle boundary.
// Taking the existing descMu orders the epoch change after any publication
// already inside descriptor I/O. It performs no callback, allocation or I/O.
// A not-yet-bound dark store has no candidate domain to invalidate.
func (p *descriptorPublisherV3) invalidateMapProofV3() error {
p.descMu.Lock()
defer p.descMu.Unlock()
if p.mapDomain == nil {
return nil
}
return p.mapDomain.invalidateV3()
}
+14 -1
View File
@@ -568,7 +568,7 @@ func (s *WALStore) HolesSuspected() uint64 {
//
// Idempotent: calling Recover twice on the same on-disk state yields
// identical results.
func (s *WALStore) Recover() (uint64, error) {
func (s *WALStore) Recover() (frontier uint64, err error) {
// Recover republishes the dirty map like a write: it holds the capture
// barrier shared, so it can never publish bytes between a quiesced
// cut's Sync (which fixes H) and that cut's copy.
@@ -579,6 +579,19 @@ func (s *WALStore) Recover() (uint64, error) {
defer s.lifecycleMu.RUnlock()
s.mu.Lock()
defer s.mu.Unlock()
if s.v3 != nil {
// The store lock orders both epoch boundaries with real map publishers.
// START invalidates old candidates; END also invalidates candidates
// prepared while this Recover was in flight, including on failure.
defer func() {
if endErr := s.v3.pub.invalidateMapProofV3(); endErr != nil {
frontier, err = 0, errors.Join(err, endErr)
}
}()
if err := s.v3.pub.invalidateMapProofV3(); err != nil {
return 0, err
}
}
if s.closed {
return 0, errors.New("storage: Recover after Close")
}
@@ -0,0 +1,155 @@
package storage
import (
"errors"
"path/filepath"
"sync"
"testing"
"time"
)
// Row7 lifecycle slice: bind a durable map to the actual store publisher.
// This fixture does not claim automatic provider/chunk-layer map attachment.
func bindRecoveryMapV3(t *testing.T, s *WALStore) (*chunkLSNMapV3, *mapProofEpochV3, []chunkLSNEntryV3, *chunkMapCandidateV3) {
t.Helper()
d := s.v3.pub.current()
m, err := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, 4)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := m.Close(); err != nil {
t.Error(err)
}
})
shape, err := mapShapeForV3(d, 4)
if err != nil {
t.Fatal(err)
}
es := make([]chunkLSNEntryV3, int(shape.chunks))
for i := range es {
es[i].Unknown = true
}
c, err := m.Prepare(d.MapGeneration+1, d.CheckpointLSN, es, nil)
if err != nil {
t.Fatal(err)
}
if _, err = s.v3.pub.publish(&s.mu, nil, func(n *descriptorV3) error { *n = c.descriptor(*n); return nil }); err != nil {
t.Fatal(err)
}
proof := newMapProofEpochV3()
if err = s.v3.pub.bindMapV3(c, proof); err != nil {
t.Fatal(err)
}
return m, proof, es, c
}
func TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd(t *testing.T) {
s, _ := newStoreV3(t, WModeLagged)
t.Cleanup(func() {
if err := s.Close(); err != nil {
t.Error(err)
}
})
m, proof, es, current := bindRecoveryMapV3(t, s)
before, err := prepareMapPublicationV3(m, proof, current.generation+1, 0, es, current)
if err != nil {
t.Fatal(err)
}
startEpoch := proof.epoch.Load()
entered, resume, joined := make(chan struct{}), make(chan struct{}), make(chan struct{})
var once sync.Once
release := func() { once.Do(func() { close(resume) }) }
done := make(chan error, 1)
// The existing slot-write hook parks the real Recover after START and before END.
s.v3.testBeforeSlotWrite = func() error { close(entered); <-resume; return nil }
t.Cleanup(func() {
release()
select {
case <-joined:
case <-time.After(5 * time.Second):
t.Error("Recover did not join")
}
})
go func() { defer close(joined); _, e := s.Recover(); done <- e }()
select {
case <-entered:
case <-time.After(5 * time.Second):
t.Fatal("Recover did not reach its slot publication")
}
if before.proof.validV3(proof) || proof.epoch.Load() != startEpoch+1 {
t.Error("actual Recover START did not invalidate the previous map proof")
}
during, err := prepareMapPublicationV3(m, proof, current.generation+2, 0, es, current)
if err != nil {
t.Fatal(err)
}
release()
select {
case err = <-done:
case <-time.After(5 * time.Second):
t.Fatal("Recover did not finish")
}
select {
case <-joined:
case <-time.After(5 * time.Second):
t.Fatal("Recover result arrived but worker did not join")
}
s.v3.testBeforeSlotWrite = nil
if err != nil {
t.Fatal(err)
}
if proof.epoch.Load() != startEpoch+2 {
t.Error("actual Recover END did not advance the map proof epoch")
}
for label, prepared := range map[string]*preparedMapPublicationV3{"before": before, "during": during} {
if _, err = s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); !errors.Is(err, ErrMapCoverageStale) {
t.Errorf("%s real Recover candidate was not refused as stale: %v", label, err)
}
}
fresh, err := prepareMapPublicationV3(m, proof, current.generation+3, 0, es, current)
if err != nil {
t.Fatal(err)
}
if _, err = s.v3.pub.publishMapV3(&s.mu, nil, fresh, nil); err != nil {
t.Fatalf("fresh post-Recover candidate refused: %v", err)
}
}
func TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries(t *testing.T) {
s, _ := newStoreV3(t, WModeStrict)
t.Cleanup(func() {
if err := s.Close(); err != nil {
t.Error(err)
}
})
if _, err := s.Write(0, blk(0x51)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
m, proof, es, current := bindRecoveryMapV3(t, s)
before, err := prepareMapPublicationV3(m, proof, current.generation+1, 0, es, current)
if err != nil {
t.Fatal(err)
}
epoch := proof.epoch.Load()
off, _, _, _, ok := s.dm.get(0)
if !ok {
t.Fatal("synced write missing from WAL dirty map")
}
// Corrupt an acknowledged WAL payload: R<W is a real recovery failure.
if _, err = s.fd.WriteAt([]byte{0x52}, int64(s.sb.WALOffset+off+walEntryPrefixSizeV3)); err != nil {
t.Fatal(err)
}
if _, err = s.Recover(); !isWALCorrupt(err) {
t.Fatalf("damaged acknowledged WAL recovery verdict = %v, want WALIntegrity", err)
}
if proof.epoch.Load() != epoch+2 {
t.Error("failed actual Recover must invalidate START and END")
}
if _, err = s.v3.pub.publishMapV3(&s.mu, nil, before, nil); !errors.Is(err, ErrMapCoverageStale) {
t.Fatalf("pre-failure map candidate was not refused as stale: %v", err)
}
}
+2 -2
View File
@@ -282,7 +282,7 @@ 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-LSN-ORDER-001` | A dark v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 (dark append only) | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | 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-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; lifecycle caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB |
| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | 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; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. 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`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | 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` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3` | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB |
@@ -294,7 +294,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
Notes:
- `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged.
- `INV-WAL-V3-MAP-PUBLISH-001`: dark-core controls only. Recover START and END invalidation (success/failure), reset/install transition hooks and real checkpoint/capture/provider wiring still require row 5b/7 integration. The lifecycle tests explicitly drive invalidation primitives; they do not claim to exercise a real Recover or flusher. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads.
- `INV-WAL-V3-MAP-PUBLISH-001`: Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. Automatic map attach, reset/install transitions and checkpoint/capture/provider wiring still require integration. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, and none claims flusher or provider coverage. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads.
- `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.