From 677b8ec40847a4e6b3b2db9f7e2794f4ac0cd82d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 12:31:19 -0800 Subject: [PATCH] fix(durable): bind local-root ownership to the claim image --- .../core/frontend/durable/provider_chunk.go | 19 +++-- .../durable/provider_reopen_belt_test.go | 69 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 8 +-- 3 files changed, 86 insertions(+), 10 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 6d762643d4..008cf75014 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -413,18 +413,25 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h } if !h.fresh { // An existing local volume is this holder's image only while HEAD is - // still this holder's publication. Another holder's HEAD means the + // still this holder's publication (INV-WS-STALE-LOCAL-ROOT-001). + // Check again on the exact claim image before its CAS. Another holder means the // workspace moved away and back: refuse rather than serve, or cut // over, the newer image with the stale one. head, err := remote.GetHead(ctx) if err != nil { return nil, fmt.Errorf("durable: read HEAD before attaching existing volume %s: %w", volumeID, err) } - if head.Gen != 0 && head.Holder != holder { - err := fmt.Errorf("%w: %w: volume %s local root %s, HEAD holder %q gen %d epoch %d, local holder %q; remove or quarantine the local root to attach fresh from HEAD", - ErrChunkStaleLocalRoot, storage.ErrChunkLayerFenced, volumeID, h.path, head.Holder, head.Gen, head.Epoch, holder) - log.Printf("durable: refusing to attach volume=%s root=%s: HEAD holder=%q gen=%d epoch=%d is not this holder %q (remove or quarantine the local root)", - volumeID, h.path, head.Holder, head.Gen, head.Epoch, holder) + cfg.PrepareRestore = func(head storage.ChunkHead) error { + if head.Gen != 0 && head.Holder != holder { + err := fmt.Errorf("%w: %w: volume %s local root %s, HEAD holder %q gen %d epoch %d, local holder %q; remove or quarantine the local root to attach fresh from HEAD", + ErrChunkStaleLocalRoot, storage.ErrChunkLayerFenced, volumeID, h.path, head.Holder, head.Gen, head.Epoch, holder) + log.Printf("durable: refusing to attach volume=%s root=%s: HEAD holder=%q gen=%d epoch=%d is not this holder %q (remove or quarantine the local root)", + volumeID, h.path, head.Holder, head.Gen, head.Epoch, holder) + return err + } + return nil + } + if err := cfg.PrepareRestore(head); err != nil { return nil, err } } diff --git a/seaweed-block/core/frontend/durable/provider_reopen_belt_test.go b/seaweed-block/core/frontend/durable/provider_reopen_belt_test.go index 559d546f07..743c9edbba 100644 --- a/seaweed-block/core/frontend/durable/provider_reopen_belt_test.go +++ b/seaweed-block/core/frontend/durable/provider_reopen_belt_test.go @@ -2,11 +2,80 @@ package durable_test import ( "bytes" + "context" + "errors" "testing" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" ) +type reopenClaimRaceRemote struct { + storage.ChunkRemote + foreign storage.ChunkHead + reads int +} + +func (r *reopenClaimRaceRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + h, err := r.ChunkRemote.GetHead(ctx) + if err != nil { + return h, err + } + r.reads++ + if r.reads == 1 { + // The early local-root check sees our publication. Before the claim's + // independent read, another holder publishes below the current epoch. + if _, err := r.ChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, r.foreign); err != nil { + return storage.ChunkHead{}, err + } + } + return h, nil +} + +func TestLocalReopenRejectsForeignClaimImage(t *testing.T) { + ctx := hangGuard(t) + r := storage.NewMemChunkRemote() + root := t.TempDir() + first := chunkProvider(t, root, r, viewAs("rA", 3), 0) + s := openRecovered(t, first) + writeSync(t, s, 0, 0x31) + if _, err := first.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + writeSync(t, s, 1, 0x42) + if err := first.Close(); err != nil { + t.Fatal(err) + } + foreign := headHolder(t, r) + foreign.Epoch, foreign.Holder = 4, "rB" + race := &reopenClaimRaceRemote{ChunkRemote: r, foreign: foreign} + second := chunkProvider(t, root, race, viewAs("rA", 5), 0) + if _, err := second.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + _, err := second.RecoverVolume(ctx, "v1") + if !errors.Is(err, durable.ErrChunkStaleLocalRoot) || !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Errorf("foreign claim image admitted over local WAL: %v", err) + } + if race.reads < 2 { + t.Fatal("control did not reach the independent claim observation") + } + if after := headHolder(t, r); after.Epoch != 4 || after.Holder != "rB" || after.Gen != foreign.Gen+1 { + t.Errorf("refused reopen changed the foreign HEAD: %+v", after) + } + be, err := second.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if _, err := be.Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) { + t.Errorf("foreign claim image exposed I/O: %v", err) + } + if got, err := second.LogicalStorage("v1").Read(1); err != nil || !bytes.Equal(got, block(0x42)) { + t.Errorf("refusal changed acknowledged local bytes: %v", err) + } +} + func TestLocalReopenClaimsBeforeServing(t *testing.T) { ctx := hangGuard(t) r := storage.NewMemChunkRemote() diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 1cfe012045..2a1d624123 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -194,8 +194,7 @@ stateDiagram-v2 | Attaching | Refused | an existing local root whose HEAD another holder has published (`ErrChunkStaleLocalRoot`) | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-STALE-LOCAL-ROOT-001` | | (startup) | Refused | `--chunk-filer` is not the only filer of its group: a master lists another filer or several, or no master lists it within 60 s (`ErrNotSingleFiler`) | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `INV-WS-SINGLE-FILER-001` | | Claiming | Holder | HEAD epoch not above the master-issued epoch, no other holder at the same epoch; fresh roots seed from HEAD before the CAS; existing roots retain local WAL; every incarnation replaces the generation (or exclusive-creates HEAD); I/O opens only after the configured cooling window (zero at one serialization point) and an exact generation/epoch/holder readback | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-WS-HEAD-CAS-001`, `INV-WS-REOPEN-FENCE-001` | -| Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-REOPEN-FENCE-001` | Before I/O, every reopened holder replaces the observed HEAD generation, including the same epoch/holder and an empty HEAD. A previous incarnation's delayed CAS cannot publish afterward. Local acknowledged WAL is retained. | M4 Claiming -> Holder | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadSameOwnerReopenRejectsKilledProcessCAS`, `TestHeadBeltSameOwnerReopenPreservesAcknowledgedWrites` (`core/storage/chunk_reopen_belt_test.go`); `TestLocalReopenClaimsBeforeServing` (`core/frontend/durable/provider_reopen_belt_test.go`) | `HeadReopenBelt` `OldCASCannotLandAfterReopen` | ACTIVE | -| `INV-WS-CAS-UNKNOWN-001` | +| Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | | Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | | Holder | HolderFenced | a conflicting HEAD owner (including a regressed epoch) or a displaced publication is observed; local data and unresolved cut intents remain | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | @@ -400,7 +399,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -163 rows: 141 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 148 new. +164 rows: 142 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 148 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -522,9 +521,10 @@ Notes: | `INV-WS-HEAD-CAS-001` | Every HEAD publish is conditional on `{gen, epoch}` at one serialization point. A conflicting observed owner fences the publisher. Multiple independent filer serialization points are not made atomic by readback. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | | `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestMemChunkRemote_RefusesLowerRemoteLSN` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`); `TestNativeReplacementCutBehindHEADRefuses` (`core/storage/legacy_replacement_v3_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | | `INV-WS-HEAD-KEY-PROVENANCE-001` | Every key a HEAD names is named by its predecessor HEAD or was uploaded by this owner under an intent that rooted it until the CAS settled; a key that left every root is never named again. | M5 Manifest → CAS | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | — | — | STUB | +| `INV-WS-REOPEN-FENCE-001` | Before I/O, every reopened holder replaces the observed HEAD generation, including the same epoch/holder and an empty HEAD. A previous incarnation's delayed CAS cannot publish afterward. Local acknowledged WAL is retained. | M4 Claiming -> Holder | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadSameOwnerReopenRejectsKilledProcessCAS`, `TestHeadBeltSameOwnerReopenPreservesAcknowledgedWrites` (`core/storage/chunk_reopen_belt_test.go`); `TestLocalReopenClaimsBeforeServing` (`core/frontend/durable/provider_reopen_belt_test.go`) | `HeadReopenBelt` `OldCASCannotLandAfterReopen` | ACTIVE | | `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | | `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | -| `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | +| `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`); `TestLocalReopenRejectsForeignClaimImage` (`core/frontend/durable/provider_reopen_belt_test.go`) | — | ACTIVE | | `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |