diff --git a/seaweed-block/core/storage/chunk_record_shadow.go b/seaweed-block/core/storage/chunk_record_shadow.go index d4ab1a8ef9..6da4bd59d1 100644 --- a/seaweed-block/core/storage/chunk_record_shadow.go +++ b/seaweed-block/core/storage/chunk_record_shadow.go @@ -38,7 +38,10 @@ type chunkRecordShadow struct { // scratchP: chunks a cut hashed while their absence stood (P), from a // scratch merge of the missing blocks. They get no event and stay P, an // extra candidate the full check exempts and names (model answer M1). - scratchP map[uint64]bool + scratchP map[uint64]uint64 // chunk -> the version the scratch cut captured + // version reads a chunk's mutation version (the engine's counter): a + // scratch exemption holds only while the chunk keeps its captured one. + version func(uint64) uint64 // killed: chunks whose clean mark only Recover's version bump killed, // with the version Recover left (an exemption the checker names). killed map[uint64]uint64 @@ -129,7 +132,7 @@ func newChunkRecordShadow(l *chunkLayerImpl) (*chunkRecordShadow, error) { return nil, err } rec.noPages = true - return &chunkRecordShadow{rec: rec, zeroSum: zero}, nil + return &chunkRecordShadow{rec: rec, zeroSum: zero, version: l.chunkVersion}, nil } func (s *chunkRecordShadow) defect(chunk uint64, ev chunkkernel.Event, err error) { @@ -185,15 +188,20 @@ func (s *chunkRecordShadow) hashed(c capturedChunk, current func() uint64, head return // a synthetic capture beyond the volume (tests drive the payload stream directly) } same := capturedAt(c.version, current) - partial := false - guard := func(k chunkkernel.Kind) bool { partial = k == chunkkernel.Partial; return same(k) } + // A scratch cut is evidence only at the version it captured: a stale + // capture (the chunk written since) proves nothing. + scratch := false + guard := func(k chunkkernel.Kind) bool { + scratch = k == chunkkernel.Partial && current() == c.version + return same(k) + } _, ok, err := s.rec.ApplyIf(c.idx, chunkkernel.Hash, dash, &c.sum, guard) - if partial { + if scratch { s.mu.Lock() if s.scratchP == nil { - s.scratchP = map[uint64]bool{} + s.scratchP = map[uint64]uint64{} } - s.scratchP[c.idx] = true + s.scratchP[c.idx] = c.version s.mu.Unlock() } if err != nil { @@ -263,6 +271,14 @@ func (s *chunkRecordShadow) changed(chunk uint64, cov string) { func dash(chunkkernel.Kind) chunkkernel.Arg { return chunkkernel.Arg{Value: "-"} } +// scratchHoldsLocked reports whether a P chunk's scratch-cut exemption +// still holds: the chunk keeps the version the scratch cut captured. A +// write since (P stays P) ends it. Caller holds s.mu. +func (s *chunkRecordShadow) scratchHoldsLocked(chunk uint64, k chunkkernel.Kind) bool { + v, ok := s.scratchP[chunk] + return ok && k == chunkkernel.Partial && s.version != nil && s.version(chunk) == v +} + // errShadowMiss is what a test sees when the record missed a candidate. var errShadowMiss = errors.New("storage: chunk record shadow: an engine candidate is not a record candidate") @@ -281,7 +297,7 @@ func (s *chunkRecordShadow) check(engine map[uint64]bool, skip func(uint64) bool s.mu.Lock() s.fullScans++ for idx, k := range s.rec.kinds { - if isRecordCandidate(k) && !engine[uint64(idx)] && !(k == chunkkernel.Partial && s.scratchP[uint64(idx)]) { + if isRecordCandidate(k) && !engine[uint64(idx)] && !s.scratchHoldsLocked(uint64(idx), k) { extra = append(extra, uint64(idx)) } } diff --git a/seaweed-block/core/storage/chunk_record_shadow_main_test.go b/seaweed-block/core/storage/chunk_record_shadow_main_test.go index c763a84378..7fef233d0d 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_main_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_main_test.go @@ -21,7 +21,7 @@ func TestMain(m *testing.M) { code := m.Run() mu.Lock() defer mu.Unlock() - if len(found) > 0 && !shadowFindingsExpected { + if len(found) > 0 { fmt.Fprintf(os.Stderr, "FAIL: %d chunk record shadow findings; first: %s\n", len(found), found[0]) if code == 0 { code = 1 @@ -30,10 +30,6 @@ func TestMain(m *testing.M) { os.Exit(code) } -// shadowFindingsExpected is set by no test today; it exists so a focused -// run can inspect findings without failing (go test -run X with it set). -var shadowFindingsExpected = os.Getenv("SHADOW_FINDINGS_OK") != "" - // forgetMarksAsARestart drops the clean marks, which are memory only, as a // restart does, and rebuilds the chunk record from the engine's state as a // restart's attach builds it (the record is memory only in shadow mode too). diff --git a/seaweed-block/core/storage/chunk_record_shadow_test.go b/seaweed-block/core/storage/chunk_record_shadow_test.go index a82b79a4bd..f3a81ce5ae 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_test.go @@ -5,7 +5,9 @@ import ( "errors" "os" "path/filepath" + "sync" "testing" + "time" "github.com/seaweedfs/seaweed-block/core/chunkkernel" ) @@ -99,17 +101,43 @@ func TestShadowFillRacedByAWriteEndsUnknown(t *testing.T) { f.getHoldOne, f.getHoldIn = release, held f.mu.Unlock() read := make(chan error, 1) + var once sync.Once + letGo := func() { once.Do(func() { close(release) }) } + // Registered before the reader starts: a failed check below still + // releases the held fetch and joins the reader before the store closes. + t.Cleanup(func() { + letGo() + select { + case <-read: + case <-time.After(ctLocalBound): + t.Error("the reader did not return") + } + }) go func() { _, err := s.Read(idx * ctChunkBlocks); read <- err }() - <-held + select { + case <-held: + case err := <-read: + read <- err // keep it for the cleanup's join + t.Fatalf("setup: the read returned before its fetch was held: %v", err) + case <-time.After(ctLocalBound): + t.Fatal("setup: the fetch was never held") + } if _, err := s.Write(idx*ctChunkBlocks+2, makeBlock(ctBlockSize, 0xE1)); err != nil { t.Fatal(err) } if k := shadowKind(l, idx); k != chunkkernel.Partial { t.Fatalf("a write during the fetch: %s, want P", k) } - close(release) - if err := <-read; err != nil { - t.Fatal(err) + letGo() + var readErr error + select { + case readErr = <-read: + read <- readErr // keep it for the cleanup's join + case <-time.After(ctLocalBound): + t.Fatal("the released read did not return") + } + if readErr != nil { + t.Fatal(readErr) } if k := shadowKind(l, idx); k != chunkkernel.Unknown { t.Fatalf("the raced fill: %s, want U", k) @@ -151,7 +179,7 @@ func TestShadowCutOfAPartialChunkKeepsItPartial(t *testing.T) { l.stMu.Unlock() k := shadowKind(l, idx) l.shadow.mu.Lock() - scratch := l.shadow.scratchP[idx] + _, scratch := l.shadow.scratchP[idx] l.shadow.mu.Unlock() switch { case absent && (k != chunkkernel.Partial || !scratch): @@ -533,3 +561,52 @@ func TestShadowProductionCheckDoesNotScanTheRecord(t *testing.T) { t.Fatalf("test check: extra %v full scans %d; want [7], 1", extra, sh.fullScans) } } + +// The scratch-cut exemption holds only at the version the scratch cut +// captured: a write since (the chunk stays P) ends it, and a stale capture +// (taken before a write) never grants it. Each case leaves a P chunk the +// engine does not name, and only the unchanged post-scratch case is exempt. +func TestShadowScratchExemptionIsBoundToItsCapturedVersion(t *testing.T) { + for _, c := range []struct { + name string + before bool // a write before the capture is hashed (the capture is stale) + after bool // a write after the scratch capture + exempt bool + }{{"unchanged after the scratch cut", false, false, true}, {"written after it", false, true, false}, {"stale capture", true, false, false}} { + t.Run(c.name, func(t *testing.T) { + s, l, _ := lazyFreshVolume(t) + const idx = 3 + if _, err := s.Write(idx*ctChunkBlocks+1, makeBlock(ctBlockSize, 0xD1)); err != nil { + t.Fatal(err) + } + captured := capturedChunk{idx: idx, version: l.chunkVersion(idx), sum: [32]byte{1}} + if c.before { + if _, err := s.Write(idx*ctChunkBlocks+2, makeBlock(ctBlockSize, 0xD2)); err != nil { + t.Fatal(err) + } + } + l.shadow.hashed(captured, func() uint64 { return l.chunkVersion(idx) }, chunkHead{}) + if c.after { + if _, err := s.Write(idx*ctChunkBlocks+2, makeBlock(ctBlockSize, 0xD3)); err != nil { + t.Fatal(err) + } + } + if k := shadowKind(l, idx); k != chunkkernel.Partial { + t.Fatalf("setup: %s, want P", k) + } + prev := shadowFindings + shadowFindings = nil // this control asserts its own extra + defer func() { shadowFindings = prev }() + l.stMu.Lock() + _, extra := l.shadow.check(map[uint64]bool{}, func(uint64) bool { return false }, true, true) + l.stMu.Unlock() + named := false + for _, e := range extra { + named = named || e == idx + } + if named == c.exempt { + t.Fatalf("chunk %d reported as an extra: %v, want %v", idx, named, !c.exempt) + } + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 4f223fc60d..181a9a9b36 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -620,7 +620,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-CHUNK-RECORD-PAGES-CURRENT-001` | An unfinished chunk record is used, and its header written, only when every page passes its check and is valid through exactly the store's synced position after recovery (behind: missed writes; ahead: not durable); an unmarked store discards it; the header follows the two-slot fence. | M1 Opened (chunk record load, v1.1 upgrade) | `core/storage/chunk_record.go` `loadChunkRecord`, `completeChunkRecord` | `TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted`, `TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded`, `TestStalePagesAreNeverCompleted`, `TestUnfinishedPagesAheadOfTheStoreAreNotTrusted`, `TestCompleteRecordAheadOfTheStoreIsNotTrusted`, `TestCompleteRecordPagePositions`, `TestRecordHeaderWaitsForTheFence`, `TestRecordHeaderIsNotWrittenAheadOfTheSyncedStore`, `TestDamagedPage` (`core/storage/chunk_record_test.go`) | SlotFence `PagesCurrent`, `FenceHolds`; pages carry chunk-kernel/2 states (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-UPGRADE-PASS-CURSOR-001` | Upgrade pass: rewinds only at open, before Run; a failed rewind latches it until reopen; the persisted cursor is only ever min(earliest unpublished rewind, last written-through position); a restart resumes there; while it runs, a request needing every hash answers in_progress. | M1 Opened (v1.1 upgrade compare pass) | `core/storage/chunk_upgrade_pass.go` `upgradePass.Run`, `advance`, `Rewind`, `Admit` | `TestUpgradePassCursorFollowsThePagesBehindIt`, `TestUpgradePassRestartContinuesAtTheCursor`, `TestUpgradePassRefusesWithProgress`, `TestUpgradePassRewindAtOpenAfterARebuiltPage`, `TestUpgradePassPauseAndHurry`, `TestUpgradePassFailedRewindLatchesUntilReopen`, `TestUpgradePassRewindOnlyBeforeRun`, `TestUpgradePassKeepsItsCountAcrossRuns`, `TestUpgradePassCursorRuleUnderInterleavings` (`core/storage/chunk_upgrade_pass_test.go`) | UpgradePass `BehindCursorKnown`, `NoWorkTwice`; UpgradeWide3 rows 119 to 124, rewinds at restart only (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-RECORD-RUNTIME-001` | While serving: state only via the kernel, a known hash only with its evidence; a page dirties only when a state or hash changes, is written by its own count or age, an evict's at once, in snapshot order; header G = min(applied, dirty pages' dirty-from). | M3 Serving (chunk record runtime) | `core/storage/chunk_record_runtime.go` `chunkRecordRuntime.Apply`, `Due`, `WriteDue`, `WriteThrough`, `Flush` | `TestRecordRuntimeAppliesTheKernel`, `TestRecordRuntimeEvictWritesThePageFirst`, `TestRecordRuntimeSchedulePerPage`, `TestRecordRuntimeFlushIsLoadedBack`, `TestRecordRuntimeWriteThrough`, `TestRecordRuntimeAnUnchangedStateWritesNothing`, `TestRecordRuntimeHeaderMovesUnderWrites`, `TestRecordRuntimeEvictDuringAFlushLandsLast`, `TestRecordRuntimePageWritesFollowChangesNotSize`, `TestRecordRuntimePageWritersPublishInOrder`, `TestRecordRuntimeHashEvidence`, `TestRecordRuntimeCopiesItsInputs`, `TestRecordRuntimeAPageChangedAtOpenHoldsG` (`core/storage/chunk_record_runtime_test.go`) | chunk-kernel/2; ChunkPages rule 1 (pages before the header) and rule 3 (an evict writes its page first) (the per-chunk state models are not in this repository) | STUB | -| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events through the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. The record decides nothing and writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks`, `TestShadowProductionCheckDoesNotScanTheRecord` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE | +| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events through the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. The record decides nothing and writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks`, `TestShadowProductionCheckDoesNotScanTheRecord`, `TestShadowScratchExemptionIsBoundToItsCapturedVersion` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE | | `INV-CHUNK-FOREIGN-ROOT-FENCE-001` | A HEAD that moved past the holder's base without superseding it and is not its own proposal must keep the chunk root; one that changed it fences the layer (`errChunkForeignRoot`), so no chunk is held clean against a root that no longer names it. | M5 Commit (head conflict, settlement) | `core/storage/chunk_layer.go` `adoptHeadLocked` (from `captureLocked`, `SettleDetach`, `resolvePending`) | `TestShadowForeignRootWithoutSupersedeFences` (`core/storage/chunk_record_shadow_test.go`) | HeadWriters (only metadata writers move HEAD without superseding; not in this repository) | ACTIVE | | `INV-CHUNK-RECORD-PAYLOAD-001` | Persisting and loading a chunk record preserves every entry's state and hash, including entries on either side of a segment boundary. | M1 chunk record codec (caller not wired) | `core/storage/chunk_record.go` `encodeChunkRecordPage`, `decodeChunkRecordPage` | `TestRecordEntryPayloadRoundTripsAcrossSegments` (`core/storage/chunk_record_test.go`; state-zero and one-entry hash-drop controls) | Encoding fidelity; no state transition change | STUB | | `INV-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | ACTIVE |