From c5841afd807d9b2ea9f4acdc880c4ac6d8cf0f69 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 09:03:38 -0800 Subject: [PATCH] Require integrity-only fallback errors and pin every authority guard --- .../core/storage/chunk_coverage_test.go | 167 ++++++++++++++++++ seaweed-block/core/storage/walstore_v3.go | 31 +++- seaweed-block/docs/design/chunk-coverage.md | 5 +- seaweed-block/docs/design/invariants.md | 2 +- .../docs/design/model-code-trace-coverage.tsv | 2 +- 5 files changed, 203 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/storage/chunk_coverage_test.go b/seaweed-block/core/storage/chunk_coverage_test.go index 2e16996eda..d7d47ccbc7 100644 --- a/seaweed-block/core/storage/chunk_coverage_test.go +++ b/seaweed-block/core/storage/chunk_coverage_test.go @@ -5,7 +5,9 @@ import ( "encoding/binary" "errors" "fmt" + "io" "os" + "syscall" "testing" ) @@ -680,3 +682,168 @@ func TestChunkCoverageBothMarkedDamagedMapNeverFallsBack(t *testing.T) { t.Fatalf("marked dependency loss was hidden: err=%v events=%d", err, events) } } + +func TestChunkCoverageFallbackRequiresIntegrityOnlyErrorTree(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + legacy := s.v3.pub.current() + marked := legacy + marked.SlotGen++ + marked.ChunkStateFormat = 1 + marked.LocalWorkEpoch = 7 + marked.MapFormatID = mapFormatIDCoverage + cases := []struct { + name string + cause error + want bool + }{ + {"nil", nil, false}, {"invalid", ErrMapInvalid, true}, {"eof", io.EOF, true}, {"short", io.ErrUnexpectedEOF, true}, + {"wrapped-eof", fmt.Errorf("read: %w", io.EOF), true}, {"joined-integrity", errors.Join(io.EOF, ErrMapInvalid), true}, + {"eio", syscall.EIO, false}, {"permission", os.ErrPermission, false}, + {"joined-eof-eio", errors.Join(io.EOF, syscall.EIO), false}, + {"nested-operational", fmt.Errorf("map: %w", errors.Join(ErrMapInvalid, fmt.Errorf("close: %w", syscall.EIO))), false}, + {"multiple-wrap-operational", fmt.Errorf("read %w; close %w", io.ErrUnexpectedEOF, os.ErrPermission), false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := coverageHalfFenceFallbackEligible(marked, &legacy, tc.cause); got != tc.want { + t.Fatalf("eligibility=%v want=%v cause=%v", got, tc.want, tc.cause) + } + }) + } +} + +func TestChunkCoverageFallbackAuthorityGuards(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + legacy := s.v3.pub.current() + marked := legacy + marked.SlotGen++ + marked.ChunkStateFormat = 1 + marked.LocalWorkEpoch = 7 + marked.MapFormatID = mapFormatIDCoverage + cases := []struct { + name string + change func(*descriptorV3, **descriptorV3) + want bool + }{ + {"intact-unmarked-half", func(*descriptorV3, **descriptorV3) {}, true}, + {"selected-unmarked", func(d *descriptorV3, _ **descriptorV3) { d.ChunkStateFormat = 0 }, false}, + {"selected-format1", func(d *descriptorV3, _ **descriptorV3) { d.MapFormatID = mapFormatIDV1 }, false}, + {"missing-other", func(_ *descriptorV3, o **descriptorV3) { *o = nil }, false}, + {"other-marked", func(_ *descriptorV3, o **descriptorV3) { (*o).ChunkStateFormat = 1 }, false}, + {"other-format2", func(_ *descriptorV3, o **descriptorV3) { (*o).MapFormatID = mapFormatIDCoverage }, false}, + {"other-migration", func(_ *descriptorV3, o **descriptorV3) { (*o).MigrationPhase = MigrationPhase(1) }, false}, + {"same-generation", func(d *descriptorV3, o **descriptorV3) { (*o).SlotGen = d.SlotGen }, false}, + {"newer-other", func(d *descriptorV3, o **descriptorV3) { (*o).SlotGen = d.SlotGen + 1 }, false}, + {"identity", func(_ *descriptorV3, o **descriptorV3) { (*o).UUID[0] ^= 1 }, false}, + {"volume-size", func(_ *descriptorV3, o **descriptorV3) { (*o).VolumeSize += 4096 }, false}, + {"extent-size", func(_ *descriptorV3, o **descriptorV3) { (*o).ExtentSize += 4096 }, false}, + {"block-size", func(_ *descriptorV3, o **descriptorV3) { (*o).BlockSize *= 2 }, false}, + {"wal-offset", func(_ *descriptorV3, o **descriptorV3) { (*o).WALOffset += 4096 }, false}, + {"wal-size", func(_ *descriptorV3, o **descriptorV3) { (*o).WALSize += 4096 }, false}, + {"nonce", func(_ *descriptorV3, o **descriptorV3) { (*o).Nonce[0] ^= 1 }, false}, + {"map-lineage", func(_ *descriptorV3, o **descriptorV3) { (*o).MapLineage[0] ^= 1 }, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + d, o := marked, legacy + other := &o + tc.change(&d, &other) + if got := coverageHalfFenceFallbackEligible(d, other, ErrMapInvalid); got != tc.want { + t.Fatalf("eligibility=%v want=%v", got, tc.want) + } + }) + } +} + +func TestChunkCoverageFallbackRefusesUnavailableOtherDependencies(t *testing.T) { + for _, point := range []string{"invalid-other-slot", "missing-map", "directory-map", "damaged-other-root", "truncated-other-root"} { + t.Run(point, func(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + writes := 0 + s.v3.testBeforeSlotWrite = func() error { + writes++ + if writes == 2 { + return errors.New("half fence") + } + return nil + } + if err := s.InitializeChunkCoverage(context.Background(), 7, func(uint64, uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{Blocks: []uint64{1}}, nil }, coverageNoPages); err == nil { + t.Fatal("half fence completed") + } + marked, legacy, slot := s.v3.pub.current(), s.v3.pub.other, s.v3.pub.curSlot + s.v3.testBeforeSlotWrite = nil + _ = s.Close() + mapPath := path + ".chunkmap" + f, err := os.OpenFile(mapPath, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + if _, err := f.WriteAt([]byte("BAD!"), int64(marked.MapRootLocator)); err != nil { + f.Close() + t.Fatal(err) + } + if point == "damaged-other-root" { + if _, err := f.WriteAt([]byte("BAD!"), int64(legacy.MapRootLocator)); err != nil { + f.Close() + t.Fatal(err) + } + } + if point == "truncated-other-root" { + if err := f.Truncate(int64(legacy.MapRootLocator + 32)); err != nil { + f.Close() + t.Fatal(err) + } + } + if err := f.Sync(); err != nil { + f.Close() + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + switch point { + case "invalid-other-slot": + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + offset := int64(slotAOffsetV3) + if slot == slotA { + offset = slotBOffsetV3 + } + if _, err := f.WriteAt([]byte("BAD!"), offset); err != nil { + f.Close() + t.Fatal(err) + } + if err := f.Sync(); err != nil { + f.Close() + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + case "missing-map", "directory-map": + if err := os.Remove(mapPath); err != nil { + t.Fatal(err) + } + if point == "directory-map" { + if err := os.Mkdir(mapPath, 0700); err != nil { + t.Fatal(err) + } + } + } + events := 0 + next, err := openWALStoreV3WithOptions(path, true, WALStoreOptions{RecoveryEvent: func(RecoveryEvent) { events++ }}) + if next != nil { + next.Close() + } + if err == nil || next != nil || events != 0 { + t.Fatalf("unavailable dependency authorized fallback: err=%v store=%v events=%d", err, next != nil, events) + } + }) + } +} diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 17e1acdbae..0ae4bf944d 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -411,6 +411,8 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO other = nil ownedMap, mapCurrent, err = back, candidate, nil ownedMap.live.halfFenceFallbacks.Add(1) + } else { + err = errors.Join(err, fmt.Errorf("half-fence fallback map: %w", backErr)) } } if err != nil { @@ -509,13 +511,40 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO // recovery to an older checkpoint. Identity, incarnation and map lineage must // agree, and operational I/O errors do not authorize another slot. func coverageHalfFenceFallbackEligible(selected descriptorV3, other *descriptorV3, cause error) bool { - integrityFailure := errors.Is(cause, ErrMapInvalid) || errors.Is(cause, io.EOF) || errors.Is(cause, io.ErrUnexpectedEOF) + integrityFailure := mapIntegrityFailureOnly(cause) return integrityFailure && selected.ChunkStateFormat != 0 && selected.MapFormatID == mapFormatIDCoverage && other != nil && other.ChunkStateFormat == 0 && other.MapFormatID == mapFormatIDV1 && other.MigrationPhase == MigrationNormal && other.SlotGen < selected.SlotGen && other.UUID == selected.UUID && sameGeometryV3(*other, selected) && other.Nonce == selected.Nonce && other.MapLineage == selected.MapLineage } +// Every leaf must be an integrity failure. errors.Is on a joined error is +// insufficient: a short root read joined with a failed close still contains an +// operational I/O failure and cannot authorize another slot. +func mapIntegrityFailureOnly(cause error) bool { + if cause == nil { + return false + } + switch wrapped := cause.(type) { + case interface{ Unwrap() []error }: + found := false + for _, child := range wrapped.Unwrap() { + if child == nil { + continue + } + found = true + if !mapIntegrityFailureOnly(child) { + return false + } + } + return found + case interface{ Unwrap() error }: + return mapIntegrityFailureOnly(wrapped.Unwrap()) + default: + return cause == ErrMapInvalid || cause == io.EOF || cause == io.ErrUnexpectedEOF + } +} + // recoverV3 is Recover for a v3 store (DESIGN 6.5, 6.6). The caller holds // captureMu, lifecycleMu and s.mu, as v2 Recover does. func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { diff --git a/seaweed-block/docs/design/chunk-coverage.md b/seaweed-block/docs/design/chunk-coverage.md index bba07468b0..7adb7a95f3 100644 --- a/seaweed-block/docs/design/chunk-coverage.md +++ b/seaweed-block/docs/design/chunk-coverage.md @@ -86,7 +86,10 @@ flowchart TD A marked map can be overwritten by an old writer before that writer publishes its next descriptor. The opener can then select the other slot only when it is valid, unmarked, and has an intact map, with the same identity, geometry, nonce -and map lineage. Operational I/O errors do not authorize fallback. The discarded +and map lineage. Every leaf of a wrapped or joined cause tree must be an integrity error; +a short-read joined with a failed close does not authorize fallback. If the +fallback map also fails, both causes are returned. Operational I/O errors do +not authorize fallback. The discarded marked slot is excluded from map binding; Recover replaces it through the sole publisher. Both-marked map damage refuses, even when the older marked map is intact, because falling back there could lose acknowledged marked writes. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 28251a8fec..7870c73b0f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -619,7 +619,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `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-CHUNK-LOCAL-COVERAGE-001` | Coverage returns local none/some/all and the chunk position from one observation; it is unavailable until successful recovery and bitmap initialization. | M1 chunk bitmap (caller not wired) | `core/storage/chunk_coverage.go` `WALStore.Coverage`, `WALStore.InitializeChunkCoverage` | `TestChunkCoverageInitializesEmptyWithoutFabricatingLocalBlocks`, `TestChunkCoverageAcknowledgedWriteSurvivesReplay`, `TestChunkCoverageCheckpointKeepsAllAcrossAPageBoundary`, `TestChunkCoverageRequiresSuccessfulRecovery` (`core/storage/chunk_coverage_test.go`) | MoveWide2 durable per-block map premise; SlotFence publication | STUB | | `INV-CHUNK-LOCAL-EPOCH-001` | After a format marker, initialization never reads legacy presence: the same epoch rebuilds pages from the bitmap; another epoch is refused without changing storage. | M1 bitmap initialization (caller not wired) | `core/storage/chunk_coverage.go` `WALStore.InitializeChunkCoverage` | `TestChunkCoverageMarkedEpochNeverReseedsPresence`, `TestChunkCoverageMarkerWithoutBitmapCannotReadPresence` (`core/storage/chunk_coverage_test.go`) | SlotFence marker authority; UpgradeWide3 | STUB | -| `INV-CHUNK-HALF-FENCE-FALLBACK-001` | A damaged selected marked map may fall back only to an intact valid unmarked slot of the same store incarnation; two marked slots never authorize fallback. Each successful fallback reports a typed event and one process-local counter increment. | M1 half-fence open (caller not wired) | `core/storage/walstore_v3.go` `openWALStoreV3File`, `coverageHalfFenceFallbackEligible` | `TestChunkCoverageHalfFenceReusedMapOpensTheIntactLegacySlot`, `TestChunkCoverageBothMarkedDamagedMapNeverFallsBack` (`core/storage/chunk_coverage_test.go`) | SlotFence2.OpenNew | STUB | +| `INV-CHUNK-HALF-FENCE-FALLBACK-001` | A damaged selected marked map may fall back only on integrity-only errors, to an intact valid unmarked slot of the same store incarnation; two marked slots never authorize fallback. Each successful fallback reports a typed event and one process-local counter increment. | M1 half-fence open (caller not wired) | `core/storage/walstore_v3.go` `openWALStoreV3File`, `coverageHalfFenceFallbackEligible` | `TestChunkCoverageHalfFenceReusedMapOpensTheIntactLegacySlot`, `TestChunkCoverageBothMarkedDamagedMapNeverFallsBack` (`core/storage/chunk_coverage_test.go`) | SlotFence2.OpenNew | 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 | diff --git a/seaweed-block/docs/design/model-code-trace-coverage.tsv b/seaweed-block/docs/design/model-code-trace-coverage.tsv index 76a9e33548..cd93d08afa 100644 --- a/seaweed-block/docs/design/model-code-trace-coverage.tsv +++ b/seaweed-block/docs/design/model-code-trace-coverage.tsv @@ -7,4 +7,4 @@ MoveWide2 typed atomic bitmap observation core/storage/chunk_coverage.go:WALStor MoveWide2 bounded fanout format and shared COW nodes core/storage/chunk_coverage_map.go:encodeCoverageTreeRootV3; core/storage/chunk_coverage_map.go:coverageTreeRefsV3 core/storage/chunk_coverage_test.go:TestChunkCoverageTreeKeepsBothIndexBranches STUB SlotFence uncertain publication resumes only after reopen and recovery core/storage/chunk_coverage.go:WALStore.InitializeChunkCoverage; core/storage/chunk_coverage.go:WALStore.finishCoverageFenceLocked core/storage/chunk_coverage_test.go:TestChunkCoverageFailedPublicationResumesAfterRecovery STUB SlotFence BASE and reset exclude upgrade before callback or publication core/storage/chunk_coverage.go:WALStore.InitializeChunkCoverage core/storage/chunk_coverage_test.go:TestChunkCoverageInitializationRefusesActiveBaseBeforeWriting STUB -SlotFence2 intact unmarked half-fence fallback only, typed event and process counter core/storage/walstore_v3.go:openWALStoreV3File; core/storage/walstore_v3.go:coverageHalfFenceFallbackEligible core/storage/chunk_coverage_test.go:TestChunkCoverageHalfFenceReusedMapOpensTheIntactLegacySlot; core/storage/chunk_coverage_test.go:TestChunkCoverageBothMarkedDamagedMapNeverFallsBack STUB +SlotFence2 intact unmarked half-fence fallback only, typed event and process counter core/storage/walstore_v3.go:openWALStoreV3File; core/storage/walstore_v3.go:coverageHalfFenceFallbackEligible core/storage/chunk_coverage_test.go:TestChunkCoverageHalfFenceReusedMapOpensTheIntactLegacySlot; core/storage/chunk_coverage_test.go:TestChunkCoverageBothMarkedDamagedMapNeverFallsBack; core/storage/chunk_coverage_test.go:TestChunkCoverageFallbackRequiresIntegrityOnlyErrorTree; core/storage/chunk_coverage_test.go:TestChunkCoverageFallbackAuthorityGuards; core/storage/chunk_coverage_test.go:TestChunkCoverageFallbackRefusesUnavailableOtherDependencies STUB