diff --git a/seaweed-block/core/storage/superblock_v3.go b/seaweed-block/core/storage/superblock_v3.go index 29500e5e27..66e418ba71 100644 --- a/seaweed-block/core/storage/superblock_v3.go +++ b/seaweed-block/core/storage/superblock_v3.go @@ -65,6 +65,10 @@ var ( // ErrMigrationIncomplete: no selectable slot exists but a prepared // migration slot does (DESIGN 2.3, 10.1). The volume must not serve. ErrMigrationIncomplete = errors.New("storage: v3 migration not committed (only a prepared descriptor slot exists)") + // ErrStoreFormatNewer: an intact descriptor slot names a store format + // newer than this binary knows (its chunk-state format). The store is + // refused as written by a newer version, never read or changed. + ErrStoreFormatNewer = errors.New("storage: store written by a newer format: use a newer binary") // ErrCounterExhausted: a persisted counter would exceed 2^64-2 // (DESIGN 2.4). Nothing is written. ErrCounterExhausted = errors.New("storage: v3 counter exhausted") @@ -127,6 +131,9 @@ const ( var crc32cTable = crc32.MakeTable(crc32.Castagnoli) +// chunkStateFormatKnownV3 is the newest chunk-state format this binary reads. +const chunkStateFormatKnownV3 = 1 + // reservedRangesV3 are the [start, end) byte ranges that must be zero. var reservedRangesV3 = [][2]int{ {9, 12}, {122, 128}, {164, 168}, {240, 256}, {273, 280}, {308, 312}, {320, slotCRCOffsetV3}, @@ -212,6 +219,11 @@ func decodeSlotV3(b []byte, accept slotImplAcceptor) (descriptorV3, error) { if f := le.Uint16(b[6:]); f != 0 { return descriptorV3{}, fmt.Errorf("%w: slot flags %#x", errSuperblockInvalid, f) } + // A newer store format is told apart before any check of its bytes: an + // intact slot of a newer version is not an invalid one. + if f := le.Uint16(b[306:]); f > chunkStateFormatKnownV3 { + return descriptorV3{}, fmt.Errorf("%w: chunk-state format %d, this binary knows %d", ErrStoreFormatNewer, f, chunkStateFormatKnownV3) + } for _, r := range reservedRangesV3 { if i := firstNonZero(b[r[0]:r[1]]); i >= 0 { return descriptorV3{}, fmt.Errorf("%w: reserved byte %d is nonzero", errSuperblockInvalid, r[0]+i) @@ -430,6 +442,9 @@ func selectSlotV3(a, b []byte, accept slotImplAcceptor) (descriptorV3, slotIDV3, da, errA := decodeSlotV3(a, accept) db, errB := decodeSlotV3(b, accept) if errA != nil && errB != nil { + if errors.Is(errA, ErrStoreFormatNewer) || errors.Is(errB, ErrStoreFormatNewer) { + return descriptorV3{}, 0, fmt.Errorf("%w (A: %v; B: %v)", ErrStoreFormatNewer, errA, errB) + } return descriptorV3{}, 0, fmt.Errorf("%w: neither descriptor slot is valid (A: %v; B: %v)", errSuperblockInvalid, errA, errB) } diff --git a/seaweed-block/core/storage/superblock_v3_format_newer_test.go b/seaweed-block/core/storage/superblock_v3_format_newer_test.go new file mode 100644 index 0000000000..408f1a9e01 --- /dev/null +++ b/seaweed-block/core/storage/superblock_v3_format_newer_test.go @@ -0,0 +1,116 @@ +package storage + +import ( + "crypto/sha256" + "errors" + "os" + "path/filepath" + "testing" +) + +// formatNewerStore is a closed store whose descriptor slots are rewritten by +// mutate (each decoded, changed, and re-sealed with its CRC), plus a planted +// cut COW side file. +func formatNewerStore(t *testing.T, mutate func(slot int, d *descriptorV3)) (path, side string) { + t.Helper() + path = filepath.Join(t.TempDir(), "volume") + s, err := CreateWALStoreWithOptions(path, 64, 4096, WALStoreOptions{ChunkBlocks: 4}) + if err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + f, err := os.OpenFile(path, os.O_RDWR, 0o644) + if err != nil { + t.Fatal(err) + } + for i, off := range []int64{slotAOffsetV3, slotBOffsetV3} { + raw := make([]byte, slotSizeV3) + if _, err := f.ReadAt(raw, off); err != nil { + t.Fatal(err) + } + d, err := decodeSlotV3(raw, nil) + if err != nil { + t.Fatalf("setup: slot %d: %v", i, err) + } + mutate(i, &d) + if _, err := f.WriteAt(d.encode(), off); err != nil { + t.Fatal(err) + } + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + side = path + ".cut-cow-planted" + if err := os.WriteFile(side, []byte("side"), 0o600); err != nil { + t.Fatal(err) + } + return path, side +} + +func fileSum(t *testing.T, path string) [32]byte { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return sha256.Sum256(b) +} + +// A store written by a newer format (its descriptor slots intact, sealed, +// naming a chunk-state format this binary does not know) is refused with the +// typed ErrStoreFormatNewer, not reported as an invalid slot, and the open +// changes nothing: the file's bytes and the directory's cut COW side files +// stay as they were. A half-fence (one slot newer, the other at a known +// format) opens on the known slot, as before; a slot invalid otherwise is +// still invalid, not newer. +func TestANewerStoreFormatIsRefusedTypedAndUntouched(t *testing.T) { + t.Run("both slots newer", func(t *testing.T) { + path, side := formatNewerStore(t, func(_ int, d *descriptorV3) { + d.ChunkStateFormat, d.LocalWorkEpoch = 2, 1 + }) + before := fileSum(t, path) + s, err := OpenWALStore(path) + if err == nil { + _ = s.Close() + } + if !errors.Is(err, ErrStoreFormatNewer) { + t.Fatalf("open of a newer-format store: %v, want ErrStoreFormatNewer", err) + } + if fileSum(t, path) != before { + t.Fatal("the refused open changed the store's bytes") + } + if _, err := os.Stat(side); err != nil { + t.Fatalf("the refused open removed a cut COW side file: %v", err) + } + }) + t.Run("half-fence opens on the known slot", func(t *testing.T) { + path, _ := formatNewerStore(t, func(slot int, d *descriptorV3) { + if slot == 0 { + d.ChunkStateFormat, d.LocalWorkEpoch = 2, 1 + } + }) + s, err := OpenWALStore(path) + if err != nil { + t.Fatalf("open with one slot newer and one known: %v", err) + } + _ = s.Close() + }) + t.Run("control: an invalid slot is not newer", func(t *testing.T) { + path, side := formatNewerStore(t, func(_ int, d *descriptorV3) { + d.ChunkStateFormat, d.LocalWorkEpoch = 0, 5 // epoch without a format: invalid + }) + s, err := OpenWALStore(path) + if err == nil { + _ = s.Close() + t.Fatal("an invalid descriptor opened") + } + if errors.Is(err, ErrStoreFormatNewer) { + t.Fatalf("an invalid descriptor reported as a newer format: %v", err) + } + if _, err := os.Stat(side); err != nil { + t.Fatalf("a refused open removed a cut COW side file: %v", err) + } + }) +} diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 2e3473ad35..9c9c3f17bd 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -347,10 +347,6 @@ func openWALStoreV3WithOptions(path string, requireMap bool, opts WALStoreOption _ = f.Close() return nil, err } - if err := discardCutCOWFiles(path); err != nil { - _ = f.Close() - return nil, err - } return openWALStoreV3File(path, f, requireMap, opts, nil, false) } @@ -376,6 +372,16 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO _ = f.Close() return nil, err } + // Side files are discarded only by an open that selected a slot: an open + // refused at slot selection (a newer format, no valid descriptor) leaves + // the directory as it was. A later refusal (a corrupt map) may follow the + // discard, as before. + if !creating { + if err := discardCutCOWFiles(path); err != nil { + _ = f.Close() + return nil, err + } + } var other *descriptorV3 otherRaw := b if id == slotB { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a2c950cd30..937946cc94 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -632,6 +632,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates, except as `INV-WAL-V3-CAPTURE-COMPARED-001`. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | | `INV-WAL-V3-CAPTURE-COMPARED-001` | A chunk known equal to HEAD is neither staged nor compared again while its mutation version and HEAD ref match; own-batch chunks remain candidates. An interrupted or refused cut retains these proofs and requeues only unproven chunks. All candidate paths use one predicate. | M5 candidate selection | `core/storage/chunk_layer.go` `knownEqualToHeadLocked`, `captureCandidates`, `captureLocked`, `recordCapturedEqualMarks`, `stage`, `requeueCut`; `chunk_cut_payload.go` `markEqualNow` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest`, `TestFilledChunksAreFirstCutCandidatesAfterARestart`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`; `TestRefusedFullCutStagesOnlyTheUnmarkedChunk` (`core/storage/chunk_staging_equal_test.go`); `TestCopyErrorKeepsCapturedEqualMarks`, `TestInterruptedStagingKeepsEqualWork` (`core/storage/chunk_copy_error_equal_test.go`); `TestTimedOutRequestsThenRefusedCommitKeepEqualWork` (`core/frontend/chunkstore/layout_staging_retry_test.go`); also in `core/storage/chunk_fresh_readback_candidates_test.go`, `core/frontend/durable/first_cut_known_zero_test.go`, `core/storage/chunk_compare_progress_test.go`, `core/storage/chunk_mutation_note_guard_test.go`, `core/storage/chunk_own_test.go` | EqualMarks.MarkSound, EqualMarks.NoRecompare (must-violate rows 102-104); conservative reachability unchanged | ACTIVE | | `INV-CHUNK-STATE-UPGRADE-FENCE-001` | The chunk-state upgrade fence succeeds only after both descriptor slots are fsynced and read back with the format marker and local-work epoch; matching reopened slots require a fresh sync; uncertain writes or readback latch until reopen. | M1 format upgrade (caller not wired) | `core/storage/chunk_state_upgrade.go` `WALStore.FenceChunkStateUpgrade` | `TestChunkStateUpgradeFencesBothSlotsBeforeCompletion`, `TestChunkStateUpgradeUncertainSecondSlotRequiresReopen`, `TestChunkStateUpgradeFailureNeverCompletesUntilReopen`, `TestChunkStateUpgradeOldReaderPublicationRestartsTheFence`, `TestChunkStateUpgradeReopenedCachedPairNeedsFreshSync`, `TestChunkStateUpgradeRejectsSuccessfulWrongReadback` (`core/storage/chunk_state_upgrade_test.go`; single-publication and unlatched-readback mutant controls) | `CHUNK-STATE-r3` section 18; `SlotFence` rows 146-149 | STUB | +| `INV-STORE-FORMAT-NEWER-001` | An intact descriptor slot naming a store format newer than this binary reads is refused typed (`ErrStoreFormatNewer`), never as an invalid descriptor; an open refused at slot selection removes no file. | M1 open | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`; `core/storage/walstore_v3.go` `openWALStoreV3File` | `TestANewerStoreFormatIsRefusedTypedAndUntouched` (`core/storage/superblock_v3_format_newer_test.go`; refusal without the typed check and discard-before-select controls) | `SlotFence2` OpenNew | ACTIVE | | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB | | `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 |