diff --git a/seaweed-block/core/storage/chunk_record_runtime.go b/seaweed-block/core/storage/chunk_record_runtime.go index 2d84ebbc7d..070e31b076 100644 --- a/seaweed-block/core/storage/chunk_record_runtime.go +++ b/seaweed-block/core/storage/chunk_record_runtime.go @@ -35,6 +35,14 @@ func chunkRecordKind(code uint8) (chunkkernel.Kind, error) { return "", fmt.Errorf("%w: state code %d", errChunkRecordCheck, code) } +var ( + // ErrChunkRecordStaleCommit refuses a commit whose captured hash is no + // longer the chunk's: the chunk changed after its cut captured it. + ErrChunkRecordStaleCommit = errors.New("storage: chunk record: commit of a hash the chunk no longer has") + // ErrChunkRecordNoHash refuses a transition into a known hash without it. + ErrChunkRecordNoHash = errors.New("storage: chunk record: a known hash needs the hash") +) + // chunkRecordRuntime is the record while the volume serves: every chunk's // state in memory, changed only through the kernel, and the pages written on // their own schedule, never tied to the store's checkpoint. @@ -56,6 +64,15 @@ func chunkRecordKind(code uint8) (chunkkernel.Kind, error) { // or maxAge since the first unwritten change. // - WriteThrough(end) writes the dirty pages of the chunks below end (the // upgrade pass persists its cursor after it). +// - PAGES ARE PUBLISHED IN ORDER. pubMu is held across a page's snapshot +// and its write, and across the header's write, so a write never lands +// an older snapshot after a newer one. Lock order: pubMu, then mu. +// - HASH EVIDENCE. A transition into a known hash needs the hash: Hash and +// Fill take it from the caller; Commit takes the hash its cut captured +// and is refused unless that is still the chunk's hash (a write and a new +// hash after the capture make the commit stale). An ignored event keeps +// the hash. A refusal changes nothing. +// - appliedPos is called under mu; it must not call back into the record. type chunkRecordRuntime struct { dir string chunks uint64 @@ -66,8 +83,9 @@ type chunkRecordRuntime struct { maxEntries int maxAge time.Duration - testBeforePageWrite func(seg uint64) // tests only: runs outside the lock before a page write + testBeforePageWrite func(seg uint64) // tests only: runs outside mu, under pubMu, before a page write + pubMu sync.Mutex // see PAGES ARE PUBLISHED IN ORDER mu sync.Mutex kinds []chunkkernel.Kind hashes [][32]byte @@ -85,7 +103,8 @@ func newChunkRecordRuntime(dir string, chunks, epoch uint64, appliedPos func() u } return &chunkRecordRuntime{dir: dir, chunks: chunks, epoch: epoch, appliedPos: appliedPos, maxEntries: 1000, maxAge: time.Minute, - kinds: kinds, hashes: hashes, valid: valid, + kinds: append([]chunkkernel.Kind(nil), kinds...), hashes: append([][32]byte(nil), hashes...), + valid: append([]uint64(nil), valid...), dirtyVer: make([]uint64, segs), writtenVer: make([]uint64, segs)}, nil } @@ -110,14 +129,24 @@ func (r *chunkRecordRuntime) Apply(chunk uint64, ev chunkkernel.Event, arg chunk r.mu.Unlock() return chunkkernel.None, err } - r.kinds[chunk] = res.State.Kind - switch res.State.Kind { - case chunkkernel.HashUnpublished, chunkkernel.HashPublished: - if hash != nil { + if res.Outcome == chunkkernel.Applied { + known := res.State.Kind == chunkkernel.HashUnpublished || res.State.Kind == chunkkernel.HashPublished + switch { + case ev == chunkkernel.Commit: + if hash == nil || *hash != r.hashes[chunk] { + r.mu.Unlock() + return chunkkernel.None, ErrChunkRecordStaleCommit + } + case known && (ev == chunkkernel.Hash || ev == chunkkernel.Fill): + if hash == nil { + r.mu.Unlock() + return chunkkernel.None, ErrChunkRecordNoHash + } r.hashes[chunk] = *hash + case !known: + r.hashes[chunk] = [32]byte{} } - default: - r.hashes[chunk] = [32]byte{} + r.kinds[chunk] = res.State.Kind } seg := chunk / chunkRecordSegment r.dirtyVer[seg]++ @@ -127,7 +156,9 @@ func (r *chunkRecordRuntime) Apply(chunk uint64, ev chunkkernel.Event, arg chunk r.changed++ r.mu.Unlock() if eff == chunkkernel.PageBeforeBytes { - if err := r.writeSegments(seg, seg+1); err != nil { + r.pubMu.Lock() + defer r.pubMu.Unlock() + if err := r.writeSegmentsLocked(seg, seg+1); err != nil { return eff, err } } @@ -147,14 +178,20 @@ func (r *chunkRecordRuntime) WriteThrough(end uint64) error { return nil } last := (min(end, r.chunks) + chunkRecordSegment - 1) / chunkRecordSegment - return r.writeSegments(0, last) + r.pubMu.Lock() + defer r.pubMu.Unlock() + return r.writeSegmentsLocked(0, last) } // Flush writes every dirty page, then, if no page was dirtied meanwhile, the // header with G = the applied position read before the pages. func (r *chunkRecordRuntime) Flush() error { + r.pubMu.Lock() + defer r.pubMu.Unlock() + r.mu.Lock() g := r.appliedPos() - if err := r.writeSegments(0, chunkRecordSegments(r.chunks)); err != nil { + r.mu.Unlock() + if err := r.writeSegmentsLocked(0, chunkRecordSegments(r.chunks)); err != nil { return err } r.mu.Lock() @@ -174,10 +211,10 @@ func (r *chunkRecordRuntime) Flush() error { return writeChunkRecordFile(r.dir, chunkRecordHeaderName, encodeChunkRecordHeader(chunkRecordHeader{Epoch: r.epoch, Chunks: r.chunks, G: g})) } -// writeSegments writes the dirty pages of segments [from, to). Each page is -// snapshotted under the lock and written outside it; a change while it is -// written leaves the page dirty. -func (r *chunkRecordRuntime) writeSegments(from, to uint64) error { +// writeSegmentsLocked writes the dirty pages of segments [from, to), with +// pubMu held. Each page is snapshotted under mu and written outside it; a +// change while it is written leaves the page dirty. +func (r *chunkRecordRuntime) writeSegmentsLocked(from, to uint64) error { for seg := from; seg < to; seg++ { r.mu.Lock() ver := r.dirtyVer[seg] @@ -204,9 +241,7 @@ func (r *chunkRecordRuntime) writeSegments(from, to uint64) error { return err } r.mu.Lock() - if r.writtenVer[seg] < ver { - r.writtenVer[seg], r.valid[seg] = ver, pos - } + r.writtenVer[seg], r.valid[seg] = ver, pos // in order under pubMu r.mu.Unlock() } return nil diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9f26deee5b..c056d0d5f6 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -616,7 +616,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `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, a chunk's state changes only through the kernel; every event dirties its page; an evict writes its page before the bytes go; pages and the header are valid through the applied position, and the header is written only when every page is clean. | M3 Serving (chunk record runtime) | `core/storage/chunk_record_runtime.go` `chunkRecordRuntime.Apply`, `Flush`, `WriteThrough` | `TestRecordRuntimeAppliesTheKernel`, `TestRecordRuntimeEvictWritesThePageFirst`, `TestRecordRuntimeSchedule`, `TestRecordRuntimeFlushIsLoadedBack`, `TestRecordRuntimeWriteThrough`, `TestRecordRuntimeAnUnchangedStateStillDirtiesThePage`, `TestRecordRuntimeNoHeaderOverAPageDirtiedDuringFlush` (`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-RUNTIME-001` | While serving, state changes only via the kernel, a known hash only with its hash (a commit only of the captured hash still held); pages publish in snapshot order, an evict's page first; header only when all pages are clean, valid through the applied position. | M3 Serving (chunk record runtime) | `core/storage/chunk_record_runtime.go` `chunkRecordRuntime.Apply`, `Flush`, `WriteThrough` | `TestRecordRuntimeAppliesTheKernel`, `TestRecordRuntimeEvictWritesThePageFirst`, `TestRecordRuntimeSchedule`, `TestRecordRuntimeFlushIsLoadedBack`, `TestRecordRuntimeWriteThrough`, `TestRecordRuntimeAnUnchangedStateStillDirtiesThePage`, `TestRecordRuntimeNoHeaderOverAPageDirtiedDuringFlush`, `TestRecordRuntimePageWritersPublishInOrder`, `TestRecordRuntimeHashEvidence`, `TestRecordRuntimeCopiesItsInputs` (`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-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 | | `INV-WAL-V3-DESCRIPTOR-CONFLICT-001` | Open is refused when both v3 descriptor slots are valid but carry the same slotGen with different bytes, or disagree on the UUID or the geometry. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3`, `sameGeometryV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`) | — | ACTIVE |