From 176bebc14adec3050d06ba00ab75c79521c83681 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 20:52:20 -0800 Subject: [PATCH 01/34] test(invcheck): check the invariant document against the code Fail when a row names a test that does not exist, an ACTIVE row names no test, an ID repeats, or the stated row count differs from the tables. Three ACTIVE rows named removed tests; drop those names (each row keeps its other tests). Co-Authored-By: Claude Fable 5.2 --- seaweed-block/docs/design/invariants.md | 6 +- .../internal/invcheck/invariants_test.go | 185 ++++++++++++++++++ 2 files changed, 188 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/internal/invcheck/invariants_test.go diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 37415d38a6..4d9d2eb33b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -381,14 +381,14 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-OWNER-001` | v3 read/write open and offline readonly open acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go` | `TestWALStoreV3CreatorKeepsOwnershipThroughPublication` (`core/storage/volume_lock_v3_test.go`); `TestWALStoreV3OwnerExcludesOpenAndReadOnly` (`core/storage/volume_lock_v3_test.go`); `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | | `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`, `TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`, `TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | | `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshAndSetWModeCloseTheWindow` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3AppendWriteErrorLatchesTheStore` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeWaitsForAHeldBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3InstallingScanErrorIsTypedNotReady` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision` (`core/storage/recovery_v3_test.go`); `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | | `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | | `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | -| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | +| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | | `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB | | `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB | | `INV-WAL-V3-MIGRATE-001` | ARCHIVED: the in-place v2 converter is removed. Public opens refuse v2 bytes without mutation; no upgrade path is provided. | M1 open refusal | `core/storage/walstore_v3.go` `openWALStoreV3WithOptions` | `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | none (retired tool) | ARCHIVED | @@ -464,7 +464,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-WS-HEAD-BELT-001` | A takeover confirms its exact HEAD before serving. The supported single-serialization-point mode has W=0; explicit experimental cooling requires W >= the 2 s HEAD operation deadline plus 100 ms settling. Each CAS and confirmation has its own 2 s deadline. A successful cut CAS requires readback before remoteLSN/map settlement and intent cleanup. Unconfirmed roots remain protected through Close; an observed different publication owner fences without retry, even after epoch regression or when the original HEAD was empty. | M4 Claiming → Cooling → Holder; M5 CAS → Confirmed or Pending/Fenced | `core/storage/chunk_head_belt.go`; `chunk_restore.go` `ClaimChunkHead`; `chunk_layer.go` `captureLocked`, `resolvePending`, `SettleDetach`, `dropIntents`, `Close` | `TestHeadBeltTakeoverRefusesLateOldCAS`; `TestHeadBeltTakeoverWaitsBeforeConfirmation`; `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`; `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`; `TestHeadBeltEmptyBaseForeignPublicationFences`; `TestHeadBeltSinglePointHasNoCoolingDelay`; `TestHeadBeltOperationsHaveOwnDeadline`; `TestHeadBeltCoolingWindowCoversCASAndSettle` (`core/storage/chunk_head_belt_test.go`) | `WorkspaceTakeover` belt extension pending | ACTIVE | | `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`); `TestChunkCut_RemoteLSNNeverDecreases` (`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-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`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`); `TestNativeReplacementCutBehindHEADRefuses` (`core/storage/legacy_replacement_v3_test.go`) | `WorkspaceTakeover` `HeadMonotone` | 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 | diff --git a/seaweed-block/internal/invcheck/invariants_test.go b/seaweed-block/internal/invcheck/invariants_test.go new file mode 100644 index 0000000000..4e5abfbecf --- /dev/null +++ b/seaweed-block/internal/invcheck/invariants_test.go @@ -0,0 +1,185 @@ +// Package invcheck checks docs/design/invariants.md against the code: the +// row count it states is the count its tables hold, every Go test a row +// names exists, and an ACTIVE row names at least one test. +package invcheck + +import ( + "fmt" + "io/fs" + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +type invRow struct { + id string + tests []string + status string + line int +} + +var ( + rowID = regexp.MustCompile("^\\| `(INV-[A-Z0-9-]+)` \\|") + testName = regexp.MustCompile("`(Test[A-Za-z0-9_]+)`") + testFunc = regexp.MustCompile(`(?m)^func (Test[A-Za-z0-9_]+)\(`) + countLine = regexp.MustCompile("(\\d+) `INV-` rows: (\\d+) ACTIVE, (\\d+) STUB, (\\d+) ARCHIVED") +) + +func repoRoot(t *testing.T) string { + t.Helper() + dir, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + for { + if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { + return dir + } + parent := filepath.Dir(dir) + if parent == dir { + t.Fatal("go.mod not found above the test directory") + } + dir = parent + } +} + +// partB returns the Part B rows of the invariant document and its text. +func partB(t *testing.T, root string) ([]invRow, string) { + t.Helper() + raw, err := os.ReadFile(filepath.Join(root, "docs", "design", "invariants.md")) + if err != nil { + t.Fatal(err) + } + doc := strings.ReplaceAll(string(raw), "\r\n", "\n") + start := strings.Index(doc, "\n## Part B") + end := strings.Index(doc, "\n## Part C") + if start < 0 || end < start { + t.Fatal("invariants.md: Part B or Part C heading not found") + } + firstLine := strings.Count(doc[:start], "\n") + 1 + var rows []invRow + for i, line := range strings.Split(doc[start:end], "\n") { + m := rowID.FindStringSubmatch(line) + if m == nil { + continue + } + cells := splitRow(line) + if len(cells) != 7 { + t.Errorf("invariants.md:%d: row %s has %d cells, want 7", firstLine+i, m[1], len(cells)) + continue + } + r := invRow{id: m[1], status: strings.TrimSpace(cells[6]), line: firstLine + i} + for _, tm := range testName.FindAllStringSubmatch(cells[4], -1) { + r.tests = append(r.tests, tm[1]) + } + rows = append(rows, r) + } + return rows, doc +} + +// splitRow splits a table row on unescaped pipes outside code spans. +func splitRow(line string) []string { + line = strings.TrimSpace(line) + line = strings.TrimPrefix(line, "|") + line = strings.TrimSuffix(line, "|") + var cells []string + var cur strings.Builder + inCode := false + for i := 0; i < len(line); i++ { + c := line[i] + switch { + case c == '\\' && i+1 < len(line) && line[i+1] == '|': + cur.WriteString(`\|`) + i++ + case c == '`': + inCode = !inCode + cur.WriteByte(c) + case c == '|' && !inCode: + cells = append(cells, cur.String()) + cur.Reset() + default: + cur.WriteByte(c) + } + } + return append(cells, cur.String()) +} + +// goTests returns every top-level Test function name in the repository. +func goTests(t *testing.T, root string) map[string]bool { + t.Helper() + found := map[string]bool{} + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if name := d.Name(); name == ".git" || name == "node_modules" { + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(path, "_test.go") { + return nil + } + src, err := os.ReadFile(path) + if err != nil { + return err + } + for _, m := range testFunc.FindAllSubmatch(src, -1) { + found[string(m[1])] = true + } + return nil + }) + if err != nil { + t.Fatal(err) + } + return found +} + +func TestInvariantRowsNameExistingTests(t *testing.T) { + root := repoRoot(t) + rows, _ := partB(t, root) + if len(rows) == 0 { + t.Fatal("no INV rows found in Part B") + } + tests := goTests(t, root) + seen := map[string]int{} + for _, r := range rows { + if prev, dup := seen[r.id]; dup { + t.Errorf("invariants.md:%d: %s is also at line %d", r.line, r.id, prev) + } + seen[r.id] = r.line + switch r.status { + case "ACTIVE": + if len(r.tests) == 0 { + t.Errorf("invariants.md:%d: %s is ACTIVE and names no test", r.line, r.id) + } + case "STUB", "ARCHIVED": + default: + t.Errorf("invariants.md:%d: %s has status %q", r.line, r.id, r.status) + } + for _, name := range r.tests { + if !tests[name] { + t.Errorf("invariants.md:%d: %s names %s, which is not a test in this repository", r.line, r.id, name) + } + } + } +} + +func TestInvariantRowCountMatchesTables(t *testing.T) { + rows, doc := partB(t, repoRoot(t)) + by := map[string]int{} + for _, r := range rows { + by[r.status]++ + } + want := fmt.Sprintf("%d `INV-` rows: %d ACTIVE, %d STUB, %d ARCHIVED", len(rows), by["ACTIVE"], by["STUB"], by["ARCHIVED"]) + m := countLine.FindString(doc) + if m == "" { + t.Fatalf("invariants.md states no row count; the tables hold: %s", want) + } + if m != want { + t.Fatalf("invariants.md says %q; its tables hold %q", m, want) + } +} From a0cbeaaafdf286747dc0e61e5ef898e4317320bb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 20:54:44 -0800 Subject: [PATCH 02/34] docs(invariants): name the renamed BASE install refusal test Co-Authored-By: Claude Fable 5.2 --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 4d9d2eb33b..8ec6e76874 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -388,7 +388,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshAndSetWModeCloseTheWindow` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3AppendWriteErrorLatchesTheStore` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeWaitsForAHeldBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3InstallingScanErrorIsTypedNotReady` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision` (`core/storage/recovery_v3_test.go`); `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | | `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | | `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | -| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | +| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | | `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB | | `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB | | `INV-WAL-V3-MIGRATE-001` | ARCHIVED: the in-place v2 converter is removed. Public opens refuse v2 bytes without mutation; no upgrade path is provided. | M1 open refusal | `core/storage/walstore_v3.go` `openWALStoreV3WithOptions` | `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | none (retired tool) | ARCHIVED | From ab3610608cd854666bd77f95c9f4dfe82bbad1d9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 03:48:27 -0800 Subject: [PATCH 03/34] blockvolume: scheduled snapshots (daily:7 by default), one COW cut each at a per-volume offset A per-volume worker takes a named snapshot of class scheduled once per period, through the same seal path as an explicit snapshot (resolve the request, one urgent cut, record that cut's HEAD). A restoring volume (chunks its HEAD names still absent) is skipped and counted; a failure keeps the control endpoint's code and is retried with a backoff doubling from 1m to 1h; status carries the schedule state and snapshot_overdue. Retention keeps the newest N scheduled snapshots (N from the newest one's swb.schedule.keep label) separately from other snapshots. --chunk-snapshot-schedule=daily:N|weekly:N|off, default daily:7. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/chunk_remote.go | 45 +++- .../cmd/blockvolume/chunk_remote_test.go | 37 +++ seaweed-block/cmd/blockvolume/main.go | 6 + .../core/frontend/chunkstore/retention.go | 52 +++- .../frontend/chunkstore/retention_test.go | 30 +++ .../durable/chunk_snapshot_schedule.go | 247 ++++++++++++++++++ .../durable/chunk_snapshot_schedule_test.go | 108 ++++++++ .../core/frontend/durable/provider.go | 38 ++- .../core/frontend/durable/provider_chunk.go | 70 +++-- .../provider_chunk_snapshot_schedule_test.go | 188 +++++++++++++ .../core/host/volume/chunk_control.go | 19 +- .../host/volume/chunk_control_adapter_test.go | 10 +- .../host/volume/chunk_scheduled_snapshot.go | 38 +++ .../volume/chunk_scheduled_snapshot_test.go | 69 +++++ seaweed-block/deploy/config/blockvolume.env | 4 + .../systemd/sw-blockvolume-ublk.service | 1 + .../deploy/systemd/sw-blockvolume.service | 1 + .../docs/design/agent-workspace-design.md | 6 +- seaweed-block/docs/design/invariants.md | 2 + seaweed-block/docs/standalone-deployment.md | 1 + seaweed-block/docs/status-schema.md | 10 + 21 files changed, 931 insertions(+), 51 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go create mode 100644 seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_chunk_snapshot_schedule_test.go create mode 100644 seaweed-block/core/host/volume/chunk_scheduled_snapshot.go create mode 100644 seaweed-block/core/host/volume/chunk_scheduled_snapshot_test.go diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index 0d690740f8..8a8e00b32b 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "path" + "strconv" "strings" "time" @@ -21,8 +22,8 @@ import ( const ( defaultChunkPath = "/swblock/chunks" - // Periodic HEAD publication bounds the host-loss recovery point. Automatic - // named snapshots remain explicit catalog operations. + // Periodic HEAD publication bounds the host-loss recovery point. Scheduled + // named snapshots are set by --chunk-snapshot-schedule. defaultChunkCaptureInterval = 0 defaultChunkMaintenanceInterval = time.Hour defaultChunkCutTimeout = 5 * time.Minute @@ -40,6 +41,7 @@ type chunkFlags struct { replication string captureInterval time.Duration maintenanceInterval time.Duration + snapshotSchedule snapshotSchedule automaticGC bool uploadConcurrency int hydrationWorkers int @@ -59,7 +61,7 @@ func validateChunkFlags(f flags) error { } if f.durableImpl != "walstore-chunk" { if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath || - c.captureInterval != defaultChunkCaptureInterval || c.maintenanceInterval != defaultChunkMaintenanceInterval || c.automaticGC || + c.captureInterval != defaultChunkCaptureInterval || c.maintenanceInterval != defaultChunkMaintenanceInterval || c.snapshotSchedule != defaultSnapshotSchedule || c.automaticGC || c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint || c.detachPrecopy || c.hostLimit.Directory != "" { return errors.New("--chunk-* flags require --durable-impl=walstore-chunk") } @@ -111,6 +113,43 @@ const chunkRF1Reason = "chunk snapshots take the cut LSN from the local WAL, whi // chunkWiring is what --durable-impl=walstore-chunk dials once: the // provider's per-volume remotes, the catalog under the same base (VOLUME // entries, snapshots) and the client's closer. +// snapshotSchedule is --chunk-snapshot-schedule: "daily:N", "weekly:N" +// (one scheduled snapshot per period at a per-volume offset, the newest N +// kept) or "off". +type snapshotSchedule struct { + period time.Duration + keep int +} + +var defaultSnapshotSchedule = snapshotSchedule{period: 24 * time.Hour, keep: 7} + +func (s *snapshotSchedule) String() string { + switch s.period { + case 0: + return "off" + case 24 * time.Hour: + return fmt.Sprintf("daily:%d", s.keep) + case 7 * 24 * time.Hour: + return fmt.Sprintf("weekly:%d", s.keep) + } + return fmt.Sprintf("%s:%d", s.period, s.keep) +} + +func (s *snapshotSchedule) Set(v string) error { + if v == "off" { + *s = snapshotSchedule{} + return nil + } + name, count, ok := strings.Cut(v, ":") + periods := map[string]time.Duration{"daily": 24 * time.Hour, "weekly": 7 * 24 * time.Hour} + keep, err := strconv.Atoi(count) + if !ok || periods[name] == 0 || err != nil || keep < 1 || keep > 1000 { + return fmt.Errorf("%q: want daily:N, weekly:N (N from 1 to 1000) or off", v) + } + *s = snapshotSchedule{period: periods[name], keep: keep} + return nil +} + type chunkWiring struct { remoteFor func(volumeID string) (storage.ChunkRemote, error) catalog *chunkstore.Catalog diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go index df897f59b0..fd82212594 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -135,3 +135,40 @@ func TestChunkDirtyThresholdFlagIsGone(t *testing.T) { t.Fatalf("--chunk-dirty-threshold: %v; want flag provided but not defined", err) } } + +// --chunk-snapshot-schedule: daily:7 by default; daily:N, weekly:N and off +// are accepted; anything else is refused; setting it without walstore-chunk +// is refused like the other chunk flags. +func TestChunkSnapshotScheduleFlag(t *testing.T) { + base := func(extra ...string) []string { + return append(phase150RequiredBlockvolumeArgs(), extra...) + } + chunk := func(extra ...string) []string { + return base(append([]string{"--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1"}, extra...)...) + } + d, err := parseFlags(chunk()) + if err != nil || d.chunk.snapshotSchedule != (snapshotSchedule{period: 24 * time.Hour, keep: 7}) { + t.Fatalf("default schedule %+v %v; want daily, keep 7", d.chunk.snapshotSchedule, err) + } + for v, want := range map[string]snapshotSchedule{ + "daily:3": {period: 24 * time.Hour, keep: 3}, + "weekly:4": {period: 7 * 24 * time.Hour, keep: 4}, + "off": {}, + } { + f, err := parseFlags(chunk("--chunk-snapshot-schedule=" + v)) + if err != nil || f.chunk.snapshotSchedule != want { + t.Fatalf("%s: %+v %v; want %+v", v, f.chunk.snapshotSchedule, err, want) + } + if got := f.chunk.snapshotSchedule.String(); got != v { + t.Fatalf("%s prints as %q", v, got) + } + } + for _, v := range []string{"hourly:7", "daily", "daily:0", "daily:x", "weekly:-1", "daily:1001", ""} { + if _, err := parseFlags(chunk("--chunk-snapshot-schedule=" + v)); err == nil { + t.Fatalf("%q accepted", v) + } + } + if _, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-snapshot-schedule=weekly:4")); err == nil { + t.Fatal("--chunk-snapshot-schedule accepted without walstore-chunk") + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 6f17805b6b..45e4af41e5 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -204,6 +204,8 @@ func parseFlags(args []string) (flags, error) { fs.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)") fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: converge rolling cuts before final detach; refuse cutover if measured tail does not fit") fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least 5m)") + f.chunk.snapshotSchedule = defaultSnapshotSchedule + fs.Var(&f.chunk.snapshotSchedule, "chunk-snapshot-schedule", "walstore-chunk: scheduled snapshots, daily:N or weekly:N (once per period at a per-volume offset, the newest N kept) or off") fs.DurationVar(&f.chunk.maintenanceInterval, "chunk-maintenance-interval", defaultChunkMaintenanceInterval, "walstore-chunk: retention and optional GC pass interval; 0 disables") fs.BoolVar(&f.chunk.automaticGC, "chunk-maintenance-gc", false, "walstore-chunk: enable scoped automatic GC; off pending restart-safe unknown-CAS settlement and density qualification") fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)") @@ -665,6 +667,10 @@ func run(f flags) int { cfg.ChunkMaintenanceInterval = f.chunk.maintenanceInterval cfg.ChunkMaintenanceTimeout = defaultChunkMaintenanceTimeout cfg.ChunkMaintenance = chunk.maintenance + if chunk.catalog != nil && f.chunk.snapshotSchedule.period > 0 { + cfg.ChunkSnapshotPeriod = f.chunk.snapshotSchedule.period + cfg.ChunkScheduledSnapshot = volume.ScheduledSnapshot(chunk.catalog, f.chunk.snapshotSchedule.keep) + } cfg.ChunkDetachPrecopy = f.chunk.detachPrecopy cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency cfg.ChunkHydrationWorkers = f.chunk.hydrationWorkers diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index 561a5fd06e..e3f950a2b3 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -23,6 +23,11 @@ import ( // - "pinned": an explicit keep. It is never expired by count or age, // only by its own ExpiresAtNs or an explicit delete. A snapshot with // ExpiresAtNs set is pinned whatever its class. +// - "scheduled": a scheduled snapshot. Retention keeps the newest K of +// this class, where K is the LabelScheduleKeep of the newest one +// (DefaultScheduleKeep when absent). +// They are not counted against KeepNewest, and the age and log-spaced +// keeps do not apply to them, so other snapshots are unaffected. // - "" (snapshots made before classes existed): treated as unpinned. // // The policy is stored on the VOLUME entry. Retain keeps @@ -61,8 +66,16 @@ import ( // it and frees the name. const ( - SnapshotClassSemantic = "semantic" - SnapshotClassPinned = "pinned" + SnapshotClassSemantic = "semantic" + SnapshotClassPinned = "pinned" + SnapshotClassScheduled = "scheduled" + + // LabelScheduleKeep, on a scheduled snapshot, is how many scheduled + // snapshots its schedule keeps (a decimal count). + LabelScheduleKeep = "swb.schedule.keep" + // DefaultScheduleKeep is the count kept when the newest scheduled + // snapshot carries no valid LabelScheduleKeep. + DefaultScheduleKeep = 7 CodeInvalidClass = "invalid_class" CodeInvalidPolicy = "invalid_policy" @@ -74,14 +87,14 @@ const ( extRetentionRev = "retention_rev" ) -// ValidateSnapshotClass refuses a class other than "", "semantic" and -// "pinned" (invalid_class). +// ValidateSnapshotClass refuses a class other than "", "semantic", +// "pinned" and "scheduled" (invalid_class). func ValidateSnapshotClass(class string) error { switch class { - case "", SnapshotClassSemantic, SnapshotClassPinned: + case "", SnapshotClassSemantic, SnapshotClassPinned, SnapshotClassScheduled: return nil } - return catErr(CodeInvalidClass, false, nil, "snapshot class %q: want %q or %q", class, SnapshotClassSemantic, SnapshotClassPinned) + return catErr(CodeInvalidClass, false, nil, "snapshot class %q: want %q, %q or %q", class, SnapshotClassSemantic, SnapshotClassPinned, SnapshotClassScheduled) } // Pinned reports whether the snapshot is an explicit keep. @@ -198,6 +211,7 @@ const ( keepHourly = "hourly" keepDaily = "daily" keepWeekly = "weekly" + keepScheduled = "scheduled_newest" reasonExpired = "expired" ) @@ -215,11 +229,27 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, now time.Time) []Ret }) nowNs := now.UnixNano() out := make([]RetentionDecision, len(ordered)) - unpinned := 0 + unpinned, scheduled := 0, 0 + scheduleKeep := -1 // read from the newest scheduled snapshot windows := map[string]bool{} for i, s := range ordered { pinned := s.Pinned() && (s.ExpiresAtNs == 0 || nowNs < s.ExpiresAtNs) d := RetentionDecision{Name: s.Name, Attempt: s.attempt, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: pinned} + if !pinned && s.Class == SnapshotClassScheduled { + if scheduleKeep < 0 { + scheduleKeep = scheduleKeepOf(s) + } + if scheduled < scheduleKeep { + d.Reasons = append(d.Reasons, keepScheduled) + } + scheduled++ + d.Keep = len(d.Reasons) > 0 + if !d.Keep { + d.Reasons = []string{reasonExpired} + } + out[i] = d + continue + } if pinned { d.Reasons = append(d.Reasons, keepPinned) } else { @@ -263,6 +293,14 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, now time.Time) []Ret return out } +// scheduleKeepOf is the count a scheduled snapshot's schedule keeps. +func scheduleKeepOf(s SnapshotInfo) int { + if n, err := strconv.Atoi(s.Labels[LabelScheduleKeep]); err == nil && n > 0 { + return n + } + return DefaultScheduleKeep +} + // RetentionFailure is the deletion that stopped a Retain pass. type RetentionFailure struct { Name string `json:"name"` diff --git a/seaweed-block/core/frontend/chunkstore/retention_test.go b/seaweed-block/core/frontend/chunkstore/retention_test.go index f329ed96be..1b2d538af0 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_test.go @@ -381,3 +381,33 @@ func TestChunkSizeClipsLastChunk(t *testing.T) { } } } + +// Scheduled snapshots form their own class: retention keeps the newest K +// of them, K from the newest one's LabelScheduleKeep, and they neither +// count against KeepNewest nor get the age keeps; other snapshots are +// planned as before. +func TestPlanRetention_ScheduledClassKeepsItsOwnNewest(t *testing.T) { + now := retBase.Add(30 * 24 * time.Hour) + keep3 := map[string]string{LabelScheduleKeep: "3"} + var snaps []SnapshotInfo + for d := 0; d < 6; d++ { // one scheduled snapshot a day, the newest first at now-1h + snaps = append(snaps, snapAt(fmt.Sprintf("sched-%d", d), now.Add(-time.Hour-time.Duration(d)*24*time.Hour), SnapshotClassScheduled, time.Time{}, keep3)) + } + snaps = append(snaps, + snapAt("manual-new", now.Add(-2*time.Hour), "", time.Time{}, nil), + snapAt("manual-old", now.Add(-20*24*time.Hour), "", time.Time{}, nil)) + k := kept(planRetention(RetentionPolicy{KeepNewest: 2, KeepYoungerNs: int64(30 * 24 * time.Hour)}, snaps, now)) + for _, name := range []string{"sched-0", "sched-1", "sched-2", "manual-new", "manual-old"} { + if k[name] == nil { + t.Fatalf("kept %v; %s missing", k, name) + } + } + if len(k) != 5 { + t.Fatalf("kept %v; want the 3 newest scheduled and both manual (KeepNewest 2 is theirs alone)", k) + } + // Without a valid label the default count applies. + snaps[0].Labels = nil + if k := kept(planRetention(RetentionPolicy{}, snaps[:6], now)); len(k) != 6 { + t.Fatalf("kept %v with no label on the newest; want min(6, DefaultScheduleKeep)", k) + } +} diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go new file mode 100644 index 0000000000..150113db64 --- /dev/null +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go @@ -0,0 +1,247 @@ +package durable + +import ( + "context" + "errors" + "log" + "sync" + "time" + + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const ( + // snapshotRetryMin and snapshotRetryMax bound the backoff after a + // failed scheduled snapshot: it doubles from the minimum up to the cap. + snapshotRetryMin = time.Minute + snapshotRetryMax = time.Hour +) + +// SnapshotSkipRestoring is the skip reason of a volume still fetching the +// chunks its HEAD names (a restore's hydration). +const SnapshotSkipRestoring = "restoring" + +// SnapshotSkip is returned by a scheduled snapshot that was not attempted +// (for example, the volume is restoring). It is counted by Reason and not +// treated as a failure. +type SnapshotSkip struct{ Reason string } + +func (s *SnapshotSkip) Error() string { return "durable: scheduled snapshot skipped: " + s.Reason } + +// SnapshotFailure is a failed scheduled snapshot with its typed code. +type SnapshotFailure struct { + Code string + Err error +} + +func (f *SnapshotFailure) Error() string { + if f.Err != nil { + return "durable: scheduled snapshot failed: " + f.Code + ": " + f.Err.Error() + } + return "durable: scheduled snapshot failed: " + f.Code +} + +func (f *SnapshotFailure) Unwrap() error { return f.Err } + +// ScheduledSnapshotFailure is the last failed attempt. +type ScheduledSnapshotFailure struct { + // Code is the failure's code, as the control endpoint reports it. + Code string `json:"code"` + // AtNs is when the attempt failed. + AtNs int64 `json:"atNs"` +} + +// ScheduledSnapshotStatus is one volume's scheduled-snapshot state. +type ScheduledSnapshotStatus struct { + // PeriodNs is the schedule period; zero means off. + PeriodNs int64 `json:"periodNs"` + // LastOkNs is when the last scheduled snapshot succeeded; zero: none + // since the schedule started. + LastOkNs int64 `json:"lastOkNs"` + // NextDueNs is when the next attempt is due. + NextDueNs int64 `json:"nextDueNs"` + // LastFailure is the last failed attempt since the last success. + LastFailure *ScheduledSnapshotFailure `json:"lastFailure,omitempty"` + // Attempts counts the failed attempts since the last success. + Attempts int `json:"attempts"` + // Skipped counts attempts not made, by reason. + Skipped map[string]int64 `json:"skipped,omitempty"` + // Overdue reports that no scheduled snapshot succeeded within one + // period plus the retry cap, counted from the last success or, before + // any, from the start of the schedule. + Overdue bool `json:"snapshot_overdue"` +} + +// snapshotSchedule decides when one volume's scheduled snapshot is due and +// records the outcome of each attempt. Each slot starts at a multiple of +// the period (from the Unix epoch) plus the volume's offset, spread over +// the whole period and stable across restarts: "daily" is once per 24 h +// at a per-volume offset, not at a wall-clock hour. It is not safe for +// concurrent use. +type snapshotSchedule struct { + period time.Duration + offset time.Duration + started time.Time + lastOK time.Time + next time.Time + failure *ScheduledSnapshotFailure + attempts int + skipped map[string]int64 +} + +// newSnapshotSchedule starts vol's schedule at now. +func newSnapshotSchedule(vol string, period time.Duration, now time.Time) *snapshotSchedule { + s := &snapshotSchedule{period: period, offset: hostlimit.Phase(vol+":snapshot", period), started: now, skipped: map[string]int64{}} + s.next = s.slotAfter(now) + return s +} + +// slotAfter returns the first slot start strictly after t. +func (s *snapshotSchedule) slotAfter(t time.Time) time.Time { + p := int64(s.period) + base := t.UnixNano() / p * p + slot := time.Unix(0, base).Add(s.offset) + if !slot.After(t) { + slot = slot.Add(s.period) + } + return slot +} + +// due returns when the next attempt is due. +func (s *snapshotSchedule) due() time.Time { return s.next } + +// record records the outcome of an attempt made at now: nil is a +// success (the next attempt is the next slot); a *SnapshotSkip is counted +// by reason and retried after the backoff cap; any other error is a +// failure, recorded with its code, and retried with a doubling backoff. +func (s *snapshotSchedule) record(now time.Time, err error) { + var skip *SnapshotSkip + switch { + case err == nil: + s.lastOK, s.failure, s.attempts = now, nil, 0 + s.next = s.slotAfter(now) + case errors.As(err, &skip): + s.skipped[skip.Reason]++ + s.next = earlier(now.Add(snapshotRetryMax), s.slotAfter(now)) + default: + s.attempts++ + s.failure = &ScheduledSnapshotFailure{Code: snapshotFailureCode(err), AtNs: now.UnixNano()} + backoff := snapshotRetryMin << min(s.attempts-1, 30) + if backoff > snapshotRetryMax || backoff <= 0 { + backoff = snapshotRetryMax + } + s.next = now.Add(backoff) + } +} + +// status returns the schedule's state at now. +func (s *snapshotSchedule) status(now time.Time) ScheduledSnapshotStatus { + from := s.started + if !s.lastOK.IsZero() { + from = s.lastOK + } + st := ScheduledSnapshotStatus{PeriodNs: int64(s.period), NextDueNs: s.next.UnixNano(), Attempts: s.attempts, + Overdue: now.Sub(from) > s.period+snapshotRetryMax} + if !s.lastOK.IsZero() { + st.LastOkNs = s.lastOK.UnixNano() + } + if s.failure != nil { + f := *s.failure + st.LastFailure = &f + } + if len(s.skipped) > 0 { + st.Skipped = make(map[string]int64, len(s.skipped)) + for k, v := range s.skipped { + st.Skipped[k] = v + } + } + return st +} + +// snapshotFailureCode is a failure's typed code: a SnapshotFailure's own +// code, else "unknown". +func snapshotFailureCode(err error) string { + var f *SnapshotFailure + if errors.As(err, &f) && f.Code != "" { + return f.Code + } + return "unknown" +} + +func earlier(a, b time.Time) time.Time { + if a.Before(b) { + return a + } + return b +} + +// snapshotSlot guards one running loop's schedule: the loop records +// outcomes, status readers read it. +type snapshotSlot struct { + mu sync.Mutex + s *snapshotSchedule +} + +func (sl *snapshotSlot) status(now time.Time) ScheduledSnapshotStatus { + sl.mu.Lock() + defer sl.mu.Unlock() + return sl.s.status(now) +} + +func (sl *snapshotSlot) due() time.Time { + sl.mu.Lock() + defer sl.mu.Unlock() + return sl.s.due() +} + +func (sl *snapshotSlot) record(now time.Time, err error) { + sl.mu.Lock() + defer sl.mu.Unlock() + sl.s.record(now, err) +} + +// chunkSnapshotLoop takes volumeID's scheduled snapshots while the +// attachment is current. Each attempt is one bounded pass: one urgent cut +// and the snapshot record. An attempt cut short by the loop's own end is +// not recorded. +func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, slot *snapshotSlot) { + timer := time.NewTimer(time.Until(slot.due())) + defer timer.Stop() + timeout := 2 * p.cfg.ChunkCutTimeout + if timeout <= 0 { + timeout = 10 * time.Minute + } + cut := func(ctx context.Context) (storage.ChunkHead, error) { + r, err := p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0) + return r.Head, err + } + for { + select { + case <-ctx.Done(): + return + case <-timer.C: + } + if ctx.Err() != nil || layer.Fenced() || !current() { + return + } + at := time.Now() + var err error + if layer.Stats().AbsentChunks > 0 { + // Restoring: HEAD names chunks this volume has not fetched yet. + err = &SnapshotSkip{Reason: SnapshotSkipRestoring} + } else { + err = boundedPass(ctx, layer, current, timeout, func(passCtx context.Context) error { + return p.cfg.ChunkScheduledSnapshot(passCtx, volumeID, at, cut) + }) + } + if ctx.Err() != nil { + return + } + slot.record(time.Now(), err) + if err != nil { + log.Printf("durable: scheduled snapshot volume=%s: %v (next attempt %s)", volumeID, err, slot.due().UTC().Format(time.RFC3339)) + } + timer.Reset(time.Until(slot.due())) + } +} diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go new file mode 100644 index 0000000000..3bd787a3e3 --- /dev/null +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go @@ -0,0 +1,108 @@ +package durable + +import ( + "errors" + "testing" + "time" +) + +var schedT0 = time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + +// Each slot starts at a period boundary plus the volume's offset, spread +// over the whole period and stable across restarts; the first attempt is +// the first slot after the start, and consecutive slots are one period +// apart. +func TestSnapshotSchedule_SlotsAreOffsetPerVolume(t *testing.T) { + day := 24 * time.Hour + offsets := map[time.Duration]bool{} + for _, vol := range []string{"v1", "v2", "v3", "a-much-longer-volume-name"} { + s := newSnapshotSchedule(vol, day, schedT0) + due := s.due() + if !due.After(schedT0) || due.Sub(schedT0) > day { + t.Fatalf("%s: first slot %v, want within one period after %v", vol, due, schedT0) + } + off := time.Duration(due.UnixNano() % int64(day)) + offsets[off] = true + if again := newSnapshotSchedule(vol, day, schedT0.Add(5*time.Hour)); time.Duration(again.due().UnixNano()%int64(day)) != off { + t.Fatalf("%s: offset changed across restarts", vol) + } + s.record(due, nil) + if s.due().Sub(due) != day { + t.Fatalf("%s: after a success the next slot is %v later; want one period", vol, s.due().Sub(due)) + } + } + if len(offsets) < 2 { + t.Fatalf("every volume got the same offset %v", offsets) + } +} + +// A restoring volume is skipped, counted by reason, and not treated as a +// failure; it is retried within the backoff cap, not a whole period later. +func TestSnapshotSchedule_RestoringIsSkippedAndCounted(t *testing.T) { + s := newSnapshotSchedule("v1", 24*time.Hour, schedT0) + at := s.due() + s.record(at, &SnapshotSkip{Reason: "restoring"}) + s.record(s.due(), &SnapshotSkip{Reason: "restoring"}) + st := s.status(s.due()) + if st.Skipped["restoring"] != 2 || st.Attempts != 0 || st.LastFailure != nil { + t.Fatalf("status %+v; want 2 restoring skips, no failure", st) + } + if gap := s.due().Sub(at); gap > 2*snapshotRetryMax { + t.Fatalf("after two skips the next attempt is %v later; want within the backoff cap", gap) + } +} + +// A failure is recorded with its typed code and retried after a backoff +// that doubles from one minute up to one hour; a success clears it and +// schedules the next slot. +func TestSnapshotSchedule_FailureIsTypedAndBacksOff(t *testing.T) { + s := newSnapshotSchedule("v1", 24*time.Hour, schedT0) + now := s.due() + want := []time.Duration{time.Minute, 2 * time.Minute, 4 * time.Minute, 8 * time.Minute, 16 * time.Minute, 32 * time.Minute, time.Hour, time.Hour} + for i, w := range want { + s.record(now, &SnapshotFailure{Code: "remote_unavailable", Err: errors.New("filer down")}) + if got := s.due().Sub(now); got != w { + t.Fatalf("after failure %d the retry is %v later; want %v", i+1, got, w) + } + now = s.due() + } + st := s.status(now) + if st.Attempts != len(want) || st.LastFailure == nil || st.LastFailure.Code != "remote_unavailable" { + t.Fatalf("status %+v; want %d attempts and code remote_unavailable", st, len(want)) + } + s.record(now, errors.New("untyped")) + if st := s.status(now); st.LastFailure.Code != "unknown" { + t.Fatalf("untyped failure code %q; want unknown", st.LastFailure.Code) + } + s.record(now, nil) + st = s.status(now) + if st.Attempts != 0 || st.LastFailure != nil || st.LastOkNs != now.UnixNano() { + t.Fatalf("after a success: %+v; want the failure cleared and lastOk set", st) + } + if next := s.due(); next.Sub(now) > 24*time.Hour || next.UnixNano()%int64(24*time.Hour) != int64(s.offset) { + t.Fatalf("after a success the next attempt is %v; want the next slot", next) + } +} + +// The schedule is overdue once no scheduled snapshot succeeded within one +// period plus the retry cap: counted from the start before any success, +// then from the last success; the failure stays visible. +func TestSnapshotSchedule_OverdueAfterPeriodPlusRetryCap(t *testing.T) { + day, grace := 24*time.Hour, snapshotRetryMax + s := newSnapshotSchedule("v1", day, schedT0) + if s.status(schedT0.Add(day + grace)).Overdue { + t.Fatal("overdue at exactly one period plus the retry cap") + } + if !s.status(schedT0.Add(day + grace + time.Second)).Overdue { + t.Fatal("not overdue past one period plus the retry cap with no success") + } + ok := schedT0.Add(day) + s.record(ok, nil) + if s.status(ok.Add(day + grace)).Overdue { + t.Fatal("overdue within one period plus the retry cap of a success") + } + s.record(ok.Add(day), &SnapshotFailure{Code: "outcome_unknown"}) + if st := s.status(ok.Add(day + grace + time.Second)); !st.Overdue || st.LastFailure.Code != "outcome_unknown" { + t.Fatalf("status %+v; want overdue with the failure visible", st) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 06dbe352ee..f004ad80f4 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -179,6 +179,14 @@ type ProviderConfig struct { ChunkMaintenanceInterval time.Duration ChunkMaintenanceTimeout time.Duration ChunkMaintenance func(context.Context, string) error + // ChunkSnapshotPeriod schedules a named snapshot of each attached + // healthy volume once per period, at a per-volume offset (zero + // disables it). ChunkScheduledSnapshot takes one: it cuts through cut + // (one urgent cut) and records the snapshot of the HEAD cut returns. A + // *SnapshotSkip skips the attempt, counted by reason; a + // *SnapshotFailure carries the failure's code. + ChunkSnapshotPeriod time.Duration + ChunkScheduledSnapshot func(ctx context.Context, volumeID string, at time.Time, cut func(context.Context) (storage.ChunkHead, error)) error // DetachFreezeTimeout bounds how long a failing DetachVolume keeps guest // I/O stopped before it resumes or settles: the drain and final cut get // three quarters of it, the settlement of a failed cut the rest (the @@ -278,6 +286,9 @@ type volHandle struct { chunkDetach bool chunkStop context.CancelFunc chunkDone chan struct{} + // snapshots is the scheduled-snapshot state of the running loop, nil + // when the schedule is off. + snapshots *snapshotSlot } // VolumeStatus is a read-only diagnostic snapshot of one durable volume @@ -315,12 +326,13 @@ type VolumeStatus struct { // AwaitingAuthority: recovered, the layer waits for master authority to // attach. Stats is zero until the layer is attached. type ChunkStatus struct { - Attached bool // the chunk layer is attached to the remote - AwaitingAuthority bool // recovered; the layer waits for master authority to attach - Fenced bool // a newer holder fenced this layer: it publishes nothing - RemoteLSN uint64 // the LSN of the remote HEAD (what the remote holds durably) - Stats storage.ChunkLayerStats // the layer's cut counters; zero until attached - HostBudget any `json:",omitempty"` // the host background-cut budget state, with --host-limit-dir + Attached bool // the chunk layer is attached to the remote + AwaitingAuthority bool // recovered; the layer waits for master authority to attach + Fenced bool // a newer holder fenced this layer: it publishes nothing + RemoteLSN uint64 // the LSN of the remote HEAD (what the remote holds durably) + Stats storage.ChunkLayerStats // the layer's cut counters; zero until attached + HostBudget any `json:",omitempty"` // the host background-cut budget state, with --host-limit-dir + ScheduledSnapshot *ScheduledSnapshotStatus `json:",omitempty"` // the scheduled-snapshot state; absent when the schedule is off or its loop has not started } // NewDurableProvider constructs a provider. view is the ONLY @@ -343,6 +355,9 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura if cfg.ChunkMaintenanceInterval > 0 && cfg.ChunkMaintenance == nil { return nil, fmt.Errorf("durable: chunk maintenance interval requires its callback") } + if cfg.ChunkSnapshotPeriod < 0 || (cfg.ChunkSnapshotPeriod > 0 && cfg.ChunkScheduledSnapshot == nil) { + return nil, fmt.Errorf("durable: a chunk snapshot period must not be negative and requires its callback") + } if cfg.ChunkBlocks == 0 { cfg.ChunkBlocks = defaultChunkBlocks } @@ -571,8 +586,9 @@ func durableIdentityConflict(got, want frontend.Identity) error { // durable lineage latching without scraping logs. func (p *DurableProvider) DurableStatuses() []VolumeStatus { type chunkView struct { - layer storage.ChunkLayer - awaiting bool + layer storage.ChunkLayer + awaiting bool + snapshots *snapshotSlot } p.mu.Lock() handles := make(map[string]*volHandle, len(p.volumes)) @@ -580,7 +596,7 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus { for volumeID, h := range p.volumes { handles[volumeID] = h if p.cfg.Impl == ImplWALStoreChunk { - chunks[volumeID] = chunkView{layer: h.chunk, awaiting: h.waitGen != 0} + chunks[volumeID] = chunkView{layer: h.chunk, awaiting: h.waitGen != 0, snapshots: h.snapshots} } } p.mu.Unlock() @@ -596,6 +612,10 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus { if budget, ok := p.cfg.ChunkBudget.(interface{ Snapshot() any }); ok { cs.HostBudget = budget.Snapshot() } + if cv.snapshots != nil { + ss := cv.snapshots.status(time.Now()) + cs.ScheduledSnapshot = &ss + } st.Chunk = cs } out = append(out, st) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 2c194a39e8..64431d4dcc 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -320,14 +320,19 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v // startChunkLoop starts the periodic cuts of an attached layer, if configured // and not already running. The caller holds h.attachMu and p.mu. func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer storage.ChunkLayer) { - if (p.cfg.ChunkCaptureInterval <= 0 && (p.cfg.ChunkMaintenanceInterval <= 0 || p.cfg.ChunkMaintenance == nil)) || h.chunkStop != nil { + snapshotsOn := p.cfg.ChunkSnapshotPeriod > 0 && p.cfg.ChunkScheduledSnapshot != nil + if (p.cfg.ChunkCaptureInterval <= 0 && (p.cfg.ChunkMaintenanceInterval <= 0 || p.cfg.ChunkMaintenance == nil) && !snapshotsOn) || h.chunkStop != nil { return } loopCtx, cancel := context.WithCancel(context.Background()) h.chunkStop, h.chunkDone = cancel, make(chan struct{}) + h.snapshots = nil + if snapshotsOn { + h.snapshots = &snapshotSlot{s: newSnapshotSchedule(volumeID, p.cfg.ChunkSnapshotPeriod, time.Now())} + } lin := h.chunkLineage current := func() bool { return p.maintenanceCurrent(volumeID, h, layer, lin) } - go p.chunkBackground(loopCtx, cancel, volumeID, layer, h.chunkDone, current) + go p.chunkBackground(loopCtx, cancel, volumeID, layer, h.chunkDone, current, h.snapshots) } func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) { @@ -800,7 +805,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer // chunkBackground owns both workers and their cancellation. A fence is observed // even while either worker is waiting on a cooperative remote call. INV-MAINT-JOIN: // done closes only after every admitted worker has returned. -func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool) { +func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool, snapshots *snapshotSlot) { defer close(done) defer cancel() var workers sync.WaitGroup @@ -816,6 +821,10 @@ func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.Ca workers.Add(1) go func() { defer workers.Done(); p.chunkMaintenanceLoop(ctx, volumeID, layer, current) }() } + if snapshots != nil { + workers.Add(1) + go func() { defer workers.Done(); p.chunkSnapshotLoop(ctx, volumeID, layer, current, snapshots) }() + } timer := time.NewTicker(chunkSchedulePoll) defer timer.Stop() for ctx.Err() == nil { @@ -864,29 +873,9 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str if timeout <= 0 { timeout = time.Minute } - passCtx, cancel := context.WithTimeout(ctx, timeout) - // The projection has no change channel. One bounded watcher belongs to - // this pass, never to an individual tick; cancellation is joined below. - watchDone := make(chan struct{}) - go func() { - defer close(watchDone) - tick := time.NewTicker(chunkSchedulePoll) - defer tick.Stop() - for { - select { - case <-passCtx.Done(): - return - case <-tick.C: - if layer.Fenced() || !current() { - cancel() - return - } - } - } - }() - err := p.cfg.ChunkMaintenance(passCtx, volumeID) - cancel() - <-watchDone + err := boundedPass(ctx, layer, current, timeout, func(passCtx context.Context) error { + return p.cfg.ChunkMaintenance(passCtx, volumeID) + }) if err != nil && ctx.Err() == nil { log.Printf("durable: maintenance volume=%s: %v", volumeID, err) } @@ -895,6 +884,35 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str } } +// boundedPass runs fn with a context that ends after timeout, or as soon +// as the layer is fenced or the attachment is no longer current. The +// projection has no change channel: one bounded watcher belongs to the +// pass, never to an individual tick, and is joined before return. +func boundedPass(ctx context.Context, layer storage.ChunkLayer, current func() bool, timeout time.Duration, fn func(context.Context) error) error { + passCtx, cancel := context.WithTimeout(ctx, timeout) + watchDone := make(chan struct{}) + go func() { + defer close(watchDone) + tick := time.NewTicker(chunkSchedulePoll) + defer tick.Stop() + for { + select { + case <-passCtx.Done(): + return + case <-tick.C: + if layer.Fenced() || !current() { + cancel() + return + } + } + } + }() + err := fn(passCtx) + cancel() + <-watchDone + return err +} + func (p *DurableProvider) stopChunkLoop(h *volHandle) { p.mu.Lock() stop, done := h.chunkStop, h.chunkDone diff --git a/seaweed-block/core/frontend/durable/provider_chunk_snapshot_schedule_test.go b/seaweed-block/core/frontend/durable/provider_chunk_snapshot_schedule_test.go new file mode 100644 index 0000000000..336c6ee039 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_snapshot_schedule_test.go @@ -0,0 +1,188 @@ +package durable_test + +// The scheduled-snapshot loop through the real provider. + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type snapCalls struct { + mu sync.Mutex + heads []storage.ChunkHead + fail error +} + +func (c *snapCalls) take(ctx context.Context, _ string, _ time.Time, cut func(context.Context) (storage.ChunkHead, error)) error { + c.mu.Lock() + fail := c.fail + c.mu.Unlock() + if fail != nil { + return fail + } + h, err := cut(ctx) + if err != nil { + return err + } + c.mu.Lock() + c.heads = append(c.heads, h) + c.mu.Unlock() + return nil +} + +func (c *snapCalls) count() int { + c.mu.Lock() + defer c.mu.Unlock() + return len(c.heads) +} + +func snapScheduleProvider(t *testing.T, remote storage.ChunkRemote, period time.Duration, calls *snapCalls) *durable.DurableProvider { + t.Helper() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + ChunkSnapshotPeriod: period, + ChunkScheduledSnapshot: calls.take, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + return p +} + +func scheduledStatus(t *testing.T, p *durable.DurableProvider) *durable.ScheduledSnapshotStatus { + t.Helper() + for _, st := range p.DurableStatuses() { + if st.VolumeID == "v1" && st.Chunk != nil { + return st.Chunk.ScheduledSnapshot + } + } + return nil +} + +func waitFor(t *testing.T, d time.Duration, what string, ok func() bool) { + t.Helper() + deadline := time.Now().Add(d) + for !ok() { + if time.Now().After(deadline) { + t.Fatalf("%s not reached within %v", what, d) + } + time.Sleep(20 * time.Millisecond) + } +} + +// With a schedule, the attached volume's snapshot is taken at its slot by +// one cut that publishes the dirty data, the snapshot callback gets that +// cut's HEAD, and the status shows the success and the next slot. A failure +// is visible in the status with its code. +func TestWALStoreChunk_ScheduledSnapshotCutsAndReports(t *testing.T) { + const period = 2 * time.Second + remote := storage.NewMemChunkRemote() + calls := &snapCalls{} + p := snapScheduleProvider(t, remote, period, calls) + s := openRecovered(t, p) + if _, err := s.Write(1, block(0x5A)); err != nil { + t.Fatal(err) + } + waitFor(t, 3*period, "the first scheduled snapshot", func() bool { return calls.count() >= 1 }) + calls.mu.Lock() + h := calls.heads[0] + calls.mu.Unlock() + if remoteHead := headGen(t, remote); h.Gen == 0 || h.Gen > remoteHead.Gen || len(h.Chunks) == 0 { + t.Fatalf("snapshot HEAD gen %d with %d chunks (remote gen %d); want the cut that published the write", h.Gen, len(h.Chunks), remoteHead.Gen) + } + waitFor(t, time.Second, "the success in the status", func() bool { + st := scheduledStatus(t, p) + return st != nil && st.LastOkNs > 0 + }) + st := scheduledStatus(t, p) + if st.PeriodNs != int64(period) || st.NextDueNs <= st.LastOkNs || st.Overdue || st.LastFailure != nil { + t.Fatalf("status %+v; want period %v, next slot after the success, not overdue, no failure", st, period) + } + + calls.mu.Lock() + calls.fail = &durable.SnapshotFailure{Code: "remote_unavailable", Err: errors.New("filer down")} + calls.mu.Unlock() + waitFor(t, 3*period, "the failure in the status", func() bool { + st := scheduledStatus(t, p) + return st != nil && st.LastFailure != nil + }) + if st := scheduledStatus(t, p); st.LastFailure.Code != "remote_unavailable" || st.Attempts < 1 { + t.Fatalf("status %+v; want the typed failure and its attempt count", st) + } +} + +// With the schedule off (period zero), no snapshot is attempted and the +// status has no scheduled-snapshot section. +func TestWALStoreChunk_ScheduledSnapshotOffTakesNone(t *testing.T) { + remote := storage.NewMemChunkRemote() + calls := &snapCalls{} + p := snapScheduleProvider(t, remote, 0, calls) + s := openRecovered(t, p) + if _, err := s.Write(1, block(0x01)); err != nil { + t.Fatal(err) + } + for i := 0; i < 10; i++ { + if calls.count() != 0 || scheduledStatus(t, p) != nil { + t.Fatal("a scheduled snapshot ran with the schedule off") + } + time.Sleep(100 * time.Millisecond) + } +} + +// A snapshot period without its callback is refused. +func TestWALStoreChunk_ScheduledSnapshotNeedsItsCallback(t *testing.T) { + _, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkSnapshotPeriod: time.Hour, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, + }, v1View()) + if err == nil { + t.Fatal("a snapshot period without its callback was accepted") + } +} + +// A volume still fetching the chunks its HEAD names (a fresh host starting +// from the remote HEAD) is restoring: its scheduled attempts are skipped, +// counted by reason, and no snapshot is taken. +func TestWALStoreChunk_ScheduledSnapshotSkipsARestoringVolume(t *testing.T) { + const period = 2 * time.Second + remote := storage.NewMemChunkRemote() + view := v1View() + first := chunkProvider(t, t.TempDir(), remote, view, 0) + s := openRecovered(t, first) + if _, err := s.Write(33, block(0x33)); err != nil { + t.Fatal(err) + } + if err := first.MakeVolumeRemoteDurable(context.Background(), "v1", 1); err != nil { + t.Fatal(err) + } + _ = first.Close() + calls := &snapCalls{} + fresh, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + ChunkSnapshotPeriod: period, ChunkScheduledSnapshot: calls.take, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = fresh.Close() }) + openRecovered(t, fresh) + waitFor(t, 3*period, "a restoring skip", func() bool { + st := scheduledStatus(t, fresh) + return st != nil && st.Skipped[durable.SnapshotSkipRestoring] >= 1 + }) + if st := scheduledStatus(t, fresh); calls.count() != 0 || st.LastFailure != nil || st.Attempts != 0 { + t.Fatalf("restoring volume: %d snapshots, status %+v; want none taken and no failure", calls.count(), st) + } +} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index c6cd4f7525..89c386d3c4 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -634,16 +634,27 @@ func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkS } sreq := chunkstore.SnapshotRequest{Name: req.Name, RequestID: req.RequestID, Labels: req.Labels, Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, CreatedBy: "blockvolume", Class: req.Class} - if info, replayed, err := c.cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed { + return sealSnapshot(ctx, c.cat, volumeID, sreq, func(ctx context.Context) (storage.ChunkHead, error) { + // A named seal is urgent even without a minimum LSN. + r, err := c.p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0) + return r.Head, err + }) +} + +// sealSnapshot resolves sreq against the catalog first: a retry of a +// recorded request returns that snapshot and another request for the name +// fails, both without cutting. Only a free name is cut, and the HEAD that +// cut installed is stored. +func sealSnapshot(ctx context.Context, cat *chunkstore.Catalog, volumeID string, sreq chunkstore.SnapshotRequest, cut func(context.Context) (storage.ChunkHead, error)) (chunkstore.SnapshotInfo, error) { + if info, replayed, err := cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed { return info, err } - // A named seal is urgent even without a minimum LSN. - r, err := c.p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0) + head, err := cut(ctx) if err != nil { return chunkstore.SnapshotInfo{}, err } sreq.SourceReadAt = time.Now() - return c.cat.CreateSnapshot(ctx, volumeID, sreq, r.Head) + return cat.CreateSnapshot(ctx, volumeID, sreq, head) } func (c *chunkControl) ListSnapshots(ctx context.Context, volumeID string, opts chunkstore.ListOptions) ([]chunkstore.SnapshotInfo, string, error) { diff --git a/seaweed-block/core/host/volume/chunk_control_adapter_test.go b/seaweed-block/core/host/volume/chunk_control_adapter_test.go index 51f9a57876..ce1ef835e7 100644 --- a/seaweed-block/core/host/volume/chunk_control_adapter_test.go +++ b/seaweed-block/core/host/volume/chunk_control_adapter_test.go @@ -67,6 +67,14 @@ func (f *fakeChunkProvider) DetachVolume(context.Context, string) (storage.Chunk } func adapterFixture(t *testing.T) (*fakeChunkProvider, ChunkControl) { + t.Helper() + fp, cat := adapterCatalog(t) + return fp, NewChunkControl(fp, cat) +} + +// adapterCatalog is a catalog holding volume v1 and a provider whose cut +// installs a published HEAD of v1. +func adapterCatalog(t *testing.T) (*fakeChunkProvider, *chunkstore.Catalog) { t.Helper() head := storage.ChunkHead{Gen: 3, Epoch: 2, Holder: "r1", RemoteLSN: 9, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e2/c0/k1"}, 5: {Key: "chunks/e2/c5/k2"}}} @@ -87,7 +95,7 @@ func adapterFixture(t *testing.T) (*fakeChunkProvider, ChunkControl) { if _, err := cat.EnsureVolume(context.Background(), "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { t.Fatal(err) } - return fp, NewChunkControl(fp, cat) + return fp, cat } // Snapshot validates before it cuts, then stores the HEAD its cut diff --git a/seaweed-block/core/host/volume/chunk_scheduled_snapshot.go b/seaweed-block/core/host/volume/chunk_scheduled_snapshot.go new file mode 100644 index 0000000000..f75c995d00 --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_scheduled_snapshot.go @@ -0,0 +1,38 @@ +package volume + +import ( + "context" + "strconv" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// ScheduledSnapshotName is the name of the scheduled snapshot attempted +// at at (UTC, to the second). +func ScheduledSnapshotName(at time.Time) string { + return "sched-" + at.UTC().Format("20060102T150405Z") +} + +// ScheduledSnapshot returns the provider's scheduled-snapshot callback +// (durable.ProviderConfig.ChunkScheduledSnapshot) over cat. Each attempt +// is one named snapshot of class "scheduled", labelled with keep (the +// count retention keeps), sealed through the same path as an explicit +// named snapshot: the request is resolved first, then one cut, then the +// record of that cut's HEAD. A failure carries the code the control +// endpoint would report. +func ScheduledSnapshot(cat *chunkstore.Catalog, keep int) func(context.Context, string, time.Time, func(context.Context) (storage.ChunkHead, error)) error { + labels := map[string]string{chunkstore.LabelScheduleKeep: strconv.Itoa(keep)} + return func(ctx context.Context, volumeID string, at time.Time, cut func(context.Context) (storage.ChunkHead, error)) error { + name := ScheduledSnapshotName(at) + sreq := chunkstore.SnapshotRequest{Name: name, RequestID: name, Labels: labels, + CreatedBy: "blockvolume-schedule", Class: chunkstore.SnapshotClassScheduled} + if _, err := sealSnapshot(ctx, cat, volumeID, sreq, cut); err != nil { + _, code, _ := chunkErrorCode(err) + return &durable.SnapshotFailure{Code: code, Err: err} + } + return nil + } +} diff --git a/seaweed-block/core/host/volume/chunk_scheduled_snapshot_test.go b/seaweed-block/core/host/volume/chunk_scheduled_snapshot_test.go new file mode 100644 index 0000000000..4290703cee --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_scheduled_snapshot_test.go @@ -0,0 +1,69 @@ +package volume + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A scheduled snapshot is one named snapshot of class "scheduled", named +// for its attempt time and labelled with the schedule's keep, recording +// exactly the HEAD its own cut installed. A retry of the same attempt +// replays without cutting again. +func TestScheduledSnapshot_SealsTheCutHeadAsScheduled(t *testing.T) { + ctx := context.Background() + fp, cat := adapterCatalog(t) + take := ScheduledSnapshot(cat, 7) + at := time.Date(2026, 11, 21, 3, 4, 5, 0, time.UTC) + cuts := 0 + cut := func(ctx context.Context) (storage.ChunkHead, error) { + cuts++ + r, err := fp.CutVolume(ctx, "v1", 0) + return r.Head, err + } + if err := take(ctx, "v1", at, cut); err != nil { + t.Fatal(err) + } + if err := take(ctx, "v1", at, cut); err != nil || cuts != 1 { + t.Fatalf("retry of the same attempt: %v, %d cuts; want a replay without a second cut", err, cuts) + } + list, _, err := cat.ListSnapshots(ctx, "v1", chunkstore.ListOptions{}) + if err != nil || len(list) != 1 { + t.Fatalf("list: %+v %v", list, err) + } + s := list[0] + if s.Name != "sched-20261121T030405Z" || s.Class != chunkstore.SnapshotClassScheduled || s.Labels[chunkstore.LabelScheduleKeep] != "7" || + s.HeadGen != fp.cut.Head.Gen || s.HeadEpoch != fp.cut.Head.Epoch || s.CutLSN != fp.cut.Head.RemoteLSN { + t.Fatalf("snapshot %+v; want sched-20261121T030405Z, class scheduled, keep 7, the cut's HEAD", s) + } +} + +// A failed cut is reported as a durable.SnapshotFailure with the code +// the control endpoint gives the same error, and records nothing. +func TestScheduledSnapshot_FailureCarriesTheEndpointCode(t *testing.T) { + ctx := context.Background() + _, cat := adapterCatalog(t) + take := ScheduledSnapshot(cat, 7) + for _, c := range []struct { + err error + code string + }{ + {storage.ErrChunkLayerFenced, codeFenced}, + {storage.ErrChunkRemoteUnavailable, chunkstore.CodeRemoteUnavailable}, + {context.DeadlineExceeded, chunkstore.CodeDeadlineExceeded}, + } { + err := take(ctx, "v1", time.Now(), func(context.Context) (storage.ChunkHead, error) { return storage.ChunkHead{}, c.err }) + var f *durable.SnapshotFailure + if !errors.As(err, &f) || f.Code != c.code || !errors.Is(err, c.err) { + t.Fatalf("cut error %v: got %v; want a SnapshotFailure with code %s", c.err, err, c.code) + } + } + if list, _, _ := cat.ListSnapshots(ctx, "v1", chunkstore.ListOptions{}); len(list) != 0 { + t.Fatalf("failed attempts recorded %+v", list) + } +} diff --git a/seaweed-block/deploy/config/blockvolume.env b/seaweed-block/deploy/config/blockvolume.env index a40f5f7c7f..5d0a211566 100644 --- a/seaweed-block/deploy/config/blockvolume.env +++ b/seaweed-block/deploy/config/blockvolume.env @@ -111,6 +111,10 @@ SWB_CHUNK_REPLICATION= # --chunk-capture-interval (default 0: no timer). Automatic cut once this long # has passed since the last successful cut, e.g. 15m as a host-loss safety net. SWB_CHUNK_CAPTURE_INTERVAL=0 +# --chunk-snapshot-schedule (default daily:7). Scheduled named snapshots: +# daily:N or weekly:N takes one snapshot per period at a per-volume offset +# (not at a wall-clock hour) and keeps the newest N; off disables them. +SWB_CHUNK_SNAPSHOT_SCHEDULE=daily:7 # --chunk-upload-concurrency (default 8; 1..64). Parallel dirty-chunk uploads. SWB_CHUNK_UPLOAD_CONCURRENCY=8 # --chunk-control-endpoint (default false). Expose /chunk/* (cut, snapshot, diff --git a/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service b/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service index c15dcbb0a2..50a3ca26f8 100644 --- a/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service +++ b/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service @@ -59,6 +59,7 @@ ExecStart=/usr/local/bin/blockvolume \ --chunk-collection=${SWB_CHUNK_COLLECTION} \ --chunk-replication=${SWB_CHUNK_REPLICATION} \ --chunk-capture-interval=${SWB_CHUNK_CAPTURE_INTERVAL} \ + --chunk-snapshot-schedule=${SWB_CHUNK_SNAPSHOT_SCHEDULE} \ --chunk-upload-concurrency=${SWB_CHUNK_UPLOAD_CONCURRENCY} \ --chunk-control-endpoint=${SWB_CHUNK_CONTROL_ENDPOINT} \ --workspace-lease=${SWB_WORKSPACE_LEASE} \ diff --git a/seaweed-block/deploy/systemd/sw-blockvolume.service b/seaweed-block/deploy/systemd/sw-blockvolume.service index 28675f37ce..6cbcb6a6fa 100644 --- a/seaweed-block/deploy/systemd/sw-blockvolume.service +++ b/seaweed-block/deploy/systemd/sw-blockvolume.service @@ -58,6 +58,7 @@ ExecStart=/usr/local/bin/blockvolume \ --chunk-collection=${SWB_CHUNK_COLLECTION} \ --chunk-replication=${SWB_CHUNK_REPLICATION} \ --chunk-capture-interval=${SWB_CHUNK_CAPTURE_INTERVAL} \ + --chunk-snapshot-schedule=${SWB_CHUNK_SNAPSHOT_SCHEDULE} \ --chunk-upload-concurrency=${SWB_CHUNK_UPLOAD_CONCURRENCY} \ --chunk-control-endpoint=${SWB_CHUNK_CONTROL_ENDPOINT} \ --workspace-lease=${SWB_WORKSPACE_LEASE} \ diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index d5318a20df..a515c581d5 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -255,7 +255,11 @@ Snapshots of the target are refused in `Forking` and `Restoring`. ### Attached-volume scheduling Periodic HEAD capture is off by default (opt-in; when set, at least 5 -minutes), and retention runs every hour. Named snapshots remain explicit. +minutes), and retention runs every hour. Named snapshots are explicit, plus scheduled snapshots +(`--chunk-snapshot-schedule`, default `daily:7`): one snapshot per period at a +per-volume offset (not at a wall-clock hour), class `scheduled`, the newest N +kept by retention; a restoring volume is skipped and counted, and a failed +attempt is retried with backoff and visible in status (`snapshot_overdue`). A five-minute context covers the whole cut; completed immutable uploads survive an expired attempt only under matching version/HEAD generation. Automatic GC is opt-in until the 50/200-volume metadata/RSS qualification accepts its full-catalog diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0c69765881..6cdcff09a5 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -289,8 +289,10 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | +| `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retention.go` `planRetention`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest` (`core/frontend/chunkstore/retention_test.go`) | — | ACTIVE | | name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | deleting | `DeleteSnapshot` or retention for this attempt, whatever forks or restores read it (no claim is read); the mark records its delete time and GC keeps the attempt rooted for its grace | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | +| published | deleting (retention, class `scheduled`) | the snapshot is not among the newest K of class `scheduled` (K from the newest one's `swb.schedule.keep`, default 7); other classes are planned without it | `core/frontend/chunkstore/retention.go` `planRetention` | `INV-SNAP-SCHEDULED-KEEP-001` | | published | fork | take the deadline start, read the parent snapshot (every attempt reads it again; deleting or absent refuses), check the source is not being deleted, write the target `VOLUME`, then its HEAD only before start + deadline; no chunk is copied and the parent is not claimed | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent` | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | | published | restore | the fork steps with `VOLUME` origin `restore`: until the first HEAD the parent stays rooted by GC's grace after any delete (the fork deadline bound), after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | | restore | independent | the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs` | `INV-RESTORE-INDEPENDENT-001` | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 1e1f3e1d4f..1a4df0c0ff 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -123,6 +123,7 @@ the example units, which turn them into flags. blockvolume itself reads only | `SWB_CHUNK_PATH` | `--chunk-path` | `/swblock/chunks` | Filer directory, one directory per volume | | `SWB_CHUNK_COLLECTION`, `SWB_CHUNK_REPLICATION` | `--chunk-collection`, `--chunk-replication` | empty (filer default) | Placement of chunk needles | | `SWB_CHUNK_CAPTURE_INTERVAL` | `--chunk-capture-interval` | `0` (no timer) | Automatic cut interval, e.g. `15m` | +| `SWB_CHUNK_SNAPSHOT_SCHEDULE` | `--chunk-snapshot-schedule` | `daily:7` | Scheduled named snapshots: `daily:N` or `weekly:N` (one per period at a per-volume offset, the newest N kept), or `off` | | `SWB_CHUNK_UPLOAD_CONCURRENCY` | `--chunk-upload-concurrency` | `8` | Parallel chunk uploads (1..64) | | `SWB_CHUNK_CONTROL_ENDPOINT` | `--chunk-control-endpoint` | `false` | `/chunk/*` routes on the status listener | | `SWB_WORKSPACE_LEASE` | `--workspace-lease` | `false` | Require a master lease; fail closed without one | diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 02d7a1d468..33559866a3 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -276,6 +276,16 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. | | `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. | | `Volumes[].Chunk.HostBudget` | interface | the host background-cut budget state, with --host-limit-dir (omitted when empty) | +| `Volumes[].Chunk.ScheduledSnapshot` | object | the scheduled-snapshot state; absent when the schedule is off or its loop has not started (omitted when empty) | +| `Volumes[].Chunk.ScheduledSnapshot.periodNs` | int64 | PeriodNs is the schedule period; zero means off. | +| `Volumes[].Chunk.ScheduledSnapshot.lastOkNs` | int64 | LastOkNs is when the last scheduled snapshot succeeded; zero: none since the schedule started. | +| `Volumes[].Chunk.ScheduledSnapshot.nextDueNs` | int64 | NextDueNs is when the next attempt is due. | +| `Volumes[].Chunk.ScheduledSnapshot.lastFailure` | object | LastFailure is the last failed attempt since the last success. (omitted when empty) | +| `Volumes[].Chunk.ScheduledSnapshot.lastFailure.code` | string | Code is the failure's code, as the control endpoint reports it. | +| `Volumes[].Chunk.ScheduledSnapshot.lastFailure.atNs` | int64 | AtNs is when the attempt failed. | +| `Volumes[].Chunk.ScheduledSnapshot.attempts` | int | Attempts counts the failed attempts since the last success. | +| `Volumes[].Chunk.ScheduledSnapshot.skipped{}` | int64 | Skipped counts attempts not made, by reason. (omitted when empty) | +| `Volumes[].Chunk.ScheduledSnapshot.snapshot_overdue` | bool | Overdue reports that no scheduled snapshot succeeded within one period plus the retry cap, counted from the last success or, before any, from the start of the schedule. | | `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | | `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | From 8935841c82b7f95bc44b4f26f2735c6a93d9d4f3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 04:47:51 -0800 Subject: [PATCH 04/34] durable: test that wall-clock steps neither repeat nor stall the snapshot schedule Co-Authored-By: Claude Opus 5.5 --- .../durable/chunk_snapshot_schedule_test.go | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go index 3bd787a3e3..0f95deef2d 100644 --- a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go @@ -106,3 +106,35 @@ func TestSnapshotSchedule_OverdueAfterPeriodPlusRetryCap(t *testing.T) { t.Fatalf("status %+v; want overdue with the failure visible", st) } } + +// Slots come from the wall clock, so the schedule must survive clock steps: +// after a step backwards or forwards, the next attempt is always the first +// slot strictly after the step's now (never in the past, so no burst of +// catch-up attempts, and never more than one period ahead), a step forwards +// past a period plus the retry cap shows as overdue, and a success after +// either step resumes the per-volume slots. +func TestSnapshotSchedule_ClockStepsNeitherRepeatNorStall(t *testing.T) { + day := 24 * time.Hour + s := newSnapshotSchedule("v1", day, schedT0) + ok := s.due() + s.record(ok, nil) + for _, step := range []time.Duration{-3 * time.Hour, -2 * day, 5 * time.Minute, 3 * day} { + now := ok.Add(step) + s.record(now, &SnapshotFailure{Code: "remote_unavailable"}) // an attempt at the stepped clock + if !s.due().After(now) || s.due().Sub(now) > time.Hour { + t.Fatalf("step %v: retry due %v for now %v; want within the backoff after now", step, s.due(), now) + } + s.record(now, nil) + due := s.due() + if !due.After(now) || due.Sub(now) > day || time.Duration(due.UnixNano()%int64(day)) != s.offset { + t.Fatalf("step %v: next slot %v for now %v; want the first per-volume slot after now", step, due, now) + } + if st := s.status(now); st.Overdue || st.LastOkNs != now.UnixNano() { + t.Fatalf("step %v: status %+v right after a success", step, st) + } + } + far := s.due().Add(3 * day) + if !s.status(far).Overdue { + t.Fatal("a clock step forwards past a period plus the retry cap with no success is not overdue") + } +} From 24405cb3b0436ea10124d6e75379f1591ad1bc32 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 05:01:42 -0800 Subject: [PATCH 05/34] durable: the snapshot schedule runs on the wall clock (observes steps both ways), keeps its state across a re-armed loop; retention keeps pinned scheduled snapshots in their class Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/retention.go | 7 +- .../frontend/chunkstore/retention_test.go | 18 ++ .../durable/chunk_snapshot_loop_test.go | 184 ++++++++++++++++++ .../durable/chunk_snapshot_schedule.go | 57 +++++- .../core/frontend/durable/provider.go | 5 +- .../core/frontend/durable/provider_chunk.go | 9 +- seaweed-block/docs/design/invariants.md | 4 +- 7 files changed, 268 insertions(+), 16 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/chunk_snapshot_loop_test.go diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index e3f950a2b3..1d18b6298e 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -235,10 +235,15 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, now time.Time) []Ret for i, s := range ordered { pinned := s.Pinned() && (s.ExpiresAtNs == 0 || nowNs < s.ExpiresAtNs) d := RetentionDecision{Name: s.Name, Attempt: s.attempt, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: pinned} - if !pinned && s.Class == SnapshotClassScheduled { + if s.Class == SnapshotClassScheduled { + // Every scheduled snapshot, pinned or not, is planned here and + // ranked among its class; a pinned one is also kept by its pin. if scheduleKeep < 0 { scheduleKeep = scheduleKeepOf(s) } + if pinned { + d.Reasons = append(d.Reasons, keepPinned) + } if scheduled < scheduleKeep { d.Reasons = append(d.Reasons, keepScheduled) } diff --git a/seaweed-block/core/frontend/chunkstore/retention_test.go b/seaweed-block/core/frontend/chunkstore/retention_test.go index 1b2d538af0..29c13a3bdd 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_test.go @@ -411,3 +411,21 @@ func TestPlanRetention_ScheduledClassKeepsItsOwnNewest(t *testing.T) { t.Fatalf("kept %v with no label on the newest; want min(6, DefaultScheduleKeep)", k) } } + +// A pinned scheduled snapshot stays in its class: it is kept by its pin, +// ranks among the scheduled ones (its label sets K when it is the newest), +// and takes no log-spaced window from a manual snapshot. +func TestPlanRetention_PinnedScheduledStaysInItsClass(t *testing.T) { + now := retBase.Add(30 * 24 * time.Hour) + newest := snapAt("sched-pinned", now.Add(-10*time.Minute), SnapshotClassScheduled, now.Add(24*time.Hour), map[string]string{LabelScheduleKeep: "2"}) + snaps := []SnapshotInfo{ + newest, + snapAt("sched-1", now.Add(-24*time.Hour), SnapshotClassScheduled, time.Time{}, map[string]string{LabelScheduleKeep: "9"}), + snapAt("sched-2", now.Add(-48*time.Hour), SnapshotClassScheduled, time.Time{}, map[string]string{LabelScheduleKeep: "9"}), + snapAt("manual", now.Add(-20*time.Minute), "", time.Time{}, nil), // same hourly window as the pinned scheduled one + } + k := kept(planRetention(RetentionPolicy{KeepHourly: 1}, snaps, now)) + if len(k) != 3 || k["sched-pinned"] == nil || k["sched-1"] == nil || k["manual"] == nil { + t.Fatalf("kept %v; want sched-pinned (pin, K=2 from its label), sched-1 (second newest scheduled) and manual (its hourly window)", k) + } +} diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_loop_test.go b/seaweed-block/core/frontend/durable/chunk_snapshot_loop_test.go new file mode 100644 index 0000000000..659470be45 --- /dev/null +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_loop_test.go @@ -0,0 +1,184 @@ +package durable + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// snapStubLayer is an attached, unfenced layer with no absent chunks. +type snapStubLayer struct{ storage.ChunkLayer } + +func (snapStubLayer) Fenced() bool { return false } +func (snapStubLayer) Stats() storage.ChunkLayerStats { return storage.ChunkLayerStats{} } + +// stepClock is a wall clock a test can step. +type stepClock struct { + mu sync.Mutex + now time.Time +} + +func (c *stepClock) get() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.now } +func (c *stepClock) set(t time.Time) { c.mu.Lock(); c.now = t; c.mu.Unlock() } + +// snapLoopFixture is a provider running the scheduled-snapshot loop of one +// volume on a stepped clock, with a 10 ms wake bound. take is called for +// every attempt; the loop is stopped and joined at cleanup. +func snapLoopFixture(t *testing.T, take func(context.Context) error) (*DurableProvider, *volHandle, *stepClock) { + t.Helper() + wake := snapshotWake + snapshotWake = 10 * time.Millisecond + t.Cleanup(func() { snapshotWake = wake }) + clock := &stepClock{now: time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC)} + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1} + layer := &snapStubLayer{} + h := &volHandle{chunk: layer, chunkLineage: chunkLineage{"v1", "r1", 3, 1}} + p := &DurableProvider{volumes: map[string]*volHandle{"v1": h}, view: precopyQueueView{id}, testSnapshotClock: clock.get, + cfg: ProviderConfig{ChunkSnapshotPeriod: 24 * time.Hour, + ChunkScheduledSnapshot: func(ctx context.Context, _ string, _ time.Time, _ func(context.Context) (storage.ChunkHead, error)) error { + return take(ctx) + }}} + p.mu.Lock() + p.startChunkLoop("v1", h, layer) + p.mu.Unlock() + t.Cleanup(func() { + done := make(chan struct{}) + go func() { p.stopChunkLoop(h); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("the snapshot loop was not joined") + } + }) + return p, h, clock +} + +func waitUntil(t *testing.T, what string, ok func() bool) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !ok() { + if time.Now().After(deadline) { + t.Fatalf("%s not reached", what) + } + time.Sleep(5 * time.Millisecond) + } +} + +// A wall-clock step forwards past the due time is observed within the wake +// bound: the attempt runs without waiting out the elapsed-time timer, and +// its success is recorded at the stepped wall time. +func TestScheduledSnapshotLoop_ForwardWallStepIsObserved(t *testing.T) { + var calls atomic.Int64 + p, h, clock := snapLoopFixture(t, func(context.Context) error { calls.Add(1); return nil }) + due := h.snapshots.status(clock.get()).NextDueNs + time.Sleep(50 * time.Millisecond) + if calls.Load() != 0 { + t.Fatal("an attempt ran before its slot") + } + stepped := time.Unix(0, due).Add(time.Second) + clock.set(stepped) + waitUntil(t, "the attempt after a forward step", func() bool { return calls.Load() == 1 }) + waitUntil(t, "the recorded success", func() bool { return h.snapshots.status(p.snapshotNow()).LastOkNs == stepped.UnixNano() }) +} + +// A wall-clock step backwards realigns the next attempt to the first slot +// after the stepped now (it does not wait the step out), and that slot is +// then taken. +func TestScheduledSnapshotLoop_BackwardWallStepRealigns(t *testing.T) { + var calls atomic.Int64 + _, h, clock := snapLoopFixture(t, func(context.Context) error { calls.Add(1); return nil }) + back := clock.get().Add(-3 * 24 * time.Hour) + clock.set(back) + waitUntil(t, "the realigned slot", func() bool { + next := time.Unix(0, h.snapshots.status(clock.get()).NextDueNs) + return next.After(back) && next.Sub(back) <= 24*time.Hour + }) + if calls.Load() != 0 { + t.Fatal("a backward step triggered an attempt") + } + clock.set(time.Unix(0, h.snapshots.status(clock.get()).NextDueNs).Add(time.Second)) + waitUntil(t, "the attempt at the realigned slot", func() bool { return calls.Load() == 1 }) +} + +// Overdue follows the wall clock: a success recorded by the loop, then a +// wall step forwards past one period plus the retry cap, reads as overdue. +func TestScheduledSnapshotLoop_OverdueFollowsTheWallClock(t *testing.T) { + var calls atomic.Int64 + p, h, clock := snapLoopFixture(t, func(context.Context) error { calls.Add(1); return nil }) + clock.set(time.Unix(0, h.snapshots.status(clock.get()).NextDueNs)) + waitUntil(t, "the first success", func() bool { return h.snapshots.status(p.snapshotNow()).LastOkNs != 0 }) + clock.set(clock.get().Add(2 * 24 * time.Hour)) + if !h.snapshots.status(p.snapshotNow()).Overdue { + t.Fatal("two days after the last success on the wall clock, not overdue") + } +} + +// A re-armed loop (stopped and started again on the same handle, as after a +// refused detach) keeps the schedule: the failed attempt, its count and +// backoff survive. +func TestScheduledSnapshotLoop_RearmKeepsTheSchedule(t *testing.T) { + p, h, clock := snapLoopFixture(t, func(context.Context) error { return &SnapshotFailure{Code: "remote_unavailable"} }) + clock.set(time.Unix(0, h.snapshots.status(clock.get()).NextDueNs)) + waitUntil(t, "the failure", func() bool { return h.snapshots.status(clock.get()).Attempts == 1 }) + slot := h.snapshots + p.stopChunkLoop(h) + p.mu.Lock() + p.startChunkLoop("v1", h, h.chunk) + p.mu.Unlock() + if st := h.snapshots.status(clock.get()); h.snapshots != slot || st.Attempts != 1 || st.LastFailure == nil { + t.Fatalf("after re-arm: %+v (same schedule %v); want the failure kept", st, h.snapshots == slot) + } +} + +// INV-MAINT-JOIN for the scheduled-snapshot worker: stopping the loop +// cancels an attempt in flight and returns only after the attempt has +// returned. +func TestScheduledSnapshotLoop_StopJoinsTheAttempt(t *testing.T) { + entered, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + finish := func() { once.Do(func() { close(release) }) } + t.Cleanup(finish) + p, h, clock := snapLoopFixture(t, func(ctx context.Context) error { + close(entered) + <-ctx.Done() + <-release // returns only when the test allows it + return errors.New("stopped") + }) + clock.set(time.Unix(0, h.snapshots.status(clock.get()).NextDueNs)) + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("no attempt started") + } + stopped := make(chan struct{}) + go func() { p.stopChunkLoop(h); close(stopped) }() + select { + case <-stopped: + t.Fatal("stop returned while the attempt was still running") + case <-time.After(100 * time.Millisecond): + } + finish() + select { + case <-stopped: + case <-time.After(5 * time.Second): + t.Fatal("stop did not return after the attempt") + } +} + +// The production clock carries no monotonic reading, so durations and +// overdue between its readings follow wall-clock steps. +func TestScheduledSnapshotWallClockHasNoMonotonicReading(t *testing.T) { + now := snapshotWallNow() + if now != now.Round(0) { + t.Fatalf("snapshotWallNow %v carries a monotonic reading", now) + } + if p := (&DurableProvider{}); p.snapshotNow() != p.snapshotNow().Round(0) { + t.Fatal("the provider's snapshot clock carries a monotonic reading") + } +} diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go index 150113db64..da0e34f717 100644 --- a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go @@ -18,6 +18,23 @@ const ( snapshotRetryMax = time.Hour ) +// snapshotWake bounds how long the loop sleeps before it reads the wall +// clock again, so a wall-clock step is observed within it. +var snapshotWake = time.Minute + +// snapshotWallNow is the wall clock the schedule runs on, without the +// monotonic reading: slots, durations and overdue all follow wall-clock +// steps. +func snapshotWallNow() time.Time { return time.Now().Round(0) } + +// snapshotNow is the provider's scheduled-snapshot clock. +func (p *DurableProvider) snapshotNow() time.Time { + if p.testSnapshotClock != nil { + return p.testSnapshotClock() + } + return snapshotWallNow() +} + // SnapshotSkipRestoring is the skip reason of a volume still fetching the // chunks its HEAD names (a restore's hydration). const SnapshotSkipRestoring = "restoring" @@ -111,6 +128,14 @@ func (s *snapshotSchedule) slotAfter(t time.Time) time.Time { // due returns when the next attempt is due. func (s *snapshotSchedule) due() time.Time { return s.next } +// align moves the next attempt to the first slot after now when a wall +// clock step backwards left it further away than any slot or retry. +func (s *snapshotSchedule) align(now time.Time) { + if s.next.Sub(now) > s.period+snapshotRetryMax { + s.next = s.slotAfter(now) + } +} + // record records the outcome of an attempt made at now: nil is a // success (the next attempt is the next slot); a *SnapshotSkip is counted // by reason and retried after the backoff cap; any other error is a @@ -189,9 +214,11 @@ func (sl *snapshotSlot) status(now time.Time) ScheduledSnapshotStatus { return sl.s.status(now) } -func (sl *snapshotSlot) due() time.Time { +// alignedDue aligns the schedule to now and returns its due time. +func (sl *snapshotSlot) alignedDue(now time.Time) time.Time { sl.mu.Lock() defer sl.mu.Unlock() + sl.s.align(now) return sl.s.due() } @@ -202,11 +229,18 @@ func (sl *snapshotSlot) record(now time.Time, err error) { } // chunkSnapshotLoop takes volumeID's scheduled snapshots while the -// attachment is current. Each attempt is one bounded pass: one urgent cut -// and the snapshot record. An attempt cut short by the loop's own end is -// not recorded. +// attachment is current. It sleeps at most snapshotWake at a time and +// compares the wall clock with the due time on each wake, so wall-clock +// steps are observed. A restoring volume is skipped. Each attempt is one +// bounded pass: one urgent cut and the snapshot record. An attempt cut +// short by the loop's own end is not recorded. chunkBackground joins it +// with its other workers (INV-MAINT-JOIN). func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, slot *snapshotSlot) { - timer := time.NewTimer(time.Until(slot.due())) + sleep := func() time.Duration { + now := p.snapshotNow() + return min(max(slot.alignedDue(now).Sub(now), 0), snapshotWake) + } + timer := time.NewTimer(sleep()) defer timer.Stop() timeout := 2 * p.cfg.ChunkCutTimeout if timeout <= 0 { @@ -225,7 +259,11 @@ func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string if ctx.Err() != nil || layer.Fenced() || !current() { return } - at := time.Now() + at := p.snapshotNow() + if at.Before(slot.alignedDue(at)) { + timer.Reset(sleep()) + continue + } var err error if layer.Stats().AbsentChunks > 0 { // Restoring: HEAD names chunks this volume has not fetched yet. @@ -238,10 +276,11 @@ func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string if ctx.Err() != nil { return } - slot.record(time.Now(), err) + now := p.snapshotNow() + slot.record(now, err) if err != nil { - log.Printf("durable: scheduled snapshot volume=%s: %v (next attempt %s)", volumeID, err, slot.due().UTC().Format(time.RFC3339)) + log.Printf("durable: scheduled snapshot volume=%s: %v (next attempt %s)", volumeID, err, slot.alignedDue(now).UTC().Format(time.RFC3339)) } - timer.Reset(time.Until(slot.due())) + timer.Reset(sleep()) } } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index f004ad80f4..2012edef19 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -231,6 +231,9 @@ type DurableProvider struct { // testAfterChunkResolve, test-only, runs in CutVolume right after the // volume's handle and layer are resolved. testAfterChunkResolve func() + // testSnapshotClock, test-only, replaces the scheduled-snapshot wall + // clock (snapshotWallNow). + testSnapshotClock func() time.Time // testDetachStopIO, test-only, replaces DetachVolume's StopIO call (so a // test can force the failed-drain branch); testDetachTrace, test-only, // observes the detach's stages and their deadlines ("cut", "settle"). @@ -613,7 +616,7 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus { cs.HostBudget = budget.Snapshot() } if cv.snapshots != nil { - ss := cv.snapshots.status(time.Now()) + ss := cv.snapshots.status(p.snapshotNow()) cs.ScheduledSnapshot = &ss } st.Chunk = cs diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 64431d4dcc..bd700e1de3 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -326,9 +326,12 @@ func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer st } loopCtx, cancel := context.WithCancel(context.Background()) h.chunkStop, h.chunkDone = cancel, make(chan struct{}) - h.snapshots = nil - if snapshotsOn { - h.snapshots = &snapshotSlot{s: newSnapshotSchedule(volumeID, p.cfg.ChunkSnapshotPeriod, time.Now())} + // A re-armed loop (for example after a refused detach) keeps the + // volume's schedule: its slots, retries and history. + if !snapshotsOn { + h.snapshots = nil + } else if h.snapshots == nil { + h.snapshots = &snapshotSlot{s: newSnapshotSchedule(volumeID, p.cfg.ChunkSnapshotPeriod, p.snapshotNow())} } lin := h.chunkLineage current := func() bool { return p.maintenanceCurrent(volumeID, h, layer, lin) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6cdcff09a5..40c14ce7af 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -289,7 +289,6 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | -| `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retention.go` `planRetention`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest` (`core/frontend/chunkstore/retention_test.go`) | — | ACTIVE | | name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | deleting | `DeleteSnapshot` or retention for this attempt, whatever forks or restores read it (no claim is read); the mark records its delete time and GC keeps the attempt rooted for its grace | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | | published | deleting (retention, class `scheduled`) | the snapshot is not among the newest K of class `scheduled` (K from the newest one's `swb.schedule.keep`, default 7); other classes are planned without it | `core/frontend/chunkstore/retention.go` `planRetention` | `INV-SNAP-SCHEDULED-KEEP-001` | @@ -569,7 +568,7 @@ Notes: | `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | | `INV-MAINT-ONE-OWNER` | Only the current attached handle with matching replica/epoch/endpoint admits maintenance; one attached volume admits at most one pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline`, `TestMaintenanceRejectsForeignLineageBeforeAdmission`, `TestMaintenanceSameHandleRearmsAfterJoinedStop` | `MaintenanceOwner` `OneOwner`, `CurrentHandleAtAdmission` | ACTIVE | | `INV-MAINT-SCOPE` | Per-volume GC traces foreign roots while restricting candidate reclamation, intent expiry and copy settlement to its volume; namespace coverage is not imported. | M8 scoped GC | `gc.go` `Collector.run`; `gc_copy.go` `SweepCopies`; `gc_execution.go` `ExecuteVolumeGC` | `TestVolumeGC_ForeignIntentRootsAndLocalCandidates`, `TestVolumeGC_DoesNotImportGlobalMark`, `TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected`, `TestVolumeGC_ForeignEligibleCopyIsNotSettled` | `ScopedMaintenanceGC` `ForeignRootSurvives`, `ForeignCandidatesUntouched`, `OwnCoverageOnly` | ACTIVE | -| `INV-MAINT-JOIN` | Detach/fence/Close cancels maintenance and joins admitted workers before releasing its catalog/storage lifetime. | M8 Running → Draining → Closed | `provider_chunk.go` `chunkBackground`, `stopChunkLoop` | `TestMaintenanceStopJoinsBeforeRelease`, `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenanceAuthorityLossCancelsHeldPass`, `TestMaintenanceHealthyLineageChangeCancelsHeldPass` | `MaintenanceOwner` `JoinedBeforeRelease` | ACTIVE | +| `INV-MAINT-JOIN` | Detach/fence/Close cancels maintenance and the scheduled-snapshot worker and joins admitted workers before releasing its catalog/storage lifetime. | M8 Running → Draining → Closed | `provider_chunk.go` `chunkBackground`, `stopChunkLoop` | `TestMaintenanceStopJoinsBeforeRelease`, `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenanceAuthorityLossCancelsHeldPass`, `TestMaintenanceHealthyLineageChangeCancelsHeldPass`, `TestScheduledSnapshotLoop_StopJoinsTheAttempt` | `MaintenanceOwner` `JoinedBeforeRelease` | ACTIVE | | `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. An owner-qualified ref roots the owner's key (load-bearing for forks and restores: a target's HEAD keeps the source's chunks live after the source snapshot and volume are gone). | M6 key: Bound → Tombstoned; M6 snapshot: published → fork \| restore | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`); `TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone` (`core/frontend/chunkstore/restore_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete`; `RestoreIndependence` `NoGap` | ACTIVE | | `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | | `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | @@ -578,6 +577,7 @@ Notes: | `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period is at least the catalog operation deadline plus the clock skew bound plus the CAS apply bound (default: the operation deadline). | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound` (`core/frontend/chunkstore/gc_volume_test.go`) | `RetentionGCTiming` `NoLiveDelete`; `ForkDelete` `NoGap` (G >= D + E + P) | ACTIVE | | `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_RetainSkipsASameNameReplacement` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | | `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` | ACTIVE | +| `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retention.go` `planRetention`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest`, `TestPlanRetention_PinnedScheduledStaysInItsClass` (`core/frontend/chunkstore/retention_test.go`) | — | ACTIVE | | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | From 5fe54fc1e13dc6ed23ded187d9c7ac544b823a07 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 05:08:23 -0800 Subject: [PATCH 06/34] durable: a scheduled-snapshot retry keeps its delay across a wall-clock step backwards Co-Authored-By: Claude Opus 5.5 --- .../durable/chunk_snapshot_schedule.go | 30 +++++++++++++------ .../durable/chunk_snapshot_schedule_test.go | 22 ++++++++++++++ 2 files changed, 43 insertions(+), 9 deletions(-) diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go index da0e34f717..62b3be580d 100644 --- a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go @@ -97,11 +97,15 @@ type ScheduledSnapshotStatus struct { // at a per-volume offset, not at a wall-clock hour. It is not safe for // concurrent use. type snapshotSchedule struct { - period time.Duration - offset time.Duration - started time.Time - lastOK time.Time - next time.Time + period time.Duration + offset time.Duration + started time.Time + lastOK time.Time + next time.Time + // setAt is when next was last set; retry says next is a retry + // (setAt plus a delay) rather than a slot. + setAt time.Time + retry bool failure *ScheduledSnapshotFailure attempts int skipped map[string]int64 @@ -110,7 +114,7 @@ type snapshotSchedule struct { // newSnapshotSchedule starts vol's schedule at now. func newSnapshotSchedule(vol string, period time.Duration, now time.Time) *snapshotSchedule { s := &snapshotSchedule{period: period, offset: hostlimit.Phase(vol+":snapshot", period), started: now, skipped: map[string]int64{}} - s.next = s.slotAfter(now) + s.next, s.setAt = s.slotAfter(now), now return s } @@ -128,12 +132,19 @@ func (s *snapshotSchedule) slotAfter(t time.Time) time.Time { // due returns when the next attempt is due. func (s *snapshotSchedule) due() time.Time { return s.next } -// align moves the next attempt to the first slot after now when a wall -// clock step backwards left it further away than any slot or retry. +// align handles a wall-clock step backwards (now earlier than when the +// next attempt was set): a retry keeps its delay, counted from now; a slot +// becomes the first slot after now. func (s *snapshotSchedule) align(now time.Time) { - if s.next.Sub(now) > s.period+snapshotRetryMax { + if !now.Before(s.setAt) { + return + } + if s.retry { + s.next = now.Add(s.next.Sub(s.setAt)) + } else { s.next = s.slotAfter(now) } + s.setAt = now } // record records the outcome of an attempt made at now: nil is a @@ -142,6 +153,7 @@ func (s *snapshotSchedule) align(now time.Time) { // failure, recorded with its code, and retried with a doubling backoff. func (s *snapshotSchedule) record(now time.Time, err error) { var skip *SnapshotSkip + s.setAt, s.retry = now, err != nil switch { case err == nil: s.lastOK, s.failure, s.attempts = now, nil, 0 diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go index 0f95deef2d..e2930c363c 100644 --- a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go @@ -138,3 +138,25 @@ func TestSnapshotSchedule_ClockStepsNeitherRepeatNorStall(t *testing.T) { t.Fatal("a clock step forwards past a period plus the retry cap with no success is not overdue") } } + +// A retry keeps its own delay across a wall-clock step backwards: a 1 min +// retry set before a 3 h step back is due 1 min after the stepped now, not +// 3 h 1 min later; a slot set before the step becomes the first slot after +// the stepped now. +func TestSnapshotSchedule_BackwardStepKeepsTheRetryDelay(t *testing.T) { + day := 24 * time.Hour + s := newSnapshotSchedule("v1", day, schedT0) + at := s.due() + s.record(at, &SnapshotFailure{Code: "remote_unavailable"}) // retry in 1 min + back := at.Add(-3 * time.Hour) + s.align(back) + if got := s.due().Sub(back); got != time.Minute { + t.Fatalf("retry after a 3 h step back is due %v after the stepped now; want 1m", got) + } + s.record(s.due(), nil) // success: the next slot + back2 := s.due().Add(-2 * day) + s.align(back2) + if due := s.due(); !due.After(back2) || due.Sub(back2) > day || time.Duration(due.UnixNano()%int64(day)) != s.offset { + t.Fatalf("slot after a 2 day step back: %v for now %v; want the first per-volume slot after now", due, back2) + } +} From a600bb8e2b713e24c9f897fe18dfddae5b025a34 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 06:19:13 -0800 Subject: [PATCH 07/34] rpc/link: one dial helper and one server builder for every gRPC link core/rpc/link builds every gRPC link: Dial is grpc.NewClient with plaintext credentials exactly as before (caller options follow), NewServer runs the caller's unary and stream interceptors in order (none by default). Every production site now goes through it: nine dials to blockmaster, the two SeaweedFS dials and both servers; the failback runtime keeps its injected dial options unchanged. No behaviour change. INV-SEC-ONE-SEAM-001: a guard test fails if a non-test file outside the package creates insecure credentials or a raw gRPC server (red on the base: it lists the 12 files with the 13 raw sites). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockcsi/main.go | 6 +- .../cmd/blockvolume/chunk_maintenance.go | 5 +- seaweed-block/cmd/sw-block/chunk_gc.go | 5 +- .../cmd/sw-block/chunk_volume_delete.go | 5 +- seaweed-block/cmd/sw-block/main.go | 5 +- .../core/frontend/chunkstore/single_filer.go | 4 +- .../core/frontend/chunkstore/swfs.go | 5 +- seaweed-block/core/host/master/host.go | 3 +- seaweed-block/core/host/volume/host.go | 4 +- .../core/ops/failback_runtime_grpc.go | 14 +- seaweed-block/core/ops/live_sources.go | 5 +- seaweed-block/core/rpc/link/link.go | 40 +++++ seaweed-block/core/rpc/link/link_test.go | 149 ++++++++++++++++++ seaweed-block/core/rpc/wsclient/wsclient.go | 4 +- seaweed-block/docs/design/invariants.md | 8 +- 15 files changed, 228 insertions(+), 34 deletions(-) create mode 100644 seaweed-block/core/rpc/link/link.go create mode 100644 seaweed-block/core/rpc/link/link_test.go diff --git a/seaweed-block/cmd/blockcsi/main.go b/seaweed-block/cmd/blockcsi/main.go index 1a61166f0b..4229e19743 100644 --- a/seaweed-block/cmd/blockcsi/main.go +++ b/seaweed-block/cmd/blockcsi/main.go @@ -21,7 +21,7 @@ import ( control "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/internal/buildinfo" "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" + "github.com/seaweedfs/seaweed-block/core/rpc/link" ) type flags struct { @@ -127,7 +127,7 @@ func run(f flags) int { registrar blockcsi.VolumeObjectRegistrar ) if f.masterAddr != "" { - masterConn, err = grpc.NewClient(f.masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + masterConn, err = link.Dial(f.masterAddr) if err != nil { fmt.Fprintln(os.Stderr, "blockcsi: master dial:", err) return 1 @@ -167,7 +167,7 @@ func run(f flags) int { nodeSrv.StartMountedNVMeReconnectOwner(reconnectCtx, f.nvmeReconnectInterval) } - srv := grpc.NewServer() + srv := link.NewServer(link.ServerConfig{}) csipb.RegisterIdentityServer(srv, blockcsi.NewIdentityServer()) csipb.RegisterControllerServer(srv, blockcsi.NewControllerServerWithProvisionerMetadataAndRegistrar(lookup, provisioner, resolver, registrar)) csipb.RegisterNodeServer(srv, nodeSrv) diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance.go b/seaweed-block/cmd/blockvolume/chunk_maintenance.go index 023a76c2f8..943619d0dd 100644 --- a/seaweed-block/cmd/blockvolume/chunk_maintenance.go +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance.go @@ -8,8 +8,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/rpc/control" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" + "github.com/seaweedfs/seaweed-block/core/rpc/link" ) // Automatic GC stays default-off until restart-safe unknown-CAS settlement and @@ -27,7 +26,7 @@ func newChunkMaintenance(cat *chunkstore.Catalog, blobs chunkstore.BlobDeleter, if defaultChunkGCGrace <= max(defaultChunkCutTimeout, chunkstore.DefaultOpDeadline)+defaultChunkMaintenanceTimeout { return nil, closeFn, errors.New("automatic GC grace does not cover cut/copy and mark bounds") } - conn, err := grpc.NewClient(master, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := link.Dial(master) if err != nil { return nil, closeFn, err } diff --git a/seaweed-block/cmd/sw-block/chunk_gc.go b/seaweed-block/cmd/sw-block/chunk_gc.go index fb46e3bc85..a354999357 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc.go +++ b/seaweed-block/cmd/sw-block/chunk_gc.go @@ -10,8 +10,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/ops" "github.com/seaweedfs/seaweed-block/core/rpc/control" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" + "github.com/seaweedfs/seaweed-block/core/rpc/link" ) // Same clock seam as GCConfig; production always uses wall time. Tests can @@ -78,7 +77,7 @@ func chunkGC(args []string, stdout, stderr io.Writer) int { // masterEvidence dials the blockmaster's evidence service (gc and // volume-delete read volume status from it). func masterEvidence(master string) (control.EvidenceServiceClient, func() error, error) { - conn, e := grpc.NewClient(master, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, e := link.Dial(master) if e != nil { return nil, nil, e } diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete.go b/seaweed-block/cmd/sw-block/chunk_volume_delete.go index 0413f1709f..72645a1186 100644 --- a/seaweed-block/cmd/sw-block/chunk_volume_delete.go +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete.go @@ -8,14 +8,13 @@ import ( "io" "time" - "google.golang.org/grpc" "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/status" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/ops" "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" ) // chunkVolumeDelete: sw-block ops chunk volume-delete --chunk-filer @@ -51,7 +50,7 @@ func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int { return exit } defer closeFn() - conn, err := grpc.NewClient(master, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := link.Dial(master) if err != nil { return chunkResult("volume-delete", nil, err, stdout, stderr) } diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index 06f94c6ee8..ecdb38e128 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -17,9 +17,8 @@ import ( "github.com/seaweedfs/seaweed-block/core/ops" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" "github.com/seaweedfs/seaweed-block/internal/buildinfo" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" "gopkg.in/yaml.v3" ) @@ -1158,7 +1157,7 @@ func liveNodeEvidenceNamespace(namespace string) string { } func readMasterClusterEvidence(ctx context.Context, masterAddr string) (ops.ClusterEvidence, error) { - conn, err := grpc.NewClient(masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := link.Dial(masterAddr) if err != nil { return ops.ClusterEvidence{}, err } diff --git a/seaweed-block/core/frontend/chunkstore/single_filer.go b/seaweed-block/core/frontend/chunkstore/single_filer.go index 7d21789c8e..121a5975e0 100644 --- a/seaweed-block/core/frontend/chunkstore/single_filer.go +++ b/seaweed-block/core/frontend/chunkstore/single_filer.go @@ -11,10 +11,10 @@ import ( "time" "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb" + "github.com/seaweedfs/seaweed-block/core/rpc/link" ) // ErrNotSingleFiler: block metadata needs exactly one filer behind the @@ -147,7 +147,7 @@ func (c *SWFS) isTarget(ctx context.Context, listed string) bool { } func listFilers(ctx context.Context, addr, group string) ([]string, error) { - conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := link.Dial(addr) if err != nil { return nil, err } diff --git a/seaweed-block/core/frontend/chunkstore/swfs.go b/seaweed-block/core/frontend/chunkstore/swfs.go index a126d1a998..f7ff0e0d8c 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs.go +++ b/seaweed-block/core/frontend/chunkstore/swfs.go @@ -12,10 +12,10 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/status" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/rpc/link" ) // SWFSConfig configures the minimal SeaweedFS client. @@ -56,8 +56,7 @@ func DialSWFS(cfg SWFSConfig) (*SWFS, error) { if cfg.HTTPTimeout == 0 { cfg.HTTPTimeout = 60 * time.Second } - conn, err := grpc.NewClient(cfg.FilerGRPC, - grpc.WithTransportCredentials(insecure.NewCredentials()), + conn, err := link.Dial(cfg.FilerGRPC, grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(64<<20), grpc.MaxCallSendMsgSize(64<<20))) if err != nil { return nil, fmt.Errorf("chunkstore: dial filer %s: %w", cfg.FilerGRPC, err) diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 92063b83cb..6b19c836e0 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -31,6 +31,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/host/bootstrap" "github.com/seaweedfs/seaweed-block/core/lifecycle" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" "github.com/seaweedfs/seaweed-block/core/storeident" "google.golang.org/grpc" ) @@ -319,7 +320,7 @@ func New(cfg Config) (*Host, error) { WriteTimeout: statusWriteTimeout, IdleTimeout: statusIdleTimeout} } - grpcSrv := grpc.NewServer() + grpcSrv := link.NewServer(link.ServerConfig{}) svc := newServices(h) control.RegisterObservationServiceServer(grpcSrv, svc) control.RegisterAssignmentServiceServer(grpcSrv, svc) diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 0dbe35410c..920ac49717 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -15,9 +15,9 @@ import ( "github.com/seaweedfs/seaweed-block/core/engine" "github.com/seaweedfs/seaweed-block/core/replication" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" "github.com/seaweedfs/seaweed-block/core/storeident" "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -259,7 +259,7 @@ func New(cfg Config) (*Host, error) { lg = log.Default() } - conn, err := grpc.NewClient(cfg.MasterAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := link.Dial(cfg.MasterAddr) if err != nil { return nil, fmt.Errorf("volume.New: dial master %q: %w", cfg.MasterAddr, err) } diff --git a/seaweed-block/core/ops/failback_runtime_grpc.go b/seaweed-block/core/ops/failback_runtime_grpc.go index 0b50989d33..5e3ef3be48 100644 --- a/seaweed-block/core/ops/failback_runtime_grpc.go +++ b/seaweed-block/core/ops/failback_runtime_grpc.go @@ -5,8 +5,8 @@ import ( "fmt" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" ) type GRPCFailbackRuntime struct { @@ -22,11 +22,15 @@ func (r *GRPCFailbackRuntime) ExecuteFailback(ctx context.Context, req FailbackR if r == nil || r.Addr == "" { return FailbackRuntimeResult{}, fmt.Errorf("failback runtime gRPC address is required") } - opts := append([]grpc.DialOption(nil), r.Opts...) - if len(opts) == 0 { - opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials())) + // Injected options replace the default link (as before); none means the + // standard link. + dial := link.Dial + if len(r.Opts) > 0 { + dial = func(target string, _ ...grpc.DialOption) (*grpc.ClientConn, error) { + return grpc.NewClient(target, r.Opts...) + } } - conn, err := grpc.NewClient(r.Addr, opts...) + conn, err := dial(r.Addr) if err != nil { return FailbackRuntimeResult{}, err } diff --git a/seaweed-block/core/ops/live_sources.go b/seaweed-block/core/ops/live_sources.go index 11241e9c32..36ba994c57 100644 --- a/seaweed-block/core/ops/live_sources.go +++ b/seaweed-block/core/ops/live_sources.go @@ -18,8 +18,7 @@ import ( hostvolume "github.com/seaweedfs/seaweed-block/core/host/volume" "github.com/seaweedfs/seaweed-block/core/replication" "github.com/seaweedfs/seaweed-block/core/rpc/control" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" + "github.com/seaweedfs/seaweed-block/core/rpc/link" ) type LiveVolumeStatusConfig struct { @@ -95,7 +94,7 @@ func NewLiveVolumeStatusReportCollector(cfg LiveVolumeStatusConfig) VolumeStatus } func queryLiveMasterStatus(ctx context.Context, masterAddr, volumeID string) (*control.StatusResponse, error) { - conn, err := grpc.NewClient(masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := link.Dial(masterAddr) if err != nil { return nil, fmt.Errorf("dial master: %w", err) } diff --git a/seaweed-block/core/rpc/link/link.go b/seaweed-block/core/rpc/link/link.go new file mode 100644 index 0000000000..ab669da136 --- /dev/null +++ b/seaweed-block/core/rpc/link/link.go @@ -0,0 +1,40 @@ +// Package link builds every gRPC link between seaweed-block processes and to +// SeaweedFS: one dial helper and one server builder, so transport security +// and call authorization have a single place to be added. Today a link is +// plaintext, exactly as before this package existed, and a server runs only +// the interceptors its caller passes (none by default). +package link + +import ( + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +// Dial opens a lazy client connection to target with plaintext transport +// credentials; opts follow (a later option overrides an earlier one). +func Dial(target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) { + all := make([]grpc.DialOption, 0, len(opts)+1) + all = append(all, grpc.WithTransportCredentials(insecure.NewCredentials())) + all = append(all, opts...) + return grpc.NewClient(target, all...) +} + +// ServerConfig is a server's interceptor chain; the zero value has none. +type ServerConfig struct { + Unary []grpc.UnaryServerInterceptor + Stream []grpc.StreamServerInterceptor +} + +// NewServer builds a gRPC server whose calls pass through cfg's interceptors, +// in order; opts follow. +func NewServer(cfg ServerConfig, opts ...grpc.ServerOption) *grpc.Server { + all := make([]grpc.ServerOption, 0, len(opts)+2) + if len(cfg.Unary) > 0 { + all = append(all, grpc.ChainUnaryInterceptor(cfg.Unary...)) + } + if len(cfg.Stream) > 0 { + all = append(all, grpc.ChainStreamInterceptor(cfg.Stream...)) + } + all = append(all, opts...) + return grpc.NewServer(all...) +} diff --git a/seaweed-block/core/rpc/link/link_test.go b/seaweed-block/core/rpc/link/link_test.go new file mode 100644 index 0000000000..dfeb961ec3 --- /dev/null +++ b/seaweed-block/core/rpc/link/link_test.go @@ -0,0 +1,149 @@ +package link + +import ( + "context" + "io/fs" + "net" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/health" + healthpb "google.golang.org/grpc/health/grpc_health_v1" +) + +func serve(t *testing.T, cfg ServerConfig) string { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := NewServer(cfg) + healthpb.RegisterHealthServer(srv, health.NewServer()) + done := make(chan struct{}) + go func() { _ = srv.Serve(lis); close(done) }() + t.Cleanup(func() { + srv.Stop() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("server did not stop") + } + }) + return lis.Addr().String() +} + +// A link dialed with Dial reaches a server built with NewServer, for a unary +// and a streaming call, as plaintext gRPC did before the seam. +func TestLink_DialReachesNewServerUnaryAndStream(t *testing.T) { + addr := serve(t, ServerConfig{}) + conn, err := Dial(addr) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + c := healthpb.NewHealthClient(conn) + if r, err := c.Check(ctx, &healthpb.HealthCheckRequest{}); err != nil || r.Status != healthpb.HealthCheckResponse_SERVING { + t.Fatalf("unary call: %v %v", r, err) + } + w, err := c.Watch(ctx, &healthpb.HealthCheckRequest{}) + if err != nil { + t.Fatal(err) + } + if r, err := w.Recv(); err != nil || r.Status != healthpb.HealthCheckResponse_SERVING { + t.Fatalf("stream call: %v %v", r, err) + } +} + +// The server runs its unary and stream interceptors in the configured order. +func TestLink_ServerRunsInterceptorsInOrder(t *testing.T) { + var mu sync.Mutex + var seen []string + note := func(s string) { mu.Lock(); seen = append(seen, s); mu.Unlock() } + unary := func(name string) grpc.UnaryServerInterceptor { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, h grpc.UnaryHandler) (any, error) { + note(name) + return h(ctx, req) + } + } + stream := func(name string) grpc.StreamServerInterceptor { + return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, h grpc.StreamHandler) error { + note(name) + return h(srv, ss) + } + } + addr := serve(t, ServerConfig{Unary: []grpc.UnaryServerInterceptor{unary("u1"), unary("u2")}, Stream: []grpc.StreamServerInterceptor{stream("s1"), stream("s2")}}) + conn, err := Dial(addr) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + c := healthpb.NewHealthClient(conn) + if _, err := c.Check(ctx, &healthpb.HealthCheckRequest{}); err != nil { + t.Fatal(err) + } + w, err := c.Watch(ctx, &healthpb.HealthCheckRequest{}) + if err != nil { + t.Fatal(err) + } + if _, err := w.Recv(); err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + if got := strings.Join(seen, ","); got != "u1,u2,s1,s2" { + t.Fatalf("interceptors ran as %q, want u1,u2,s1,s2", got) + } +} + +// Every production gRPC link goes through this package: no other non-test Go +// file builds plaintext credentials or a gRPC server directly. +func TestLink_NoProductionSiteBypassesTheSeam(t *testing.T) { + root, err := filepath.Abs(filepath.Join("..", "..", "..")) + if err != nil { + t.Fatal(err) + } + self, err := filepath.Abs(".") + if err != nil { + t.Fatal(err) + } + var bad []string + err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if name := d.Name(); name == ".git" || name == "vendor" || name == "testdata" || p == self { + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { + return nil + } + b, err := os.ReadFile(p) + if err != nil { + return err + } + src := string(b) + if strings.Contains(src, "insecure.NewCredentials(") || strings.Contains(src, "grpc.NewServer(") { + rel, _ := filepath.Rel(root, p) + bad = append(bad, rel) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if len(bad) > 0 { + t.Fatalf("gRPC links built outside core/rpc/link (use link.Dial / link.NewServer): %v", bad) + } +} diff --git a/seaweed-block/core/rpc/wsclient/wsclient.go b/seaweed-block/core/rpc/wsclient/wsclient.go index 14370cfc09..ec8c868973 100644 --- a/seaweed-block/core/rpc/wsclient/wsclient.go +++ b/seaweed-block/core/rpc/wsclient/wsclient.go @@ -17,9 +17,9 @@ import ( "time" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" "google.golang.org/grpc" "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/status" ) @@ -124,7 +124,7 @@ func New(rpc control.WorkspaceServiceClient) *Client { return &Client{rpc: rpc} // Dial connects to the blockmaster gRPC address (plaintext, as the other // operator commands). func Dial(addr string) (*Client, error) { - conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := link.Dial(addr) if err != nil { return nil, err } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0c69765881..998e3f1168 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -382,7 +382,7 @@ with a separate scope/config-bound mark. Incomplete marks carry no coverage. ## Part B. Invariant ledger -136 rows: 116 ACTIVE, 17 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 121 new. +137 rows: 117 ACTIVE, 17 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 122 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. @@ -633,6 +633,12 @@ Notes: |---|---|---|---|---|---|---| | `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | +### B.9 Security: gRPC links + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-SEC-ONE-SEAM-001` | Every production gRPC client and server is built by core/rpc/link; a non-test file outside it that creates insecure credentials or a raw grpc server fails the guard test. | AUTHORITY: every gRPC link (client dial, server build) | `core/rpc/link` `Dial`, `NewServer` | `TestLink_NoProductionSiteBypassesTheSeam`, `TestLink_DialReachesNewServerUnaryAndStream`, `TestLink_ServerRunsInterceptorsInOrder` (`core/rpc/link/link_test.go`) | — (no state machine; the guard test is the proof form) | ACTIVE | + ### Experimental data-file synchronization | ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status | From 7fff8f288ea40473f85455ab4a23e1195eb17e84 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 06:38:41 -0800 Subject: [PATCH 08/34] fold: injected failback dial through link.DialWith; AST guard covers raw client constructors and import aliases - link.DialWith(target, opts...) builds a link with exactly the caller's options (no default credentials); the failback runtime uses it for injected options, so its prior semantics hold and no production file calls grpc.NewClient directly. - The guard parses every non-test file and finds grpc.NewClient / Dial / DialContext / NewServer and insecure.NewCredentials under any import name (alias or dot import); a detector test proves each form is found and a link-only file is clean; routing failback back to grpc.NewClient fails the guard. Co-Authored-By: Claude Opus 5.5 --- .../core/ops/failback_runtime_grpc.go | 10 +- seaweed-block/core/rpc/link/link.go | 7 + seaweed-block/core/rpc/link/link_test.go | 132 +++++++++++++++++- seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 139 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/ops/failback_runtime_grpc.go b/seaweed-block/core/ops/failback_runtime_grpc.go index 5e3ef3be48..d104e13b83 100644 --- a/seaweed-block/core/ops/failback_runtime_grpc.go +++ b/seaweed-block/core/ops/failback_runtime_grpc.go @@ -24,13 +24,13 @@ func (r *GRPCFailbackRuntime) ExecuteFailback(ctx context.Context, req FailbackR } // Injected options replace the default link (as before); none means the // standard link. - dial := link.Dial + var conn *grpc.ClientConn + var err error if len(r.Opts) > 0 { - dial = func(target string, _ ...grpc.DialOption) (*grpc.ClientConn, error) { - return grpc.NewClient(target, r.Opts...) - } + conn, err = link.DialWith(r.Addr, r.Opts...) + } else { + conn, err = link.Dial(r.Addr) } - conn, err := dial(r.Addr) if err != nil { return FailbackRuntimeResult{}, err } diff --git a/seaweed-block/core/rpc/link/link.go b/seaweed-block/core/rpc/link/link.go index ab669da136..b67617a799 100644 --- a/seaweed-block/core/rpc/link/link.go +++ b/seaweed-block/core/rpc/link/link.go @@ -19,6 +19,13 @@ func Dial(target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) { return grpc.NewClient(target, all...) } +// DialWith opens a lazy client connection to target with exactly opts: the +// caller supplies the transport credentials (no default is added). It is the +// one place a link with caller-chosen options is built. +func DialWith(target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) { + return grpc.NewClient(target, opts...) +} + // ServerConfig is a server's interceptor chain; the zero value has none. type ServerConfig struct { Unary []grpc.UnaryServerInterceptor diff --git a/seaweed-block/core/rpc/link/link_test.go b/seaweed-block/core/rpc/link/link_test.go index dfeb961ec3..1ad13d99e2 100644 --- a/seaweed-block/core/rpc/link/link_test.go +++ b/seaweed-block/core/rpc/link/link_test.go @@ -2,10 +2,15 @@ package link import ( "context" + "fmt" + "go/ast" + "go/parser" + "go/token" "io/fs" "net" "os" "path/filepath" + "strconv" "strings" "sync" "testing" @@ -104,8 +109,120 @@ func TestLink_ServerRunsInterceptorsInOrder(t *testing.T) { } } +// rawLinkCalls lists the gRPC link constructions in one Go source that +// bypass this package: a client (grpc.NewClient, grpc.Dial, grpc.DialContext), +// a server (grpc.NewServer) or plaintext credentials (insecure.NewCredentials), +// whatever local name the import has (aliases and dot imports included). +func rawLinkCalls(name string, src []byte) ([]string, error) { + fset := token.NewFileSet() + f, err := parser.ParseFile(fset, name, src, parser.SkipObjectResolution) + if err != nil { + return nil, err + } + banned := map[string]map[string]bool{ + "google.golang.org/grpc": {"NewClient": true, "Dial": true, "DialContext": true, "NewServer": true}, + "google.golang.org/grpc/credentials/insecure": {"NewCredentials": true}, + } + local := map[string]map[string]bool{} // import name -> banned functions + dot := map[string]bool{} // banned functions reachable unqualified + for _, im := range f.Imports { + path, _ := strconv.Unquote(im.Path.Value) + fns, ok := banned[path] + if !ok { + continue + } + name := filepath.Base(path) + if im.Name != nil { + name = im.Name.Name + } + switch name { + case "_": + case ".": + for fn := range fns { + dot[fn] = true + } + default: + local[name] = fns + } + } + var found []string + ast.Inspect(f, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + switch fun := call.Fun.(type) { + case *ast.SelectorExpr: + if x, ok := fun.X.(*ast.Ident); ok && local[x.Name][fun.Sel.Name] { + found = append(found, fmt.Sprintf("%s: %s.%s", fset.Position(call.Pos()), x.Name, fun.Sel.Name)) + } + case *ast.Ident: + if dot[fun.Name] { + found = append(found, fmt.Sprintf("%s: %s", fset.Position(call.Pos()), fun.Name)) + } + } + return true + }) + return found, nil +} + +// The detector finds every form of a raw construction, and nothing in a file +// that only uses this package. +func TestLink_GuardDetectsRawConstructionsAndAliases(t *testing.T) { + cases := map[string]string{ + "client": `package p +import "google.golang.org/grpc" +func f() { grpc.NewClient("x") } +`, + "dial": `package p +import "google.golang.org/grpc" +func f() { grpc.Dial("x") } +`, + "dialContext": `package p +import "google.golang.org/grpc" +func f() { grpc.DialContext(nil, "x") } +`, + "server": `package p +import "google.golang.org/grpc" +func f() { grpc.NewServer() } +`, + "aliasClient": `package p +import g "google.golang.org/grpc" +func f() { g.NewClient("x") } +`, + "aliasCreds": `package p +import ins "google.golang.org/grpc/credentials/insecure" +func f() { ins.NewCredentials() } +`, + "dotImport": `package p +import . "google.golang.org/grpc" +func f() { NewServer() } +`, + "plainCredsFn": `package p +import "google.golang.org/grpc/credentials/insecure" +func f() { insecure.NewCredentials() } +`, + } + for name, src := range cases { + got, err := rawLinkCalls(name+".go", []byte(src)) + if err != nil || len(got) != 1 { + t.Errorf("%s: found %v (%v), want exactly one raw construction", name, got, err) + } + } + clean := `package p +import ( + "google.golang.org/grpc" + "github.com/seaweedfs/seaweed-block/core/rpc/link" +) +func f() { link.Dial("x", grpc.WithBlock()) } +` + if got, err := rawLinkCalls("clean.go", []byte(clean)); err != nil || len(got) != 0 { + t.Errorf("clean: found %v (%v), want none", got, err) + } +} + // Every production gRPC link goes through this package: no other non-test Go -// file builds plaintext credentials or a gRPC server directly. +// file constructs a gRPC client or server or plaintext credentials directly. func TestLink_NoProductionSiteBypassesTheSeam(t *testing.T) { root, err := filepath.Abs(filepath.Join("..", "..", "..")) if err != nil { @@ -129,14 +246,17 @@ func TestLink_NoProductionSiteBypassesTheSeam(t *testing.T) { if !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { return nil } - b, err := os.ReadFile(p) + src, err := os.ReadFile(p) if err != nil { return err } - src := string(b) - if strings.Contains(src, "insecure.NewCredentials(") || strings.Contains(src, "grpc.NewServer(") { + found, err := rawLinkCalls(p, src) + if err != nil { + return err + } + for _, f := range found { rel, _ := filepath.Rel(root, p) - bad = append(bad, rel) + bad = append(bad, rel+" ("+f[strings.LastIndex(f, ": ")+2:]+")") } return nil }) @@ -144,6 +264,6 @@ func TestLink_NoProductionSiteBypassesTheSeam(t *testing.T) { t.Fatal(err) } if len(bad) > 0 { - t.Fatalf("gRPC links built outside core/rpc/link (use link.Dial / link.NewServer): %v", bad) + t.Fatalf("gRPC links built outside core/rpc/link (use link.Dial, link.DialWith or link.NewServer): %v", bad) } } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 998e3f1168..95b60eca56 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -637,7 +637,7 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-SEC-ONE-SEAM-001` | Every production gRPC client and server is built by core/rpc/link; a non-test file outside it that creates insecure credentials or a raw grpc server fails the guard test. | AUTHORITY: every gRPC link (client dial, server build) | `core/rpc/link` `Dial`, `NewServer` | `TestLink_NoProductionSiteBypassesTheSeam`, `TestLink_DialReachesNewServerUnaryAndStream`, `TestLink_ServerRunsInterceptorsInOrder` (`core/rpc/link/link_test.go`) | — (no state machine; the guard test is the proof form) | ACTIVE | +| `INV-SEC-ONE-SEAM-001` | Every production gRPC client and server is built by core/rpc/link; a non-test file outside it that constructs a gRPC client or server or insecure credentials, under any import name, fails the guard test. | AUTHORITY: every gRPC link (client dial, server build) | `core/rpc/link` `Dial`, `DialWith`, `NewServer` | `TestLink_NoProductionSiteBypassesTheSeam`, `TestLink_GuardDetectsRawConstructionsAndAliases`, `TestLink_DialReachesNewServerUnaryAndStream`, `TestLink_ServerRunsInterceptorsInOrder` (`core/rpc/link/link_test.go`) | — (no state machine; the guard test is the proof form) | ACTIVE | ### Experimental data-file synchronization From f30d91fec54569963f79381a1fffd2196a2e6ee0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 06:38:49 -0800 Subject: [PATCH 09/34] test(authority): expose uncertain move refusal precedence --- .../workspace_outcome_uncertain_test.go | 50 +++++++++++ .../workspace_uncertain_precedence_test.go | 84 +++++++++++++++++++ 2 files changed, 134 insertions(+) create mode 100644 seaweed-block/core/host/master/workspace_uncertain_precedence_test.go diff --git a/seaweed-block/core/authority/workspace_outcome_uncertain_test.go b/seaweed-block/core/authority/workspace_outcome_uncertain_test.go index aab5f3ec8e..e6fb4d8ba5 100644 --- a/seaweed-block/core/authority/workspace_outcome_uncertain_test.go +++ b/seaweed-block/core/authority/workspace_outcome_uncertain_test.go @@ -3,6 +3,7 @@ package authority import ( "context" "errors" + "reflect" "testing" "time" ) @@ -67,3 +68,52 @@ func TestWorkspaceUncertainIssueWriteIsTyped(t *testing.T) { t.Fatalf("readout after reload: %+v %v", got, err) } } + +func TestWorkspaceUncertaintyPrecedesRequestRefusal(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + p, _, _ := forcedLostRangeFixture(t, disk, false) + bad := forcedLostRangeReq + bad.TargetReplicaID = "other-slot" + if _, err := p.MoveWorkspace(ctx, bad, forcedLostRangeHead); err == nil || errors.Is(err, ErrWorkspaceOutcomeUncertain) { + t.Fatalf("healthy refusal changed: %v", err) + } + faults := 0 + SetPutAfterRenameFaultForTest(func(r DurableRecord) error { + if r.Workspace != nil && r.Workspace.Lease != nil && r.Workspace.Lease.Revoking { + faults++ + return errInjected + } + return nil + }) + t.Cleanup(func() { SetPutAfterRenameFaultForTest(nil) }) + if err := p.BeginWorkspaceRevocation(ctx, "v", "old", 1); !errors.Is(err, errInjected) { + t.Fatalf("failed persistence not witnessed: %v", err) + } + SetPutAfterRenameFaultForTest(nil) + if faults != 1 || p.WorkspaceState("v").Lease.Revoking { + t.Fatal("fixture did not retain pre-write memory") + } + records, err := disk.Load() + if err != nil { + t.Fatal(err) + } + landed := false + for _, r := range records { + if r.Workspace != nil && r.Workspace.Lease != nil && r.Workspace.Lease.Revoking { + landed = true + } + } + if !landed { + t.Fatal("faulted write did not land on disk") + } + before := p.WorkspaceState("v") + for _, req := range []WorkspaceMoveRequest{bad, forcedLostRangeReq} { + if _, err := p.MoveWorkspace(ctx, req, forcedLostRangeHead); !errors.Is(err, ErrWorkspaceOutcomeUncertain) { + t.Errorf("uncertain volume answered a definite admission refusal: %v", err) + } + } + if !reflect.DeepEqual(before, p.WorkspaceState("v")) { + t.Fatal("refused requests changed authority memory") + } +} diff --git a/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go b/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go new file mode 100644 index 0000000000..7dc9f426f2 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go @@ -0,0 +1,84 @@ +package master + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/authority" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "strings" + "sync/atomic" + "testing" +) + +func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) { + for _, duringRead := range []bool{false, true} { + t.Run(map[bool]string{false: "already_uncertain", true: "uncertain_during_HEAD"}[duringRead], func(t *testing.T) { + var inject, failRead atomic.Bool + var latch func() error + h, c, ctx := reviewBindingHostWithReader(t, func(context.Context, string) (authority.WorkspaceHead, error) { + if inject.Swap(false) { + if err := latch(); err != nil { + return authority.WorkspaceHead{}, err + } + } + if failRead.Load() { + return authority.WorkspaceHead{}, errors.New("test HEAD unavailable") + } + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil + }) + reviewLegacyBind(t, h, c, ctx, "v") + if _, err := h.Publisher().RenewWorkspaceLease(ctx, "v", "r1", 1); err != nil { + t.Fatal(err) + } + client := control.NewWorkspaceServiceClient(c) + request := func(kind string) *control.WorkspaceMove { + return &control.WorkspaceMove{VolumeId: "v", RequestId: "precedence-" + kind, ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "missing-node", TargetDataAddr: "127.0.0.1:29901", TargetCtrlAddr: "127.0.0.1:29902", Kind: kind, Force: kind == "forced"} + } + for _, kind := range []string{"clean", "forced"} { + if _, err := client.MoveWorkspace(ctx, request(kind)); status.Code(err) != codes.FailedPrecondition { + t.Fatalf("healthy admission control: %v", err) + } + } + faults := atomic.Int64{} + injected := errors.New("test persistence reply lost after rename") + authority.SetPutAfterRenameFaultForTest(func(r authority.DurableRecord) error { + if r.Workspace != nil && r.Workspace.Lease != nil && r.Workspace.Lease.Revoking { + faults.Add(1) + return injected + } + return nil + }) + t.Cleanup(func() { authority.SetPutAfterRenameFaultForTest(nil) }) + latch = func() error { + err := h.Publisher().BeginWorkspaceRevocation(ctx, "v", "r1", 1) + if !errors.Is(err, injected) { + return errors.New("test failed to latch uncertain persistence") + } + return nil + } + if duringRead { + inject.Store(true) + } else if err := latch(); err != nil { + t.Fatal(err) + } + for _, kind := range []string{"clean", "forced"} { + q := request(kind) + if _, err := client.MoveWorkspace(ctx, q); status.Code(err) != codes.Internal || !strings.Contains(status.Convert(err).Message(), "UNKNOWN") || !strings.Contains(status.Convert(err).Message(), q.RequestId) { + t.Errorf("uncertain %s move answered definite refusal: %v", kind, err) + } + } + failRead.Store(true) + if _, err := client.MoveWorkspace(ctx, request("clean")); status.Code(err) != codes.Internal || !strings.Contains(status.Convert(err).Message(), "UNKNOWN") { + t.Errorf("early HEAD error hid uncertainty: %v", err) + } + authority.SetPutAfterRenameFaultForTest(nil) + state := h.Publisher().WorkspaceState("v") + line, ok := h.Publisher().VolumeAuthorityLine("v") + if faults.Load() != 1 || state.Lease.Revoking || len(state.Moves) != 0 || !ok || line.Epoch != 1 || line.ReplicaID != "r1" { + t.Fatalf("unknown requests changed authority: faults=%d state=%+v line=%+v", faults.Load(), state, line) + } + }) + } +} From 677e0a50d439d74c512c652f0861be18b4b5a1bb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 06:43:27 -0800 Subject: [PATCH 10/34] fix(authority): report uncertain move outcomes before refusals --- seaweed-block/core/authority/workspace.go | 19 ++++++- .../workspace_outcome_uncertain_test.go | 11 ++++ .../core/host/master/workspace_service.go | 53 ++++++++++--------- .../workspace_uncertain_precedence_test.go | 20 +++++++ seaweed-block/docs/design/invariants.md | 5 +- seaweed-block/docs/spec/README.md | 29 ++++++++++ .../docs/spec/WorkspaceMoveOutcome.tla | 25 +++++++++ .../docs/spec/cfg/WorkspaceMoveOutcome.cfg | 3 ++ 8 files changed, 139 insertions(+), 26 deletions(-) create mode 100644 seaweed-block/docs/spec/WorkspaceMoveOutcome.tla create mode 100644 seaweed-block/docs/spec/cfg/WorkspaceMoveOutcome.cfg diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 27f50cabe1..849ae04d24 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -199,7 +199,24 @@ func (p *Publisher) IssuedWorkspaceMove(req WorkspaceMoveRequest) bool { return replay && err == nil } -func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, head WorkspaceHead) (WorkspaceMoveRecord, error) { +// WorkspaceMoveOutcomeError classifies a failed move at the reply boundary. +// M2 Uncertain / INV-AUTH-UNCERTAIN-001: admission cannot promise no effect +// while an earlier workspace write may have landed. Cancellation stays typed. +func (p *Publisher) WorkspaceMoveOutcomeError(volume string, err error) error { + if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return err + } + p.mu.Lock() + uncertain := p.workspaceUncertain[volume] + p.mu.Unlock() + if uncertain { + return errors.Join(ErrWorkspaceOutcomeUncertain, err) + } + return err +} + +func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, head WorkspaceHead) (_ WorkspaceMoveRecord, resultErr error) { + defer func() { resultErr = p.WorkspaceMoveOutcomeError(req.VolumeID, resultErr) }() if err := ctx.Err(); err != nil { return WorkspaceMoveRecord{}, err } diff --git a/seaweed-block/core/authority/workspace_outcome_uncertain_test.go b/seaweed-block/core/authority/workspace_outcome_uncertain_test.go index e6fb4d8ba5..61d9bf3f9b 100644 --- a/seaweed-block/core/authority/workspace_outcome_uncertain_test.go +++ b/seaweed-block/core/authority/workspace_outcome_uncertain_test.go @@ -73,6 +73,7 @@ func TestWorkspaceUncertaintyPrecedesRequestRefusal(t *testing.T) { ctx := context.Background() disk, _ := newTempStore(t) p, _, _ := forcedLostRangeFixture(t, disk, false) + t.Cleanup(p.CloseWorkspaceExtenders) bad := forcedLostRangeReq bad.TargetReplicaID = "other-slot" if _, err := p.MoveWorkspace(ctx, bad, forcedLostRangeHead); err == nil || errors.Is(err, ErrWorkspaceOutcomeUncertain) { @@ -113,6 +114,16 @@ func TestWorkspaceUncertaintyPrecedesRequestRefusal(t *testing.T) { t.Errorf("uncertain volume answered a definite admission refusal: %v", err) } } + canceled, cancel := context.WithCancel(ctx) + cancel() + if _, err := p.MoveWorkspace(canceled, bad, forcedLostRangeHead); err != context.Canceled { + t.Errorf("caller cancellation changed: %v", err) + } + other := bad + other.VolumeID = "other" + if _, err := p.MoveWorkspace(ctx, other, forcedLostRangeHead); err == nil || errors.Is(err, ErrWorkspaceOutcomeUncertain) { + t.Errorf("uncertainty leaked across volumes: %v", err) + } if !reflect.DeepEqual(before, p.WorkspaceState("v")) { t.Fatal("refused requests changed authority memory") } diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 60507669ef..499b6af680 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -180,7 +180,35 @@ func (s *services) logForcedGrant(g *control.WorkspaceGrant, replay bool, postIs g.GetVolumeId(), g.GetRequestId(), g.GetOldHost(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewHost(), g.GetNewReplicaId(), g.GetNewEpoch(), replay, lost) } -func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { +func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) (_ *control.WorkspaceGrant, resultErr error) { + // Remote reads never hold the workspace mutation lock. Re-read every + // local precondition below; Publisher checks the expected epoch atomically. + // A refusal is logged after the lock is released (deferred first, so it + // runs last): a slow log writer never holds workspaceMu. + // An issued forced grant is logged the same way, also after the unlock. + var refusal string + var issued *control.WorkspaceGrant + var replay bool + var postIssue, unknown error + defer func() { + // M2 Uncertain reply precedence applies even to preflight/HEAD errors. + outcome := resultErr + if code := status.Code(resultErr); code != codes.Canceled && code != codes.DeadlineExceeded { + outcome = s.host.Publisher().WorkspaceMoveOutcomeError(q.GetVolumeId(), resultErr) + } + if errors.Is(outcome, authority.ErrWorkspaceOutcomeUncertain) { + unknown, refusal = outcome, "" + resultErr = status.Errorf(codes.Internal, "workspace move %q of volume %q has an UNKNOWN outcome: %v; the volume's workspace authority stays uncertain until the master restarts; after the restart, rerun with the same request id", q.GetRequestId(), q.GetVolumeId(), outcome) + } + if refusal != "" { + s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal) + } + s.logForcedGrant(issued, replay, postIssue) + if unknown != nil { + s.host.log.Printf("blockmaster: MoveWorkspace outcome unknown volume=%q request=%q kind=%q: %v", q.GetVolumeId(), q.GetRequestId(), q.GetKind(), unknown) + } + }() + if err := s.workspaceVolume(q.GetVolumeId()); err != nil { return nil, err } @@ -201,24 +229,6 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) if err != nil { return nil, workspaceError(err) } - // Remote reads never hold the workspace mutation lock. Re-read every - // local precondition below; Publisher checks the expected epoch atomically. - // A refusal is logged after the lock is released (deferred first, so it - // runs last): a slow log writer never holds workspaceMu. - // An issued forced grant is logged the same way, also after the unlock. - var refusal string - var issued *control.WorkspaceGrant - var replay bool - var postIssue, unknown error - defer func() { - if refusal != "" { - s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal) - } - s.logForcedGrant(issued, replay, postIssue) - if unknown != nil { - s.host.log.Printf("blockmaster: MoveWorkspace outcome unknown volume=%q request=%q kind=%q: %v", q.GetVolumeId(), q.GetRequestId(), q.GetKind(), unknown) - } - }() s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() if err := ctx.Err(); err != nil { @@ -246,11 +256,6 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) issued, postIssue = s.issuedRecord(req), err return nil, postIssueError(q, err) } - if errors.Is(err, authority.ErrWorkspaceOutcomeUncertain) { - unknown = err - return nil, status.Errorf(codes.Internal, "workspace move %q of volume %q has an UNKNOWN outcome: %v; the volume's workspace authority stays uncertain until the master restarts; after the restart, rerun with the same request id", - q.GetRequestId(), q.GetVolumeId(), err) - } return nil, workspaceError(err) } // The move is issued from here on: record it for the audit log before diff --git a/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go b/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go index 7dc9f426f2..30d6f42bf1 100644 --- a/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go +++ b/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go @@ -10,6 +10,7 @@ import ( "strings" "sync/atomic" "testing" + "time" ) func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) { @@ -73,6 +74,25 @@ func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) { if _, err := client.MoveWorkspace(ctx, request("clean")); status.Code(err) != codes.Internal || !strings.Contains(status.Convert(err).Message(), "UNKNOWN") { t.Errorf("early HEAD error hid uncertainty: %v", err) } + // These direct calls inspect the server result, not the client's own + // deadline override, so reply classification must preserve both. + for _, deadline := range []bool{false, true} { + var ended context.Context + var end context.CancelFunc + want := codes.Canceled + if deadline { + ended, end = context.WithDeadline(ctx, time.Unix(0, 1)) + want = codes.DeadlineExceeded + } else { + ended, end = context.WithCancel(ctx) + end() + } + _, err := (&services{host: h}).MoveWorkspace(ended, request("forced")) + end() + if status.Code(err) != want { + t.Errorf("server caller-end classification changed: %v want %v", err, want) + } + } authority.SetPutAfterRenameFaultForTest(nil) state := h.Publisher().WorkspaceState("v") line, ok := h.Publisher().VolumeAuthorityLine("v") diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0c69765881..1a773c0457 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -82,6 +82,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` | | any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing, but its durable outcome may be unknown | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | | any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` | +| Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` | | Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | **Workspace lease and move, in blockmaster.** @@ -432,6 +433,8 @@ The "Machine / transition" column refers to Part A. Notes under a table record w Notes: +- `INV-AUTH-UNCERTAIN-001` detail: After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. Move error classification reads the per-volume uncertainty latch under the publisher lock at reply time, covering RPC preflight, HEAD reads and local admission as well as the publisher. The unknown outcome overrides the refusal audit entry. It adds no authority write and does not clear uncertainty. + - `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged. - `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. @@ -455,7 +458,7 @@ Notes: | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | -| `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-UNCERTAIN-001` | Failed workspace writes latch uncertainty until reload. Authority and lease extensions refuse; revoking leases keep bounded drain replies. A failed move is UNKNOWN before admission refusal; caller cancellation/deadline stays typed. Known issued replays remain valid. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `WorkspaceMoveOutcomeError`, `MoveWorkspace`; `core/host/master/workspace_service.go` `MoveWorkspace` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUncertaintyPrecedesRequestRefusal`, `TestWorkspaceMoveUnknownPrecedesAdmissionRefusals`, `TestWorkspaceUncertainIssueWriteIsTyped` | `ControlPlane` `UniqueEpoch`; `WorkspaceMoveOutcome` `NoFalseRefusal`, `CallerEndTyped` | ACTIVE | | `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. A move issue publishes the derived view and the new holder's initial deadline in one lease-lock section, never lowering a deadline a renewal raised. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`, `publishIssuedLeaseLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceIssuePublishNeverLowersARenewedDeadline` (`core/authority/workspace_issue_publish_test.go`) | — | ACTIVE | | `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that replaces the lease with the new holder's is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 5dc3e958cf..fbcc5e29ad 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -517,3 +517,32 @@ checked by native Go tests; this derived arithmetic model does not model the HTT encoder, sampler atomicity, orchestrator timing or an unbounded estimator overrun. #344 review qualification: `TestChunkFrozenDrainRefusalCarriesObservedBudget` drives a real admitted Sync through frontend drain expiry, durable provider and HTTP, with no report injection; `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation` covers the known observation. `TestFrozenSaturatedTailRemainsKnownButNonActionable` and the literal 60 s/61 s candidate cases preserve the existing saturation sentinel (zero slack, not a complete duration). These native controls add no model claim or admission guard. + + +### Workspace move reply precedence + +`WorkspaceMoveOutcome.tla` covers M2's `Uncertain -> Uncertain (move answer)` +transition and `INV-AUTH-UNCERTAIN-001`. One volume can receive one failed +workspace write (landed or not), one error from request validation, forced +preflight, HEAD read, target or endpoint admission, or a caller cancellation / +deadline. The write may fail before or after the error is selected. Reply-time +classification must never report a definite refusal while uncertainty is +observed; caller cancellation/deadline stays typed. No authority changes are +modeled here: journal durability, lease safety, RPC delivery and reload remain +with their existing specs and native controls. + +TLC 2.19 (tools SHA256 +`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`), +2026-11-21: `cfg/WorkspaceMoveOutcome.cfg` exhausted 59 generated / 45 distinct +states, depth 4, queue empty. Bounds: one volume, seven error causes, one failed +write with Boolean durable outcome, one reply. `NoFalseRefusal` and +`CallerEndTyped` hold. The `BypassUncertainty=TRUE` negative must violate +`NoFalseRefusal`; native controls map to +`TestWorkspaceUncertaintyPrecedesRequestRefusal` (publisher validation), +`TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` (real gRPC preflight/HEAD/ +target paths, uncertainty before the call or during HEAD read, plus direct +server caller-end classification), and the retained +`TestWorkspaceUncertainIssueWriteIsTyped` (issue failure and replay after reload). +The new tests use a real file-store rename followed by an injected error; +a readout verifies that the failed write actually landed while memory rolled +back. They also check no new authority epoch/move and per-volume scope. diff --git a/seaweed-block/docs/spec/WorkspaceMoveOutcome.tla b/seaweed-block/docs/spec/WorkspaceMoveOutcome.tla new file mode 100644 index 0000000000..6e7fb17834 --- /dev/null +++ b/seaweed-block/docs/spec/WorkspaceMoveOutcome.tla @@ -0,0 +1,25 @@ +------------------------- MODULE WorkspaceMoveOutcome ------------------------- +EXTENDS Naturals, FiniteSets +CONSTANT BypassUncertainty +VARIABLES uncertain, landed, cause, reply, uncertainAtReply +vars == <> +Causes == {"request", "forced_preflight", "head", "target", "endpoint", "canceled", "deadline"} +Init == /\ uncertain = FALSE /\ landed = FALSE /\ cause = "none" + /\ reply = "none" /\ uncertainAtReply = FALSE +FailedWrite == /\ ~uncertain /\ reply = "none" + /\ uncertain' = TRUE /\ landed' \in BOOLEAN + /\ UNCHANGED <> +AdmissionError == /\ cause = "none" /\ reply = "none" + /\ cause' \in Causes + /\ UNCHANGED <> +Reply == /\ cause # "none" /\ reply = "none" + /\ reply' = IF cause \in {"canceled", "deadline"} THEN cause + ELSE IF uncertain /\ ~BypassUncertainty THEN "unknown" + ELSE "refused" + /\ uncertainAtReply' = uncertain + /\ UNCHANGED <> +Next == FailedWrite \/ AdmissionError \/ Reply +Spec == Init /\ [][Next]_vars +NoFalseRefusal == ~(reply = "refused" /\ uncertainAtReply) +CallerEndTyped == cause \in {"canceled", "deadline"} /\ reply # "none" => reply = cause +============================================================================= diff --git a/seaweed-block/docs/spec/cfg/WorkspaceMoveOutcome.cfg b/seaweed-block/docs/spec/cfg/WorkspaceMoveOutcome.cfg new file mode 100644 index 0000000000..86f9b1b177 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/WorkspaceMoveOutcome.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +CONSTANT BypassUncertainty = FALSE +INVARIANTS NoFalseRefusal CallerEndTyped From 2cda71d4c3e492c92f3562a77eb46f5b22c92d72 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 06:45:08 -0800 Subject: [PATCH 11/34] docs(authority): map uncertain move reply precedence --- seaweed-block/docs/design/agent-workspace-design.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index d5318a20df..8e6736df1f 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -285,6 +285,17 @@ intents remain rooted after restart; elapsed TTL is not a settlement proof. **Master side of a renewal** (`core/authority/workspace_lease_view.go`): blockmaster answers a renewal of an established lease from memory, under a small leaf lock, with no disk write and without waiting for other authority writes. The grant is min(now + TTL, durable horizon), where the horizon is the lease expiry stored on disk; a background extension, an ordinary authority write, keeps the horizon about 1.5·TTL ahead of the last renewal that triggered it. Only the first grant of a lease is written synchronously. If extensions fall behind, grants shrink and the host fences by the horizon minus half the skew bound; a failed extension write makes the volume uncertain and refuses renewals that would issue a new or extended grant (a Revoking lease still gets its bounded drain reply). +**Uncertain move outcomes** (`INV-AUTH-UNCERTAIN-001`): at a failed move's reply boundary, the publisher's per-volume persistence latch takes precedence over request, forced-admission, HEAD-read and target refusals. Such a reply is UNKNOWN with same-request recovery after reload, without another authority write. Caller cancellation/deadline stays typed; a known successful issued replay remains valid. + +```mermaid +flowchart LR + E[Move error] --> C{Caller canceled or deadline?} + C -->|yes| T[Typed caller error] + C -->|no| U{Persistence uncertain at reply?} + U -->|yes| X[UNKNOWN, never definite admission refusal] + U -->|no| R[Ordinary error classification] +``` + **CLEAN move:** Detach publishes the final cut with `State = detached` in one CAS �' revoke �' the host drains frontend, replication and provider and acknowledges the stored detached HEAD generation �' blockmaster checks the detached HEAD and the matching acknowledgement �' new epoch �' the new host claims HEAD. **FORCED move:** blockmaster waits until both the persisted lease horizon (at least every grant, so at most TTL/2 later than the last grant) and the granted or conservative restart deadline, plus the full skew bound, have passed (`core/authority/workspace.go` `prepareWorkspaceMoveLocked`). The old host's late CAS fails on the epoch; its uploads become orphans for GC. Writes since the old host's last cut are lost. From 9cf35805e1e82fffb43c5a4a3ed0c36ceb191f10 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 06:46:04 -0800 Subject: [PATCH 12/34] fold: the guard flags a constructor taken as a function value, not only called Any use of grpc.NewClient / Dial / DialContext / NewServer or insecure.NewCredentials counts (f := grpc.NewClient builds a raw link just the same), qualified under any import name or unqualified under a dot import; fixtures for a function value, an aliased value and a dot-imported value. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/rpc/link/link_test.go | 45 +++++++++++++++++------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/seaweed-block/core/rpc/link/link_test.go b/seaweed-block/core/rpc/link/link_test.go index 1ad13d99e2..18e4556d7b 100644 --- a/seaweed-block/core/rpc/link/link_test.go +++ b/seaweed-block/core/rpc/link/link_test.go @@ -109,10 +109,11 @@ func TestLink_ServerRunsInterceptorsInOrder(t *testing.T) { } } -// rawLinkCalls lists the gRPC link constructions in one Go source that -// bypass this package: a client (grpc.NewClient, grpc.Dial, grpc.DialContext), -// a server (grpc.NewServer) or plaintext credentials (insecure.NewCredentials), -// whatever local name the import has (aliases and dot imports included). +// rawLinkCalls lists the uses in one Go source of a gRPC link constructor +// that bypass this package: a client (grpc.NewClient, grpc.Dial, +// grpc.DialContext), a server (grpc.NewServer) or plaintext credentials +// (insecure.NewCredentials), called or taken as a function value, whatever +// local name the import has (aliases and dot imports included). func rawLinkCalls(name string, src []byte) ([]string, error) { fset := token.NewFileSet() f, err := parser.ParseFile(fset, name, src, parser.SkipObjectResolution) @@ -145,20 +146,26 @@ func rawLinkCalls(name string, src []byte) ([]string, error) { local[name] = fns } } + // Any use counts, not only a call: a function value (f := grpc.NewClient) + // builds a raw link just the same. A selector's own name is not an + // unqualified use. + sels := map[*ast.Ident]bool{} + ast.Inspect(f, func(n ast.Node) bool { + if sel, ok := n.(*ast.SelectorExpr); ok { + sels[sel.Sel] = true + } + return true + }) var found []string ast.Inspect(f, func(n ast.Node) bool { - call, ok := n.(*ast.CallExpr) - if !ok { - return true - } - switch fun := call.Fun.(type) { + switch e := n.(type) { case *ast.SelectorExpr: - if x, ok := fun.X.(*ast.Ident); ok && local[x.Name][fun.Sel.Name] { - found = append(found, fmt.Sprintf("%s: %s.%s", fset.Position(call.Pos()), x.Name, fun.Sel.Name)) + if x, ok := e.X.(*ast.Ident); ok && local[x.Name][e.Sel.Name] { + found = append(found, fmt.Sprintf("%s: %s.%s", fset.Position(e.Pos()), x.Name, e.Sel.Name)) } case *ast.Ident: - if dot[fun.Name] { - found = append(found, fmt.Sprintf("%s: %s", fset.Position(call.Pos()), fun.Name)) + if dot[e.Name] && !sels[e] { + found = append(found, fmt.Sprintf("%s: %s", fset.Position(e.Pos()), e.Name)) } } return true @@ -197,6 +204,18 @@ func f() { ins.NewCredentials() } "dotImport": `package p import . "google.golang.org/grpc" func f() { NewServer() } +`, + "funcValue": `package p +import "google.golang.org/grpc" +var dial = grpc.NewClient +`, + "aliasValue": `package p +import g "google.golang.org/grpc" +func f() { mk := g.NewServer; _ = mk } +`, + "dotValue": `package p +import . "google.golang.org/grpc" +var dial = NewClient `, "plainCredsFn": `package p import "google.golang.org/grpc/credentials/insecure" From 6e57df9a50c7e84d35f4dd845f8cf4b87bfb3801 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 06:59:26 -0800 Subject: [PATCH 13/34] test(authority): expose dependency timeout misclassified as caller end --- .../workspace_outcome_uncertain_test.go | 8 +++++ .../workspace_uncertain_precedence_test.go | 32 ++++++++++++++++--- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/authority/workspace_outcome_uncertain_test.go b/seaweed-block/core/authority/workspace_outcome_uncertain_test.go index 61d9bf3f9b..a92794f0ea 100644 --- a/seaweed-block/core/authority/workspace_outcome_uncertain_test.go +++ b/seaweed-block/core/authority/workspace_outcome_uncertain_test.go @@ -114,6 +114,14 @@ func TestWorkspaceUncertaintyPrecedesRequestRefusal(t *testing.T) { t.Errorf("uncertain volume answered a definite admission refusal: %v", err) } } + for _, dependencyErr := range []error{context.Canceled, context.DeadlineExceeded} { + if ctx.Err() != nil { + t.Fatal("request parent unexpectedly ended") + } + if err := p.WorkspaceMoveOutcomeError("v", dependencyErr); !errors.Is(err, ErrWorkspaceOutcomeUncertain) { + t.Errorf("live caller dependency error bypassed UNKNOWN: %v", err) + } + } canceled, cancel := context.WithCancel(ctx) cancel() if _, err := p.MoveWorkspace(canceled, bad, forcedLostRangeHead); err != context.Canceled { diff --git a/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go b/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go index 30d6f42bf1..07777d9a8e 100644 --- a/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go +++ b/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go @@ -16,16 +16,29 @@ import ( func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) { for _, duringRead := range []bool{false, true} { t.Run(map[bool]string{false: "already_uncertain", true: "uncertain_during_HEAD"}[duringRead], func(t *testing.T) { - var inject, failRead atomic.Bool + var inject atomic.Bool + var headFailure atomic.Int32 + var childDeadlineObserved atomic.Bool var latch func() error - h, c, ctx := reviewBindingHostWithReader(t, func(context.Context, string) (authority.WorkspaceHead, error) { + h, c, ctx := reviewBindingHostWithReader(t, func(readCtx context.Context, _ string) (authority.WorkspaceHead, error) { if inject.Swap(false) { if err := latch(); err != nil { return authority.WorkspaceHead{}, err } } - if failRead.Load() { + switch headFailure.Load() { + case 1: return authority.WorkspaceHead{}, errors.New("test HEAD unavailable") + case 2: + // Expire the service's actual child read context. The + // request parent below stays live indefinitely. + <-readCtx.Done() + childDeadlineObserved.Store(readCtx.Err() == context.DeadlineExceeded) + return authority.WorkspaceHead{}, readCtx.Err() + case 3: + dependency, cancel := context.WithCancel(readCtx) + cancel() + return authority.WorkspaceHead{}, dependency.Err() } return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil }) @@ -70,10 +83,21 @@ func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) { t.Errorf("uncertain %s move answered definite refusal: %v", kind, err) } } - failRead.Store(true) + headFailure.Store(1) if _, err := client.MoveWorkspace(ctx, request("clean")); status.Code(err) != codes.Internal || !strings.Contains(status.Convert(err).Message(), "UNKNOWN") { t.Errorf("early HEAD error hid uncertainty: %v", err) } + liveParent := context.Background() + for _, mode := range []int32{2, 3} { + headFailure.Store(mode) + _, err := (&services{host: h}).MoveWorkspace(liveParent, request("clean")) + if liveParent.Err() != nil || (mode == 2 && !childDeadlineObserved.Load()) { + t.Fatal("dependency-end witness did not preserve live request") + } + if status.Code(err) != codes.Internal || !strings.Contains(status.Convert(err).Message(), "UNKNOWN") || !strings.Contains(status.Convert(err).Message(), "same request id") { + t.Errorf("live-parent HEAD dependency end bypassed UNKNOWN: mode=%d err=%v", mode, err) + } + } // These direct calls inspect the server result, not the client's own // deadline override, so reply classification must preserve both. for _, deadline := range []bool{false, true} { From 41fffe6c5a7a5638475961c30766028c0ba12c77 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 07:01:26 -0800 Subject: [PATCH 14/34] durable: the periodic-cut timer and the scheduled-snapshot schedule run on in-process monotonic time; a restart starts a fresh schedule Co-Authored-By: Claude Opus 5.5 --- .../durable/chunk_snapshot_loop_test.go | 307 ++++++++++-------- .../durable/chunk_snapshot_schedule.go | 110 ++----- .../durable/chunk_snapshot_schedule_test.go | 77 +---- .../core/frontend/durable/cut_policy_test.go | 67 ++-- .../durable/maintenance_policy_test.go | 2 +- .../core/frontend/durable/provider.go | 5 +- .../core/frontend/durable/provider_chunk.go | 69 ++-- seaweed-block/docs/design/invariants.md | 3 +- 8 files changed, 300 insertions(+), 340 deletions(-) diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_loop_test.go b/seaweed-block/core/frontend/durable/chunk_snapshot_loop_test.go index 659470be45..a21cdbc878 100644 --- a/seaweed-block/core/frontend/durable/chunk_snapshot_loop_test.go +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_loop_test.go @@ -1,11 +1,14 @@ package durable +// The scheduled-snapshot loop on virtual time (testing/synctest): the +// bubble's clock is the monotonic clock the schedule runs on. + import ( "context" "errors" - "sync" "sync/atomic" "testing" + "testing/synctest" "time" "github.com/seaweedfs/seaweed-block/core/frontend" @@ -18,167 +21,187 @@ type snapStubLayer struct{ storage.ChunkLayer } func (snapStubLayer) Fenced() bool { return false } func (snapStubLayer) Stats() storage.ChunkLayerStats { return storage.ChunkLayerStats{} } -// stepClock is a wall clock a test can step. -type stepClock struct { - mu sync.Mutex - now time.Time -} - -func (c *stepClock) get() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.now } -func (c *stepClock) set(t time.Time) { c.mu.Lock(); c.now = t; c.mu.Unlock() } - -// snapLoopFixture is a provider running the scheduled-snapshot loop of one -// volume on a stepped clock, with a 10 ms wake bound. take is called for -// every attempt; the loop is stopped and joined at cleanup. -func snapLoopFixture(t *testing.T, take func(context.Context) error) (*DurableProvider, *volHandle, *stepClock) { - t.Helper() - wake := snapshotWake - snapshotWake = 10 * time.Millisecond - t.Cleanup(func() { snapshotWake = wake }) - clock := &stepClock{now: time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC)} +// snapLoop sets up volume v1's scheduled-snapshot loop (period one day) in +// the current bubble; take runs each attempt. start arms the loop; stop +// stops it and reports whether it was joined within an hour of virtual +// time. +func snapLoop(take func(context.Context) error) (h *volHandle, start func(), stop func() bool) { id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1} layer := &snapStubLayer{} - h := &volHandle{chunk: layer, chunkLineage: chunkLineage{"v1", "r1", 3, 1}} - p := &DurableProvider{volumes: map[string]*volHandle{"v1": h}, view: precopyQueueView{id}, testSnapshotClock: clock.get, + h = &volHandle{chunk: layer, chunkLineage: chunkLineage{"v1", "r1", 3, 1}} + p := &DurableProvider{volumes: map[string]*volHandle{"v1": h}, view: precopyQueueView{id}, cfg: ProviderConfig{ChunkSnapshotPeriod: 24 * time.Hour, ChunkScheduledSnapshot: func(ctx context.Context, _ string, _ time.Time, _ func(context.Context) (storage.ChunkHead, error)) error { return take(ctx) }}} - p.mu.Lock() - p.startChunkLoop("v1", h, layer) - p.mu.Unlock() - t.Cleanup(func() { + start = func() { + p.mu.Lock() + p.startChunkLoop("v1", h, layer) + p.mu.Unlock() + } + stop = func() bool { done := make(chan struct{}) go func() { p.stopChunkLoop(h); close(done) }() select { case <-done: - case <-time.After(5 * time.Second): - t.Error("the snapshot loop was not joined") + return true + case <-time.After(time.Hour): + return false + } + } + return h, start, stop +} + +// The first attempt is at the start plus the volume's offset and the next +// one a period later, both on the monotonic clock. +func TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var calls atomic.Int64 + h, start, stop := snapLoop(func(context.Context) error { calls.Add(1); return nil }) + begin := time.Now() + start() + defer func() { + if !stop() { + t.Error("the loop was not joined") + } + }() + first := h.snapshots.due() + if off := first.Sub(begin); off < 0 || off >= 24*time.Hour { + t.Fatalf("first slot %v after the start; want within one period", off) + } + time.Sleep(time.Until(first) - time.Second) + synctest.Wait() + if calls.Load() != 0 { + t.Fatal("an attempt ran before its slot") + } + time.Sleep(2 * time.Second) + synctest.Wait() + if calls.Load() != 1 { + t.Fatalf("%d attempts at the first slot; want 1", calls.Load()) + } + if next := h.snapshots.due(); next.Sub(first) != 24*time.Hour { + t.Fatalf("next slot %v after the first; want one period", next.Sub(first)) + } + time.Sleep(24 * time.Hour) + synctest.Wait() + if calls.Load() != 2 { + t.Fatalf("%d attempts after one period; want 2", calls.Load()) } }) - return p, h, clock } -func waitUntil(t *testing.T, what string, ok func() bool) { - t.Helper() - deadline := time.Now().Add(5 * time.Second) - for !ok() { - if time.Now().After(deadline) { - t.Fatalf("%s not reached", what) - } - time.Sleep(5 * time.Millisecond) - } -} - -// A wall-clock step forwards past the due time is observed within the wake -// bound: the attempt runs without waiting out the elapsed-time timer, and -// its success is recorded at the stepped wall time. -func TestScheduledSnapshotLoop_ForwardWallStepIsObserved(t *testing.T) { - var calls atomic.Int64 - p, h, clock := snapLoopFixture(t, func(context.Context) error { calls.Add(1); return nil }) - due := h.snapshots.status(clock.get()).NextDueNs - time.Sleep(50 * time.Millisecond) - if calls.Load() != 0 { - t.Fatal("an attempt ran before its slot") - } - stepped := time.Unix(0, due).Add(time.Second) - clock.set(stepped) - waitUntil(t, "the attempt after a forward step", func() bool { return calls.Load() == 1 }) - waitUntil(t, "the recorded success", func() bool { return h.snapshots.status(p.snapshotNow()).LastOkNs == stepped.UnixNano() }) -} - -// A wall-clock step backwards realigns the next attempt to the first slot -// after the stepped now (it does not wait the step out), and that slot is -// then taken. -func TestScheduledSnapshotLoop_BackwardWallStepRealigns(t *testing.T) { - var calls atomic.Int64 - _, h, clock := snapLoopFixture(t, func(context.Context) error { calls.Add(1); return nil }) - back := clock.get().Add(-3 * 24 * time.Hour) - clock.set(back) - waitUntil(t, "the realigned slot", func() bool { - next := time.Unix(0, h.snapshots.status(clock.get()).NextDueNs) - return next.After(back) && next.Sub(back) <= 24*time.Hour - }) - if calls.Load() != 0 { - t.Fatal("a backward step triggered an attempt") - } - clock.set(time.Unix(0, h.snapshots.status(clock.get()).NextDueNs).Add(time.Second)) - waitUntil(t, "the attempt at the realigned slot", func() bool { return calls.Load() == 1 }) -} - -// Overdue follows the wall clock: a success recorded by the loop, then a -// wall step forwards past one period plus the retry cap, reads as overdue. -func TestScheduledSnapshotLoop_OverdueFollowsTheWallClock(t *testing.T) { - var calls atomic.Int64 - p, h, clock := snapLoopFixture(t, func(context.Context) error { calls.Add(1); return nil }) - clock.set(time.Unix(0, h.snapshots.status(clock.get()).NextDueNs)) - waitUntil(t, "the first success", func() bool { return h.snapshots.status(p.snapshotNow()).LastOkNs != 0 }) - clock.set(clock.get().Add(2 * 24 * time.Hour)) - if !h.snapshots.status(p.snapshotNow()).Overdue { - t.Fatal("two days after the last success on the wall clock, not overdue") - } -} - -// A re-armed loop (stopped and started again on the same handle, as after a -// refused detach) keeps the schedule: the failed attempt, its count and -// backoff survive. +// A re-armed loop (stopped and started again on the same handle, as after +// a refused detach) keeps the volume's schedule: the failure, its count and +// its retry time survive, and the retry runs at that time. func TestScheduledSnapshotLoop_RearmKeepsTheSchedule(t *testing.T) { - p, h, clock := snapLoopFixture(t, func(context.Context) error { return &SnapshotFailure{Code: "remote_unavailable"} }) - clock.set(time.Unix(0, h.snapshots.status(clock.get()).NextDueNs)) - waitUntil(t, "the failure", func() bool { return h.snapshots.status(clock.get()).Attempts == 1 }) - slot := h.snapshots - p.stopChunkLoop(h) - p.mu.Lock() - p.startChunkLoop("v1", h, h.chunk) - p.mu.Unlock() - if st := h.snapshots.status(clock.get()); h.snapshots != slot || st.Attempts != 1 || st.LastFailure == nil { - t.Fatalf("after re-arm: %+v (same schedule %v); want the failure kept", st, h.snapshots == slot) - } + synctest.Test(t, func(t *testing.T) { + var calls atomic.Int64 + h, start, stop := snapLoop(func(context.Context) error { + calls.Add(1) + return &SnapshotFailure{Code: "remote_unavailable"} + }) + start() + time.Sleep(time.Until(h.snapshots.due()) + time.Second) + synctest.Wait() + slot, retry := h.snapshots, h.snapshots.due() + if st := slot.status(time.Now()); st.Attempts != 1 || st.LastFailure == nil { + t.Fatalf("after the first attempt: %+v; want one failure", st) + } + if !stop() { + t.Fatal("the loop was not joined") + } + start() + defer func() { + if !stop() { + t.Error("the re-armed loop was not joined") + } + }() + if h.snapshots != slot || h.snapshots.due() != retry || slot.status(time.Now()).Attempts != 1 { + t.Fatalf("after re-arm: same schedule %v, due %v (want %v), %+v", h.snapshots == slot, h.snapshots.due(), retry, slot.status(time.Now())) + } + time.Sleep(time.Until(retry) + time.Second) + synctest.Wait() + if calls.Load() != 2 || slot.status(time.Now()).Attempts != 2 { + t.Fatalf("%d attempts after the retry time; want the re-armed loop to retry once", calls.Load()) + } + }) } // INV-MAINT-JOIN for the scheduled-snapshot worker: stopping the loop -// cancels an attempt in flight and returns only after the attempt has -// returned. +// cancels an attempt in flight (the attempt observes the cancellation) and +// returns only after the attempt has returned. The attempt is released +// before the loop is joined, whatever the outcome. func TestScheduledSnapshotLoop_StopJoinsTheAttempt(t *testing.T) { - entered, release := make(chan struct{}), make(chan struct{}) - var once sync.Once - finish := func() { once.Do(func() { close(release) }) } - t.Cleanup(finish) - p, h, clock := snapLoopFixture(t, func(ctx context.Context) error { - close(entered) - <-ctx.Done() - <-release // returns only when the test allows it - return errors.New("stopped") + synctest.Test(t, func(t *testing.T) { + entered, cancelled, release := make(chan struct{}), make(chan struct{}), make(chan struct{}) + h, start, stop := snapLoop(func(ctx context.Context) error { + close(entered) + <-ctx.Done() + close(cancelled) + <-release // returns only when the test allows it + return errors.New("stopped") + }) + start() + joined := make(chan bool, 1) + stopping := false + defer func() { // runs after the release below: join the stop, bounded + if !stopping { + joined <- stop() + } + select { + case ok := <-joined: + if !ok { + t.Error("stop was not joined after the attempt returned") + } + case <-time.After(2 * time.Hour): + t.Error("stop did not return") + } + }() + var released atomic.Bool + defer func() { + if released.CompareAndSwap(false, true) { + close(release) + } + }() + time.Sleep(time.Until(h.snapshots.due()) + time.Second) + <-entered + stopping = true + go func() { joined <- stop() }() + <-cancelled // the attempt saw the cancellation + synctest.Wait() + select { + case <-joined: + t.Fatal("stop returned while the attempt was still running") + default: + } + if released.CompareAndSwap(false, true) { + close(release) + } }) - clock.set(time.Unix(0, h.snapshots.status(clock.get()).NextDueNs)) - select { - case <-entered: - case <-time.After(5 * time.Second): - t.Fatal("no attempt started") - } - stopped := make(chan struct{}) - go func() { p.stopChunkLoop(h); close(stopped) }() - select { - case <-stopped: - t.Fatal("stop returned while the attempt was still running") - case <-time.After(100 * time.Millisecond): - } - finish() - select { - case <-stopped: - case <-time.After(5 * time.Second): - t.Fatal("stop did not return after the attempt") - } } -// The production clock carries no monotonic reading, so durations and -// overdue between its readings follow wall-clock steps. -func TestScheduledSnapshotWallClockHasNoMonotonicReading(t *testing.T) { - now := snapshotWallNow() - if now != now.Round(0) { - t.Fatalf("snapshotWallNow %v carries a monotonic reading", now) - } - if p := (&DurableProvider{}); p.snapshotNow() != p.snapshotNow().Round(0) { - t.Fatal("the provider's snapshot clock carries a monotonic reading") - } +// With every attempt failing, the schedule is overdue once no success +// came within one period plus the retry cap from the start; never before. +func TestScheduledSnapshotLoop_OverdueWithNoSuccess(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + h, start, stop := snapLoop(func(context.Context) error { return &SnapshotFailure{Code: "remote_unavailable"} }) + begin := time.Now() + start() + defer func() { + if !stop() { + t.Error("the loop was not joined") + } + }() + limit := 24*time.Hour + snapshotRetryMax + time.Sleep(time.Until(begin.Add(limit))) + synctest.Wait() + if st := h.snapshots.status(time.Now()); st.Overdue || st.LastOkNs != 0 { + t.Fatalf("at one period plus the retry cap: %+v; want not yet overdue", st) + } + time.Sleep(time.Minute) + synctest.Wait() + if st := h.snapshots.status(time.Now()); !st.Overdue || st.LastFailure == nil { + t.Fatalf("past one period plus the retry cap with only failures: %+v; want overdue with the failure", st) + } + }) } diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go index 62b3be580d..c75494a707 100644 --- a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go @@ -18,23 +18,6 @@ const ( snapshotRetryMax = time.Hour ) -// snapshotWake bounds how long the loop sleeps before it reads the wall -// clock again, so a wall-clock step is observed within it. -var snapshotWake = time.Minute - -// snapshotWallNow is the wall clock the schedule runs on, without the -// monotonic reading: slots, durations and overdue all follow wall-clock -// steps. -func snapshotWallNow() time.Time { return time.Now().Round(0) } - -// snapshotNow is the provider's scheduled-snapshot clock. -func (p *DurableProvider) snapshotNow() time.Time { - if p.testSnapshotClock != nil { - return p.testSnapshotClock() - } - return snapshotWallNow() -} - // SnapshotSkipRestoring is the skip reason of a volume still fetching the // chunks its HEAD names (a restore's hydration). const SnapshotSkipRestoring = "restoring" @@ -91,69 +74,48 @@ type ScheduledSnapshotStatus struct { } // snapshotSchedule decides when one volume's scheduled snapshot is due and -// records the outcome of each attempt. Each slot starts at a multiple of -// the period (from the Unix epoch) plus the volume's offset, spread over -// the whole period and stable across restarts: "daily" is once per 24 h -// at a per-volume offset, not at a wall-clock hour. It is not safe for -// concurrent use. +// records the outcome of each attempt, on this process's monotonic time +// (every time in it is a time.Now() reading or derived from one), so +// wall-clock steps move nothing. Slots are the start plus the volume's +// offset (spread over the whole period) plus whole periods: "daily" is +// once per 24 h at a per-volume offset, not at a wall-clock hour. A +// restart starts a fresh schedule. It is not safe for concurrent use. type snapshotSchedule struct { - period time.Duration - offset time.Duration - started time.Time - lastOK time.Time - next time.Time - // setAt is when next was last set; retry says next is a retry - // (setAt plus a delay) rather than a slot. - setAt time.Time - retry bool + period time.Duration + origin time.Time // the first slot: the start plus the volume's offset + started time.Time + lastOK time.Time + next time.Time failure *ScheduledSnapshotFailure attempts int skipped map[string]int64 } -// newSnapshotSchedule starts vol's schedule at now. +// newSnapshotSchedule starts vol's schedule at now, a time.Now() reading. func newSnapshotSchedule(vol string, period time.Duration, now time.Time) *snapshotSchedule { - s := &snapshotSchedule{period: period, offset: hostlimit.Phase(vol+":snapshot", period), started: now, skipped: map[string]int64{}} - s.next, s.setAt = s.slotAfter(now), now + s := &snapshotSchedule{period: period, origin: now.Add(hostlimit.Phase(vol+":snapshot", period)), started: now, skipped: map[string]int64{}} + s.next = s.origin return s } -// slotAfter returns the first slot start strictly after t. +// slotAfter returns the first slot strictly after t: the origin plus a +// whole number of periods. func (s *snapshotSchedule) slotAfter(t time.Time) time.Time { - p := int64(s.period) - base := t.UnixNano() / p * p - slot := time.Unix(0, base).Add(s.offset) - if !slot.After(t) { - slot = slot.Add(s.period) + if t.Before(s.origin) { + return s.origin } - return slot + return s.origin.Add((t.Sub(s.origin)/s.period + 1) * s.period) } // due returns when the next attempt is due. func (s *snapshotSchedule) due() time.Time { return s.next } -// align handles a wall-clock step backwards (now earlier than when the -// next attempt was set): a retry keeps its delay, counted from now; a slot -// becomes the first slot after now. -func (s *snapshotSchedule) align(now time.Time) { - if !now.Before(s.setAt) { - return - } - if s.retry { - s.next = now.Add(s.next.Sub(s.setAt)) - } else { - s.next = s.slotAfter(now) - } - s.setAt = now -} - // record records the outcome of an attempt made at now: nil is a // success (the next attempt is the next slot); a *SnapshotSkip is counted // by reason and retried after the backoff cap; any other error is a // failure, recorded with its code, and retried with a doubling backoff. func (s *snapshotSchedule) record(now time.Time, err error) { var skip *SnapshotSkip - s.setAt, s.retry = now, err != nil switch { case err == nil: s.lastOK, s.failure, s.attempts = now, nil, 0 @@ -226,11 +188,9 @@ func (sl *snapshotSlot) status(now time.Time) ScheduledSnapshotStatus { return sl.s.status(now) } -// alignedDue aligns the schedule to now and returns its due time. -func (sl *snapshotSlot) alignedDue(now time.Time) time.Time { +func (sl *snapshotSlot) due() time.Time { sl.mu.Lock() defer sl.mu.Unlock() - sl.s.align(now) return sl.s.due() } @@ -241,18 +201,13 @@ func (sl *snapshotSlot) record(now time.Time, err error) { } // chunkSnapshotLoop takes volumeID's scheduled snapshots while the -// attachment is current. It sleeps at most snapshotWake at a time and -// compares the wall clock with the due time on each wake, so wall-clock -// steps are observed. A restoring volume is skipped. Each attempt is one -// bounded pass: one urgent cut and the snapshot record. An attempt cut -// short by the loop's own end is not recorded. chunkBackground joins it -// with its other workers (INV-MAINT-JOIN). +// attachment is current, on this process's monotonic time. A restoring +// volume is skipped. Each attempt is one bounded pass: one urgent cut and +// the snapshot record. An attempt cut short by the loop's own end is not +// recorded. chunkBackground joins it with its other workers +// (INV-MAINT-JOIN). func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, slot *snapshotSlot) { - sleep := func() time.Duration { - now := p.snapshotNow() - return min(max(slot.alignedDue(now).Sub(now), 0), snapshotWake) - } - timer := time.NewTimer(sleep()) + timer := time.NewTimer(time.Until(slot.due())) defer timer.Stop() timeout := 2 * p.cfg.ChunkCutTimeout if timeout <= 0 { @@ -271,11 +226,7 @@ func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string if ctx.Err() != nil || layer.Fenced() || !current() { return } - at := p.snapshotNow() - if at.Before(slot.alignedDue(at)) { - timer.Reset(sleep()) - continue - } + at := time.Now() var err error if layer.Stats().AbsentChunks > 0 { // Restoring: HEAD names chunks this volume has not fetched yet. @@ -288,11 +239,10 @@ func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string if ctx.Err() != nil { return } - now := p.snapshotNow() - slot.record(now, err) + slot.record(time.Now(), err) if err != nil { - log.Printf("durable: scheduled snapshot volume=%s: %v (next attempt %s)", volumeID, err, slot.alignedDue(now).UTC().Format(time.RFC3339)) + log.Printf("durable: scheduled snapshot volume=%s: %v (next attempt in %s)", volumeID, err, time.Until(slot.due()).Round(time.Second)) } - timer.Reset(sleep()) + timer.Reset(time.Until(slot.due())) } } diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go index e2930c363c..6501e1002a 100644 --- a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go @@ -8,28 +8,29 @@ import ( var schedT0 = time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) -// Each slot starts at a period boundary plus the volume's offset, spread -// over the whole period and stable across restarts; the first attempt is -// the first slot after the start, and consecutive slots are one period -// apart. +// The first slot is the start plus the volume's offset, which lies within +// one period and differs between volumes; after a success the next slot is +// one period later, and a slot is never in the past. func TestSnapshotSchedule_SlotsAreOffsetPerVolume(t *testing.T) { day := 24 * time.Hour offsets := map[time.Duration]bool{} for _, vol := range []string{"v1", "v2", "v3", "a-much-longer-volume-name"} { s := newSnapshotSchedule(vol, day, schedT0) due := s.due() - if !due.After(schedT0) || due.Sub(schedT0) > day { - t.Fatalf("%s: first slot %v, want within one period after %v", vol, due, schedT0) + off := due.Sub(schedT0) + if off < 0 || off >= day { + t.Fatalf("%s: first slot %v after the start, want within one period", vol, off) } - off := time.Duration(due.UnixNano() % int64(day)) offsets[off] = true - if again := newSnapshotSchedule(vol, day, schedT0.Add(5*time.Hour)); time.Duration(again.due().UnixNano()%int64(day)) != off { - t.Fatalf("%s: offset changed across restarts", vol) - } s.record(due, nil) if s.due().Sub(due) != day { t.Fatalf("%s: after a success the next slot is %v later; want one period", vol, s.due().Sub(due)) } + late := due.Add(3*day + time.Hour) // an attempt that ran very late + s.record(late, nil) + if next := s.due(); !next.After(late) || next.Sub(late) > day || next.Sub(due)%day != 0 { + t.Fatalf("%s: after a late success the next slot is %v; want the first slot after it", vol, next) + } } if len(offsets) < 2 { t.Fatalf("every volume got the same offset %v", offsets) @@ -79,7 +80,7 @@ func TestSnapshotSchedule_FailureIsTypedAndBacksOff(t *testing.T) { if st.Attempts != 0 || st.LastFailure != nil || st.LastOkNs != now.UnixNano() { t.Fatalf("after a success: %+v; want the failure cleared and lastOk set", st) } - if next := s.due(); next.Sub(now) > 24*time.Hour || next.UnixNano()%int64(24*time.Hour) != int64(s.offset) { + if next := s.due(); !next.After(now) || next.Sub(now) > 24*time.Hour || next.Sub(s.origin)%(24*time.Hour) != 0 { t.Fatalf("after a success the next attempt is %v; want the next slot", next) } } @@ -106,57 +107,3 @@ func TestSnapshotSchedule_OverdueAfterPeriodPlusRetryCap(t *testing.T) { t.Fatalf("status %+v; want overdue with the failure visible", st) } } - -// Slots come from the wall clock, so the schedule must survive clock steps: -// after a step backwards or forwards, the next attempt is always the first -// slot strictly after the step's now (never in the past, so no burst of -// catch-up attempts, and never more than one period ahead), a step forwards -// past a period plus the retry cap shows as overdue, and a success after -// either step resumes the per-volume slots. -func TestSnapshotSchedule_ClockStepsNeitherRepeatNorStall(t *testing.T) { - day := 24 * time.Hour - s := newSnapshotSchedule("v1", day, schedT0) - ok := s.due() - s.record(ok, nil) - for _, step := range []time.Duration{-3 * time.Hour, -2 * day, 5 * time.Minute, 3 * day} { - now := ok.Add(step) - s.record(now, &SnapshotFailure{Code: "remote_unavailable"}) // an attempt at the stepped clock - if !s.due().After(now) || s.due().Sub(now) > time.Hour { - t.Fatalf("step %v: retry due %v for now %v; want within the backoff after now", step, s.due(), now) - } - s.record(now, nil) - due := s.due() - if !due.After(now) || due.Sub(now) > day || time.Duration(due.UnixNano()%int64(day)) != s.offset { - t.Fatalf("step %v: next slot %v for now %v; want the first per-volume slot after now", step, due, now) - } - if st := s.status(now); st.Overdue || st.LastOkNs != now.UnixNano() { - t.Fatalf("step %v: status %+v right after a success", step, st) - } - } - far := s.due().Add(3 * day) - if !s.status(far).Overdue { - t.Fatal("a clock step forwards past a period plus the retry cap with no success is not overdue") - } -} - -// A retry keeps its own delay across a wall-clock step backwards: a 1 min -// retry set before a 3 h step back is due 1 min after the stepped now, not -// 3 h 1 min later; a slot set before the step becomes the first slot after -// the stepped now. -func TestSnapshotSchedule_BackwardStepKeepsTheRetryDelay(t *testing.T) { - day := 24 * time.Hour - s := newSnapshotSchedule("v1", day, schedT0) - at := s.due() - s.record(at, &SnapshotFailure{Code: "remote_unavailable"}) // retry in 1 min - back := at.Add(-3 * time.Hour) - s.align(back) - if got := s.due().Sub(back); got != time.Minute { - t.Fatalf("retry after a 3 h step back is due %v after the stepped now; want 1m", got) - } - s.record(s.due(), nil) // success: the next slot - back2 := s.due().Add(-2 * day) - s.align(back2) - if due := s.due(); !due.After(back2) || due.Sub(back2) > day || time.Duration(due.UnixNano()%int64(day)) != s.offset { - t.Fatalf("slot after a 2 day step back: %v for now %v; want the first per-volume slot after now", due, back2) - } -} diff --git a/seaweed-block/core/frontend/durable/cut_policy_test.go b/seaweed-block/core/frontend/durable/cut_policy_test.go index 18ad8b8d3a..51bc38ab3f 100644 --- a/seaweed-block/core/frontend/durable/cut_policy_test.go +++ b/seaweed-block/core/frontend/durable/cut_policy_test.go @@ -37,21 +37,21 @@ func TestCutPolicy_OnlyTheTimerTriggers(t *testing.T) { func TestCutPolicy_AnySuccessfulCutResetsTheTimer(t *testing.T) { pol := testPolicy() s := cutSchedule{lastSuccess: t0} - // An explicit Cut, Snapshot or Detach succeeded at 20 s: the layer - // reports it and the timer restarts from there. - s = s.observe(at(20 * time.Second).UnixNano()) + // An explicit Cut, Snapshot or Detach succeeded; the loop sees the + // layer's new LastCutNs at 20 s and the timer restarts from there. + s = s.observe(101, at(20*time.Second)) if r, ok := pol.dueNR(s, at(45*time.Second)); ok { t.Fatalf("due (%s) 25 s after an explicit cut", r) } if _, ok := pol.dueNR(s, at(50*time.Second)); !ok { t.Fatal("not due 30 s after the explicit cut") } - // An older report never moves the timer back. - if got := s.observe(at(5 * time.Second).UnixNano()); !got.lastSuccess.Equal(at(20 * time.Second)) { - t.Fatalf("older report moved the timer to %v", got.lastSuccess) + // The same report seen again does not move the timer. + if got := s.observe(101, at(40*time.Second)); !got.lastSuccess.Equal(at(20 * time.Second)) { + t.Fatalf("a repeated report moved the timer to %v", got.lastSuccess) } // An automatic success restarts it too. - s = pol.after(s, at(50*time.Second), at(50*time.Second+200*time.Millisecond), nil) + s = pol.after(s, at(50*time.Second), at(50*time.Second+200*time.Millisecond), nil, 102) if _, ok := pol.dueNR(s, at(79*time.Second)); ok { t.Fatal("due less than 30 s after an automatic success") } @@ -61,7 +61,7 @@ func TestCutPolicy_MinimumSpacingBetweenAutomaticCuts(t *testing.T) { pol := testPolicy() pol.interval = 500 * time.Millisecond s := cutSchedule{lastSuccess: t0} - s = pol.after(s, at(10*time.Second), at(10*time.Second+50*time.Millisecond), nil) + s = pol.after(s, at(10*time.Second), at(10*time.Second+50*time.Millisecond), nil, 101) if r, ok := pol.dueNR(s, at(10*time.Second+900*time.Millisecond)); ok { t.Fatalf("automatic cut again after 0.9 s (%s)", r) } @@ -77,7 +77,7 @@ func TestCutPolicy_FailureBacksOffAndResetsNothing(t *testing.T) { now := at(30 * time.Second) var waits []time.Duration for i := 0; i < 7; i++ { - s = pol.after(s, now, now, fail) + s = pol.after(s, now, now, fail, 0) waits = append(waits, s.backoff) if _, ok := pol.dueNR(s, now.Add(s.backoff-time.Millisecond)); ok { t.Fatalf("retry %d due before its backoff %s", i, s.backoff) @@ -96,7 +96,7 @@ func TestCutPolicy_FailureBacksOffAndResetsNothing(t *testing.T) { if !s.lastSuccess.Equal(t0) { t.Fatalf("a failure moved the last success to %v", s.lastSuccess) } - s = pol.after(s, now, now, nil) + s = pol.after(s, now, now, nil, 101) if s.backoff != 0 || !s.retryAt.IsZero() || !s.lastSuccess.Equal(now) { t.Fatalf("success did not clear the backoff: %+v", s) } @@ -112,12 +112,12 @@ func TestCutPolicy_ExplicitSuccessClearsFailedAutoBackoff(t *testing.T) { fail := errors.New("remote unavailable") now := at(time.Second) for s.backoff < pol.backoffMax { - s = pol.after(s, now, now, fail) + s = pol.after(s, now, now, fail, 100) now = now.Add(time.Millisecond) } retryAt := s.retryAt explicit := now.Add(2 * time.Second) // well before retryAt (30 s away) - s = s.observe(explicit.UnixNano()) + s = s.observe(200, explicit) next := explicit.Add(pol.interval) if !next.Before(retryAt) { t.Fatalf("test setup: next timer cut %v not before the old retry %v", next, retryAt) @@ -128,12 +128,13 @@ func TestCutPolicy_ExplicitSuccessClearsFailedAutoBackoff(t *testing.T) { if r, ok := pol.dueNR(s, next); !ok || r != "periodic" { t.Fatalf("one interval after the explicit success: %q %v; want periodic (backoff %s, retry at %v)", r, ok, s.backoff, s.retryAt) } - // A success older than the failure leaves the backoff in force. - s2 := cutSchedule{lastSuccess: t0} - s2 = pol.after(s2, at(10*time.Second), at(10*time.Second), fail) - s2 = s2.observe(at(5 * time.Second).UnixNano()) + // The cut the failure already saw (it completed before the failure) + // leaves the backoff in force. + s2 := cutSchedule{lastSuccess: t0, seenNs: 90} + s2 = pol.after(s2, at(10*time.Second), at(10*time.Second), fail, 100) + s2 = s2.observe(100, at(11*time.Second)) if s2.retryAt.IsZero() { - t.Fatal("a success older than the failure cleared its backoff") + t.Fatal("a success the failure already saw cleared its backoff") } } @@ -159,7 +160,7 @@ func TestCutPolicy_NothingDueWhileReconciling(t *testing.T) { func TestCutPolicy_StaggerPreservesExplicitTimerReset(t *testing.T) { pol := testPolicy() - s := initialCutSchedule("v1", pol.interval, t0, true) + s := initialCutSchedule("v1", pol.interval, t0, true, 0) if !s.lastSuccess.Equal(t0) || !s.firstDue.After(t0) || s.firstDue.After(t0.Add(pol.interval)) { t.Fatal("phase fabricated success or exceeded first period", s) } @@ -170,7 +171,7 @@ func TestCutPolicy_StaggerPreservesExplicitTimerReset(t *testing.T) { t.Fatal("first phased cut not due") } explicit := t0.Add(s.firstDue.Sub(t0) / 2) - s = s.observe(explicit.UnixNano()) + s = s.observe(5, explicit) if !s.lastSuccess.Equal(explicit) || !s.firstDue.IsZero() { t.Fatal("stagger hid explicit success", s) } @@ -181,3 +182,31 @@ func TestCutPolicy_StaggerPreservesExplicitTimerReset(t *testing.T) { t.Fatal("explicit success did not restart timer") } } + +// The timer runs on this process's monotonic time: the layer's LastCutNs +// is only the identity of the latest cut. A stamp from a wall clock that +// lags or leaps (a step, another host) is taken in at the moment it is +// observed, so the next timer cut is one interval after the observation; +// and at start the layer's existing cut (from before a restart) is not +// new, so the startup phase stands. +func TestCutPolicy_TimerIgnoresTheWallClockOfLastCutNs(t *testing.T) { + pol := testPolicy() + s := cutSchedule{lastSuccess: t0} + for _, stamp := range []time.Time{t0.Add(-3 * time.Hour), t0.Add(48 * time.Hour)} { + seen := at(20 * time.Second) + s = cutSchedule{lastSuccess: t0}.observe(stamp.UnixNano(), seen) + if !s.lastSuccess.Equal(seen) { + t.Fatalf("stamp %v: last success %v; want the observation time %v", stamp, s.lastSuccess, seen) + } + if _, ok := pol.dueNR(s, seen.Add(pol.interval-time.Nanosecond)); ok { + t.Fatalf("stamp %v: due before one interval after the observation", stamp) + } + if _, ok := pol.dueNR(s, seen.Add(pol.interval)); !ok { + t.Fatalf("stamp %v: not due one interval after the observation", stamp) + } + } + restart := initialCutSchedule("v1", pol.interval, t0, true, 777) + if got := restart.observe(777, at(time.Second)); got.firstDue.IsZero() || !got.lastSuccess.Equal(t0) { + t.Fatalf("after a restart the existing cut was taken in as new: %+v", got) + } +} diff --git a/seaweed-block/core/frontend/durable/maintenance_policy_test.go b/seaweed-block/core/frontend/durable/maintenance_policy_test.go index 734e5b89e6..bf06023849 100644 --- a/seaweed-block/core/frontend/durable/maintenance_policy_test.go +++ b/seaweed-block/core/frontend/durable/maintenance_policy_test.go @@ -13,7 +13,7 @@ func TestMaintenanceVolumePhasesDoNotAlign(t *testing.T) { interval := 15 * time.Minute seen := map[time.Duration]bool{} for i := 0; i < 200; i++ { - s := initialCutSchedule(fmt.Sprintf("volume-%d", i), interval, t0, true) + s := initialCutSchedule(fmt.Sprintf("volume-%d", i), interval, t0, true, 0) offset := s.firstDue.Sub(t0) if offset <= 0 || offset >= interval { t.Fatalf("phase outside interval: %s", offset) diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 2012edef19..f004ad80f4 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -231,9 +231,6 @@ type DurableProvider struct { // testAfterChunkResolve, test-only, runs in CutVolume right after the // volume's handle and layer are resolved. testAfterChunkResolve func() - // testSnapshotClock, test-only, replaces the scheduled-snapshot wall - // clock (snapshotWallNow). - testSnapshotClock func() time.Time // testDetachStopIO, test-only, replaces DetachVolume's StopIO call (so a // test can force the failed-drain branch); testDetachTrace, test-only, // observes the detach's stages and their deadlines ("cut", "settle"). @@ -616,7 +613,7 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus { cs.HostBudget = budget.Snapshot() } if cv.snapshots != nil { - ss := cv.snapshots.status(p.snapshotNow()) + ss := cv.snapshots.status(time.Now()) cs.ScheduledSnapshot = &ss } st.Chunk = cs diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index bd700e1de3..614e05b2ae 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -331,7 +331,7 @@ func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer st if !snapshotsOn { h.snapshots = nil } else if h.snapshots == nil { - h.snapshots = &snapshotSlot{s: newSnapshotSchedule(volumeID, p.cfg.ChunkSnapshotPeriod, p.snapshotNow())} + h.snapshots = &snapshotSlot{s: newSnapshotSchedule(volumeID, p.cfg.ChunkSnapshotPeriod, time.Now())} } lin := h.chunkLineage current := func() bool { return p.maintenanceCurrent(volumeID, h, layer, lin) } @@ -663,28 +663,36 @@ type cutPolicy struct { interval, minSpacing, backoffMin, backoffMax time.Duration } +// cutSchedule runs on in-process monotonic time: every time in it is a +// time.Now() reading of this process (or derived from one), never the +// layer's persisted LastCutNs, so wall-clock steps move nothing and a +// restart starts a fresh schedule. LastCutNs is used only as the identity +// of the latest cut: a value not seen before is a new successful cut. type cutSchedule struct { - lastSuccess time.Time // last successful cut of any kind - lastAuto time.Time // start of the last automatic cut - failedAt time.Time // end of the last failed automatic cut - retryAt time.Time // a failed automatic cut's backoff ends here - backoff time.Duration - firstDue time.Time // startup phase only; never a fabricated success + lastSuccess time.Time // last successful cut of any kind, as observed here + lastAuto time.Time // start of the last automatic cut + failedAt time.Time // end of the last failed automatic cut + retryAt time.Time // a failed automatic cut's backoff ends here + backoff time.Duration + firstDue time.Time // startup phase only; never a fabricated success + seenNs int64 // the layer's LastCutNs last taken in + failedSeenNs int64 // the layer's LastCutNs when the last automatic cut failed } -// observe takes in a successful cut the layer reports (any trigger). A -// success after the last failed automatic cut makes that failure's -// backoff obsolete. -func (s cutSchedule) observe(lastCutNs int64) cutSchedule { - if lastCutNs > 0 { - c := time.Unix(0, lastCutNs) - if c.After(s.lastSuccess) { - s.lastSuccess = c - s.firstDue = time.Time{} - } - if !s.failedAt.IsZero() && c.After(s.failedAt) { - s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{} - } +// observe takes in, at now, the latest cut the layer reports (any +// trigger): a LastCutNs not seen before is a success at now. A cut other +// than the one the last failure saw makes that failure's backoff obsolete. +func (s cutSchedule) observe(lastCutNs int64, now time.Time) cutSchedule { + if lastCutNs == 0 || lastCutNs == s.seenNs { + return s + } + s.seenNs = lastCutNs + if now.After(s.lastSuccess) { + s.lastSuccess = now + } + s.firstDue = time.Time{} + if !s.failedAt.IsZero() && lastCutNs != s.failedSeenNs { + s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{} } return s } @@ -709,10 +717,12 @@ func (pol cutPolicy) due(s cutSchedule, now time.Time, reconciling bool) (string return "", false } -// after records the outcome of an automatic cut started at start. -func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error) cutSchedule { +// after records the outcome of an automatic cut started at start, with +// the layer's LastCutNs read after it. +func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error, lastCutNs int64) cutSchedule { s.lastAuto = start if err == nil { + s.seenNs = lastCutNs s.firstDue = time.Time{} s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{} if end.After(s.lastSuccess) { @@ -728,12 +738,15 @@ func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error) cutSc default: s.backoff *= 2 } - s.failedAt, s.retryAt = end, end.Add(s.backoff) + s.failedAt, s.retryAt, s.failedSeenNs = end, end.Add(s.backoff), lastCutNs return s } -func initialCutSchedule(volumeID string, interval time.Duration, now time.Time, stagger bool) cutSchedule { - s := cutSchedule{lastSuccess: now} +// initialCutSchedule starts a fresh schedule at now; lastCutNs is the +// layer's latest cut at start, so a cut from before (another process +// lifetime) is not taken in as new. +func initialCutSchedule(volumeID string, interval time.Duration, now time.Time, stagger bool, lastCutNs int64) cutSchedule { + s := cutSchedule{lastSuccess: now, seenNs: lastCutNs} if stagger && interval > 0 { phase := hostlimit.Phase(volumeID, interval) startup := hostlimit.Phase(volumeID+":startup", min(interval, 10*time.Second)) @@ -754,7 +767,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer backoffMin: chunkCutBackoffMin, backoffMax: chunkCutBackoffMax, } - s := initialCutSchedule(volumeID, pol.interval, time.Now(), p.cfg.ChunkStagger) + s := initialCutSchedule(volumeID, pol.interval, time.Now(), p.cfg.ChunkStagger, layer.Stats().LastCutNs) t := time.NewTicker(chunkSchedulePoll) defer t.Stop() for { @@ -767,8 +780,8 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer return } ls := layer.Stats() - s = s.observe(ls.LastCutNs) start := time.Now() + s = s.observe(ls.LastCutNs, start) reason, ok := pol.due(s, start, ls.Reconciling) if !ok { continue @@ -798,7 +811,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer } } cancel() - s = pol.after(s, start, time.Now(), err) + s = pol.after(s, start, time.Now(), err, layer.Stats().LastCutNs) if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil { log.Printf("durable: %s chunk cut for volume=%s: %v (retry in %s)", reason, volumeID, err, s.backoff) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 40c14ce7af..a8403a48ae 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -549,12 +549,13 @@ Notes: | `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | | `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE | | `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | -| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind (explicit, snapshot, detach, no-op) restarts the periodic timer. A periodic cut the loop decided from an older last cut, while another cut was still running, is skipped under the capture lock once that cut has completed: no automatic cut follows another cut within the interval. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestChunkPeriodicCut_SkipsAfterANewerCut` (`core/storage/chunk_periodic_cut_test.go`) | — | ACTIVE | +| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestChunkPeriodicCut_SkipsAfterANewerCut` (`core/storage/chunk_periodic_cut_test.go`); `TestCutPolicy_TimerIgnoresTheWallClockOfLastCutNs` (`core/frontend/durable/cut_policy_test.go`) | — | ACTIVE | A guest read has a cooperative arrival budget; internal contextless readers keep the owned fill timeout (default 30 s). With five immediate host retries, cold fills slower than roughly 20–24 s can still end in guest EIO despite shared work; retry-delay advertisement remains separate. A changed generation replaces its promise without abandoning the old worker. `AllBlocks` returns an error and no partial image on a failed read; the rebuild sender propagates it before sending blocks. Notes: +- `INV-CUT-TIMER-RESTART-001`: the layer's persisted `LastCutNs` is only the identity of the latest cut: a value not seen before is a success at the moment it is observed; at start the existing value is not new, so a restart keeps the startup phase. The scheduled-snapshot worker (`INV-SNAP-SCHEDULED-KEEP-001`) runs on the same monotonic time: slots are the loop start plus the volume's offset plus whole periods; a re-armed loop on the same handle keeps its schedule (failures, retry time); a restart starts a fresh one. Tests: `TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime`, `_RearmKeepsTheSchedule`, `_OverdueWithNoSuccess`, `TestSnapshotSchedule_SlotsAreOffsetPerVolume`. - `INV-CUT-PRECOPY-001`: Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Ordinary refusal reopens tentative admission before rolling uploads; guest-frozen refusal instead sends no payload. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; on resume every queued waiter is granted in arrival order under one lock hold; each then passes the normal gate; completion is unordered. The ended pause is cleared before those normal gate checks; queue deadlines are measured once from each command arrival and capped by five seconds or its earlier caller deadline, so independent I/O is concurrent and later arrivals cannot inherit an expired pause; host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Ordinary admission never uses unknown samples. A guest-frozen attempt skips staging, forecasts and rechecks against five seconds minus guest elapsed, and refuses without uploading if it cannot fit. Only an explicit final override can bypass that estimate guard, with over_budget recorded; authority and publication settlement remain mandatory. Checkpoint tails are advisory same-window measurements. Nested Sync phases and live barrier-prefix spans explain fixed cost without double counting. - `INV-CUT-STAGED-REUSE-001`: `captureLocked` also requires HEAD's generation to be the one the stage was compared against (code reading; not asserted by these tests). From 746c5a1a8aea9af81d24c1dded75b989e721ce57 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 07:05:29 -0800 Subject: [PATCH 15/34] fix: classify workspace caller end from request context --- seaweed-block/core/authority/workspace.go | 14 +++++---- .../workspace_outcome_uncertain_test.go | 2 +- .../core/host/master/workspace_service.go | 9 +++--- .../workspace_uncertain_precedence_test.go | 14 +++++++++ .../docs/design/agent-workspace-design.md | 4 +-- seaweed-block/docs/design/invariants.md | 6 ++-- seaweed-block/docs/spec/README.md | 15 ++++++++++ .../docs/spec/WorkspaceMoveOutcome.tla | 30 ++++++++++++------- .../docs/spec/cfg/WorkspaceMoveOutcome.cfg | 4 +-- 9 files changed, 69 insertions(+), 29 deletions(-) diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 849ae04d24..9f3046cbb2 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -201,10 +201,14 @@ func (p *Publisher) IssuedWorkspaceMove(req WorkspaceMoveRequest) bool { // WorkspaceMoveOutcomeError classifies a failed move at the reply boundary. // M2 Uncertain / INV-AUTH-UNCERTAIN-001: admission cannot promise no effect -// while an earlier workspace write may have landed. Cancellation stays typed. -func (p *Publisher) WorkspaceMoveOutcomeError(volume string, err error) error { - if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { - return err +// while an earlier workspace write may have landed. Actual request cancellation +// stays typed; dependency errors do not bypass uncertainty. +func (p *Publisher) WorkspaceMoveOutcomeError(ctx context.Context, volume string, err error) error { + if err == nil { + return nil + } + if callerErr := ctx.Err(); callerErr != nil { + return callerErr } p.mu.Lock() uncertain := p.workspaceUncertain[volume] @@ -216,7 +220,7 @@ func (p *Publisher) WorkspaceMoveOutcomeError(volume string, err error) error { } func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, head WorkspaceHead) (_ WorkspaceMoveRecord, resultErr error) { - defer func() { resultErr = p.WorkspaceMoveOutcomeError(req.VolumeID, resultErr) }() + defer func() { resultErr = p.WorkspaceMoveOutcomeError(ctx, req.VolumeID, resultErr) }() if err := ctx.Err(); err != nil { return WorkspaceMoveRecord{}, err } diff --git a/seaweed-block/core/authority/workspace_outcome_uncertain_test.go b/seaweed-block/core/authority/workspace_outcome_uncertain_test.go index a92794f0ea..46d9050b3c 100644 --- a/seaweed-block/core/authority/workspace_outcome_uncertain_test.go +++ b/seaweed-block/core/authority/workspace_outcome_uncertain_test.go @@ -118,7 +118,7 @@ func TestWorkspaceUncertaintyPrecedesRequestRefusal(t *testing.T) { if ctx.Err() != nil { t.Fatal("request parent unexpectedly ended") } - if err := p.WorkspaceMoveOutcomeError("v", dependencyErr); !errors.Is(err, ErrWorkspaceOutcomeUncertain) { + if err := p.WorkspaceMoveOutcomeError(ctx, "v", dependencyErr); !errors.Is(err, ErrWorkspaceOutcomeUncertain) { t.Errorf("live caller dependency error bypassed UNKNOWN: %v", err) } } diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 499b6af680..fa363061f0 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -192,11 +192,10 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) var postIssue, unknown error defer func() { // M2 Uncertain reply precedence applies even to preflight/HEAD errors. - outcome := resultErr - if code := status.Code(resultErr); code != codes.Canceled && code != codes.DeadlineExceeded { - outcome = s.host.Publisher().WorkspaceMoveOutcomeError(q.GetVolumeId(), resultErr) - } - if errors.Is(outcome, authority.ErrWorkspaceOutcomeUncertain) { + outcome := s.host.Publisher().WorkspaceMoveOutcomeError(ctx, q.GetVolumeId(), resultErr) + if callerErr := ctx.Err(); resultErr != nil && callerErr != nil { + resultErr = workspaceError(callerErr) + } else if errors.Is(outcome, authority.ErrWorkspaceOutcomeUncertain) { unknown, refusal = outcome, "" resultErr = status.Errorf(codes.Internal, "workspace move %q of volume %q has an UNKNOWN outcome: %v; the volume's workspace authority stays uncertain until the master restarts; after the restart, rerun with the same request id", q.GetRequestId(), q.GetVolumeId(), outcome) } diff --git a/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go b/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go index 07777d9a8e..91d381a3bd 100644 --- a/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go +++ b/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go @@ -20,6 +20,7 @@ func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) { var headFailure atomic.Int32 var childDeadlineObserved atomic.Bool var latch func() error + var cancelRequest context.CancelFunc h, c, ctx := reviewBindingHostWithReader(t, func(readCtx context.Context, _ string) (authority.WorkspaceHead, error) { if inject.Swap(false) { if err := latch(); err != nil { @@ -39,6 +40,11 @@ func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) { dependency, cancel := context.WithCancel(readCtx) cancel() return authority.WorkspaceHead{}, dependency.Err() + case 4: + dependency, cancel := context.WithDeadline(readCtx, time.Unix(0, 1)) + defer cancel() + cancelRequest() + return authority.WorkspaceHead{}, dependency.Err() } return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil }) @@ -98,6 +104,14 @@ func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) { t.Errorf("live-parent HEAD dependency end bypassed UNKNOWN: mode=%d err=%v", mode, err) } } + caller, cancelCaller := context.WithCancel(context.Background()) + cancelRequest = cancelCaller + headFailure.Store(4) + _, err := (&services{host: h}).MoveWorkspace(caller, request("clean")) + cancelCaller() + if caller.Err() != context.Canceled || status.Code(err) != codes.Canceled { + t.Errorf("actual caller end lost to dependency status: %v", err) + } // These direct calls inspect the server result, not the client's own // deadline override, so reply classification must preserve both. for _, deadline := range []bool{false, true} { diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 8e6736df1f..43813012d6 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -285,11 +285,11 @@ intents remain rooted after restart; elapsed TTL is not a settlement proof. **Master side of a renewal** (`core/authority/workspace_lease_view.go`): blockmaster answers a renewal of an established lease from memory, under a small leaf lock, with no disk write and without waiting for other authority writes. The grant is min(now + TTL, durable horizon), where the horizon is the lease expiry stored on disk; a background extension, an ordinary authority write, keeps the horizon about 1.5·TTL ahead of the last renewal that triggered it. Only the first grant of a lease is written synchronously. If extensions fall behind, grants shrink and the host fences by the horizon minus half the skew bound; a failed extension write makes the volume uncertain and refuses renewals that would issue a new or extended grant (a Revoking lease still gets its bounded drain reply). -**Uncertain move outcomes** (`INV-AUTH-UNCERTAIN-001`): at a failed move's reply boundary, the publisher's per-volume persistence latch takes precedence over request, forced-admission, HEAD-read and target refusals. Such a reply is UNKNOWN with same-request recovery after reload, without another authority write. Caller cancellation/deadline stays typed; a known successful issued replay remains valid. +**Uncertain move outcomes** (`INV-AUTH-UNCERTAIN-001`): at a failed move's reply boundary, the publisher's per-volume persistence latch takes precedence over request, forced-admission, HEAD-read and target refusals. Such a reply is UNKNOWN with same-request recovery after reload, without another authority write. Only an ended request context preserves typed cancellation/deadline; dependency context errors with a live request are UNKNOWN. A known successful issued replay remains valid. ```mermaid flowchart LR - E[Move error] --> C{Caller canceled or deadline?} + E[Move error] --> C{Request context ended?} C -->|yes| T[Typed caller error] C -->|no| U{Persistence uncertain at reply?} U -->|yes| X[UNKNOWN, never definite admission refusal] diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 1a773c0457..59225bc177 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -82,7 +82,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` | | any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing, but its durable outcome may be unknown | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | | any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` | -| Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` | +| Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; request-context cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` | | Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | **Workspace lease and move, in blockmaster.** @@ -433,7 +433,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w Notes: -- `INV-AUTH-UNCERTAIN-001` detail: After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. Move error classification reads the per-volume uncertainty latch under the publisher lock at reply time, covering RPC preflight, HEAD reads and local admission as well as the publisher. The unknown outcome overrides the refusal audit entry. It adds no authority write and does not clear uncertainty. +- `INV-AUTH-UNCERTAIN-001` detail: After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. Move error classification reads the per-volume uncertainty latch under the publisher lock at reply time, covering RPC preflight, HEAD reads and local admission as well as the publisher. Only the actual request context proves caller end; a dependency timeout/cancellation with a live request is UNKNOWN too. The unknown outcome overrides the refusal audit entry. It adds no authority write and does not clear uncertainty. - `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged. - `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. @@ -458,7 +458,7 @@ Notes: | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | -| `INV-AUTH-UNCERTAIN-001` | Failed workspace writes latch uncertainty until reload. Authority and lease extensions refuse; revoking leases keep bounded drain replies. A failed move is UNKNOWN before admission refusal; caller cancellation/deadline stays typed. Known issued replays remain valid. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `WorkspaceMoveOutcomeError`, `MoveWorkspace`; `core/host/master/workspace_service.go` `MoveWorkspace` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUncertaintyPrecedesRequestRefusal`, `TestWorkspaceMoveUnknownPrecedesAdmissionRefusals`, `TestWorkspaceUncertainIssueWriteIsTyped` | `ControlPlane` `UniqueEpoch`; `WorkspaceMoveOutcome` `NoFalseRefusal`, `CallerEndTyped` | ACTIVE | +| `INV-AUTH-UNCERTAIN-001` | Failed workspace writes latch uncertainty until reload. Authority and lease extensions refuse; revoking leases keep bounded drain replies. A failed move is UNKNOWN before admission refusal; request-context cancellation/deadline stays typed. Known issued replays remain valid. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `WorkspaceMoveOutcomeError`, `MoveWorkspace`; `core/host/master/workspace_service.go` `MoveWorkspace` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUncertaintyPrecedesRequestRefusal` (`core/authority/workspace_outcome_uncertain_test.go`), `TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` (`core/host/master/workspace_uncertain_precedence_test.go`), `TestWorkspaceUncertainIssueWriteIsTyped` (`core/authority/workspace_outcome_uncertain_test.go`) | `ControlPlane` `UniqueEpoch`; `WorkspaceMoveOutcome` `NoFalseRefusal`, `CallerEndTyped`, `UncertainReplyClass` | ACTIVE | | `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. A move issue publishes the derived view and the new holder's initial deadline in one lease-lock section, never lowering a deadline a renewal raised. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`, `publishIssuedLeaseLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceIssuePublishNeverLowersARenewedDeadline` (`core/authority/workspace_issue_publish_test.go`) | — | ACTIVE | | `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that replaces the lease with the new holder's is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index fbcc5e29ad..edd9521d8c 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -546,3 +546,18 @@ server caller-end classification), and the retained The new tests use a real file-store rename followed by an injected error; a readout verifies that the failed write actually landed while memory rolled back. They also check no new authority epoch/move and per-volume scope. + + +2026-11-21 caller-provenance fold: `cfg/WorkspaceMoveOutcome.cfg` exhausts +223 generated / 135 distinct states, depth 5, queue empty (TLC 2.19 above). +Bounds remain one volume, seven dependency/admission causes, one failed write +and one reply; the actual request independently remains live or ends canceled / +deadline. `NoFalseRefusal`, `CallerEndTyped` and `UncertainReplyClass` hold. +`ConfuseDependencyEnd=TRUE` violates `UncertainReplyClass` (69 distinct states +before the counterexample); `BypassUncertainty=TRUE` violates `NoFalseRefusal` +(54 distinct states). The dependency-confusion negative maps to the live-parent +HEAD-read deadline/cancellation controls in +`TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` and the live-context helper +controls in `TestWorkspaceUncertaintyPrecedesRequestRefusal`. Actual request +cancellation retains its own controls, including a conflicting dependency status. +These are reply-classification claims, not authority-durability or delivery proof. diff --git a/seaweed-block/docs/spec/WorkspaceMoveOutcome.tla b/seaweed-block/docs/spec/WorkspaceMoveOutcome.tla index 6e7fb17834..e38d5be5a1 100644 --- a/seaweed-block/docs/spec/WorkspaceMoveOutcome.tla +++ b/seaweed-block/docs/spec/WorkspaceMoveOutcome.tla @@ -1,25 +1,33 @@ ------------------------- MODULE WorkspaceMoveOutcome ------------------------- EXTENDS Naturals, FiniteSets -CONSTANT BypassUncertainty -VARIABLES uncertain, landed, cause, reply, uncertainAtReply -vars == <> -Causes == {"request", "forced_preflight", "head", "target", "endpoint", "canceled", "deadline"} +CONSTANTS BypassUncertainty, ConfuseDependencyEnd +VARIABLES uncertain, landed, cause, callerEnd, reply, uncertainAtReply +vars == <> +Causes == {"request", "forced_preflight", "head", "target", "endpoint", + "dependency_canceled", "dependency_deadline"} Init == /\ uncertain = FALSE /\ landed = FALSE /\ cause = "none" - /\ reply = "none" /\ uncertainAtReply = FALSE + /\ callerEnd = "live" /\ reply = "none" /\ uncertainAtReply = FALSE FailedWrite == /\ ~uncertain /\ reply = "none" /\ uncertain' = TRUE /\ landed' \in BOOLEAN - /\ UNCHANGED <> + /\ UNCHANGED <> AdmissionError == /\ cause = "none" /\ reply = "none" /\ cause' \in Causes - /\ UNCHANGED <> + /\ UNCHANGED <> +CallerEnds == /\ callerEnd = "live" /\ reply = "none" + /\ callerEnd' \in {"canceled", "deadline"} + /\ UNCHANGED <> +DependencyEnd == cause \in {"dependency_canceled", "dependency_deadline"} Reply == /\ cause # "none" /\ reply = "none" - /\ reply' = IF cause \in {"canceled", "deadline"} THEN cause + /\ reply' = IF callerEnd # "live" THEN callerEnd + ELSE IF ConfuseDependencyEnd /\ DependencyEnd + THEN IF cause = "dependency_canceled" THEN "canceled" ELSE "deadline" ELSE IF uncertain /\ ~BypassUncertainty THEN "unknown" ELSE "refused" /\ uncertainAtReply' = uncertain - /\ UNCHANGED <> -Next == FailedWrite \/ AdmissionError \/ Reply + /\ UNCHANGED <> +Next == FailedWrite \/ AdmissionError \/ CallerEnds \/ Reply Spec == Init /\ [][Next]_vars NoFalseRefusal == ~(reply = "refused" /\ uncertainAtReply) -CallerEndTyped == cause \in {"canceled", "deadline"} /\ reply # "none" => reply = cause +CallerEndTyped == callerEnd # "live" /\ reply # "none" => reply = callerEnd +UncertainReplyClass == uncertainAtReply /\ callerEnd = "live" /\ reply # "none" => reply = "unknown" ============================================================================= diff --git a/seaweed-block/docs/spec/cfg/WorkspaceMoveOutcome.cfg b/seaweed-block/docs/spec/cfg/WorkspaceMoveOutcome.cfg index 86f9b1b177..b1095f5df5 100644 --- a/seaweed-block/docs/spec/cfg/WorkspaceMoveOutcome.cfg +++ b/seaweed-block/docs/spec/cfg/WorkspaceMoveOutcome.cfg @@ -1,3 +1,3 @@ SPECIFICATION Spec -CONSTANT BypassUncertainty = FALSE -INVARIANTS NoFalseRefusal CallerEndTyped +CONSTANTS BypassUncertainty = FALSE ConfuseDependencyEnd = FALSE +INVARIANTS NoFalseRefusal CallerEndTyped UncertainReplyClass From 5e4f2f3d45e018e85e39d131128c62ee97002f44 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 07:12:20 -0800 Subject: [PATCH 16/34] storage, durable: cuts are ordered by an in-process CutSeq, never by wall stamps; the periodic decision skips once CutSeq moved Co-Authored-By: Claude Opus 5.5 --- .../durable/chunk_snapshot_loop_test.go | 57 ++++++++++++------- .../core/frontend/durable/cut_policy_test.go | 44 +++++++------- .../core/frontend/durable/provider_chunk.go | 55 +++++++++--------- seaweed-block/core/storage/chunk_layer.go | 1 + .../core/storage/chunk_periodic_cut.go | 14 +++-- .../core/storage/chunk_periodic_cut_test.go | 41 ++++++++++++- seaweed-block/core/storage/chunk_seam.go | 5 +- seaweed-block/docs/design/invariants.md | 14 ++++- seaweed-block/docs/status-schema.md | 1 + 9 files changed, 147 insertions(+), 85 deletions(-) diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_loop_test.go b/seaweed-block/core/frontend/durable/chunk_snapshot_loop_test.go index a21cdbc878..cdfd91df56 100644 --- a/seaweed-block/core/frontend/durable/chunk_snapshot_loop_test.go +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_loop_test.go @@ -52,6 +52,16 @@ func snapLoop(take func(context.Context) error) (h *volHandle, start func(), sto return h, start, stop } +// recv waits for ch for at most an hour of virtual time. +func recv(t *testing.T, ch <-chan struct{}, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(time.Hour): + t.Fatalf("%s did not happen", what) + } +} + // The first attempt is at the start plus the volume's offset and the next // one a period later, both on the monotonic clock. func TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime(t *testing.T) { @@ -101,21 +111,24 @@ func TestScheduledSnapshotLoop_RearmKeepsTheSchedule(t *testing.T) { return &SnapshotFailure{Code: "remote_unavailable"} }) start() + running := true + defer func() { // registered before any check: whichever loop runs is joined + if running && !stop() { + t.Error("the loop was not joined") + } + }() time.Sleep(time.Until(h.snapshots.due()) + time.Second) synctest.Wait() slot, retry := h.snapshots, h.snapshots.due() if st := slot.status(time.Now()); st.Attempts != 1 || st.LastFailure == nil { t.Fatalf("after the first attempt: %+v; want one failure", st) } + running = false if !stop() { t.Fatal("the loop was not joined") } start() - defer func() { - if !stop() { - t.Error("the re-armed loop was not joined") - } - }() + running = true if h.snapshots != slot || h.snapshots.due() != retry || slot.status(time.Now()).Attempts != 1 { t.Fatalf("after re-arm: same schedule %v, due %v (want %v), %+v", h.snapshots == slot, h.snapshots.due(), retry, slot.status(time.Now())) } @@ -143,9 +156,18 @@ func TestScheduledSnapshotLoop_StopJoinsTheAttempt(t *testing.T) { }) start() joined := make(chan bool, 1) - stopping := false - defer func() { // runs after the release below: join the stop, bounded - if !stopping { + stopStarted := false + var released atomic.Bool + free := func() { + if released.CompareAndSwap(false, true) { + close(release) + } + } + // Registered before any check, run last: release the attempt, then + // join the stop (bounded), starting it if the test never did. + defer func() { + free() + if !stopStarted { joined <- stop() } select { @@ -157,26 +179,19 @@ func TestScheduledSnapshotLoop_StopJoinsTheAttempt(t *testing.T) { t.Error("stop did not return") } }() - var released atomic.Bool - defer func() { - if released.CompareAndSwap(false, true) { - close(release) - } - }() time.Sleep(time.Until(h.snapshots.due()) + time.Second) - <-entered - stopping = true + recv(t, entered, "the attempt") + stopStarted = true go func() { joined <- stop() }() - <-cancelled // the attempt saw the cancellation + recv(t, cancelled, "the attempt seeing the cancellation") synctest.Wait() select { - case <-joined: + case ok := <-joined: + joined <- ok // leave it for the deferred join t.Fatal("stop returned while the attempt was still running") default: } - if released.CompareAndSwap(false, true) { - close(release) - } + free() }) } diff --git a/seaweed-block/core/frontend/durable/cut_policy_test.go b/seaweed-block/core/frontend/durable/cut_policy_test.go index 51bc38ab3f..415a178d1e 100644 --- a/seaweed-block/core/frontend/durable/cut_policy_test.go +++ b/seaweed-block/core/frontend/durable/cut_policy_test.go @@ -130,7 +130,7 @@ func TestCutPolicy_ExplicitSuccessClearsFailedAutoBackoff(t *testing.T) { } // The cut the failure already saw (it completed before the failure) // leaves the backoff in force. - s2 := cutSchedule{lastSuccess: t0, seenNs: 90} + s2 := cutSchedule{lastSuccess: t0, seenSeq: 90} s2 = pol.after(s2, at(10*time.Second), at(10*time.Second), fail, 100) s2 = s2.observe(100, at(11*time.Second)) if s2.retryAt.IsZero() { @@ -183,30 +183,26 @@ func TestCutPolicy_StaggerPreservesExplicitTimerReset(t *testing.T) { } } -// The timer runs on this process's monotonic time: the layer's LastCutNs -// is only the identity of the latest cut. A stamp from a wall clock that -// lags or leaps (a step, another host) is taken in at the moment it is -// observed, so the next timer cut is one interval after the observation; -// and at start the layer's existing cut (from before a restart) is not -// new, so the startup phase stands. -func TestCutPolicy_TimerIgnoresTheWallClockOfLastCutNs(t *testing.T) { +// The timer runs on this process's monotonic time and keys on the layer's +// CutSeq, never on a cut's wall stamp: a cut seen for the first time is a +// success at the moment it is observed, so the next timer cut is one +// interval after the observation; at start the layer's existing CutSeq is +// not new, so the startup phase stands. +func TestCutPolicy_TimerRunsOnObservationTime(t *testing.T) { pol := testPolicy() - s := cutSchedule{lastSuccess: t0} - for _, stamp := range []time.Time{t0.Add(-3 * time.Hour), t0.Add(48 * time.Hour)} { - seen := at(20 * time.Second) - s = cutSchedule{lastSuccess: t0}.observe(stamp.UnixNano(), seen) - if !s.lastSuccess.Equal(seen) { - t.Fatalf("stamp %v: last success %v; want the observation time %v", stamp, s.lastSuccess, seen) - } - if _, ok := pol.dueNR(s, seen.Add(pol.interval-time.Nanosecond)); ok { - t.Fatalf("stamp %v: due before one interval after the observation", stamp) - } - if _, ok := pol.dueNR(s, seen.Add(pol.interval)); !ok { - t.Fatalf("stamp %v: not due one interval after the observation", stamp) - } + seen := at(20 * time.Second) + s := cutSchedule{lastSuccess: t0}.observe(1, seen) + if !s.lastSuccess.Equal(seen) { + t.Fatalf("last success %v; want the observation time %v", s.lastSuccess, seen) } - restart := initialCutSchedule("v1", pol.interval, t0, true, 777) - if got := restart.observe(777, at(time.Second)); got.firstDue.IsZero() || !got.lastSuccess.Equal(t0) { - t.Fatalf("after a restart the existing cut was taken in as new: %+v", got) + if _, ok := pol.dueNR(s, seen.Add(pol.interval-time.Nanosecond)); ok { + t.Fatal("due before one interval after the observation") + } + if _, ok := pol.dueNR(s, seen.Add(pol.interval)); !ok { + t.Fatal("not due one interval after the observation") + } + restart := initialCutSchedule("v1", pol.interval, t0, true, 7) + if got := restart.observe(7, at(time.Second)); got.firstDue.IsZero() || !got.lastSuccess.Equal(t0) { + t.Fatalf("the cut existing at start was taken in as new: %+v", got) } } diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 614e05b2ae..5660441c98 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -666,32 +666,32 @@ type cutPolicy struct { // cutSchedule runs on in-process monotonic time: every time in it is a // time.Now() reading of this process (or derived from one), never the // layer's persisted LastCutNs, so wall-clock steps move nothing and a -// restart starts a fresh schedule. LastCutNs is used only as the identity -// of the latest cut: a value not seen before is a new successful cut. +// restart starts a fresh schedule. The layer's CutSeq identifies the +// latest cut: a value not seen before is a new successful cut. type cutSchedule struct { - lastSuccess time.Time // last successful cut of any kind, as observed here - lastAuto time.Time // start of the last automatic cut - failedAt time.Time // end of the last failed automatic cut - retryAt time.Time // a failed automatic cut's backoff ends here - backoff time.Duration - firstDue time.Time // startup phase only; never a fabricated success - seenNs int64 // the layer's LastCutNs last taken in - failedSeenNs int64 // the layer's LastCutNs when the last automatic cut failed + lastSuccess time.Time // last successful cut of any kind, as observed here + lastAuto time.Time // start of the last automatic cut + failedAt time.Time // end of the last failed automatic cut + retryAt time.Time // a failed automatic cut's backoff ends here + backoff time.Duration + firstDue time.Time // startup phase only; never a fabricated success + seenSeq uint64 // the layer's CutSeq last taken in + failedSeenSeq uint64 // the layer's CutSeq when the last automatic cut failed } // observe takes in, at now, the latest cut the layer reports (any -// trigger): a LastCutNs not seen before is a success at now. A cut other +// trigger): a CutSeq not seen before is a success at now. A cut other // than the one the last failure saw makes that failure's backoff obsolete. -func (s cutSchedule) observe(lastCutNs int64, now time.Time) cutSchedule { - if lastCutNs == 0 || lastCutNs == s.seenNs { +func (s cutSchedule) observe(seq uint64, now time.Time) cutSchedule { + if seq == 0 || seq == s.seenSeq { return s } - s.seenNs = lastCutNs + s.seenSeq = seq if now.After(s.lastSuccess) { s.lastSuccess = now } s.firstDue = time.Time{} - if !s.failedAt.IsZero() && lastCutNs != s.failedSeenNs { + if !s.failedAt.IsZero() && seq != s.failedSeenSeq { s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{} } return s @@ -718,11 +718,11 @@ func (pol cutPolicy) due(s cutSchedule, now time.Time, reconciling bool) (string } // after records the outcome of an automatic cut started at start, with -// the layer's LastCutNs read after it. -func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error, lastCutNs int64) cutSchedule { +// the layer's CutSeq read after it. +func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error, seq uint64) cutSchedule { s.lastAuto = start if err == nil { - s.seenNs = lastCutNs + s.seenSeq = seq s.firstDue = time.Time{} s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{} if end.After(s.lastSuccess) { @@ -738,15 +738,14 @@ func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error, lastC default: s.backoff *= 2 } - s.failedAt, s.retryAt, s.failedSeenNs = end, end.Add(s.backoff), lastCutNs + s.failedAt, s.retryAt, s.failedSeenSeq = end, end.Add(s.backoff), seq return s } -// initialCutSchedule starts a fresh schedule at now; lastCutNs is the -// layer's latest cut at start, so a cut from before (another process -// lifetime) is not taken in as new. -func initialCutSchedule(volumeID string, interval time.Duration, now time.Time, stagger bool, lastCutNs int64) cutSchedule { - s := cutSchedule{lastSuccess: now, seenNs: lastCutNs} +// initialCutSchedule starts a fresh schedule at now; seq is the layer's +// CutSeq at start, so a cut already made is not taken in as new. +func initialCutSchedule(volumeID string, interval time.Duration, now time.Time, stagger bool, seq uint64) cutSchedule { + s := cutSchedule{lastSuccess: now, seenSeq: seq} if stagger && interval > 0 { phase := hostlimit.Phase(volumeID, interval) startup := hostlimit.Phase(volumeID+":startup", min(interval, 10*time.Second)) @@ -767,7 +766,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer backoffMin: chunkCutBackoffMin, backoffMax: chunkCutBackoffMax, } - s := initialCutSchedule(volumeID, pol.interval, time.Now(), p.cfg.ChunkStagger, layer.Stats().LastCutNs) + s := initialCutSchedule(volumeID, pol.interval, time.Now(), p.cfg.ChunkStagger, layer.Stats().CutSeq) t := time.NewTicker(chunkSchedulePoll) defer t.Stop() for { @@ -781,7 +780,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer } ls := layer.Stats() start := time.Now() - s = s.observe(ls.LastCutNs, start) + s = s.observe(ls.CutSeq, start) reason, ok := pol.due(s, start, ls.Reconciling) if !ok { continue @@ -796,7 +795,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer // A cut that completed after this decision (an explicit one // running meanwhile) restarted the timer: no cut now. var skipped bool - _, skipped, err = pc.CutUnlessCutSince(cutCtx, ls.LastCutNs) + _, skipped, err = pc.CutUnlessCutSince(cutCtx, ls.CutSeq) if trace != nil { trace("cut", ls.LastCutNs, skipped) } @@ -811,7 +810,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer } } cancel() - s = pol.after(s, start, time.Now(), err, layer.Stats().LastCutNs) + s = pol.after(s, start, time.Now(), err, layer.Stats().CutSeq) if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil { log.Printf("durable: %s chunk cut for volume=%s: %v (retry in %s)", reason, volumeID, err, s.backoff) } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 3ed9ec97b5..39e9b7a5a9 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1443,6 +1443,7 @@ func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error } if err == nil { l.stats.LastCut, l.stats.LastCutH, l.stats.LastCutNs = st, r.H, time.Now().UnixNano() + l.stats.CutSeq++ } if st.BarrierOverBound { l.stats.BarrierOverBound++ diff --git a/seaweed-block/core/storage/chunk_periodic_cut.go b/seaweed-block/core/storage/chunk_periodic_cut.go index 49822ee959..72522b7994 100644 --- a/seaweed-block/core/storage/chunk_periodic_cut.go +++ b/seaweed-block/core/storage/chunk_periodic_cut.go @@ -8,20 +8,22 @@ import "context" // complete before this one gets the capture lock. That cut restarted the // timer, so the due cut is not taken. type ChunkPeriodicCutter interface { - // CutUnlessCutSince cuts unless a cut succeeded after lastCutNs (the - // LastCutNs the timer decided on); skipped reports that it did not cut. - CutUnlessCutSince(ctx context.Context, lastCutNs int64) (r ChunkCutResult, skipped bool, err error) + // CutUnlessCutSince cuts unless a cut succeeded since the timer decided + // (CutSeq is no longer seq, the CutSeq it decided on); skipped reports + // that it did not cut. Cuts are ordered by CutSeq, never by their wall + // stamps. + CutUnlessCutSince(ctx context.Context, seq uint64) (r ChunkCutResult, skipped bool, err error) } var _ ChunkPeriodicCutter = (*chunkLayerImpl)(nil) -func (l *chunkLayerImpl) CutUnlessCutSince(ctx context.Context, lastCutNs int64) (chunkCutResult, bool, error) { +func (l *chunkLayerImpl) CutUnlessCutSince(ctx context.Context, seq uint64) (chunkCutResult, bool, error) { l.capMu.Lock() defer l.capMu.Unlock() l.stMu.Lock() - last := l.stats.LastCutNs + cur := l.stats.CutSeq l.stMu.Unlock() - if last > lastCutNs { + if cur != seq { return chunkCutResult{}, true, nil } r, err := l.captureLocked(ctx, false) diff --git a/seaweed-block/core/storage/chunk_periodic_cut_test.go b/seaweed-block/core/storage/chunk_periodic_cut_test.go index 5289cb8b9a..8ec256b21a 100644 --- a/seaweed-block/core/storage/chunk_periodic_cut_test.go +++ b/seaweed-block/core/storage/chunk_periodic_cut_test.go @@ -1,6 +1,9 @@ package storage -import "testing" +import ( + "testing" + "time" +) // A periodic cut decided before another cut completed is skipped; decided // after the last cut, it cuts. @@ -14,7 +17,7 @@ func TestChunkPeriodicCut_SkipsAfterANewerCut(t *testing.T) { } w := newWriteLog() w.write(t, s, 2, 0x22) - decided := layer.Stats().LastCutNs // the timer decides here... + decided := layer.Stats().CutSeq // the timer decides here... if _, err := layer.Cut(ctTimeout(t)); err != nil { // ...then another cut completes first t.Fatal(err) } @@ -26,7 +29,7 @@ func TestChunkPeriodicCut_SkipsAfterANewerCut(t *testing.T) { if f.stats().cas != casBefore { t.Fatal("a skipped periodic cut published") } - r, skipped, err := pc.CutUnlessCutSince(ctTimeout(t), layer.Stats().LastCutNs) + r, skipped, err := pc.CutUnlessCutSince(ctTimeout(t), layer.Stats().CutSeq) if err != nil || skipped || r.Noop { t.Fatalf("periodic cut decided after the last cut: skipped=%v noop=%v err=%v; want a cut", skipped, r.Noop, err) } @@ -34,3 +37,35 @@ func TestChunkPeriodicCut_SkipsAfterANewerCut(t *testing.T) { t.Fatalf("CAS calls %d -> %d; want one", casBefore, f.stats().cas) } } + +// Cuts are ordered by CutSeq, not by their wall stamps: a newer cut whose +// stamp reads earlier than the one the timer decided on (a backward clock +// step between them) still makes the stale periodic decision skip. +func TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + pc := layer.(ChunkPeriodicCutter) + impl := layer.(*chunkLayerImpl) + w := newWriteLog() + w.write(t, s, 2, 0x22) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + decided, decidedNs := layer.Stats().CutSeq, layer.Stats().LastCutNs + w.write(t, s, 5, 0x25) + if _, err := layer.Cut(ctTimeout(t)); err != nil { // a newer cut completes... + t.Fatal(err) + } + impl.stMu.Lock() + impl.stats.LastCutNs = decidedNs - int64(time.Hour) // ...stamped by a clock stepped back an hour + impl.stMu.Unlock() + w.write(t, s, 9, 0x29) + casBefore := f.stats().cas + if _, skipped, err := pc.CutUnlessCutSince(ctTimeout(t), decided); err != nil || !skipped { + t.Fatalf("stale periodic decision after a newer cut with an older stamp: skipped=%v err=%v; want skipped", skipped, err) + } + if f.stats().cas != casBefore { + t.Fatal("the stale periodic decision published") + } +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index c8461ba69a..293d0aebdd 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -474,7 +474,9 @@ type chunkCutStats struct { // publishes until it is done. ReconcileDone of ReconcileTotal chunks // are compared. // - LastCut, LastCutH and LastCutNs (wall clock, Unix ns) describe the -// last successful cut, whatever triggered it. +// last successful cut, whatever triggered it. CutSeq counts the +// successful cuts of this layer (in-process): it identifies the latest +// cut and orders cuts without any clock. type chunkLayerStats struct { Hydration ChunkHydrationStats // lazy fetches of absent chunks from the remote CutsOK uint64 // cuts that installed a HEAD @@ -492,6 +494,7 @@ type chunkLayerStats struct { LastCut chunkCutStats // the last successful cut's measurements LastCutH uint64 // the LSN the last successful cut published LastCutNs int64 // when it completed (wall clock, Unix ns) + CutSeq uint64 // successful cuts of this layer so far (in-process); the latest cut's identity // BarrierOverBound counts cuts whose barrier copied more than the // bound after the staging rounds. BarrierOverBound uint64 diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a8403a48ae..3256f64fe6 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -381,6 +381,16 @@ A pass has one minute for retention and optional GC; retention failure skips GC. A scoped GC pass traces the whole catalog but mutates only its target volume, with a separate scope/config-bound mark. Incomplete marks carry no coverage. +The scheduled-snapshot worker runs beside it under the same owner and join, on +in-process monotonic time: `Armed -> Due -> Running -> Armed`. A success sets the +next slot (loop start + the volume's offset + whole periods); a failure keeps +its typed code and retries after a backoff doubling from 1 min to 1 h; a +restoring volume (absent chunks) is skipped, counted, and retried within 1 h. +A re-armed loop on the same handle keeps this state; a restart starts fresh. +Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksOff`, +`_RestoringIsSkippedAndCounted`, `TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime`, +`_RearmKeepsTheSchedule`. + ## Part B. Invariant ledger 136 rows: 116 ACTIVE, 17 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 121 new. @@ -549,13 +559,13 @@ Notes: | `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | | `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE | | `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | -| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestChunkPeriodicCut_SkipsAfterANewerCut` (`core/storage/chunk_periodic_cut_test.go`); `TestCutPolicy_TimerIgnoresTheWallClockOfLastCutNs` (`core/frontend/durable/cut_policy_test.go`) | — | ACTIVE | +| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestChunkPeriodicCut_SkipsAfterANewerCut` (`core/storage/chunk_periodic_cut_test.go`); `TestCutPolicy_TimerRunsOnObservationTime` (`core/frontend/durable/cut_policy_test.go`); `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`) | — | ACTIVE | A guest read has a cooperative arrival budget; internal contextless readers keep the owned fill timeout (default 30 s). With five immediate host retries, cold fills slower than roughly 20–24 s can still end in guest EIO despite shared work; retry-delay advertisement remains separate. A changed generation replaces its promise without abandoning the old worker. `AllBlocks` returns an error and no partial image on a failed read; the rebuild sender propagates it before sending blocks. Notes: -- `INV-CUT-TIMER-RESTART-001`: the layer's persisted `LastCutNs` is only the identity of the latest cut: a value not seen before is a success at the moment it is observed; at start the existing value is not new, so a restart keeps the startup phase. The scheduled-snapshot worker (`INV-SNAP-SCHEDULED-KEEP-001`) runs on the same monotonic time: slots are the loop start plus the volume's offset plus whole periods; a re-armed loop on the same handle keeps its schedule (failures, retry time); a restart starts a fresh one. Tests: `TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime`, `_RearmKeepsTheSchedule`, `_OverdueWithNoSuccess`, `TestSnapshotSchedule_SlotsAreOffsetPerVolume`. +- `INV-CUT-TIMER-RESTART-001`: cuts are identified and ordered by the layer's in-process `CutSeq`, never by the `LastCutNs` wall stamp: a `CutSeq` not seen before is a success at the moment it is observed, and a periodic decision is skipped once `CutSeq` has moved; at start the existing value is not new, so a restart keeps the startup phase. The scheduled-snapshot worker (`INV-SNAP-SCHEDULED-KEEP-001`) runs on the same monotonic time: slots are the loop start plus the volume's offset plus whole periods; a re-armed loop on the same handle keeps its schedule (failures, retry time); a restart starts a fresh one. Tests: `TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime`, `_RearmKeepsTheSchedule`, `_OverdueWithNoSuccess`, `TestSnapshotSchedule_SlotsAreOffsetPerVolume`. - `INV-CUT-PRECOPY-001`: Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Ordinary refusal reopens tentative admission before rolling uploads; guest-frozen refusal instead sends no payload. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; on resume every queued waiter is granted in arrival order under one lock hold; each then passes the normal gate; completion is unordered. The ended pause is cleared before those normal gate checks; queue deadlines are measured once from each command arrival and capped by five seconds or its earlier caller deadline, so independent I/O is concurrent and later arrivals cannot inherit an expired pause; host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Ordinary admission never uses unknown samples. A guest-frozen attempt skips staging, forecasts and rechecks against five seconds minus guest elapsed, and refuses without uploading if it cannot fit. Only an explicit final override can bypass that estimate guard, with over_budget recorded; authority and publication settlement remain mandatory. Checkpoint tails are advisory same-window measurements. Nested Sync phases and live barrier-prefix spans explain fixed cost without double counting. - `INV-CUT-STAGED-REUSE-001`: `captureLocked` also requires HEAD's generation to be the one the stage was compared against (code reading; not asserted by these tests). diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 33559866a3..a5d5b4f682 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -273,6 +273,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCut.BarrierOverBound` | bool | (group of `StageRounds`) Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | | `Volumes[].Chunk.Stats.LastCutH` | uint64 | the LSN the last successful cut published | | `Volumes[].Chunk.Stats.LastCutNs` | int64 | when it completed (wall clock, Unix ns) | +| `Volumes[].Chunk.Stats.CutSeq` | uint64 | successful cuts of this layer so far (in-process); the latest cut's identity | | `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. | | `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. | | `Volumes[].Chunk.HostBudget` | interface | the host background-cut budget state, with --host-limit-dir (omitted when empty) | From 6070108c5c74a7b1363cdfa49933e31476ebc0e4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 07:50:33 -0800 Subject: [PATCH 17/34] blockmaster: refuse a non-loopback control bind unless --insecure-external-bind The gRPC control API (--listen) and the runtime HTTP API (--frontend-publication-runtime-listen, when enabled) are unauthenticated, so binding them to the node network is now an explicit choice: a non-loopback address is refused at startup unless --insecure-external-bind is given. The Helm chart and the shipped k8s manifests, which bind 0.0.0.0 with host networking, pass the opt-in explicitly. Co-Authored-By: Claude Opus 5.5 --- .../seaweed-block/templates/blockmaster.yaml | 1 + .../cmd/blockmaster/external_bind_test.go | 53 +++++++++++++++++++ seaweed-block/cmd/blockmaster/main.go | 12 ++++- seaweed-block/cmd/blockmaster/main_test.go | 1 + .../core/host/master/journal_isolation.go | 21 ++++++++ .../deploy/k8s/alpha/block-stack.yaml | 1 + .../deploy/k8s/g15b/block-stack.yaml | 1 + .../deploy/k8s/g15d/block-stack.yaml | 1 + 8 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/cmd/blockmaster/external_bind_test.go diff --git a/seaweed-block/charts/seaweed-block/templates/blockmaster.yaml b/seaweed-block/charts/seaweed-block/templates/blockmaster.yaml index 3aee686426..2e7535f715 100644 --- a/seaweed-block/charts/seaweed-block/templates/blockmaster.yaml +++ b/seaweed-block/charts/seaweed-block/templates/blockmaster.yaml @@ -106,6 +106,7 @@ spec: {{- end }} - "--launcher-kubernetes-apply" - "--listen=0.0.0.0:{{ .Values.blockmaster.listenPort }}" + - "--insecure-external-bind" {{- if .Values.blockmaster.failbackRuntimeRPC }} - "--failback-runtime-rpc" {{- end }} diff --git a/seaweed-block/cmd/blockmaster/external_bind_test.go b/seaweed-block/cmd/blockmaster/external_bind_test.go new file mode 100644 index 0000000000..1aa740a42e --- /dev/null +++ b/seaweed-block/cmd/blockmaster/external_bind_test.go @@ -0,0 +1,53 @@ +package main + +import ( + "os" + "strings" + "testing" +) + +// The unauthenticated control listeners bind loopback unless +// --insecure-external-bind is given: --listen always, and the runtime HTTP +// listener when its API is enabled. +func TestParseFlags_ControlListenersNeedInsecureExternalBind(t *testing.T) { + base := func(extra ...string) []string { return append([]string{"--authority-store", t.TempDir()}, extra...) } + for _, ok := range []string{"127.0.0.1:9333", "localhost:9333", "[::1]:9333", "127.0.0.1:0"} { + if _, err := parseFlags(base("--listen", ok)); err != nil { + t.Fatalf("--listen %s: %v", ok, err) + } + } + for _, bad := range []string{"0.0.0.0:9333", ":9333", "10.0.0.5:9333", "[::]:9333"} { + _, err := parseFlags(base("--listen", bad)) + if err == nil || !strings.Contains(err.Error(), "--insecure-external-bind") { + t.Fatalf("--listen %s without the opt-in: %v, want a refusal naming --insecure-external-bind", bad, err) + } + if _, err := parseFlags(base("--listen", bad, "--insecure-external-bind")); err != nil { + t.Fatalf("--listen %s with --insecure-external-bind: %v", bad, err) + } + } + if _, err := parseFlags(base("--frontend-publication-runtime-listen", "0.0.0.0:9334")); err != nil { + t.Fatalf("runtime listener disabled: its address is not checked: %v", err) + } + _, err := parseFlags(base("--frontend-publication-runtime-http", "--frontend-publication-runtime-listen", "0.0.0.0:9334")) + if err == nil || !strings.Contains(err.Error(), "frontend-publication-runtime-listen") { + t.Fatalf("enabled runtime listener on 0.0.0.0 without the opt-in: %v", err) + } + if _, err := parseFlags(base("--frontend-publication-runtime-http", "--frontend-publication-runtime-listen", "0.0.0.0:9334", "--insecure-external-bind")); err != nil { + t.Fatalf("with the opt-in: %v", err) + } +} + +// Every shipped manifest that binds blockmaster to 0.0.0.0 carries the +// explicit opt-in, so the change refuses nothing that ships. +func TestManifests_ExternalBlockmasterBindCarriesTheOptIn(t *testing.T) { + for _, p := range []string{"../../charts/seaweed-block/templates/blockmaster.yaml", "../../deploy/k8s/alpha/block-stack.yaml", "../../deploy/k8s/g15b/block-stack.yaml", "../../deploy/k8s/g15d/block-stack.yaml"} { + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + s := string(b) + if strings.Contains(s, "--listen=0.0.0.0") && !strings.Contains(s, "--insecure-external-bind") { + t.Fatalf("%s binds blockmaster to 0.0.0.0 without --insecure-external-bind", p) + } + } +} diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index 297321ad2b..5bf22362f6 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -21,6 +21,7 @@ import ( ) type flags struct { + insecureExternalBind bool authorityStore string lifecycleStore string lifecyclePlacementSeed string @@ -77,7 +78,8 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.lifecycleStore, "lifecycle-store", "", "optional G9D product lifecycle registration store directory (desired volumes, node inventory, placement intents); read-only with respect to assignment publication") fs.StringVar(&f.lifecyclePlacementSeed, "lifecycle-placement-seed", "", "placement-only seed JSON; lifecycle volumes must already be registered (CreateVolume)") fs.StringVar(&f.clusterSpec, "cluster-spec", "", "cluster spec YAML; positive size_bytes imports desired volumes before topology/placement publication") - fs.StringVar(&f.listen, "listen", "127.0.0.1:0", "gRPC listen address (e.g. 127.0.0.1:9180)") + fs.StringVar(&f.listen, "listen", "127.0.0.1:0", "gRPC listen address (e.g. 127.0.0.1:9180); non-loopback requires --insecure-external-bind") + fs.BoolVar(&f.insecureExternalBind, "insecure-external-bind", false, "allow the unauthenticated control listeners (--listen, --frontend-publication-runtime-listen) on non-loopback addresses") fs.StringVar(&f.topology, "topology", "", "path to accepted-topology YAML (required for assignment to mint)") fs.IntVar(&f.expectedSlotsPerVol, "expected-slots-per-volume", 3, "RF/expected slot count per volume; the controller rejects observation snapshots whose slot count differs (default 3, set to 2 for 2-node smoke clusters)") fs.DurationVar(&f.freshnessWindow, "freshness-window", 30*time.Second, "observation freshness window before a server's heartbeat expires") @@ -138,6 +140,14 @@ func parseFlags(args []string) (flags, error) { if err := master.ValidateStatusListen(f.statusListen); err != nil { return flags{}, err } + if err := master.ValidateControlListen("listen", f.listen, f.insecureExternalBind); err != nil { + return flags{}, err + } + if f.frontendPublicationRuntimeHTTP { + if err := master.ValidateControlListen("frontend-publication-runtime-listen", f.frontendPublicationRuntimeListen, f.insecureExternalBind); err != nil { + return flags{}, err + } + } if f.launcherExternalISCSI && f.launcherCHAPSecretName == "" { return flags{}, fmt.Errorf("cannot enable --launcher-external-iscsi without --launcher-iscsi-chap-secret-name") } diff --git a/seaweed-block/cmd/blockmaster/main_test.go b/seaweed-block/cmd/blockmaster/main_test.go index c0432ee35c..0bed50e3c5 100644 --- a/seaweed-block/cmd/blockmaster/main_test.go +++ b/seaweed-block/cmd/blockmaster/main_test.go @@ -87,6 +87,7 @@ func TestParseFlags_FrontendPublicationRuntimeHTTPDisabledByDefault(t *testing.T "--authority-store", "authority-dir", "--frontend-publication-runtime-http", "--frontend-publication-runtime-listen", "0.0.0.0:9334", + "--insecure-external-bind", // a non-loopback control listener is an explicit choice }) if err != nil { t.Fatalf("parseFlags with frontend publication runtime HTTP: %v", err) diff --git a/seaweed-block/core/host/master/journal_isolation.go b/seaweed-block/core/host/master/journal_isolation.go index d49448d2c1..4f9b51fc32 100644 --- a/seaweed-block/core/host/master/journal_isolation.go +++ b/seaweed-block/core/host/master/journal_isolation.go @@ -169,6 +169,27 @@ func ValidateStatusListen(addr string) error { return fmt.Errorf("--status-listen %q must be a loopback address (127.0.0.0/8, ::1 or localhost)", addr) } +// ValidateControlListen refuses a control listener on a non-loopback address +// unless allowExternal: the gRPC control API and the runtime HTTP API are +// unauthenticated, so binding them to the node network must be an explicit +// choice (--insecure-external-bind). An empty address is off. +func ValidateControlListen(flag, addr string, allowExternal bool) error { + if addr == "" || allowExternal { + return nil + } + host, _, err := net.SplitHostPort(addr) + if err != nil { + return fmt.Errorf("--%s %q: %v", flag, addr, err) + } + if host == "localhost" { + return nil + } + if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() { + return nil + } + return fmt.Errorf("--%s %q is not a loopback address: the control API is unauthenticated; pass --insecure-external-bind to expose it on the node network", flag, addr) +} + // WorkspaceLeaseStatus is the GET /status/workspace-lease body. type WorkspaceLeaseStatus struct { ColocatedNodes int `json:"colocated_nodes"` diff --git a/seaweed-block/deploy/k8s/alpha/block-stack.yaml b/seaweed-block/deploy/k8s/alpha/block-stack.yaml index 03499f6be8..12630817d5 100644 --- a/seaweed-block/deploy/k8s/alpha/block-stack.yaml +++ b/seaweed-block/deploy/k8s/alpha/block-stack.yaml @@ -46,6 +46,7 @@ spec: - "--launcher-iscsi-port-base=3260" - "--launcher-kubernetes-apply" - "--listen=0.0.0.0:9333" + - "--insecure-external-bind" - "--expected-slots-per-volume=__EXPECTED_SLOTS_PER_VOLUME__" ports: - name: grpc diff --git a/seaweed-block/deploy/k8s/g15b/block-stack.yaml b/seaweed-block/deploy/k8s/g15b/block-stack.yaml index cbe6a90c70..08a4c558c8 100644 --- a/seaweed-block/deploy/k8s/g15b/block-stack.yaml +++ b/seaweed-block/deploy/k8s/g15b/block-stack.yaml @@ -43,6 +43,7 @@ spec: - "--cluster-spec=/config/cluster-spec.yaml" - "--lifecycle-product-loop-interval=100ms" - "--listen=0.0.0.0:9333" + - "--insecure-external-bind" - "--expected-slots-per-volume=2" ports: - name: grpc diff --git a/seaweed-block/deploy/k8s/g15d/block-stack.yaml b/seaweed-block/deploy/k8s/g15d/block-stack.yaml index 44c94da9ed..932db66b7b 100644 --- a/seaweed-block/deploy/k8s/g15d/block-stack.yaml +++ b/seaweed-block/deploy/k8s/g15d/block-stack.yaml @@ -48,6 +48,7 @@ spec: - "--launcher-durable-root=/var/lib/sw-block" - "--launcher-iscsi-port-base=3260" - "--listen=0.0.0.0:9333" + - "--insecure-external-bind" - "--expected-slots-per-volume=1" ports: - name: grpc From 93f6008f1367652de317cf051f15c1f8d6735f40 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 07:51:11 -0800 Subject: [PATCH 18/34] docs: INV-SEC-CONTROL-BIND-001 Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0c69765881..c3e72366fc 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -382,7 +382,7 @@ with a separate scope/config-bound mark. Incomplete marks carry no coverage. ## Part B. Invariant ledger -136 rows: 116 ACTIVE, 17 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 121 new. +137 rows: 117 ACTIVE, 17 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 122 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. @@ -461,6 +461,7 @@ Notes: | `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | +| `INV-SEC-CONTROL-BIND-001` | blockmaster's unauthenticated control listeners (--listen, and the runtime HTTP listener when enabled) bind only loopback unless --insecure-external-bind is given; a non-loopback address is refused at startup. | AUTHORITY: control API reachability | `core/host/master/journal_isolation.go` `ValidateControlListen`; `cmd/blockmaster/main.go` `parseFlags` | `TestParseFlags_ControlListenersNeedInsecureExternalBind`, `TestManifests_ExternalBlockmasterBindCarriesTheOptIn` (`cmd/blockmaster/external_bind_test.go`) | — (no state machine; the flag test is the proof form) | ACTIVE | Notes: From 163560c691eacf0f5a4cc61c0d127e34507aa9d5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 07:55:09 -0800 Subject: [PATCH 19/34] docs: upgrade note for --insecure-external-bind Co-Authored-By: Claude Opus 5.5 --- seaweed-block/README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/seaweed-block/README.md b/seaweed-block/README.md index d5f6be76d4..b9cc163ea1 100644 --- a/seaweed-block/README.md +++ b/seaweed-block/README.md @@ -182,6 +182,12 @@ bash scripts/uninstall-k8s-alpha.sh "$PWD" && bash scripts/verify-helm-cleanup.s Full table and conditions: [Kubernetes status](docs/kubernetes-status.md); run evidence: [release notes](docs/releases/README.md). +**Upgrade note:** blockmaster now refuses a non-loopback `--listen` (and a +non-loopback `--frontend-publication-runtime-listen` when that API is on) +unless `--insecure-external-bind` is given, because its control API is +unauthenticated. The Helm chart and the shipped manifests already pass it; +a launcher of your own that binds blockmaster to a node address must add it. + ### Not claimed yet - Production readiness, SLOs, or a published performance, RTO or RPO claim. From 296bb664d20037e3b2e18f9d70a47c9b2327de17 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:10:23 -0800 Subject: [PATCH 20/34] test: offline seal inherits the caller deadline --- .../durable/provider_offline_seal_test.go | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/provider_offline_seal_test.go diff --git a/seaweed-block/core/frontend/durable/provider_offline_seal_test.go b/seaweed-block/core/frontend/durable/provider_offline_seal_test.go new file mode 100644 index 0000000000..cb70ca763d --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_offline_seal_test.go @@ -0,0 +1,65 @@ +package durable_test + +import ( + "bytes" + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// G.GONE.SEALED: an idle plain detach seals under the caller's deadline, +// including after the frontend handle closes; no live-serving timer applies. +func TestOfflineSealUsesCallerDeadline(t *testing.T) { + for _, closed := range []bool{false, true} { + t.Run(map[bool]string{false: "idle", true: "closed"}[closed], func(t *testing.T) { + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, DetachFreezeTimeout: time.Second, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + openRecovered(t, p) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + b, err := p.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if _, err = b.Write(ctx, 4096, block(0x61)); err != nil { + t.Fatal(err) + } + if closed { + if err = b.Close(); err != nil { + t.Fatal(err) + } + } + deadline, _ := ctx.Deadline() + observed := false + durable.SetTestDetachStopIO(p, func(c context.Context) error { + observed = true + got, ok := c.Deadline() + if !ok || !got.Equal(deadline) { + t.Errorf("offline seal inherited live timer: got %v known=%t want caller %v", got, ok, deadline) + } + return b.(*durable.StorageBackend).StopIO(c, "offline seal test") + }) + r, last, err := p.DetachVolumePlain(ctx, "v1") + if err != nil || r.Head.State != storage.ChunkHeadDetached || r.H != last { + t.Fatalf("offline seal failed: %+v last=%d err=%v", r, last, err) + } + if !observed { + t.Error("offline seal did not drain") + } + if !bytes.Equal(headBlock(t, remote, 1), block(0x61)) { + t.Fatal("offline seal lost acknowledged bytes") + } + }) + } +} From 49f083acdfc43096cdc674da55a09588fcc64d9f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:10:44 -0800 Subject: [PATCH 21/34] test: witness the offline cut timer deadline --- .../core/frontend/durable/provider_offline_seal_test.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/seaweed-block/core/frontend/durable/provider_offline_seal_test.go b/seaweed-block/core/frontend/durable/provider_offline_seal_test.go index cb70ca763d..b16f55a5eb 100644 --- a/seaweed-block/core/frontend/durable/provider_offline_seal_test.go +++ b/seaweed-block/core/frontend/durable/provider_offline_seal_test.go @@ -42,6 +42,11 @@ func TestOfflineSealUsesCallerDeadline(t *testing.T) { } deadline, _ := ctx.Deadline() observed := false + durable.SetTestDetachTrace(p, func(stage string, got time.Time) { + if stage == "cut" && !got.Equal(deadline) { + t.Errorf("offline seal inherited live cut deadline: got %v want caller %v", got, deadline) + } + }) durable.SetTestDetachStopIO(p, func(c context.Context) error { observed = true got, ok := c.Deadline() From 1b780fe940aeae9663016fcce06650b1625c56a9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:11:59 -0800 Subject: [PATCH 22/34] test: offline detach HTTP preserves caller deadline --- .../host/volume/chunk_offline_seal_test.go | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 seaweed-block/core/host/volume/chunk_offline_seal_test.go diff --git a/seaweed-block/core/host/volume/chunk_offline_seal_test.go b/seaweed-block/core/host/volume/chunk_offline_seal_test.go new file mode 100644 index 0000000000..e6f2832e96 --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_offline_seal_test.go @@ -0,0 +1,44 @@ +package volume + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +type offlineSealControl struct { + *plainDetachControl + got context.Context +} + +func (c *offlineSealControl) DetachPlain(ctx context.Context, id string) (ChunkDetachResponse, error) { + c.got = ctx + return c.plainDetachControl.DetachPlain(ctx, id) +} +func TestChunkPlainDetachUsesCallerDeadline(t *testing.T) { + for _, limited := range []bool{false, true} { + c := &offlineSealControl{plainDetachControl: &plainDetachControl{fakeChunkControl: &fakeChunkControl{}}} + s := chunkServer(t, c, true) + ctx := context.Background() + cancel := func() {} + if limited { + ctx, cancel = context.WithTimeout(ctx, time.Hour) + } + req := httptest.NewRequest(http.MethodPost, "/chunk/detach", strings.NewReader(`{"volumeID":"v1","plain":true}`)).WithContext(ctx) + req.RemoteAddr = "127.0.0.1:5555" + w := httptest.NewRecorder() + s.chunkMux().ServeHTTP(w, req) + cancel() + if w.Code != 200 || c.got == nil { + t.Fatalf("plain dispatch failed: %d %s", w.Code, w.Body) + } + got, gok := c.got.Deadline() + want, wok := ctx.Deadline() + if gok != wok || !got.Equal(want) { + t.Errorf("offline HTTP inherited operation cap: got=%v known=%t want=%v known=%t", got, gok, want, wok) + } + } +} From d75c61cff58e35d08531a07a9e282d8ed567de8b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:14:16 -0800 Subject: [PATCH 23/34] feat: seal idle volumes under the caller deadline --- .../core/frontend/durable/provider_chunk.go | 21 +++++++-- .../durable/provider_offline_seal_test.go | 47 +++++++++++++++++++ .../core/frontend/durable/storage_adapter.go | 3 -- .../core/host/volume/chunk_control.go | 9 ++++ seaweed-block/docs/design/invariants.md | 7 +-- seaweed-block/docs/spec/PlainDetach.tla | 21 +++++---- seaweed-block/docs/spec/README.md | 11 +++++ 7 files changed, 99 insertions(+), 20 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 2c194a39e8..5acf59d19d 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -1049,7 +1049,8 @@ func (p *DurableProvider) DetachVolumeFrozen(ctx context.Context, volumeID strin var ErrPlainDetachBusy = errors.New("durable: plain detach requires idle frontend I/O") // DetachVolumePlain bypasses pre-copy cost admission only after atomically -// closing an idle frontend. Publication and failure settlement are unchanged. +// closing an idle frontend (including a closed handle). G.GONE.SEALED uses +// only the caller context, not the live-serving freeze timer. func (p *DurableProvider) DetachVolumePlain(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) { return p.detachVolume(ctx, volumeID, true) } @@ -1107,6 +1108,10 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla start = guestFreeze.StartedAt } casAtFreeze = countCAS() + if plain { // G.GONE.SEALED: no live frontend, caller owns the bound. + settleDeadline, _ = ctx.Deadline() + return + } operationStart := start if guestFrozen && guestFreeze.AllowOverBudget { operationStart = time.Now() @@ -1123,7 +1128,7 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla if timer != nil { timer.Stop() } - if !start.IsZero() { + if !plain && !start.IsZero() { if d := time.Since(start); d > detachFreezeTarget { log.Printf("durable: ALARM detach of volume=%s held guest I/O for %s (target %s, bound %s)", volumeID, d.Round(time.Millisecond), detachFreezeTarget, freeze) } @@ -1204,7 +1209,11 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla } } if trace := p.testDetachTrace; trace != nil { - trace("cut", start.Add(freeze*3/4)) + deadline := start.Add(freeze * 3 / 4) + if plain { + deadline, _ = cutCtx.Deadline() + } + trace("cut", deadline) } h.chunkDetach = true notifyDetach() @@ -1228,7 +1237,11 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla // resumes: an earlier detach that applied, an unresolved detach CAS or a // fenced layer must never resume serving. The settlement keeps the rest // of the freeze budget even when the caller's context is gone. - sctx, scancel := context.WithDeadline(context.WithoutCancel(cutCtx), settleDeadline) + sctx, scancel := context.WithCancel(cutCtx) + if !plain { // Live detach retains its reserved settlement budget. + scancel() + sctx, scancel = context.WithDeadline(context.WithoutCancel(cutCtx), settleDeadline) + } defer scancel() if trace := p.testDetachTrace; trace != nil { dl, _ := sctx.Deadline() diff --git a/seaweed-block/core/frontend/durable/provider_offline_seal_test.go b/seaweed-block/core/frontend/durable/provider_offline_seal_test.go index b16f55a5eb..4f149ef382 100644 --- a/seaweed-block/core/frontend/durable/provider_offline_seal_test.go +++ b/seaweed-block/core/frontend/durable/provider_offline_seal_test.go @@ -3,6 +3,8 @@ package durable_test import ( "bytes" "context" + "errors" + "sync" "testing" "time" @@ -68,3 +70,48 @@ func TestOfflineSealUsesCallerDeadline(t *testing.T) { }) } } + +// Caller cancellation ends an offline upload; the closed backend stays closed, +// and a new caller can retry the seal without losing acknowledged bytes. +type cancelSealRemote struct { + *storage.MemChunkRemote + once sync.Once + cancel context.CancelFunc +} + +func (r *cancelSealRemote) Put(ctx context.Context, key string, b []byte) error { + r.once.Do(r.cancel) + if err := ctx.Err(); err != nil { + return err + } + return r.MemChunkRemote.Put(ctx, key, b) +} +func TestOfflineSealCallerCancelCanRetry(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + remote := &cancelSealRemote{MemChunkRemote: storage.NewMemChunkRemote(), cancel: cancel} + p := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err = b.Write(context.Background(), 4096, block(0x72)); err != nil { + t.Fatal(err) + } + if err = b.Close(); err != nil { + t.Fatal(err) + } + if _, _, err = p.DetachVolumePlain(ctx, "v1"); !errors.Is(err, context.Canceled) { + t.Fatalf("offline caller cancellation lost: %v", err) + } + if _, err = b.Write(context.Background(), 8192, block(0x73)); err == nil { + t.Fatal("failed offline seal reopened closed frontend") + } + retry, end := context.WithTimeout(context.Background(), time.Minute) + defer end() + r, _, err := p.DetachVolumePlain(retry, "v1") + if err != nil || r.Head.State != storage.ChunkHeadDetached || !bytes.Equal(headBlock(t, remote.MemChunkRemote, 1), block(0x72)) { + t.Fatalf("offline retry failed: %+v %v", r, err) + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 9ac6db58e4..a7641ecd08 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -554,9 +554,6 @@ func (b *StorageBackend) stopPlainDetachIfIdle() error { defer b.ioMu.Unlock() b.mu.Lock() defer b.mu.Unlock() - if b.closed { - return frontend.ErrBackendClosed - } if b.admittedIO != 0 { return ErrPlainDetachBusy } diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index c6cd4f7525..b66bc2c910 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -556,6 +556,15 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) return } ctx, cancel := chunkContext(r, req.TimeoutMs) + if req.Plain { // G.GONE.SEALED: offline work is bounded by its caller. + cancel() + ctx, cancel = context.WithCancel(r.Context()) + if req.TimeoutMs > 0 { + const maxTimeoutMs = int64((1<<63 - 1) / time.Millisecond) + cancel() + ctx, cancel = context.WithTimeout(r.Context(), time.Duration(min(req.TimeoutMs, maxTimeoutMs))*time.Millisecond) + } + } defer cancel() var res ChunkDetachResponse var err error diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0c69765881..618daa6d22 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -209,7 +209,7 @@ stateDiagram-v2 [*] --> Refused: invalid frozen request; invalid_freeze_budget; no provider mutation Admit --> Refused: budget refused, closed, fenced, detached, base install, or lineage or lease invalid Admit --> PlainStop: plain detach and idle frontend lock acquired - PlainStop --> Quiesce: frontend stopped; ordinary detached cut + PlainStop --> Quiesce: idle frontend closed; caller-bounded offline seal Admit --> FrozenForecast: guest already frozen with an explicit origin FrozenForecast --> Refused: unknown or non-fitting remaining budget FrozenForecast --> Quiesce: plausible estimate or explicit final override; skip staging @@ -243,7 +243,7 @@ stateDiagram-v2 | Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease) | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-WS-LEASE-001` | | Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | | Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001` | -| Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses the ordinary StopIO, final cut and outcome settlement. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | +| Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses StopIO and a final detached cut under the caller context, including a closed idle frontend (G.GONE.SEALED). | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | | Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | @@ -526,7 +526,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | +| `INV-CUT-PLAIN-DETACH-001` | Plain detach excludes entering/admitted I/O, then seals under the caller context, including a closed idle frontend. Publication and unknown/fenced settlement remain enforced. Closed frontend handles never reopen; absent/false preserves live policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` ; `TestOfflineSealUsesCallerDeadline`, `TestOfflineSealCallerCancelCanRetry` (`core/frontend/durable/provider_offline_seal_test.go`); `TestChunkPlainDetachUsesCallerDeadline` (`core/host/volume/chunk_offline_seal_test.go`) | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | | `INV-WS-FREEZE-ACCOUNTING-001` | Frozen detach validates its origin and rechecks elapsed + known estimate against 5 s; override is explicit. Storage reports its admission estimate and quiesce slack using same-host monotonic durations. Stale advice is rechecked before upload; override and actual elapsed remain visible. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess`; `TestCandidateTailReportsCompleteFrozenBudget`, `TestFrozenRefusalRetainsUnknownCompleteEstimate`, `TestChunkFrozenRefusalCarriesServerBudget`, `TestChunkFrozenDrainRefusalCarriesObservedBudget`, `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation`, `TestFrozenSaturatedTailRemainsKnownButNonActionable` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible`, `ReportSlackSound` | ACTIVE | | `INV-WS-FREEZE-REFUSAL-001` | HTTP400 `invalid_freeze_budget`, retryable=false, is emitted only for frozen-request validation before any provider admission or mutation. Missing/zero/future origin, override without frozen, and frozen+plain preserve that boundary. Generic `bad_request` is not a clean-refusal proof. Terminal and unknown-publication causes retain precedence; no production path emits this typed code after mutation. | G frozen detach: request → refused before admission (M5) | `core/host/volume/chunk_control.go` `handleChunkDetach`, `chunkErrorCode`; `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestChunkFrozenValidationHasDistinctPreMutationCode`, `TestFrozenValidationPrecedesAnyProviderAccess` | — (wire classification; validation/admission guards unchanged) | ACTIVE | | `INV-CUT-PRECOPY-001` | Resume grants waiters FIFO under one lock; gates and completion are independent. Each command keeps its arrival/caller bound. Only pause refusals requeue; stale and terminal errors survive. Detached handoff requires settled publication. See Notes for admission and freeze guards. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestCheckpointTailScanIncludedInTotalAndFixedCosts`, `TestCheckpointTailUsesLiteralLatestThreeConservativeRate`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestChunkFrozenDetachWireContractAndPrecedence`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyResumeReleasesAllWaiters` (FIFO grants under one lock, concurrent outstanding I/O), `TestPrecopyResumedArrivalDoesNotInheritExpiredPause`, `TestPrecopyQueueBoundStartsAtCommandArrival`, `TestPrecopyResumeGrantVersusExpiry`, `TestPrecopyGrantedWaiterFollowsReplacementPause`, `TestPrecopyNewPauseCannotEraseObservedStalePrimary`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); controlled callers and measured latency are not a model proof | ACTIVE | @@ -668,6 +668,7 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a | Wait | Machine / invariant | Bound | Release and cancellation | Locks / remote work | |---|---|---|---|---| +| Offline seal | G.GONE.SEALED; `INV-CUT-PLAIN-DETACH-001` | Caller context, including its optional explicit HTTP timeout; no live-serving timer | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. | | Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. | Frozen estimate reporting: a tail above the existing 60 s estimator ceiling reports the same 60 s rejection sentinel used by admission. It is known but saturated, not a complete fixed-plus-tail duration; quiesce slack is zero. Consumers must not use it as a completion forecast. Drain refusals retain the observation before their reason changes; this reporting does not reclassify refusal causes. diff --git a/seaweed-block/docs/spec/PlainDetach.tla b/seaweed-block/docs/spec/PlainDetach.tla index 0bd3733bb2..3ec5322b96 100644 --- a/seaweed-block/docs/spec/PlainDetach.tla +++ b/seaweed-block/docs/spec/PlainDetach.tla @@ -3,17 +3,18 @@ \* remain the existing detach/cut obligations, outside this abstraction. EXTENDS Naturals, TLC CONSTANT IdleGuard -VARIABLES phase, readers -vars == <> -Init == /\ phase = "serving" /\ readers = 0 -BeginIO == /\ phase = "serving" /\ readers < 2 - /\ readers' = readers + 1 /\ UNCHANGED phase -EndIO == /\ readers > 0 /\ readers' = readers - 1 /\ UNCHANGED phase +VARIABLES phase, readers, closed +vars == <> +Init == /\ phase = "serving" /\ readers = 0 /\ closed = FALSE +BeginIO == /\ phase = "serving" /\ ~closed /\ readers < 2 + /\ readers' = readers + 1 /\ UNCHANGED <> +EndIO == /\ readers > 0 /\ readers' = readers - 1 /\ UNCHANGED <> Plain == /\ phase = "serving" /\ (~IdleGuard \/ readers = 0) - /\ phase' = "stopped" /\ UNCHANGED readers -Publish == /\ phase = "stopped" /\ phase' = "detached" /\ UNCHANGED readers -Abort == /\ phase = "stopped" /\ phase' = "serving" /\ UNCHANGED readers -Next == BeginIO \/ EndIO \/ Plain \/ Publish \/ Abort + /\ phase' = "stopped" /\ UNCHANGED <> +Publish == /\ phase = "stopped" /\ phase' = "detached" /\ UNCHANGED <> +Abort == /\ phase = "stopped" /\ phase' = "serving" /\ UNCHANGED <> +Close == /\ ~closed /\ closed' = TRUE /\ UNCHANGED <> +Next == Close \/ BeginIO \/ EndIO \/ Plain \/ Publish \/ Abort Spec == Init /\ [][Next]_vars IdleAtStop == phase \in {"stopped", "detached"} => readers = 0 ============================================================================= diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 5dc3e958cf..87fad51d5c 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -517,3 +517,14 @@ checked by native Go tests; this derived arithmetic model does not model the HTT encoder, sampler atomicity, orchestrator timing or an unbounded estimator overrun. #344 review qualification: `TestChunkFrozenDrainRefusalCarriesObservedBudget` drives a real admitted Sync through frontend drain expiry, durable provider and HTTP, with no report injection; `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation` covers the known observation. `TestFrozenSaturatedTailRemainsKnownButNonActionable` and the literal 60 s/61 s candidate cases preserve the existing saturation sentinel (zero slack, not a complete duration). These native controls add no model claim or admission guard. + + +2026-11-21 offline-seal extension: `PlainDetach` now includes frontend Close, +which disables new readers without discarding readers already admitted. An idle +closed frontend may enter PlainStop; abort does not clear its closed bit. +`cfg/PlainDetach.cfg` exhausts 18 generated / 10 distinct states, depth 4, queue +empty (TLC 2.19 with the tools hash above). `PlainDetach_no_idle.cfg` violates +`IdleAtStop` in 8 distinct states. This remains an admission model, not a timing +model. Caller deadline and cancellation are witnessed natively by +`TestOfflineSealUsesCallerDeadline`, `TestOfflineSealCallerCancelCanRetry` and +`TestChunkPlainDetachUsesCallerDeadline`; live-detach bounds retain their tests. From 3588903f6f929b4b5bc3f6d92de8d07e3f9e8618 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:16:22 -0800 Subject: [PATCH 24/34] docs: condense offline seal transition statement --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 618daa6d22..68792f2889 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -243,7 +243,7 @@ stateDiagram-v2 | Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease) | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-WS-LEASE-001` | | Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | | Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001` | -| Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses StopIO and a final detached cut under the caller context, including a closed idle frontend (G.GONE.SEALED). | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | +| Plain detach | plain=true acquires exclusive idle frontend admission (closed handles allowed), then StopIO and caller-bounded seal. Busy requests mutate nothing; publication and settlement retain authority/HEAD checks. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | | Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | From 9be118360aa028ede07e9ab123d7f49915624862 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:28:00 -0800 Subject: [PATCH 25/34] test: refuse offline HTTP seals without an explicit bound --- .../host/volume/chunk_offline_seal_test.go | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/host/volume/chunk_offline_seal_test.go b/seaweed-block/core/host/volume/chunk_offline_seal_test.go index e6f2832e96..245e4984b2 100644 --- a/seaweed-block/core/host/volume/chunk_offline_seal_test.go +++ b/seaweed-block/core/host/volume/chunk_offline_seal_test.go @@ -2,6 +2,7 @@ package volume import ( "context" + "fmt" "net/http" "net/http/httptest" "strings" @@ -25,20 +26,36 @@ func TestChunkPlainDetachUsesCallerDeadline(t *testing.T) { ctx := context.Background() cancel := func() {} if limited { - ctx, cancel = context.WithTimeout(ctx, time.Hour) + ctx, cancel = context.WithTimeout(ctx, 5*time.Minute) } - req := httptest.NewRequest(http.MethodPost, "/chunk/detach", strings.NewReader(`{"volumeID":"v1","plain":true}`)).WithContext(ctx) + req := httptest.NewRequest(http.MethodPost, "/chunk/detach", strings.NewReader(`{"volumeID":"v1","plain":true,"timeoutMs":3600000}`)).WithContext(ctx) req.RemoteAddr = "127.0.0.1:5555" w := httptest.NewRecorder() + before := time.Now() s.chunkMux().ServeHTTP(w, req) + after := time.Now() cancel() if w.Code != 200 || c.got == nil { t.Fatalf("plain dispatch failed: %d %s", w.Code, w.Body) } got, gok := c.got.Deadline() - want, wok := ctx.Deadline() - if gok != wok || !got.Equal(want) { - t.Errorf("offline HTTP inherited operation cap: got=%v known=%t want=%v known=%t", got, gok, want, wok) + if want, ok := ctx.Deadline(); ok { + if !gok || !got.Equal(want) { + t.Errorf("offline HTTP ignored earlier caller: got=%v want=%v", got, want) + } + } else if !gok || got.Before(before.Add(time.Hour)) || got.After(after.Add(time.Hour)) { + t.Errorf("offline HTTP inherited operation cap: got=%v want explicit one-hour bound", got) + } + } +} + +func TestChunkPlainDetachRequiresExplicitBound(t *testing.T) { + for _, suffix := range []string{"", `,"timeoutMs":0`, `,"timeoutMs":-1`} { + c := &plainDetachControl{fakeChunkControl: &fakeChunkControl{}} + s := chunkServer(t, c, true) + w := serve(t, s, http.MethodPost, "/chunk/detach", fmt.Sprintf(`{"volumeID":"v1","plain":true%s}`, suffix), "") + if w.Code != http.StatusBadRequest || c.calls != 0 || c.plainCalls != 0 { + t.Errorf("unbounded plain request reached provider: status=%d calls=%d plain=%d", w.Code, c.calls, c.plainCalls) } } } From 889a85eab4238e4aa0b0e5caa0e8849d80345db6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:28:29 -0800 Subject: [PATCH 26/34] fix: require a bounded offline seal request and use M5 names --- .../core/frontend/durable/provider_chunk.go | 4 ++-- .../durable/provider_offline_seal_test.go | 2 +- seaweed-block/core/host/volume/chunk_control.go | 15 ++++++++------- .../core/host/volume/chunk_plain_detach_test.go | 6 +++--- seaweed-block/docs/design/invariants.md | 4 ++-- seaweed-block/docs/spec/README.md | 1 + 6 files changed, 17 insertions(+), 15 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 5acf59d19d..9d6f26e1b0 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -1049,7 +1049,7 @@ func (p *DurableProvider) DetachVolumeFrozen(ctx context.Context, volumeID strin var ErrPlainDetachBusy = errors.New("durable: plain detach requires idle frontend I/O") // DetachVolumePlain bypasses pre-copy cost admission only after atomically -// closing an idle frontend (including a closed handle). G.GONE.SEALED uses +// closing an idle frontend (including a closed handle). M5 PlainStop -> Quiesce uses // only the caller context, not the live-serving freeze timer. func (p *DurableProvider) DetachVolumePlain(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) { return p.detachVolume(ctx, volumeID, true) @@ -1108,7 +1108,7 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla start = guestFreeze.StartedAt } casAtFreeze = countCAS() - if plain { // G.GONE.SEALED: no live frontend, caller owns the bound. + if plain { // M5 PlainStop -> Quiesce: no live frontend, caller owns the bound. settleDeadline, _ = ctx.Deadline() return } diff --git a/seaweed-block/core/frontend/durable/provider_offline_seal_test.go b/seaweed-block/core/frontend/durable/provider_offline_seal_test.go index 4f149ef382..5f47d335ee 100644 --- a/seaweed-block/core/frontend/durable/provider_offline_seal_test.go +++ b/seaweed-block/core/frontend/durable/provider_offline_seal_test.go @@ -12,7 +12,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) -// G.GONE.SEALED: an idle plain detach seals under the caller's deadline, +// M5 PlainStop -> Quiesce: an idle plain detach seals under the caller's deadline, // including after the frontend handle closes; no live-serving timer applies. func TestOfflineSealUsesCallerDeadline(t *testing.T) { for _, closed := range []bool{false, true} { diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index b66bc2c910..016c635d97 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -551,19 +551,20 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) writeChunkErr(w, http.StatusBadRequest, codeInvalidFreezeBudget, false, "frozen requires a non-future freezeStartedAtNs and cannot combine with plain; allowOverBudget requires frozen") return } + // M5 PlainStop -> Quiesce: the offline caller owns a finite wait. + if req.Plain && req.TimeoutMs <= 0 { + writeChunkErr(w, http.StatusBadRequest, codeBadRequest, false, "plain detach requires positive timeoutMs") + return + } ctl := s.chunkTarget(w, req.VolumeID) if ctl == nil { return } ctx, cancel := chunkContext(r, req.TimeoutMs) - if req.Plain { // G.GONE.SEALED: offline work is bounded by its caller. + if req.Plain { // M5 PlainStop -> Quiesce: offline work is bounded by its caller. cancel() - ctx, cancel = context.WithCancel(r.Context()) - if req.TimeoutMs > 0 { - const maxTimeoutMs = int64((1<<63 - 1) / time.Millisecond) - cancel() - ctx, cancel = context.WithTimeout(r.Context(), time.Duration(min(req.TimeoutMs, maxTimeoutMs))*time.Millisecond) - } + const maxTimeoutMs = int64((1<<63 - 1) / time.Millisecond) + ctx, cancel = context.WithTimeout(r.Context(), time.Duration(min(req.TimeoutMs, maxTimeoutMs))*time.Millisecond) } defer cancel() var res ChunkDetachResponse diff --git a/seaweed-block/core/host/volume/chunk_plain_detach_test.go b/seaweed-block/core/host/volume/chunk_plain_detach_test.go index 1d129984aa..b6825b347a 100644 --- a/seaweed-block/core/host/volume/chunk_plain_detach_test.go +++ b/seaweed-block/core/host/volume/chunk_plain_detach_test.go @@ -28,7 +28,7 @@ func TestChunkDetachPlainFieldDispatch(t *testing.T) { t.Fatalf("ordinary request changed: %d %s plain=%d", w.Code, w.Body, c.plainCalls) } } - w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true}`, "") + w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true,"timeoutMs":60000}`, "") if w.Code != 200 || c.plainCalls != 1 { t.Fatalf("plain request not dispatched: %d %s plain=%d", w.Code, w.Body, c.plainCalls) } @@ -50,12 +50,12 @@ func (p *plainDetachProvider) DetachVolumePlain(ctx context.Context, id string) func TestChunkDetachPlainAdapterAndBusyResponse(t *testing.T) { p := &plainDetachProvider{fakeChunkProvider: &fakeChunkProvider{detach: storage.ChunkCutResult{H: 9, Head: storage.ChunkHead{Gen: 3, Epoch: 2, State: storage.ChunkHeadDetached}}, last: 9}} s := chunkServer(t, NewChunkControl(p, nil), true) - w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true}`, "") + w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true,"timeoutMs":60000}`, "") if w.Code != 200 || p.plainCalls != 1 { t.Fatalf("plain adapter: %d %s calls=%d", w.Code, w.Body, p.plainCalls) } p.err = errors.Join(durable.ErrPlainDetachBusy, errors.New("held I/O")) - w = serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true}`, "") + w = serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true,"timeoutMs":60000}`, "") if w.Code != 409 { t.Fatalf("busy status: %d %s", w.Code, w.Body) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 68792f2889..b55cf2b24f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -526,7 +526,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-PLAIN-DETACH-001` | Plain detach excludes entering/admitted I/O, then seals under the caller context, including a closed idle frontend. Publication and unknown/fenced settlement remain enforced. Closed frontend handles never reopen; absent/false preserves live policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` ; `TestOfflineSealUsesCallerDeadline`, `TestOfflineSealCallerCancelCanRetry` (`core/frontend/durable/provider_offline_seal_test.go`); `TestChunkPlainDetachUsesCallerDeadline` (`core/host/volume/chunk_offline_seal_test.go`) | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | +| `INV-CUT-PLAIN-DETACH-001` | Plain detach excludes entering/admitted I/O, then seals under the caller context, including a closed idle frontend. Publication and unknown/fenced settlement remain enforced. Closed frontend handles never reopen; absent/false preserves live policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` ; `TestOfflineSealUsesCallerDeadline`, `TestOfflineSealCallerCancelCanRetry` (`core/frontend/durable/provider_offline_seal_test.go`); `TestChunkPlainDetachUsesCallerDeadline`, `TestChunkPlainDetachRequiresExplicitBound` (`core/host/volume/chunk_offline_seal_test.go`) | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | | `INV-WS-FREEZE-ACCOUNTING-001` | Frozen detach validates its origin and rechecks elapsed + known estimate against 5 s; override is explicit. Storage reports its admission estimate and quiesce slack using same-host monotonic durations. Stale advice is rechecked before upload; override and actual elapsed remain visible. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess`; `TestCandidateTailReportsCompleteFrozenBudget`, `TestFrozenRefusalRetainsUnknownCompleteEstimate`, `TestChunkFrozenRefusalCarriesServerBudget`, `TestChunkFrozenDrainRefusalCarriesObservedBudget`, `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation`, `TestFrozenSaturatedTailRemainsKnownButNonActionable` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible`, `ReportSlackSound` | ACTIVE | | `INV-WS-FREEZE-REFUSAL-001` | HTTP400 `invalid_freeze_budget`, retryable=false, is emitted only for frozen-request validation before any provider admission or mutation. Missing/zero/future origin, override without frozen, and frozen+plain preserve that boundary. Generic `bad_request` is not a clean-refusal proof. Terminal and unknown-publication causes retain precedence; no production path emits this typed code after mutation. | G frozen detach: request → refused before admission (M5) | `core/host/volume/chunk_control.go` `handleChunkDetach`, `chunkErrorCode`; `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestChunkFrozenValidationHasDistinctPreMutationCode`, `TestFrozenValidationPrecedesAnyProviderAccess` | — (wire classification; validation/admission guards unchanged) | ACTIVE | | `INV-CUT-PRECOPY-001` | Resume grants waiters FIFO under one lock; gates and completion are independent. Each command keeps its arrival/caller bound. Only pause refusals requeue; stale and terminal errors survive. Detached handoff requires settled publication. See Notes for admission and freeze guards. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestCheckpointTailScanIncludedInTotalAndFixedCosts`, `TestCheckpointTailUsesLiteralLatestThreeConservativeRate`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestChunkFrozenDetachWireContractAndPrecedence`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyResumeReleasesAllWaiters` (FIFO grants under one lock, concurrent outstanding I/O), `TestPrecopyResumedArrivalDoesNotInheritExpiredPause`, `TestPrecopyQueueBoundStartsAtCommandArrival`, `TestPrecopyResumeGrantVersusExpiry`, `TestPrecopyGrantedWaiterFollowsReplacementPause`, `TestPrecopyNewPauseCannotEraseObservedStalePrimary`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); controlled callers and measured latency are not a model proof | ACTIVE | @@ -668,7 +668,7 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a | Wait | Machine / invariant | Bound | Release and cancellation | Locks / remote work | |---|---|---|---|---| -| Offline seal | G.GONE.SEALED; `INV-CUT-PLAIN-DETACH-001` | Caller context, including its optional explicit HTTP timeout; no live-serving timer | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. | +| Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; HTTP requires positive timeoutMs before provider dispatch; no live-serving timer | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. | | Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. | Frozen estimate reporting: a tail above the existing 60 s estimator ceiling reports the same 60 s rejection sentinel used by admission. It is known but saturated, not a complete fixed-plus-tail duration; quiesce slack is zero. Consumers must not use it as a completion forecast. Drain refusals retain the observation before their reason changes; this reporting does not reclassify refusal causes. diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 87fad51d5c..8d1db68493 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -528,3 +528,4 @@ empty (TLC 2.19 with the tools hash above). `PlainDetach_no_idle.cfg` violates model. Caller deadline and cancellation are witnessed natively by `TestOfflineSealUsesCallerDeadline`, `TestOfflineSealCallerCancelCanRetry` and `TestChunkPlainDetachUsesCallerDeadline`; live-detach bounds retain their tests. +The HTTP plain caller must supply positive timeoutMs; `TestChunkPlainDetachRequiresExplicitBound` witnesses rejection before provider dispatch. From 09cac1bcf2ab00bd495926fc4395aa34bc5f25c3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:29:29 -0800 Subject: [PATCH 27/34] ci: run the full suites on the per-train test VM, not on the shared runner Main pushes and train PRs run the light set only; the legacy-fixture job is removed. Each train runs both full configurations on a separate test VM before it merges. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/.github/workflows/test.yml | 58 +++--------------------- 1 file changed, 7 insertions(+), 51 deletions(-) diff --git a/seaweed-block/.github/workflows/test.yml b/seaweed-block/.github/workflows/test.yml index f37cdca486..4b32f0a04b 100644 --- a/seaweed-block/.github/workflows/test.yml +++ b/seaweed-block/.github/workflows/test.yml @@ -62,18 +62,18 @@ jobs: run: go vet ./... - name: Test default configuration - # A PR runs the light set plus every heavy package its own diff touches; - # the long, disk-heavy, timing-sensitive packages run in full on main and - # on train PRs. A green PR check does not cover an untouched heavy package. + # The runner disk is shared, so the long, disk-heavy, timing-sensitive + # packages do not run here on main or on train PRs: every train runs the + # whole suite (both configurations) on a separate test VM before it + # merges, and main moves only by those trains. A PR runs the light set + # plus every heavy package its own diff touches. env: EVENT: ${{ github.event_name }} HEAD_REF: ${{ github.head_ref }} run: | set -euo pipefail - if [ "$EVENT" = push ] || [[ "$HEAD_REF" == train/* ]]; then - pkgs=$(go list ./...) - else - pkgs=$(go list ./... | grep -vE '/core/(storage|frontend/durable|host/master|authority)$') + pkgs=$(go list ./... | grep -vE '/core/(storage|frontend/durable|host/master|authority)$') + if [ "$EVENT" != push ] && [[ "$HEAD_REF" != train/* ]]; then mod=$(go list -m) changed=$(git diff --name-only HEAD^1 HEAD) for p in core/storage core/frontend/durable core/host/master core/authority; do @@ -83,47 +83,3 @@ jobs: done fi go test -p=1 -short -count=1 -timeout 10m $pkgs - - test-legacy: - name: go test legacy-fixture - # A second full pass (legacy-fixture tag) writes as much again: it runs on - # main and on train PRs, which carry every change that merges. - if: github.event_name == 'push' || startsWith(github.head_ref, 'train/') - # Same routing as the default job: same-repo PRs and pushes use the tp04 - # runners (two instances, so both passes run in parallel); fork PRs stay on - # a GitHub-hosted runner, whose shared queue can wait for hours. - runs-on: ${{ (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && 'tp04-seaweed-block' || 'ubuntu-latest' }} - timeout-minutes: 40 - env: - CGO_ENABLED: "0" - steps: - - name: Checkout - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - with: - persist-credentials: false - - - name: Set up Go - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 - with: - go-version-file: go.mod - # The self-hosted runner keeps GOCACHE/GOMODCACHE on its own disk; - # uploading them as an Actions cache (~4 GB) in the post step - # outlasted the job timeout after every test had passed. Only the - # GitHub-hosted (fork PR) runner uses the Actions cache. - cache: ${{ runner.environment == 'github-hosted' }} - cache-dependency-path: go.sum - - - name: Go version - run: go version - - - name: Build - run: go build ./... - - - name: Vet - run: go vet ./... - - - name: Test legacy-fixture configuration - # Legacy-input fixtures and native caller controls stay executable after - # their constructors move behind the explicit test-only build tag. - # Bound package concurrency for existing short wall-clock assertions. - run: go test -p=1 -short -tags=swblock_format_v3_test -count=1 -timeout 10m ./... From 08df12ff4782babdec7e7a6bee2f77783849b1f7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:30:01 -0800 Subject: [PATCH 28/34] test: use the closed gate readiness interface --- .../core/frontend/durable/plain_detach_closed_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/durable/plain_detach_closed_test.go b/seaweed-block/core/frontend/durable/plain_detach_closed_test.go index 249c6027b7..599653339e 100644 --- a/seaweed-block/core/frontend/durable/plain_detach_closed_test.go +++ b/seaweed-block/core/frontend/durable/plain_detach_closed_test.go @@ -1,7 +1,6 @@ package durable import ( - "context" "errors" "testing" @@ -18,7 +17,7 @@ func TestPlainDetachStopAcceptsClosedIdleBackend(t *testing.T) { if err := b.stopPlainDetachIfIdle(); err != nil { t.Fatalf("closed idle backend cannot seal: %v", err) } - if err := b.readyCheck(context.Background()); !errors.Is(err, frontend.ErrBackendClosed) { + if err := b.readyCheck(); !errors.Is(err, frontend.ErrBackendClosed) { t.Fatalf("offline admission reopened frontend: %v", err) } } From 5c14e42b42fb0929397842c2dc7965014835d6a3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:30:03 -0800 Subject: [PATCH 29/34] Merge main: the check runs on the current document Three stale test names it found are fixed (one rename, one test removed with the retired engine and replaced by its neighbour, one name that exists nowhere). The count check accepts the document's wording. Co-Authored-By: Claude Fable 5.2 --- .../.github/pull_request_template.md | 27 +- seaweed-block/.github/scripts/sametokens.go | 111 + .../.github/scripts/spec-trace-check-test.sh | 153 ++ .../.github/scripts/spec-trace-check.sh | 158 ++ .../.github/workflows/spec-trace.yml | 62 + seaweed-block/.github/workflows/test.yml | 33 +- seaweed-block/README.md | 1 + .../cmd/blockvolume/chunk_maintenance.go | 59 + .../cmd/blockvolume/chunk_maintenance_test.go | 114 + seaweed-block/cmd/blockvolume/chunk_remote.go | 49 +- .../cmd/blockvolume/chunk_remote_test.go | 46 +- seaweed-block/cmd/blockvolume/main.go | 16 +- seaweed-block/cmd/sw-block/chunk.go | 55 +- seaweed-block/cmd/sw-block/chunk_gc.go | 7 +- .../cmd/sw-block/chunk_gc_integration_test.go | 4 +- seaweed-block/cmd/sw-block/chunk_gc_test.go | 18 + .../sw-block/chunk_manifest_fixture_test.go | 2 +- seaweed-block/cmd/sw-block/chunk_restore.go | 30 + .../cmd/sw-block/chunk_restore_test.go | 39 + seaweed-block/cmd/sw-block/chunk_retain.go | 4 +- .../cmd/sw-block/chunk_start_check_test.go | 93 + seaweed-block/cmd/sw-block/chunk_verify.go | 158 ++ .../cmd/sw-block/chunk_verify_test.go | 229 ++ .../cmd/sw-block/chunk_volume_delete.go | 2 +- seaweed-block/cmd/sw-block/main.go | 8 +- seaweed-block/cmd/sw-block/workspace.go | 274 +++ .../cmd/sw-block/workspace_master_test.go | 173 ++ .../cmd/sw-block/workspace_postissue_test.go | 83 + seaweed-block/cmd/sw-block/workspace_test.go | 450 ++++ .../cmd/sw-block/workspace_uncertain_test.go | 90 + seaweed-block/core/authority/authority.go | 11 + .../core/authority/authority_store_file.go | 23 + seaweed-block/core/authority/workspace.go | 129 +- .../authority/workspace_lease_horizon_test.go | 20 +- .../core/authority/workspace_lost_range.go | 140 +- .../workspace_lost_range_readout_test.go | 339 +++ .../workspace_outcome_uncertain_test.go | 69 + seaweed-block/core/engine/projection.go | 20 +- seaweed-block/core/frontend/chunkstore/GC.md | 158 ++ .../core/frontend/chunkstore/catalog.go | 237 +- .../chunkstore/catalog_settle_test.go | 19 +- .../core/frontend/chunkstore/chunk_remote.go | 26 + .../core/frontend/chunkstore/fake_test.go | 2 +- seaweed-block/core/frontend/chunkstore/gc.go | 151 +- .../frontend/chunkstore/gc_clock_skew_test.go | 308 +++ .../core/frontend/chunkstore/gc_copy.go | 16 +- .../core/frontend/chunkstore/gc_copy_test.go | 2 +- .../chunkstore/gc_delete_progress_test.go | 97 + .../core/frontend/chunkstore/gc_execution.go | 52 +- .../frontend/chunkstore/gc_execution_test.go | 2 +- .../core/frontend/chunkstore/gc_test.go | 9 +- .../frontend/chunkstore/gc_volume_test.go | 251 ++ .../frontend/chunkstore/reclaim_key_test.go | 47 + .../core/frontend/chunkstore/remote.go | 8 +- .../core/frontend/chunkstore/restore.go | 163 ++ .../core/frontend/chunkstore/restore_test.go | 392 ++++ .../core/frontend/chunkstore/retention.go | 251 +- .../chunkstore/retention_integration_test.go | 23 +- .../chunkstore/retention_review_test.go | 228 +- .../frontend/chunkstore/retention_test.go | 60 +- .../core/frontend/chunkstore/share_guard.go | 61 + .../frontend/chunkstore/share_guard_test.go | 204 ++ .../chunkstore/snapshot_delete_test.go | 204 ++ .../core/frontend/chunkstore/swfs.go | 84 +- .../core/frontend/chunkstore/swfs_test.go | 2 + .../core/frontend/chunkstore/usage.go | 36 +- .../core/frontend/chunkstore/verify.go | 1633 +++++++++++++ .../core/frontend/chunkstore/verify_test.go | 2036 +++++++++++++++++ .../volume_delete_integration_test.go | 2 +- .../frontend/chunkstore/volume_delete_test.go | 13 +- .../durable/attach_ready_fail_fast_test.go | 102 + .../frozen_validation_before_access_test.go | 22 + .../durable/maintenance_lineage_test.go | 92 + .../durable/maintenance_policy_test.go | 60 + .../durable/plain_detach_closed_test.go | 20 + .../frontend/durable/precopy_admission.go | 138 +- .../frontend/durable/precopy_arrival_test.go | 314 +++ .../durable/precopy_drain_admitted_io_test.go | 162 ++ .../precopy_drain_readiness_loss_test.go | 80 + .../frontend/durable/precopy_fifo_test.go | 104 +- .../precopy_pause_entry_checks_test.go | 81 + .../frontend/durable/precopy_resume_test.go | 192 ++ .../durable/precopy_stale_retry_test.go | 52 + .../core/frontend/durable/provider.go | 83 +- .../core/frontend/durable/provider_chunk.go | 156 +- .../durable/provider_chunk_sched_test.go | 54 +- .../provider_initial_memory_linux_test.go | 6 - .../durable/provider_maintenance_test.go | 360 +++ .../core/frontend/durable/provider_restore.go | 74 + .../frontend/durable/provider_restore_test.go | 81 + .../core/frontend/durable/spill_free_linux.go | 17 + .../frontend/durable/spill_free_linux_test.go | 29 + .../core/frontend/durable/spill_free_other.go | 6 + .../core/frontend/durable/storage_adapter.go | 13 +- .../core/frontend/durable/write_profile.go | 92 +- seaweed-block/core/frontend/nvme/stats.go | 54 +- seaweed-block/core/frontend/types.go | 29 +- seaweed-block/core/frontend/ublk/dispatch.go | 12 +- .../core/host/master/workspace_head.go | 20 +- .../workspace_lost_range_readout_test.go | 255 +++ .../core/host/master/workspace_service.go | 236 +- .../core/host/volume/chunk_control.go | 44 +- .../host/volume/chunk_control_class_test.go | 3 - .../host/volume/chunk_control_order_test.go | 55 + .../host/volume/chunk_frozen_budget_test.go | 172 ++ .../core/host/volume/chunk_restore.go | 246 ++ .../core/host/volume/chunk_restore_test.go | 394 ++++ .../core/host/volume/memory_status.go | 14 +- .../core/host/volume/status_schema_test.go | 308 +++ .../core/host/volume/status_server.go | 52 +- seaweed-block/core/iolatency/latency.go | 30 +- .../receiver_install_format_v3_test.go | 19 +- seaweed-block/core/replication/peer.go | 18 +- .../core/rpc/control/workspace.pb.go | 548 ++++- .../core/rpc/control/workspace_grpc.pb.go | 86 + seaweed-block/core/rpc/proto/workspace.proto | 33 + seaweed-block/core/rpc/wsclient/wsclient.go | 318 +++ .../core/rpc/wsclient/wsclient_test.go | 224 ++ .../storage/base_install_reopen_v3_test.go | 2 +- .../storage/base_install_resume_v3_test.go | 10 +- seaweed-block/core/storage/base_install_v3.go | 6 +- .../core/storage/base_install_v3_test.go | 19 +- .../core/storage/checkpoint_diagnostics.go | 12 +- seaweed-block/core/storage/chunk_base_v3.go | 4 +- seaweed-block/core/storage/chunk_cut_cow.go | 64 +- .../storage/chunk_cut_cow_spillfree_test.go | 225 ++ .../core/storage/chunk_cut_payload.go | 2 +- .../storage/chunk_cut_payload_budget_test.go | 2 +- .../core/storage/chunk_cut_progress_test.go | 95 + .../core/storage/chunk_frontier_v3_test.go | 2 +- .../core/storage/chunk_frozen_budget.go | 59 +- .../core/storage/chunk_frozen_report_test.go | 102 + .../core/storage/chunk_hydrate_all.go | 272 +++ .../core/storage/chunk_hydrate_all_test.go | 459 ++++ seaweed-block/core/storage/chunk_hydration.go | 101 +- seaweed-block/core/storage/chunk_layer.go | 51 +- .../core/storage/chunk_layer_contract_test.go | 107 +- seaweed-block/core/storage/chunk_own.go | 142 ++ seaweed-block/core/storage/chunk_own_test.go | 192 ++ .../core/storage/chunk_periodic_cut.go | 2 +- seaweed-block/core/storage/chunk_precopy.go | 6 +- .../chunk_precopy_retry_errors_test.go | 47 + .../chunk_precopy_sample_bound_test.go | 25 + .../core/storage/chunk_publish_settled.go | 72 + .../storage/chunk_publish_settled_test.go | 366 +++ seaweed-block/core/storage/chunk_seam.go | 92 +- seaweed-block/core/storage/data_sync.go | 4 +- seaweed-block/core/storage/descriptor_v3.go | 2 +- .../core/storage/descriptor_v3_test.go | 6 +- .../core/storage/durability_latency.go | 6 +- .../core/storage/install_log_v3_test.go | 4 +- seaweed-block/core/storage/recovery_v3.go | 5 +- .../core/storage/recovery_v3_test.go | 6 +- .../core/storage/reset_store_v3_test.go | 8 +- .../core/storage/superblock_v3_test.go | 2 +- .../format_v3/slot/gen_slot_vectors.py | 2 +- .../core/storage/walstore_batch_v3_test.go | 12 +- .../core/storage/walstore_close_v3_test.go | 2 +- .../core/storage/walstore_recovery.go | 2 +- seaweed-block/core/storage/walstore_v3.go | 34 +- .../core/storage/walstore_v3_test.go | 22 +- .../replica_install_format_v3_test.go | 4 +- seaweed-block/deploy/config/blockvolume.env | 3 - .../systemd/sw-blockvolume-ublk.service | 1 - .../deploy/systemd/sw-blockvolume.service | 1 - .../docs/design/agent-workspace-design.md | 72 +- seaweed-block/docs/design/invariants.md | 183 +- seaweed-block/docs/spec/ForkDelete.tla | 305 +++ .../docs/spec/FrozenDetachBudget.tla | 9 +- seaweed-block/docs/spec/GCClockSkew.tla | 24 + .../docs/spec/GCClockSkew_abort_future.cfg | 7 + .../docs/spec/GCClockSkew_no_resolution.cfg | 7 + .../docs/spec/GCClockSkew_no_skew.cfg | 7 + seaweed-block/docs/spec/GCClockSkew_safe.cfg | 7 + seaweed-block/docs/spec/GCDeleteProgress.tla | 24 + .../docs/spec/GCDeleteProgress_safe.cfg | 4 + .../docs/spec/GCDeleteProgress_stop.cfg | 4 + seaweed-block/docs/spec/MaintenanceOwner.tla | 37 + .../spec/MaintenanceOwner_early_release.cfg | 6 + .../docs/spec/MaintenanceOwner_overlap.cfg | 6 + .../docs/spec/MaintenanceOwner_safe.cfg | 6 + .../spec/MaintenanceOwner_stale_rearm.cfg | 6 + seaweed-block/docs/spec/README.md | 111 +- .../docs/spec/RestoreIndependence.tla | 256 +++ .../docs/spec/ScopedMaintenanceGC.tla | 25 + .../ScopedMaintenanceGC_import_global.cfg | 6 + .../spec/ScopedMaintenanceGC_narrow_roots.cfg | 6 + .../docs/spec/ScopedMaintenanceGC_safe.cfg | 6 + .../spec/ScopedMaintenanceGC_wide_sweep.cfg | 6 + seaweed-block/docs/spec/WALReclaim.tla | 4 +- .../spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg | 19 + .../spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg | 19 + .../spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg | 19 + .../spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg | 19 + .../cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg | 19 + .../cfg/ForkDelete_red_deletedNotRooted.cfg | 19 + .../spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg | 19 + .../spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg | 19 + .../spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg | 19 + .../spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg | 19 + .../cfg/ForkDelete_red_noDeadlineCheck.cfg | 19 + .../spec/cfg/ForkDelete_red_noRetryReread.cfg | 19 + .../docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg | 19 + .../docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg | 19 + .../docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg | 19 + .../docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg | 19 + .../docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg | 19 + .../docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg | 19 + .../spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg | 19 + .../spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg | 19 + .../spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg | 19 + .../spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg | 19 + .../spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg | 19 + .../docs/spec/cfg/ForkDelete_wit_benefit.cfg | 20 + .../spec/cfg/ForkDelete_wit_benefit_na_P1.cfg | 20 + .../spec/cfg/ForkDelete_wit_deadlineLoss.cfg | 20 + .../spec/cfg/ForkDelete_wit_gcDeletes.cfg | 20 + .../spec/cfg/ForkDelete_wit_retryNotFound.cfg | 20 + .../docs/spec/cfg/FrozenDetachBudget.cfg | 2 +- .../docs/spec/cfg/Maintenance_lifecycle.cfg | 20 + .../cfg/RestoreIndependence_nc_bnd_G0D1.cfg | 30 + .../cfg/RestoreIndependence_nc_bnd_G1D1.cfg | 30 + .../cfg/RestoreIndependence_nc_bnd_G2D3.cfg | 30 + .../cfg/RestoreIndependence_nc_bnd_G3D3.cfg | 30 + ...oreIndependence_nc_red_CasBeforeUpload.cfg | 30 + .../cfg/RestoreIndependence_nc_red_GltD.cfg | 30 + ...RestoreIndependence_nc_red_ListForeign.cfg | 30 + ...oreIndependence_nc_red_MarkerBeforeCas.cfg | 30 + ...RestoreIndependence_nc_red_MarkerEarly.cfg | 30 + .../RestoreIndependence_nc_red_NoIntent.cfg | 30 + ...RestoreIndependence_nc_red_ResumeLocal.cfg | 30 + ...eIndependence_nc_red_SnapDuringRestore.cfg | 30 + .../RestoreIndependence_nc_red_noDeadline.cfg | 30 + .../RestoreIndependence_nc_red_notRooted.cfg | 30 + ...toreIndependence_nc_red_resumeNoReread.cfg | 30 + .../spec/cfg/RestoreIndependence_nc_safe.cfg | 30 + .../cfg/RestoreIndependence_nc_safe_G3D2.cfg | 30 + .../cfg/RestoreIndependence_nc_safe_b2.cfg | 30 + .../cfg/RestoreIndependence_nc_safe_n4.cfg | 30 + .../RestoreIndependence_nc_wit_DelInFork.cfg | 31 + ...estoreIndependence_nc_wit_FailNotFound.cfg | 31 + .../spec/cfg/RestoreIndependence_oldframe.cfg | 32 + .../cfg/RestoreIndependence_oldframe_drop.cfg | 31 + .../cfg/RestoreIndependence_opt1_safe.cfg | 31 + ...reIndependence_red_DropClaimAtFork_gap.cfg | 30 + .../spec/cfg/RestoreIndependence_safe.cfg | 31 + seaweed-block/docs/standalone-deployment.md | 1 - seaweed-block/docs/status-schema.md | 404 ++++ ...shedplan_iscsi_session_backend_pressure.md | 6 +- .../cluster-ops-inventory-chain-validation.md | 2 +- ...ockvolume-lifecycle-mvp-close-hard-gate.md | 4 +- ...-blockvolume-lifecycle-mvp-close-report.md | 2 +- .../same-node-alpha-attach-validation.md | 4 +- .../docs/ref/product-positioning-v1.md | 6 +- .../ref/testops-runner-binary-contract.md | 4 +- .../internal/invcheck/invariants_test.go | 6 +- seaweed-block/testops/README.md | 6 +- 257 files changed, 19580 insertions(+), 1645 deletions(-) create mode 100644 seaweed-block/.github/scripts/sametokens.go create mode 100644 seaweed-block/.github/scripts/spec-trace-check-test.sh create mode 100644 seaweed-block/.github/scripts/spec-trace-check.sh create mode 100644 seaweed-block/.github/workflows/spec-trace.yml create mode 100644 seaweed-block/cmd/blockvolume/chunk_maintenance.go create mode 100644 seaweed-block/cmd/blockvolume/chunk_maintenance_test.go create mode 100644 seaweed-block/cmd/sw-block/chunk_restore.go create mode 100644 seaweed-block/cmd/sw-block/chunk_restore_test.go create mode 100644 seaweed-block/cmd/sw-block/chunk_start_check_test.go create mode 100644 seaweed-block/cmd/sw-block/chunk_verify.go create mode 100644 seaweed-block/cmd/sw-block/chunk_verify_test.go create mode 100644 seaweed-block/cmd/sw-block/workspace.go create mode 100644 seaweed-block/cmd/sw-block/workspace_master_test.go create mode 100644 seaweed-block/cmd/sw-block/workspace_postissue_test.go create mode 100644 seaweed-block/cmd/sw-block/workspace_test.go create mode 100644 seaweed-block/cmd/sw-block/workspace_uncertain_test.go create mode 100644 seaweed-block/core/authority/workspace_lost_range_readout_test.go create mode 100644 seaweed-block/core/authority/workspace_outcome_uncertain_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/gc_clock_skew_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/gc_delete_progress_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/gc_volume_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/reclaim_key_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/restore.go create mode 100644 seaweed-block/core/frontend/chunkstore/restore_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/share_guard.go create mode 100644 seaweed-block/core/frontend/chunkstore/share_guard_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/verify.go create mode 100644 seaweed-block/core/frontend/chunkstore/verify_test.go create mode 100644 seaweed-block/core/frontend/durable/attach_ready_fail_fast_test.go create mode 100644 seaweed-block/core/frontend/durable/frozen_validation_before_access_test.go create mode 100644 seaweed-block/core/frontend/durable/maintenance_lineage_test.go create mode 100644 seaweed-block/core/frontend/durable/maintenance_policy_test.go create mode 100644 seaweed-block/core/frontend/durable/plain_detach_closed_test.go create mode 100644 seaweed-block/core/frontend/durable/precopy_arrival_test.go create mode 100644 seaweed-block/core/frontend/durable/precopy_drain_admitted_io_test.go create mode 100644 seaweed-block/core/frontend/durable/precopy_drain_readiness_loss_test.go create mode 100644 seaweed-block/core/frontend/durable/precopy_pause_entry_checks_test.go create mode 100644 seaweed-block/core/frontend/durable/precopy_resume_test.go create mode 100644 seaweed-block/core/frontend/durable/precopy_stale_retry_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_maintenance_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_restore.go create mode 100644 seaweed-block/core/frontend/durable/provider_restore_test.go create mode 100644 seaweed-block/core/frontend/durable/spill_free_linux.go create mode 100644 seaweed-block/core/frontend/durable/spill_free_linux_test.go create mode 100644 seaweed-block/core/frontend/durable/spill_free_other.go create mode 100644 seaweed-block/core/host/master/workspace_lost_range_readout_test.go create mode 100644 seaweed-block/core/host/volume/chunk_restore.go create mode 100644 seaweed-block/core/host/volume/chunk_restore_test.go create mode 100644 seaweed-block/core/host/volume/status_schema_test.go create mode 100644 seaweed-block/core/rpc/wsclient/wsclient.go create mode 100644 seaweed-block/core/rpc/wsclient/wsclient_test.go create mode 100644 seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go create mode 100644 seaweed-block/core/storage/chunk_frozen_report_test.go create mode 100644 seaweed-block/core/storage/chunk_hydrate_all.go create mode 100644 seaweed-block/core/storage/chunk_hydrate_all_test.go create mode 100644 seaweed-block/core/storage/chunk_own.go create mode 100644 seaweed-block/core/storage/chunk_own_test.go create mode 100644 seaweed-block/core/storage/chunk_precopy_retry_errors_test.go create mode 100644 seaweed-block/core/storage/chunk_precopy_sample_bound_test.go create mode 100644 seaweed-block/core/storage/chunk_publish_settled.go create mode 100644 seaweed-block/core/storage/chunk_publish_settled_test.go create mode 100644 seaweed-block/docs/spec/ForkDelete.tla create mode 100644 seaweed-block/docs/spec/GCClockSkew.tla create mode 100644 seaweed-block/docs/spec/GCClockSkew_abort_future.cfg create mode 100644 seaweed-block/docs/spec/GCClockSkew_no_resolution.cfg create mode 100644 seaweed-block/docs/spec/GCClockSkew_no_skew.cfg create mode 100644 seaweed-block/docs/spec/GCClockSkew_safe.cfg create mode 100644 seaweed-block/docs/spec/GCDeleteProgress.tla create mode 100644 seaweed-block/docs/spec/GCDeleteProgress_safe.cfg create mode 100644 seaweed-block/docs/spec/GCDeleteProgress_stop.cfg create mode 100644 seaweed-block/docs/spec/MaintenanceOwner.tla create mode 100644 seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg create mode 100644 seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg create mode 100644 seaweed-block/docs/spec/MaintenanceOwner_safe.cfg create mode 100644 seaweed-block/docs/spec/MaintenanceOwner_stale_rearm.cfg create mode 100644 seaweed-block/docs/spec/RestoreIndependence.tla create mode 100644 seaweed-block/docs/spec/ScopedMaintenanceGC.tla create mode 100644 seaweed-block/docs/spec/ScopedMaintenanceGC_import_global.cfg create mode 100644 seaweed-block/docs/spec/ScopedMaintenanceGC_narrow_roots.cfg create mode 100644 seaweed-block/docs/spec/ScopedMaintenanceGC_safe.cfg create mode 100644 seaweed-block/docs/spec/ScopedMaintenanceGC_wide_sweep.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg create mode 100644 seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G0D1.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_CasBeforeUpload.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ListForeign.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerBeforeCas.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerEarly.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_NoIntent.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ResumeLocal.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_SnapDuringRestore.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_b2.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_n4.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_opt1_safe.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_red_DropClaimAtFork_gap.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg create mode 100644 seaweed-block/docs/status-schema.md diff --git a/seaweed-block/.github/pull_request_template.md b/seaweed-block/.github/pull_request_template.md index 15de39f911..25ad685875 100644 --- a/seaweed-block/.github/pull_request_template.md +++ b/seaweed-block/.github/pull_request_template.md @@ -1 +1,26 @@ -Machine / invariants (INV ids) / spec covered: +Feature: +Machine/INV: / +Model: +Red-first: +Simplest: + + diff --git a/seaweed-block/.github/scripts/sametokens.go b/seaweed-block/.github/scripts/sametokens.go new file mode 100644 index 0000000000..c167f2429d --- /dev/null +++ b/seaweed-block/.github/scripts/sametokens.go @@ -0,0 +1,111 @@ +// Command sametokens reports whether two versions of a Go source file have the +// same tokens in the same order, ignoring comments that the compiler ignores. +// +// Usage: go run sametokens.go OLD NEW +// +// A missing file counts as empty. Directive comments are compared as tokens: +// //go:..., // +build, //line, /*line, //export; in a file that uses cgo +// (any "C" string literal, as in import "C"), every comment counts, since the +// preamble is code. Exit 0: same tokens; 1: different +// (the first difference is printed); 2: usage error or a file that does not scan. +package main + +import ( + "fmt" + "go/scanner" + "go/token" + "os" + "strings" +) + +type tok struct { + t token.Token + lit string +} + +func main() { + if len(os.Args) != 3 { + fmt.Fprintln(os.Stderr, "usage: sametokens OLD NEW") + os.Exit(2) + } + a, err := tokens(os.Args[1]) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + b, err := tokens(os.Args[2]) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + for i := 0; i < len(a) || i < len(b); i++ { + if i >= len(a) || i >= len(b) || a[i] != b[i] { + fmt.Printf("token %d differs: %v vs %v\n", i, at(a, i), at(b, i)) + os.Exit(1) + } + } +} + +func at(ts []tok, i int) string { + if i >= len(ts) { + return "end of file" + } + return fmt.Sprintf("%s %q", ts[i].t, ts[i].lit) +} + +// tokens scans a file and keeps every token except comments the compiler +// ignores. An automatic semicolon is compared by kind only. +func tokens(path string) ([]tok, error) { + src, err := os.ReadFile(path) + if os.IsNotExist(err) { + return nil, nil + } else if err != nil { + return nil, err + } + fset := token.NewFileSet() + file := fset.AddFile(path, -1, len(src)) + var s scanner.Scanner + var scanErr error + s.Init(file, src, func(pos token.Position, msg string) { + if scanErr == nil { + scanErr = fmt.Errorf("%s: %s", pos, msg) + } + }, scanner.ScanComments) + var all []tok + for { + _, t, lit := s.Scan() + if t == token.EOF { + break + } + if t == token.SEMICOLON { + lit = "" + } + all = append(all, tok{t, lit}) + } + if scanErr != nil { + return nil, scanErr + } + cgo := false + for _, x := range all { + if x.t == token.STRING && x.lit == "\"C\"" { + cgo = true + } + } + var out []tok + for _, x := range all { + if x.t == token.COMMENT && !cgo && !directive(x.lit) { + continue + } + out = append(out, x) + } + return out, nil +} + +func directive(c string) bool { + for _, p := range []string{"//go:", "// +build", "//+build", "//line ", "/*line ", "//export "} { + if strings.HasPrefix(c, p) { + return true + } + } + return false +} diff --git a/seaweed-block/.github/scripts/spec-trace-check-test.sh b/seaweed-block/.github/scripts/spec-trace-check-test.sh new file mode 100644 index 0000000000..c5379d0ff5 --- /dev/null +++ b/seaweed-block/.github/scripts/spec-trace-check-test.sh @@ -0,0 +1,153 @@ +#!/usr/bin/env bash +# Self-test of the spec-trace check: PR descriptions and change lists against +# the exit code they must give. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +check=$here/spec-trace-check.sh +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +fail=0 + +# expect WANT_EXIT NAME BODY [STATUS PATH]... +expect() { + local want=$1 name=$2 body=$3 got=0 + shift 3 + printf '%s' "$body" >"$tmp/body" + if (($#)); then printf '%s\0' "$@"; fi | bash "$check" "$tmp/body" >/dev/null || got=$? + if [[ $got != "$want" ]]; then + echo "FAIL $name: exit $got, want $want" + fail=1 + fi +} + +ok='Feature: O-SNAP-2 +Machine/INV: IMPL M5.Quiesce>Copy / INV-MAINT-ONE-OWNER +Model: docs/spec/MaintenanceOwner.tla, exhausted +Red-first: 7f542dbc TestMaintenanceHeldPass failed on base' +simplest='Simplest: one owner per volume on the existing cut path; no new machine.' + +expect 0 "all four lines, docs only" "$ok" M docs/a.md +expect 0 "FIX kind" "${ok/IMPL M5.Quiesce>Copy/FIX INV-GC-SKEW-001}" +expect 0 "CHANGE kind" "${ok/IMPL M5.Quiesce>Copy/CHANGE M5}" +expect 0 "core change with Simplest" "$ok +$simplest" M core/storage/gc.go +expect 0 "core test only needs no Simplest" "$ok" M core/storage/gc_test.go +expect 0 "CRLF body" "$(printf '%s\n' "$ok" | sed 's/$/\r/')" +expect 0 "CHANGE of two machines" "${ok/IMPL M5.Quiesce>Copy/CHANGE M4, M6}" +expect 0 "list markers and bold keys" "$(printf '%s\n' "$ok" | sed "s/^Feature:/- **Feature:**/; s/^Model:/* Model:/")" +expect 0 "Model NONE with a reason" "${ok/Model: docs\/spec\/MaintenanceOwner.tla, exhausted/Model: NONE: CI wiring only, no state}" + +expect 1 "empty body" "" +expect 1 "missing Red-first" "$(printf '%s\n' "$ok" | grep -v Red-first)" +expect 1 "short NONE" "${ok/Model: docs\/spec\/MaintenanceOwner.tla, exhausted/Model: NONE: n/a}" +expect 1 "no kind" "${ok/IMPL M5.Quiesce>Copy/B,D,E}" +expect 1 "IMPL without transition" "${ok/IMPL M5.Quiesce>Copy/IMPL M5}" +expect 1 "NONE is not a kind" "${ok/IMPL M5.Quiesce>Copy \/ INV-MAINT-ONE-OWNER/NONE: tooling only, no machine}" +expect 1 "core file deleted without Simplest" "$ok" D core/storage/old.go +expect 1 "two kinds" "${ok/IMPL M5.Quiesce>Copy/IMPL M5.Quiesce>Copy FIX INV-MAINT-ONE-OWNER}" +expect 1 "second Machine/INV line with another kind" "$ok +Machine/INV: FIX INV-MAINT-ONE-OWNER" +expect 1 "second Machine/INV line in list and bold form" "$ok +- **Machine/INV:** CHANGE M5" +expect 1 "Simplest declared twice" "$ok +$simplest +$simplest" M core/storage/gc.go +expect 1 "kind token with a trailing junk" "${ok/IMPL M5.Quiesce>Copy/FIX INV-GC-SKEW-001x}" +expect 1 "transition with a stray character" "${ok/IMPL M5.Quiesce>Copy/IMPL M5.Quiesce>Copy;x}" +expect 1 "key inside another word" "${ok/Feature: O-SNAP-2/Not-Feature: O-SNAP-2}" +expect 1 "placeholder left in Feature" "${ok/Feature: O-SNAP-2/Feature: }" +expect 1 "placeholder left in Red-first" "$(printf '%s\n' "$ok" | sed "s/^Red-first:.*/Red-first: /")" +expect 1 "placeholder left in Simplest" "$ok +Simplest: " M core/storage/gc.go +expect 1 "unfilled template" "$(cat "$here/../pull_request_template.md")" +expect 1 "core change without Simplest" "$ok" M core/storage/gc.go +expect 1 "cmd change, short Simplest" "$ok +Simplest: small" A cmd/sw-block/new.go + +# expect_raw WANT_EXIT NAME BYTES: a change list given as printf format. +expect_raw() { + local want=$1 name=$2 got=0 + printf "%s" "$ok" >"$tmp/body" + printf "$3" | bash "$check" "$tmp/body" >/dev/null 2>&1 || got=$? + if [[ $got != "$want" ]]; then + echo "FAIL $name: exit $got, want $want" + fail=1 + fi +} +expect_raw 2 "record cut off before its NUL" "M\0core/storage/gc.go" +expect_raw 2 "status without a path" "M\0" +expect_raw 2 "status cut off before its NUL" "M\0docs/a.md\0M" +expect_raw 2 "unknown status" "R100\0core/a.go\0" +expect_raw 0 "well-formed docs change" "M\0docs/a.md\0" + + +# Kinds for PRs that change no behaviour: each is checked against its paths; +# DOCS also compares the old and new tokens of each changed non-test Go file. +# expect_kind WANT_EXIT NAME KIND OLD_GO NEW_GO [STATUS PATH]... +# OLD_GO/NEW_GO are core/x/s.go before and after ("-" = no blob for that side). +expect_kind() { + local want=$1 name=$2 k=$3 old=$4 new=$5 got=0 + shift 5 + printf '%s' "${ok/IMPL M5.Quiesce>Copy/$k} +$simplest" >"$tmp/body" + rm -rf "$tmp/blobs"; mkdir -p "$tmp/blobs/old/core/x" "$tmp/blobs/new/core/x" + [[ $old == - ]] || printf '%s' "$old" >"$tmp/blobs/old/core/x/s.go" + [[ $new == - ]] || printf '%s' "$new" >"$tmp/blobs/new/core/x/s.go" + if (($#)); then printf '%s\0' "$@"; fi | bash "$check" "$tmp/body" "$tmp/blobs" >/dev/null || got=$? + if [[ $got != "$want" ]]; then + echo "FAIL $name: exit $got, want $want" + fail=1 + fi +} +P=$'package x\n' +expect_kind 0 "DOCS: comment-only Go" DOCS "${P}var A = 1"$'\n' "${P}"$'// A is one.\nvar A = 1 // one\n' M docs/a.md M core/x/s.go A core/x/s_test.go +expect_kind 0 "DOCS: gofmt realignment" DOCS "${P}var A = 1"$'\n' "${P}var A = 1"$'\n' M core/x/s.go +expect_kind 0 "DOCS: block comment" DOCS "${P}var A = 1"$'\n' "${P}"$'/* doc */\nvar A = 1\n' M core/x/s.go +expect_kind 1 "DOCS: reorder" DOCS "${P}func f() { u(); p() }"$'\n' "${P}func f() { p(); u() }"$'\n' M core/x/s.go +expect_kind 1 "DOCS: build constraint comment" DOCS "$P" $'//go:build never\n\npackage x\n' M core/x/s.go +expect_kind 1 "DOCS: rune quote then // in a string" DOCS "${P}var _ = f('\"', \"http://a\")"$'\n' "${P}var _ = f('\"', \"http://b\")"$'\n' M core/x/s.go +expect_kind 1 "DOCS: line inside a raw string" DOCS "${P}var s = \`a"$'\n'"curl http://old | sh"$'\n'"\`"$'\n' "${P}var s = \`a"$'\n'"curl http://new | sh"$'\n'"\`"$'\n' M core/x/s.go +expect_kind 1 "DOCS: spaces inside a string" DOCS "${P}var s = \"a b\""$'\n' "${P}var s = \"a b\""$'\n' M core/x/s.go +expect_kind 1 "DOCS: cgo preamble" DOCS "${P}// #include "$'\nimport "C"\n' "${P}// #include "$'\nimport "C"\n' M core/x/s.go +expect_kind 1 "DOCS: cgo preamble, grouped import" DOCS "${P}// #include "$'\nimport (\n\t"C"\n)\n' "${P}// #include "$'\nimport (\n\t"C"\n)\n' M core/x/s.go +expect_kind 1 "DOCS: Go changed, no blob" DOCS - - M core/x/s.go +expect_kind 1 "DOCS: a model under docs/spec" DOCS - - M docs/spec/X.tla +expect_kind 1 "DOCS: a non-docs, non-Go file" DOCS - - M deploy/x.env +expect_kind 0 "TEST: tests and testdata" TEST - - M core/x/s_test.go A core/x/testdata/in.bin +expect_kind 1 "TEST: production Go" TEST - - M core/x/s.go +expect_kind 0 "CI: workflow" CI - - M .github/workflows/w.yml +expect_kind 1 "CI: scripts/ is shipped" CI - - A scripts/install.sh +expect_kind 1 "DOCS next to another kind" "DOCS FIX INV-X-001" - - M docs/a.md + +[[ $fail == 0 ]] && echo "spec-trace self-test: ok" +exit $fail + +import ( + "C" +) +' "${P}// #include " DOCS - - M core/x/s.go +expect_kind 1 "DOCS: a model under docs/spec" DOCS - - M docs/spec/X.tla +expect_kind 1 "DOCS: a non-docs, non-Go file" DOCS - - M deploy/x.env +expect_kind 0 "TEST: tests and testdata" TEST - - M core/x/s_test.go A core/x/testdata/in.bin +expect_kind 1 "TEST: production Go" TEST - - M core/x/s.go +expect_kind 0 "CI: workflow" CI - - M .github/workflows/w.yml +expect_kind 1 "CI: scripts/ is shipped" CI - - A scripts/install.sh +expect_kind 1 "DOCS next to another kind" "DOCS FIX INV-X-001" - - M docs/a.md + +[[ $fail == 0 ]] && echo "spec-trace self-test: ok" +exit $fail + +import ( + "C" +) +' M core/x/s.go +expect_kind 1 "DOCS: a model under docs/spec" DOCS - - M docs/spec/X.tla +expect_kind 1 "DOCS: a non-docs, non-Go file" DOCS - - M deploy/x.env +expect_kind 0 "TEST: tests and testdata" TEST - - M core/x/s_test.go A core/x/testdata/in.bin +expect_kind 1 "TEST: production Go" TEST - - M core/x/s.go +expect_kind 0 "CI: workflow" CI - - M .github/workflows/w.yml +expect_kind 1 "CI: scripts/ is shipped" CI - - A scripts/install.sh +expect_kind 1 "DOCS next to another kind" "DOCS FIX INV-X-001" - - M docs/a.md + +[[ $fail == 0 ]] && echo "spec-trace self-test: ok" +exit $fail diff --git a/seaweed-block/.github/scripts/spec-trace-check.sh b/seaweed-block/.github/scripts/spec-trace-check.sh new file mode 100644 index 0000000000..0021fa1a37 --- /dev/null +++ b/seaweed-block/.github/scripts/spec-trace-check.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +# Usage: spec-trace-check.sh BODY_FILE [BLOBS] < changes +# +# Checks the spec trace in a PR description. changes are NUL-separated +# STATUS, PATH pairs (post-merge-review-changed.sh). +# +# - Feature:, Machine/INV:, Model: and Red-first: each start a line (after +# optional indentation, a list marker or bold) and carry a value that is not +# a template placeholder; "NONE:" needs a reason of at least 10 characters. +# - Machine/INV: starts with exactly one PR kind: "IMPL .", +# "FIX ", "CHANGE ", or one of the kinds a PR that changes +# no behaviour may use, each checked against what it changes: +# DOCS (docs outside docs/spec/, tests, and non-test Go whose tokens are +# unchanged: BLOBS holds old/ and new/ for each changed non-test +# Go file, compared by sametokens.go), TEST (only tests, testdata and test +# helpers), CI (only .github/). NONE is not a kind. Known limit: a docs file +# that is go:embed-ed into a binary changes behaviour under DOCS (none today). +# - Simplest: (20+ characters) is present when the PR adds, modifies or +# deletes non-test Go under core/ or cmd/. +# +# Prints every problem and exits 1 if there is one; exits 0 if none, 2 on a +# usage error or a malformed change list. +set -euo pipefail + +body_file=${1:?usage: spec-trace-check.sh BODY_FILE [BLOBS] < changes} +blobs=${2-} +here=$(cd "$(dirname "$0")" && pwd) +[[ -f $body_file ]] || { echo "spec-trace: body file $body_file missing" >&2; exit 2; } +body=$(tr -d '\r' <"$body_file") + +# value KEY: the text after KEY on the first line that starts with KEY, +# trimmed. A key inside another word ("Not-Feature:") does not count. +value() { + local line + line=$(printf '%s\n' "$body" | grep -m1 -E "^[[:space:]]*([-*][[:space:]]+)?(\*\*)?$1" || true) + [[ -n $line ]] || return 0 + line=${line#*"$1"} + line=${line#\*\*} + line=${line#"${line%%[![:space:]]*}"} + printf '%s' "${line%"${line##*[![:space:]]}"}" +} + +bad=0 +problem() { echo "spec-trace: $1"; bad=1; } + +# Each trace line is declared once: a second Machine/INV line could carry a +# second kind past the check. +for key in Feature: Machine/INV: Model: Red-first: Simplest:; do + n=$(printf '%s\n' "$body" | grep -cE "^[[:space:]]*([-*][[:space:]]+)?(\*\*)?$key" || true) + ((n <= 1)) || problem "$key is declared $n times; declare it once" +done + +for key in Feature: Machine/INV: Model: Red-first:; do + v=$(value "$key") + if [[ -z $v ]]; then + problem "missing or empty $key" + elif [[ $v == '<'* ]]; then + problem "$key still holds the template placeholder" + elif [[ $v == NONE:* ]]; then + r=${v#NONE:} + r=${r#"${r%%[![:space:]]*}"} + ((${#r} >= 10)) || problem "$key NONE needs a reason of at least 10 characters" + fi +done + +# One kind token, ending at the line end, a space, a comma or a slash. +end='($|[[:space:],/])' +kind_re="^(IMPL [A-Za-z0-9_]+[.][A-Za-z0-9_>.-]+|FIX INV-[A-Z0-9]+(-[A-Z0-9]+)*|CHANGE [A-Za-z0-9_]+|DOCS|TEST|CI)$end" +kind="" +mi=$(value Machine/INV:) +if [[ -n $mi && $mi != '<'* ]]; then + if [[ ! $mi =~ $kind_re ]]; then + problem "Machine/INV: must start with IMPL ., FIX , CHANGE , DOCS, TEST or CI" + else + token=${BASH_REMATCH[1]} + if [[ ${mi#"${BASH_REMATCH[0]}"} =~ (^|[^A-Za-z0-9_])(IMPL|FIX|CHANGE|DOCS|TEST|CI)([^A-Za-z0-9_]|$) ]]; then + problem "Machine/INV: names more than one kind; a PR is exactly one kind" + else + kind=${token%% *} + fi + fi +fi + +is_test() { [[ $1 == *_test.go || $1 == testdata/* || $1 == */testdata/* || $1 == */testutil/* ]]; } +# docs/spec holds the models: changing one is not a docs change. +is_doc() { [[ $1 != docs/spec/* ]] && [[ $1 == *.md || $1 == docs/* ]]; } +core=0 +paths=() +while IFS= read -r -d '' status; do + [[ $status == [ADMT] ]] || { echo "spec-trace: malformed change list: status ${status@Q}" >&2; exit 2; } + IFS= read -r -d '' path || { echo "spec-trace: malformed change list: status $status without a path" >&2; exit 2; } + [[ -n $path ]] || { echo "spec-trace: malformed change list: empty path" >&2; exit 2; } + paths+=("$path") + if [[ $path == core/*.go || $path == cmd/*.go ]] && [[ $path != *_test.go ]]; then + core=1 + fi +done +# A record cut off before its NUL is malformed, not skipped. +[[ -z ${status-} ]] || { echo "spec-trace: malformed change list: unterminated record" >&2; exit 2; } +if ((core)); then + s=$(value Simplest:) + if ((${#s} < 20)) || [[ $s == '<'* ]]; then + problem "Simplest: (20+ characters) is required when non-test Go under core/ or cmd/ changes" + fi +fi + +case $kind in +CI) + for p in ${paths[@]+"${paths[@]}"}; do + [[ $p == .github/* ]] || problem "kind CI: $p is outside .github/ (scripts/ holds shipped install and deploy scripts)" + done + ;; +TEST) + for p in ${paths[@]+"${paths[@]}"}; do + is_test "$p" || problem "kind TEST: $p is not a test, testdata or test helper" + done + ;; +DOCS) + gofiles=() + for p in ${paths[@]+"${paths[@]}"}; do + if is_doc "$p" || is_test "$p"; then continue; fi + if [[ $p == *.go ]]; then gofiles+=("$p"); continue; fi + problem "kind DOCS: $p is neither docs, a test, nor Go" + done + if ((${#gofiles[@]})); then + if [[ -z $blobs || ! -d $blobs ]]; then + problem "kind DOCS: non-test Go changed but no old/new blobs were given to compare" + else + # Built here, not run with "go run": that would take the .go + # arguments as more source files of the program. + bin=$(mktemp -d) + trap 'rm -rf "$bin"' EXIT + if ! go build -o "$bin/sametokens" "$here/sametokens.go"; then + echo "spec-trace: could not build sametokens.go; the DOCS check did not run" >&2 + exit 2 + fi + for p in "${gofiles[@]}"; do + if [[ ! -e $blobs/old/$p && ! -e $blobs/new/$p ]]; then + problem "kind DOCS: $p has no old or new blob, so it was not compared" + continue + fi + rc=0 + "$bin/sametokens" "$blobs/old/$p" "$blobs/new/$p" >/dev/null || rc=$? + case $rc in + 0) ;; + 1) problem "kind DOCS: $p changes more than comments (its Go tokens differ)" ;; + *) + echo "spec-trace: sametokens failed on $p (exit $rc); the DOCS check did not run" >&2 + exit 2 + ;; + esac + done + fi + fi + ;; +esac + +exit $bad diff --git a/seaweed-block/.github/workflows/spec-trace.yml b/seaweed-block/.github/workflows/spec-trace.yml new file mode 100644 index 0000000000..2e09b1c3cb --- /dev/null +++ b/seaweed-block/.github/workflows/spec-trace.yml @@ -0,0 +1,62 @@ +name: spec trace + +# Every PR description carries the spec trace (see the PR template); this +# check fails a PR whose description does not. +# +# pull_request_target: the workflow and the script come from the base branch, +# so a PR cannot change its own check. The PR's code is never checked out or +# run: only its commit is fetched, for the file list. The description is read +# from the event through an environment variable, never interpolated. +on: + pull_request_target: + # edited: the check reads the description and the base. + types: [opened, synchronize, reopened, edited] + +permissions: + contents: read + +concurrency: + group: spec-trace-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + trace: + name: spec trace + # Same-repository PRs use the project's self-hosted runners, as the test + # workflow does; fork PRs stay on a GitHub-hosted runner, whose shared queue + # can wait for hours. No PR code runs here either way. + runs-on: ${{ github.event.pull_request.head.repo.full_name == github.repository && 'tp04-seaweed-block' || 'ubuntu-latest' }} + timeout-minutes: 5 + steps: + - name: Checkout base + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + # github.sha is the tip of the base branch when the event fires; the + # PR's base.sha can predate this workflow's own scripts. + ref: ${{ github.sha }} + fetch-depth: 0 + persist-credentials: false + + - name: Check spec trace + env: + BASE: ${{ github.event.pull_request.base.sha }} + HEAD: ${{ github.event.pull_request.head.sha }} + PR: ${{ github.event.pull_request.number }} + BODY: ${{ github.event.pull_request.body }} + run: | + set -euo pipefail + bash .github/scripts/spec-trace-check-test.sh + git fetch --no-tags origin "+refs/pull/${PR}/head:refs/remotes/pr/head" + printf '%s' "$BODY" >body.txt + bash .github/scripts/post-merge-review-changed.sh "$BASE" "$HEAD" >changed.bin + # Old and new blobs of each changed non-test Go file, for kind DOCS + # (objects only; nothing from the PR is built or run). + mb=$(git merge-base "$BASE" "$HEAD") + git diff --name-only --no-renames -z "$mb" "$HEAD" -- "*.go" ":(exclude)*_test.go" | + while IFS= read -r -d "" p; do + mkdir -p "blobs/old/$(dirname "$p")" "blobs/new/$(dirname "$p")" + git show "$mb:$p" >"blobs/old/$p" 2>/dev/null || rm -f "blobs/old/$p" + git show "$HEAD:$p" >"blobs/new/$p" 2>/dev/null || rm -f "blobs/new/$p" + done + mkdir -p blobs + bash .github/scripts/spec-trace-check.sh body.txt blobs --source v1 --snapshot s1 --t sw-block ops chunk detach --volume v1 --status-addr # final cut and release; resume elsewhere sw-block ops chunk volume-delete --volume v2 --chunk-filer --master --request-id del-v2 sw-block ops chunk gc --chunk-filer --master # preview; --apply to reclaim +sw-block ops chunk verify --volume v1 --chunk-filer # read-only check of the remote image ``` `volume-delete` is refused while the volume is attached or has snapshots. diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance.go b/seaweed-block/cmd/blockvolume/chunk_maintenance.go new file mode 100644 index 0000000000..023a76c2f8 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance.go @@ -0,0 +1,59 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +// Automatic GC stays default-off until restart-safe unknown-CAS settlement and +// the 50/200-volume root-scan measurement both pass. Retention remains enabled. +// The CLI fixes the maximum cut/copy lifetime at five minutes and the HEAD +// hydration reader at thirty seconds. A one-minute mark fits strictly inside +// the one-hour grace. No elapsed TTL alone authorizes capture-intent expiry. +func newChunkMaintenance(cat *chunkstore.Catalog, blobs chunkstore.BlobDeleter, collect bool, master string) (func(context.Context, string) error, func() error, error) { + closeFn := func() error { return nil } + cfg := chunkstore.GCConfig{Grace: defaultChunkGCGrace, IntentTTL: defaultChunkIntentTTL} + if collect { + if master == "" { + return nil, closeFn, errors.New("automatic chunk GC requires blockmaster authority") + } + if defaultChunkGCGrace <= max(defaultChunkCutTimeout, chunkstore.DefaultOpDeadline)+defaultChunkMaintenanceTimeout { + return nil, closeFn, errors.New("automatic GC grace does not cover cut/copy and mark bounds") + } + conn, err := grpc.NewClient(master, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return nil, closeFn, err + } + closeFn = conn.Close + evidence := control.NewEvidenceServiceClient(conn) + cfg.IssuedEpoch = func(ctx context.Context, vol string) (uint64, error) { + reply, err := evidence.QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: vol}) + if err != nil { + return 0, err + } + if reply.GetVolumeId() != vol || !reply.GetAssigned() || reply.GetEpoch() == 0 { + return 0, fmt.Errorf("blockmaster has no issued authority for %s", vol) + } + return reply.Epoch, nil + } + } + return func(ctx context.Context, vol string) error { + retained, err := cat.Retain(ctx, vol, false) + if err != nil { + return fmt.Errorf("retain deleted=%d not_attempted=%d: %w", len(retained.Deleted), len(retained.NotAttempted), err) + } + if !collect { + return nil + } + out, err := cat.ExecuteVolumeGC(ctx, vol, blobs, cfg, true) + log.Printf("blockvolume: maintenance volume=%s mark=%s reclaimed=%d settled=%d unknown=%v", vol, out.MarkOutcome, out.Reclaimed, out.SettledCopies, out.UnknownOutcomes) + return err + }, closeFn, nil +} diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go b/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go new file mode 100644 index 0000000000..e086b1846e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go @@ -0,0 +1,114 @@ +package main + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" + "path" + "testing" + "time" +) + +type maintenanceGCFiler struct { + chunkstore.Filer + gcCalls, marked, freed int + failSecond bool +} + +func (f *maintenanceGCFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if name == "_GC_MARK" { + f.gcCalls++ + return nil, errors.New("witness: GC reached") + } + return f.Filer.LookupEntry(ctx, dir, name) +} +func (f *maintenanceGCFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error { + if string(e.Extended["swb.snap.state"]) == chunkstore.SnapDeleting { + if f.failSecond && f.marked == 1 { + return errors.New("second retention mark refused") + } + f.marked++ + } + return f.Filer.UpdateEntry(ctx, dir, e, expected) +} +func (f *maintenanceGCFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { + err := f.Filer.DeleteEntry(ctx, dir, name, expected) + if err == nil && path.Base(dir) == "snapnames" { + f.freed++ + } + return err +} + +type maintenanceBlobs struct{} + +func (maintenanceBlobs) DeleteBlob(context.Context, string) error { return nil } +func (maintenanceBlobs) Put(context.Context, []byte) (string, error) { return "unused", nil } +func (maintenanceBlobs) Get(context.Context, string) ([]byte, error) { + return nil, errors.New("unexpected blob read") +} +func TestMaintenanceRetentionFailureNeverStartsGC(t *testing.T) { + for _, partial := range []bool{false, true} { + t.Run(map[bool]string{false: "missing", true: "partial"}[partial], func(t *testing.T) { + ctx := context.Background() + f := &maintenanceGCFiler{Filer: chunkstore.NewMemFiler(), failSecond: partial} + cat, err := chunkstore.NewCatalog(f, defaultChunkPath) + if err != nil { + t.Fatal(err) + } + vol := "missing-volume" + if partial { + vol = "v1" + if _, err = cat.EnsureVolume(ctx, vol, chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { + t.Fatal(err) + } + if err = cat.SetRetentionPolicy(ctx, vol, chunkstore.RetentionPolicy{}); err != nil { + t.Fatal(err) + } + now := time.Now().Add(-48 * time.Hour) + cat.SetClock(func() time.Time { return now }) + for _, name := range []string{"a", "b"} { + if _, err = cat.CreateSnapshot(ctx, vol, chunkstore.SnapshotRequest{Name: name, RequestID: "req"}, storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "h1", RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{}}); err != nil { + t.Fatal(err) + } + now = now.Add(time.Second) + } + now = time.Now() + } + pass, closeFn, err := newChunkMaintenance(cat, maintenanceBlobs{}, true, "unused-master:1234") + if err != nil { + t.Fatal(err) + } + defer closeFn() + if err = pass(ctx, vol); err == nil { + t.Fatal("retention failure accepted") + } + if f.gcCalls != 0 { + t.Fatalf("retention failure entered GC %d times", f.gcCalls) + } + if partial && (f.marked != 1 || f.freed != 1) { + t.Fatalf("partial retention effects not retained: marked=%d freed=%d err=%v", f.marked, f.freed, err) + } + }) + } +} + +func TestMaintenanceDefaultRetainNeedsNoEpochClient(t *testing.T) { + f := chunkstore.NewMemFiler() + cat, err := chunkstore.NewCatalog(f, defaultChunkPath) + if err != nil { + t.Fatal(err) + } + if _, err = cat.EnsureVolume(context.Background(), "v", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { + t.Fatal(err) + } + pass, closeFn, err := newChunkMaintenance(cat, nil, false, "") + if err != nil { + t.Fatal(err) + } + defer closeFn() + if err = pass(context.Background(), "v"); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index ad55735dc9..0d690740f8 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -21,12 +21,14 @@ import ( const ( defaultChunkPath = "/swblock/chunks" - // The remote holds snapshots, not live data: cuts are published at - // snapshots, at detach/stop and on explicit request. The timer is off - // by default (an operator may set one, e.g. 15m, as a host-loss safety - // net); the dirty threshold only bounds how large one cut can grow. - defaultChunkCaptureInterval = 0 - defaultChunkDirtyThreshold = 512 // chunks, 2 GiB at 4 MiB chunks + // Periodic HEAD publication bounds the host-loss recovery point. Automatic + // named snapshots remain explicit catalog operations. + defaultChunkCaptureInterval = 0 + defaultChunkMaintenanceInterval = time.Hour + defaultChunkCutTimeout = 5 * time.Minute + defaultChunkMaintenanceTimeout = time.Minute + defaultChunkGCGrace = time.Hour + defaultChunkIntentTTL = time.Hour ) type chunkFlags struct { @@ -37,7 +39,8 @@ type chunkFlags struct { collection string replication string captureInterval time.Duration - dirtyThreshold int + maintenanceInterval time.Duration + automaticGC bool uploadConcurrency int hydrationWorkers int hydrationQueueDepth int @@ -56,7 +59,7 @@ func validateChunkFlags(f flags) error { } if f.durableImpl != "walstore-chunk" { if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath || - c.captureInterval != defaultChunkCaptureInterval || c.dirtyThreshold != defaultChunkDirtyThreshold || + c.captureInterval != defaultChunkCaptureInterval || c.maintenanceInterval != defaultChunkMaintenanceInterval || c.automaticGC || c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint || c.detachPrecopy || c.hostLimit.Directory != "" { return errors.New("--chunk-* flags require --durable-impl=walstore-chunk") } @@ -77,6 +80,12 @@ func validateChunkFlags(f flags) error { if !path.IsAbs(c.path) || path.Clean(c.path) != c.path || c.path == "/" { return fmt.Errorf("--chunk-path=%q must be a clean absolute filer directory other than /", c.path) } + if c.maintenanceInterval < 0 { + return errors.New("--chunk-maintenance-interval must not be negative") + } + if c.captureInterval > 0 && c.captureInterval < 5*time.Minute { + return errors.New("--chunk-capture-interval must be 0 or at least 5m") + } if c.captureInterval < 0 { return fmt.Errorf("--chunk-capture-interval=%s must not be negative", c.captureInterval) } @@ -89,9 +98,6 @@ func validateChunkFlags(f flags) error { if c.hydrationQueueDepth < 1 || c.hydrationQueueDepth > 65536 { return errors.New("--chunk-hydration-queue-depth must be between 1 and 65536") } - if c.dirtyThreshold < 0 { - return fmt.Errorf("--chunk-dirty-threshold=%d must not be negative", c.dirtyThreshold) - } return nil } @@ -106,14 +112,15 @@ const chunkRF1Reason = "chunk snapshots take the cut LSN from the local WAL, whi // provider's per-volume remotes, the catalog under the same base (VOLUME // entries, snapshots) and the client's closer. type chunkWiring struct { - remoteFor func(volumeID string) (storage.ChunkRemote, error) - catalog *chunkstore.Catalog - close func() error + remoteFor func(volumeID string) (storage.ChunkRemote, error) + catalog *chunkstore.Catalog + maintenance func(context.Context, string) error + close func() error } // newChunkWiring dials the filer and refuses unless it is the only filer of // its group (chunkstore.CheckSingleFiler). -func newChunkWiring(c chunkFlags) (chunkWiring, error) { +func newChunkWiring(c chunkFlags, master ...string) (chunkWiring, error) { client, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{ FilerGRPC: c.filer, Collection: c.collection, @@ -133,7 +140,17 @@ func newChunkWiring(c chunkFlags) (chunkWiring, error) { _ = client.Close() return chunkWiring{}, err } + var masterAddr string + if len(master) > 0 { + masterAddr = master[0] + } + maintenance, closeMaintenance, err := newChunkMaintenance(cat, client, c.automaticGC, masterAddr) + if err != nil { + _ = client.Close() + return chunkWiring{}, err + } return chunkWiring{ + maintenance: maintenance, remoteFor: func(volumeID string) (storage.ChunkRemote, error) { root, err := chunkVolumeRoot(c.path, volumeID) if err != nil { @@ -142,7 +159,7 @@ func newChunkWiring(c chunkFlags) (chunkWiring, error) { return chunkstore.NewSWFSChunkRemote(client, root) }, catalog: cat, - close: client.Close, + close: func() error { return errors.Join(closeMaintenance(), client.Close()) }, }, nil } diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go index 5bf1bfcdfb..df897f59b0 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -15,11 +15,11 @@ func TestWALStoreChunkFlags(t *testing.T) { return append(phase150RequiredBlockvolumeArgs(), extra...) } f, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", - "--chunk-filer=127.0.0.1:18888", "--chunk-capture-interval=30s")) + "--chunk-filer=127.0.0.1:18888", "--chunk-capture-interval=5m")) if err != nil { t.Fatalf("walstore-chunk with a filer: %v", err) } - if f.chunk.filer != "127.0.0.1:18888" || f.chunk.path != defaultChunkPath || f.chunk.captureInterval != 30*time.Second || f.chunk.controlEndpoint { + if f.chunk.filer != "127.0.0.1:18888" || f.chunk.path != defaultChunkPath || f.chunk.captureInterval != 5*time.Minute || f.chunk.controlEndpoint { t.Fatalf("parsed chunk flags = %+v", f.chunk) } f, err = parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", @@ -31,33 +31,37 @@ func TestWALStoreChunkFlags(t *testing.T) { if err != nil { t.Fatal(err) } - if d.chunk.captureInterval != 0 || d.chunk.dirtyThreshold != 512 { - t.Fatalf("scheduler defaults interval %s threshold %d, want timer off and 512", d.chunk.captureInterval, d.chunk.dirtyThreshold) + if d.chunk.captureInterval != 0 || d.chunk.maintenanceInterval != time.Hour || d.chunk.automaticGC { + t.Fatalf("scheduler defaults interval %s, want capture off (0), maintenance 1h and GC off", d.chunk.captureInterval) + } + on, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=15m")) + if err != nil || on.chunk.captureInterval != 15*time.Minute { + t.Fatalf("opting in to a 15m periodic cut: %+v %v", on.chunk, err) } off, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", - "--chunk-capture-interval=0", "--chunk-dirty-threshold=0")) - if err != nil || off.chunk.captureInterval != 0 || off.chunk.dirtyThreshold != 0 { - t.Fatalf("disabling both triggers: %+v %v", off.chunk, err) + "--chunk-capture-interval=0")) + if err != nil || off.chunk.captureInterval != 0 { + t.Fatalf("disabling the timer: %+v %v", off.chunk, err) } if _, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore")); err != nil { t.Fatalf("walstore with the chunk defaults untouched: %v", err) } refused := map[string][]string{ - "no filer": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk"), - "no durable root": base("--durable-impl=walstore-chunk", "--chunk-filer=127.0.0.1:18888"), - "relative path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=swblock"), - "root path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=/"), - "negative interval": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=-1s"), - "chunk flag on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-filer=x:1"), - "chunk path on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-path=/other"), + "no filer": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk"), + "no durable root": base("--durable-impl=walstore-chunk", "--chunk-filer=127.0.0.1:18888"), + "relative path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=swblock"), + "root path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=/"), + "below OSS capture floor": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=4m59s"), + "negative maintenance": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-maintenance-interval=-1s"), + "negative interval": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=-1s"), + "chunk flag on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-filer=x:1"), + "chunk path on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-path=/other"), "control endpoint on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--status-addr=127.0.0.1:0", "--chunk-control-endpoint"), "control endpoint without a status listener": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-control-endpoint"), "zero upload concurrency": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-upload-concurrency=0"), "too many uploads": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-upload-concurrency=65"), - "negative threshold": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=-1"), - "threshold on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-dirty-threshold=8"), "interval on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-capture-interval=5s"), } for name, args := range refused { @@ -121,3 +125,13 @@ func TestChunkHolderIsServerAndReplica(t *testing.T) { t.Fatalf("chunk holder %q, want m02/r1", got) } } + +// --chunk-dirty-threshold is gone: a cut stages by the +// copy-on-write budget (M5 Stage), so the flag never had an effect. A unit +// that still passes it fails at start. +func TestChunkDirtyThresholdFlagIsGone(t *testing.T) { + args := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=512") + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "flag provided but not defined") { + t.Fatalf("--chunk-dirty-threshold: %v; want flag provided but not defined", err) + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index ca2a80a683..6f17805b6b 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -203,11 +203,12 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)") fs.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)") fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: converge rolling cuts before final detach; refuse cutover if measured tail does not fit") - fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: automatic cut once this long has passed since the last successful cut; 0 (default) disables the timer, e.g. 15m as a host-loss safety net") + fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least 5m)") + fs.DurationVar(&f.chunk.maintenanceInterval, "chunk-maintenance-interval", defaultChunkMaintenanceInterval, "walstore-chunk: retention and optional GC pass interval; 0 disables") + fs.BoolVar(&f.chunk.automaticGC, "chunk-maintenance-gc", false, "walstore-chunk: enable scoped automatic GC; off pending restart-safe unknown-CAS settlement and density qualification") fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)") fs.IntVar(&f.chunk.hydrationWorkers, "chunk-hydration-workers", 2, "walstore-chunk: concurrent lazy chunk fetches per volume (1..64)") fs.IntVar(&f.chunk.hydrationQueueDepth, "chunk-hydration-queue-depth", 64, "walstore-chunk: distinct queued/in-flight hydration chunks per volume (1..65536)") - fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", defaultChunkDirtyThreshold, "walstore-chunk: number of candidate chunks above which a cut pre-copies (stages) chunks before its barrier, in rounds of this size; copy-before-write copies the rest outside the barrier; never triggers a cut; 0 = no pre-copy") fs.BoolVar(&f.chunk.controlEndpoint, "chunk-control-endpoint", false, "walstore-chunk: expose the /chunk/* control routes (cut, snapshot, snapshots, snapshot/delete, detach) on the status HTTP listener; off by default; loopback-only like the listener") fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)") fs.UintVar(&f.durableBlockSize, "durable-blocksize", 4096, "block size in bytes on first create") @@ -249,8 +250,8 @@ func parseFlags(args []string) (flags, error) { return flags{}, err } memoryFlagSet := false - fs.Visit(func(f *flag.Flag) { - if f.Name == "memory-limit-mib" { + fs.Visit(func(fl *flag.Flag) { + if fl.Name == "memory-limit-mib" { memoryFlagSet = true } }) @@ -658,10 +659,13 @@ func run(f flags) int { var chunkErr error var chunk chunkWiring if cfg.Impl == durable.ImplWALStoreChunk { - chunk, chunkErr = newChunkWiring(f.chunk) + chunk, chunkErr = newChunkWiring(f.chunk, f.masterAddr) cfg.ChunkCaptureInterval = f.chunk.captureInterval + cfg.ChunkCutTimeout = defaultChunkCutTimeout + cfg.ChunkMaintenanceInterval = f.chunk.maintenanceInterval + cfg.ChunkMaintenanceTimeout = defaultChunkMaintenanceTimeout + cfg.ChunkMaintenance = chunk.maintenance cfg.ChunkDetachPrecopy = f.chunk.detachPrecopy - cfg.ChunkDirtyThreshold = f.chunk.dirtyThreshold cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency cfg.ChunkHydrationWorkers = f.chunk.hydrationWorkers cfg.ChunkHydrationQueueDepth = f.chunk.hydrationQueueDepth diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 80cc5f67ad..bc15628796 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -28,7 +28,9 @@ import ( ) const ( - chunkExitFailed = 1 + chunkExitFailed = 1 + // chunkExitFindings: the command completed and found problems (verify). + chunkExitFindings = 3 defaultChunkPathCLI = "/swblock/chunks" chunkResponseLimit = 64 << 20 ) @@ -42,9 +44,36 @@ var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) { return c, c.Close, nil } +// checkSingleFiler is the start check of a command that writes chunk +// metadata: block metadata goes through exactly one filer, the +// same rule blockvolume enforces at start. Tests replace it. +var checkSingleFiler = func(ctx context.Context, f chunkstore.Filer) error { + if s, ok := f.(*chunkstore.SWFS); ok { + return s.CheckSingleFiler(ctx) + } + return nil +} + +// refuseUnlessSingleFiler runs the start check within the command's own +// timeout (a stalled filer or master cannot hold the command longer); exit +// >= 0 means refused. +func refuseUnlessSingleFiler(name string, f chunkstore.Filer, timeout time.Duration, stdout, stderr io.Writer) int { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + err := checkSingleFiler(ctx, f) + switch { + case err == nil: + return -1 + case errors.Is(err, chunkstore.ErrNotSingleFiler): + return chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + default: + return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "single-filer start check: "+err.Error(), true) + } +} + func runOpsChunk(args []string, stdout, stderr io.Writer) int { if len(args) == 0 { - return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|volume-delete", false) + return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|verify|volume-delete|restore", false) } switch args[0] { case "gc": @@ -67,8 +96,12 @@ func runOpsChunk(args []string, stdout, stderr io.Writer) int { return chunkUsage(args[1:], stdout, stderr) case "retain": return chunkRetain(args[1:], stdout, stderr) + case "verify": + return chunkVerify(args[1:], stdout, stderr) case "volume-delete": return chunkVolumeDelete(args[1:], stdout, stderr) + case "restore": + return chunkRestore(args[1:], stdout, stderr) default: return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, fmt.Sprintf("unknown subcommand %q", args[0]), false) } @@ -259,7 +292,9 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int { // chunkCatalog opens the catalog under --chunk-path on --chunk-filer. // It returns exit -1 on success, else the exit code after reporting. -func chunkCatalog(name, filer, base string, stdout, stderr io.Writer) (*chunkstore.Catalog, func() error, int) { +// chunkCatalog dials the filer and opens the catalog; a command that writes +// (writes) first passes the single-filer start check. +func chunkCatalog(name, filer, base string, writes bool, timeout time.Duration, stdout, stderr io.Writer) (*chunkstore.Catalog, func() error, int) { if filer == "" { return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false) } @@ -267,6 +302,12 @@ func chunkCatalog(name, filer, base string, stdout, stderr io.Writer) (*chunksto if err != nil { return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) } + if writes { + if exit := refuseUnlessSingleFiler(name, f, timeout, stdout, stderr); exit >= 0 { + _ = closeFn() + return nil, nil, exit + } + } cat, err := chunkstore.NewCatalog(f, base) if err != nil { _ = closeFn() @@ -364,7 +405,7 @@ func chunkSnapshots(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("snapshots", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("snapshots", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("snapshots", filer, base, false, timeout, stdout, stderr) if exit >= 0 { return exit } @@ -392,7 +433,7 @@ func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int { if volumeID == "" || name == "" { return chunkFail("snapshot-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --name are required", false) } - cat, closeFn, exit := chunkCatalog("snapshot-delete", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("snapshot-delete", filer, base, true, timeout, stdout, stderr) if exit >= 0 { return exit } @@ -428,7 +469,7 @@ func chunkFork(args []string, stdout, stderr io.Writer) int { requestID = newRequestID() fmt.Fprintf(stderr, "sw-block ops chunk fork: request id %s (reuse it to retry)\n", requestID) } - cat, closeFn, exit := chunkCatalog("fork", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("fork", filer, base, true, timeout, stdout, stderr) if exit >= 0 { return exit } @@ -456,7 +497,7 @@ func chunkShow(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("show", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("show", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("show", filer, base, false, timeout, stdout, stderr) if exit >= 0 { return exit } diff --git a/seaweed-block/cmd/sw-block/chunk_gc.go b/seaweed-block/cmd/sw-block/chunk_gc.go index a5a8cdfc61..fb46e3bc85 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc.go +++ b/seaweed-block/cmd/sw-block/chunk_gc.go @@ -27,7 +27,7 @@ func chunkGC(args []string, stdout, stderr io.Writer) int { fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "chunk catalog namespace") fs.StringVar(&master, "master", "", "authoritative blockmaster gRPC address") fs.BoolVar(&apply, "apply", false, "settle intents, save completed marks and reclaim eligible chunks; default is read-only") - fs.DurationVar(&grace, "grace", time.Hour, "two-mark interval and minimum upload age (must exceed the operation deadline plus mark time)") + fs.DurationVar(&grace, "grace", time.Hour, "two-mark interval and minimum upload age (at least the operation deadline + clock skew + CAS apply bound, and more than the operation deadline plus mark time)") fs.DurationVar(&ttl, "intent-ttl", time.Hour, "minimum capture-intent age before authoritative epoch expiry") fs.DurationVar(&timeout, "timeout", time.Minute, "bound for this pass, including master/filer/blob calls") if e := fs.Parse(args); e != nil { @@ -41,6 +41,11 @@ func chunkGC(args []string, stdout, stderr io.Writer) int { return chunkResult("gc", nil, e, stdout, stderr) } defer closeFn() + if apply { + if exit := refuseUnlessSingleFiler("gc", f, timeout, stdout, stderr); exit >= 0 { + return exit + } + } blobs, ok := f.(chunkstore.BlobDeleter) if !ok { return chunkFail("gc", stdout, stderr, chunkExitFailed, codeInternalCLI, "chunk store cannot delete immutable blobs", false) diff --git a/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go b/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go index 92d2e90d13..2215732638 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go +++ b/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go @@ -208,7 +208,7 @@ func TestIntegration_OpsChunkGC_RealMasterAndStore(t *testing.T) { if !first.MarkSaved || first.Reclaimed != 0 { t.Fatalf("first mark: %+v", first) } - now = now.Add(time.Hour + time.Second) + now = now.Add(time.Hour + chunkstore.DefaultGCClockSkew + time.Second) preview = call(false) if preview.Reclaimed != 0 || len(preview.WouldDelete) != 1 || preview.WouldDelete[0].Key != "orphan" { t.Fatalf("mature preview: %+v", preview) @@ -278,7 +278,7 @@ func TestIntegration_OpsChunkGC_RealMasterAndStore(t *testing.T) { if expired.ExpiredIntents != 1 || expired.Reclaimed != 0 { t.Fatalf("fenced intent admission: %+v", expired) } - now = now.Add(time.Hour + time.Second) + now = now.Add(time.Hour + chunkstore.DefaultGCClockSkew + time.Second) reclaimed := call(true) if reclaimed.Reclaimed != 1 || len(reclaimed.WouldDelete) != 1 || reclaimed.WouldDelete[0].Key != "held" { t.Fatalf("expired capture: %+v", reclaimed) diff --git a/seaweed-block/cmd/sw-block/chunk_gc_test.go b/seaweed-block/cmd/sw-block/chunk_gc_test.go index aaf158c4cf..c8d49708c0 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc_test.go +++ b/seaweed-block/cmd/sw-block/chunk_gc_test.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "context" "encoding/json" "errors" @@ -264,3 +265,20 @@ func TestOpsChunkGC_FailedMarkLookupPreservesUnknownUnbound(t *testing.T) { }) } } + +func TestOpsChunkGC_PermanentDeleteReportsFailureWithSavedCoverage(t *testing.T) { + var stdout, stderr bytes.Buffer + out := chunkstore.GCExecution{MarkOutcome: "complete", MarkSaved: true, GCResult: chunkstore.GCResult{ + Reclaimed: 1, FailedDeletes: []chunkstore.GCDeleteFailure{{GCObject: chunkstore.GCObject{Volume: "v1", Key: "bad", FID: "3,bad"}, Error: "http 400"}}, + }} + rc := chunkGCResult(out, chunkstore.ErrBlobDeleteRejected, &stdout, &stderr) + var body struct { + GC chunkstore.GCExecution `json:"gc"` + } + if err := json.Unmarshal(stdout.Bytes(), &body); err != nil { + t.Fatal(err) + } + if rc != 1 || !body.GC.MarkSaved || body.GC.MarkOutcome != "complete" || body.GC.Reclaimed != 1 || len(body.GC.FailedDeletes) != 1 || body.GC.FailedDeletes[0].FID != "3,bad" { + t.Fatalf("partial failure lost saved coverage or object identity: rc=%d body=%s", rc, stdout.String()) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go index e9e52d078c..99dd726bf2 100644 --- a/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go +++ b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go @@ -33,7 +33,7 @@ func (f *manifestFixtureFiler) Get(_ context.Context, id string) ([]byte, error) defer f.mu.Unlock() b, ok := f.blobs[id] if !ok { - return nil, chunkstore.ErrNotFound + return nil, fmt.Errorf("%w: %w", chunkstore.ErrBlobNotFound, chunkstore.ErrNotFound) } return append([]byte(nil), b...), nil } diff --git a/seaweed-block/cmd/sw-block/chunk_restore.go b/seaweed-block/cmd/sw-block/chunk_restore.go new file mode 100644 index 0000000000..4a94e2f456 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_restore.go @@ -0,0 +1,30 @@ +package main + +import ( + "io" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// chunkRestore starts (or joins) the independent-restore driver of a volume +// restored from a snapshot and prints its status; with --status it only +// prints the status. The driver runs in blockvolume and outlives this call. +func chunkRestore(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("restore", stderr) + var ( + volumeID, statusAddr string + statusOnly bool + ) + fs.StringVar(&volumeID, "volume", "", "restored volume id") + fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") + fs.BoolVar(&statusOnly, "status", false, "print the restore status without starting a run") + if err := fs.Parse(args); err != nil { + return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + if volumeID == "" || statusAddr == "" { + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false) + } + body := map[string]any{"volumeID": volumeID, "statusOnly": statusOnly} + return chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr) +} diff --git a/seaweed-block/cmd/sw-block/chunk_restore_test.go b/seaweed-block/cmd/sw-block/chunk_restore_test.go new file mode 100644 index 0000000000..2c9c32f1c2 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_restore_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestOpsChunk_RestoreStartsAndReportsStatus(t *testing.T) { + var got []map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/chunk/restore" || r.Method != http.MethodPost { + http.Error(w, "unexpected "+r.Method+" "+r.URL.Path, http.StatusNotFound) + return + } + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + got = append(got, body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"volumeID":"v2","phase":"owning","running":true,"foreign":3}`)) + })) + defer srv.Close() + for _, args := range [][]string{{"restore", "--volume", "v2", "--status-addr", srv.URL}, {"restore", "--volume", "v2", "--status-addr", srv.URL, "--status"}} { + var out, errb bytes.Buffer + if code := runOpsChunk(args, &out, &errb); code != 0 || !strings.Contains(out.String(), `"phase":"owning"`) { + t.Fatalf("%v: exit %d out %q err %q", args, code, out.String(), errb.String()) + } + } + if len(got) != 2 || got[0]["volumeID"] != "v2" || got[0]["statusOnly"] != false || got[1]["statusOnly"] != true { + t.Fatalf("requests %v: want a start, then a status-only call", got) + } + var out, errb bytes.Buffer + if code := runOpsChunk([]string{"restore", "--status-addr", srv.URL}, &out, &errb); code == 0 { + t.Fatal("restore without --volume must be refused") + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_retain.go b/seaweed-block/cmd/sw-block/chunk_retain.go index 7b9702672c..dee26ad7a7 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain.go +++ b/seaweed-block/cmd/sw-block/chunk_retain.go @@ -31,7 +31,7 @@ func chunkUsage(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("usage", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("usage", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("usage", filer, base, false, timeout, stdout, stderr) if exit >= 0 { return exit } @@ -74,7 +74,7 @@ func chunkRetain(args []string, stdout, stderr io.Writer) int { if setPolicy && dryRun { return chunkFail("retain", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--set-policy and --dry-run do not combine", false) } - cat, closeFn, exit := chunkCatalog("retain", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("retain", filer, base, !dryRun, timeout, stdout, stderr) if exit >= 0 { return exit } diff --git a/seaweed-block/cmd/sw-block/chunk_start_check_test.go b/seaweed-block/cmd/sw-block/chunk_start_check_test.go new file mode 100644 index 0000000000..05ff3c2399 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_start_check_test.go @@ -0,0 +1,93 @@ +package main + +import ( + "bytes" + "context" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" +) + +// Every ops chunk command that writes chunk metadata runs the +// single-filer start check before it reads or writes anything, and refuses +// when the filer is not the only one of its group; read-only commands (and +// read-only modes) do not run it. +func TestOpsChunk_WritingCommandsRunTheSingleFilerCheck(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checks := 0 + checkSingleFiler = func(context.Context, chunkstore.Filer) error { + checks++ + return chunkstore.ErrNotSingleFiler + } + filer := []string{"--chunk-filer", "filer:18888"} + writing := map[string][]string{ + "snapshot-delete": append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--name", "s1"}, filer...), + "fork": append([]string{"ops", "chunk", "fork", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--request-id", "r"}, filer...), + "retain": append([]string{"ops", "chunk", "retain", "--volume", "v1"}, filer...), + "volume-delete": append([]string{"ops", "chunk", "volume-delete", "--volume", "v1", "--master", "m:1", "--request-id", "r"}, filer...), + "gc --apply": append([]string{"ops", "chunk", "gc", "--master", "m:1", "--apply"}, filer...), + } + for name, args := range writing { + before := checks + var out, errb bytes.Buffer + code := run(args, &out, &errb) + if checks != before+1 { + t.Errorf("%s: start check ran %d times; want once", name, checks-before) + } + if code == 0 || !strings.Contains(out.String()+errb.String(), "exactly one filer") { + t.Errorf("%s: exit %d, out %q err %q; want the single-filer refusal", name, code, out.String(), errb.String()) + } + } + readOnly := map[string][]string{ + "snapshots": append([]string{"ops", "chunk", "snapshots", "--volume", "v1"}, filer...), + "show": append([]string{"ops", "chunk", "show", "--volume", "v1"}, filer...), + "usage": append([]string{"ops", "chunk", "usage", "--volume", "v1"}, filer...), + "retain --dry-run": append([]string{"ops", "chunk", "retain", "--volume", "v1", "--dry-run"}, filer...), + "gc (read-only)": append([]string{"ops", "chunk", "gc", "--master", "m:1"}, filer...), + } + for name, args := range readOnly { + before := checks + var out, errb bytes.Buffer + run(args, &out, &errb) + if checks != before { + t.Errorf("%s: a read-only command ran the start check", name) + } + } +} + +// The start check runs within the command's own --timeout: a check stalled +// on its filer or master (here one that blocks until its context ends) ends +// the command at the timeout, as a retryable refusal. +func TestOpsChunk_StartCheckIsBoundedByTheTimeout(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checkSingleFiler = func(ctx context.Context, _ chunkstore.Filer) error { + <-ctx.Done() + return ctx.Err() + } + filer := []string{"--chunk-filer", "filer:18888", "--timeout", "200ms"} + for name, args := range map[string][]string{ + "snapshot-delete": append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--name", "s1"}, filer...), + "gc --apply": append([]string{"ops", "chunk", "gc", "--master", "m:1", "--apply"}, filer...), + } { + done := make(chan struct{}) + var out, errb bytes.Buffer + var code int + go func() { code = run(args, &out, &errb); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatalf("%s: a stalled start check held the command past its 200ms --timeout", name) + } + if code == 0 || !strings.Contains(out.String(), "remote_unavailable") || !strings.Contains(out.String(), `"retryable":true`) { + t.Errorf("%s: exit %d, out %q; want a retryable remote_unavailable refusal", name, code, out.String()) + } + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_verify.go b/seaweed-block/cmd/sw-block/chunk_verify.go new file mode 100644 index 0000000000..1d70e92f0d --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_verify.go @@ -0,0 +1,158 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// chunkVerify: sw-block ops chunk verify --volume v --chunk-filer host:port +// checks the volume's remote image against its HEAD (and, on request, its +// snapshots), read-only (chunkstore.Catalog.Verify). Exit 0: clean; 3: the +// pass completed with findings; 1: it could not complete (the partial result +// is printed with the error); 2: usage. +func chunkVerify(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("verify", stderr) + var ( + volumeID, filer, base, snapshot, depth string + allSnapshots bool + concurrency int + bytesPerSec int64 + timeout time.Duration + ) + fs.StringVar(&volumeID, "volume", "", "volume id") + fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") + fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") + fs.StringVar(&snapshot, "snapshot", "", "also check this snapshot") + fs.BoolVar(&allSnapshots, "all-snapshots", false, "also check every snapshot") + fs.StringVar(&depth, "depth", string(chunkstore.VerifyBindings), "meta, bindings or data (data reads every chunk once)") + fs.IntVar(&concurrency, "concurrency", chunkstore.DefaultVerifyConcurrency, "chunk reads in flight (depth data)") + fs.Int64Var(&bytesPerSec, "bytes-per-sec", chunkstore.DefaultVerifyBytesPerSecond, "pace chunk reads (depth data); 0 leaves them unpaced") + fs.DurationVar(&timeout, "timeout", 10*time.Minute, "bound for the whole pass; required with --depth data") + if err := fs.Parse(args); err != nil { + return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + timeoutSet := false + fs.Visit(func(f *flag.Flag) { + if f.Name == "timeout" { + timeoutSet = true + } + }) + usage := func(msg string) int { + return chunkFail("verify", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, msg, false) + } + d := chunkstore.VerifyDepth(depth) + switch { + case fs.NArg() != 0: + return usage("unexpected arguments") + case volumeID == "": + return usage("--volume is required") + case d != chunkstore.VerifyMeta && d != chunkstore.VerifyBindings && d != chunkstore.VerifyData: + return usage(fmt.Sprintf("--depth %q: meta, bindings or data", depth)) + case snapshot != "" && allSnapshots: + return usage("--snapshot and --all-snapshots do not combine") + case d == chunkstore.VerifyData && !timeoutSet: + return usage("--depth data reads every chunk: give an explicit --timeout for the pass") + case timeout <= 0 || concurrency <= 0 || bytesPerSec < 0: + return usage("--timeout and --concurrency must be positive and --bytes-per-sec not negative") + } + // One bound for the whole pass, the single-filer start check included: + // the deadline starts before the check. Verify writes nothing, but it + // runs the check (writes=true): against a split filer view it would + // report false findings. + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cat, closeFn, exit := chunkCatalog("verify", filer, base, true, timeout, stdout, stderr) + if exit >= 0 { + return exit + } + defer closeFn() + if bytesPerSec == 0 { + bytesPerSec = -1 // the library's "unpaced" + } + res, err := cat.Verify(ctx, volumeID, chunkstore.VerifyOptions{Depth: d, Snapshot: snapshot, AllSnapshots: allSnapshots, + Concurrency: concurrency, BytesPerSecond: bytesPerSec}) + if err != nil { + return verifyIncomplete(res, err, stdout, stderr) + } + out, err := verifyJSON(res) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk verify: %v\n", err) + return chunkExitFailed + } + if err := writeAll(stdout, out); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk verify: write the result: %v\n", err) + return chunkExitFailed + } + if len(res.Findings) != 0 { + fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %d findings %v\n", volumeID, len(res.Findings), res.FindingsByClass) + if res.ChunksNotRead != 0 { + // READ_ERROR is not damage: those objects were not verified. + fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %d could not be read and were not verified; re-run\n", volumeID, res.ChunksNotRead) + } + return chunkExitFindings + } + return ops.VolumeStatusExitOK +} + +// verifyJSON is the result as one JSON object whose findings array holds +// one finding per line. +func verifyJSON(res chunkstore.VerifyResult) ([]byte, error) { + findings := res.Findings + res.Findings = nil + head, err := json.Marshal(res) + if err != nil { + return nil, err + } + const tail = `"findings":null}` + if !bytes.HasSuffix(head, []byte(tail)) { + return nil, errors.New("verify result: unexpected field order") + } + var buf bytes.Buffer + buf.Write(head[:len(head)-len(tail)]) + buf.WriteString(`"findings":[`) + for i, f := range findings { + line, err := json.Marshal(f) + if err != nil { + return nil, err + } + if i > 0 { + buf.WriteByte(',') + } + buf.WriteByte('\n') + buf.Write(line) + } + if len(findings) > 0 { + buf.WriteByte('\n') + } + buf.WriteString("]}\n") + return buf.Bytes(), nil +} + +// verifyIncomplete prints the error body with the partial result under +// "verify", and fails. +func verifyIncomplete(res chunkstore.VerifyResult, err error, stdout, stderr io.Writer) int { + body := struct { + chunkErrBody + Verify chunkstore.VerifyResult `json:"verify"` + }{Verify: res} + body.Code, body.Message = codeInternalCLI, err.Error() + var ce *chunkstore.CatalogError + switch { + case errors.As(err, &ce): + body.Code, body.Message, body.Retryable = ce.Code, ce.Detail(), ce.Retryable + case errors.Is(err, context.DeadlineExceeded): + body.Code, body.Retryable = chunkstore.CodeDeadlineExceeded, true + } + fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %s (incomplete)\n", body.Code, body.Message) + chunkResult("verify", body, nil, stdout, stderr) + return chunkExitFailed +} diff --git a/seaweed-block/cmd/sw-block/chunk_verify_test.go b/seaweed-block/cmd/sw-block/chunk_verify_test.go new file mode 100644 index 0000000000..bdf82a3447 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_verify_test.go @@ -0,0 +1,229 @@ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/url" + "path" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// verifyCLIFixture is volume v1 with two published chunks on an in-memory +// filer and blob store; it returns the store and the HEAD. +func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, storage.ChunkHead) { + t.Helper() + ctx := context.Background() + mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) + prev := dialChunkFiler + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return mem, func() error { return nil }, nil + } + t.Cleanup(func() { dialChunkFiler = prev }) + cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { + t.Fatal(err) + } + r, err := chunkstore.NewChunkRemote(mem, mem, defaultChunkPathCLI+"/v1") + if err != nil { + t.Fatal(err) + } + cur, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}} + for idx := uint64(0); idx < 2; idx++ { + data := bytes.Repeat([]byte{byte(0x30 + idx)}, 8*4096) + key := fmt.Sprintf("chunks/e1/c%d/k", idx) + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + h.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + h, ids, err := r.PrepareManifest(ctx, cur, h, 8*4096) + if err != nil { + t.Fatal(err) + } + if h.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil { + t.Fatal(err) + } + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + return mem, h +} + +func decodeVerify(t *testing.T, out string) chunkstore.VerifyResult { + t.Helper() + var res chunkstore.VerifyResult + if err := json.Unmarshal([]byte(out), &res); err != nil || res.VolumeID == "" { + t.Fatalf("stdout is not a verify result: %q (%v)", out, err) + } + return res +} + +// verify's exit codes: 0 clean, 3 completed with findings, 1 could not +// complete, 2 usage; the result is one JSON object with one finding per line. +func TestOpsChunk_VerifyExitCodes(t *testing.T) { + mem, h := verifyCLIFixture(t) + filer := []string{"--volume", "v1", "--chunk-filer", "filer:18888"} + + code, out, errs := runChunk(append([]string{"verify"}, filer...)...) + res := decodeVerify(t, out) + if code != 0 || !res.Complete || res.Depth != chunkstore.VerifyBindings || len(res.Findings) != 0 || res.ChunksChecked != 2 || + !strings.Contains(out, `"findings":[]`) || len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen { + t.Fatalf("clean verify: %d %q %q", code, out, errs) + } + code, out, errs = runChunk(append([]string{"verify", "--depth", "data", "--timeout", "10s", "--bytes-per-sec", "0"}, filer...)...) + if res = decodeVerify(t, out); code != 0 || res.DistinctChunksRead != 2 || res.BytesRead != 2*8*4096 { + t.Fatalf("clean data verify: %d %q %q", code, out, errs) + } + + // A binding gone: completed with a finding. + own := strings.TrimPrefix(h.Chunks[1].Key, "@v1/") + if err := mem.DeleteEntry(context.Background(), path.Join(defaultChunkPathCLI, "v1", "keys"), url.PathEscape(own), nil); err != nil { + t.Fatal(err) + } + code, out, errs = runChunk(append([]string{"verify"}, filer...)...) + res = decodeVerify(t, out) + if chunkExitFindings != 3 || code != chunkExitFindings || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != chunkstore.FindingBindingMissing || + res.FindingsByClass[chunkstore.FindingBindingMissing] != 1 || !strings.Contains(errs, "1 findings") { + t.Fatalf("verify with a missing binding: %d %q %q", code, out, errs) + } + lines := strings.Split(strings.TrimSpace(out), "\n") + if len(lines) != 3 || !strings.HasPrefix(lines[1], `{"volume":"v1"`) || !strings.Contains(lines[1], `"class":"BINDING_MISSING"`) || lines[2] != "]}" { + t.Fatalf("findings are not one per line:\n%s", out) + } + + // Could not complete: the error body, with what was covered. + code, out, _ = runChunk("verify", "--volume", "nope", "--chunk-filer", "filer:18888") + if e := chunkErrorOut(t, out); code != chunkExitFailed || e.Code != chunkstore.CodeNotChunkVolume || !strings.Contains(out, `"verify":{`) || + !strings.Contains(out, `"incomplete":"error"`) { + t.Fatalf("verify of a missing volume: %d %q", code, out) + } + + for _, args := range [][]string{ + {"verify", "--chunk-filer", "f:1"}, // no volume + {"verify", "--volume", "v1"}, // no filer + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--depth", "all"}, // bad depth + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--depth", "data"}, // data without --timeout + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--snapshot", "s1", "--all-snapshots"}, + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--concurrency", "0"}, + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--bytes-per-sec", "-1"}, + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "extra"}, + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--bogus"}, + } { + code, out, _ := runChunk(args...) + if code != 2 || chunkErrorOut(t, out).Code != codeBadRequestCLI { + t.Fatalf("%v: exit %d %q; want 2 and bad_request", args, code, out) + } + } + if code, out, _ := runChunk("verify", "--volume", "v1", "--chunk-filer", "f:1", "--depth", "data"); !strings.Contains(out, "--timeout") { + t.Fatalf("data without --timeout: %d %q; want the reason", code, out) + } +} + +// unreadableStore fails every read of one needle with an error that is not +// "not found" (a volume server answering 503). +type unreadableStore struct { + *manifestFixtureFiler + fid string +} + +func (s unreadableStore) Get(ctx context.Context, fid string) ([]byte, error) { + if fid == s.fid { + return nil, fmt.Errorf("chunkstore: read %s: http 503 from volume:8080", fid) + } + return s.manifestFixtureFiler.Get(ctx, fid) +} + +// A chunk that cannot be read is READ_ERROR (not verified), and the pass +// exits 3: it did not verify everything. +func TestOpsChunk_VerifyReadErrorExits3(t *testing.T) { + mem, h := verifyCLIFixture(t) + own := strings.TrimPrefix(h.Chunks[0].Key, "@v1/") + e, err := mem.LookupEntry(context.Background(), path.Join(defaultChunkPathCLI, "v1", "keys"), url.PathEscape(own)) + if err != nil { + t.Fatal(err) + } + store := unreadableStore{mem, string(e.Extended["swb.fid"])} + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return store, func() error { return nil }, nil + } + code, out, errs := runChunk("verify", "--volume", "v1", "--chunk-filer", "filer:18888", "--depth", "data", "--timeout", "10s") + res := decodeVerify(t, out) + if code != chunkExitFindings || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != chunkstore.FindingReadError || + res.ChunksNotRead != 1 || res.ReadRetries != 2 || !strings.Contains(errs, "not verified") { + t.Fatalf("verify with an unreadable chunk: %d %q %q", code, out, errs) + } +} + +// verify writes nothing, yet it is in the set that runs the single-filer +// start check (a split filer view would give false findings), and it refuses +// the way the writing commands do (TestOpsChunk_WritingCommandsRunTheSingleFilerCheck). +func TestOpsChunk_VerifyRunsTheSingleFilerCheck(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checks := 0 + checkSingleFiler = func(context.Context, chunkstore.Filer) error { + checks++ + return chunkstore.ErrNotSingleFiler + } + filer := []string{"--chunk-filer", "filer:18888"} + for name, args := range map[string][]string{ + "verify": append([]string{"ops", "chunk", "verify", "--volume", "v1"}, filer...), + "verify --depth data": append([]string{"ops", "chunk", "verify", "--volume", "v1", "--depth", "data", "--timeout", "10s"}, filer...), + } { + before := checks + var out, errb bytes.Buffer + code := run(args, &out, &errb) + if checks != before+1 { + t.Errorf("%s: start check ran %d times; want once", name, checks-before) + } + if code == 0 || !strings.Contains(out.String()+errb.String(), "exactly one filer") { + t.Errorf("%s: exit %d, out %q err %q; want the single-filer refusal", name, code, out.String(), errb.String()) + } + } +} + +// The start check runs within verify's --timeout, as for the writing +// commands (TestOpsChunk_StartCheckIsBoundedByTheTimeout): a check stalled on +// its filer or master ends verify at the timeout, as a retryable refusal. +func TestOpsChunk_VerifyStartCheckIsBoundedByTheTimeout(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checkSingleFiler = func(ctx context.Context, _ chunkstore.Filer) error { + <-ctx.Done() + return ctx.Err() + } + args := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", "filer:18888", "--timeout", "200ms"} + done := make(chan struct{}) + var out, errb bytes.Buffer + var code int + go func() { code = run(args, &out, &errb); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatalf("a stalled start check held verify past its 200ms --timeout") + } + if code == 0 || !strings.Contains(out.String(), "remote_unavailable") || !strings.Contains(out.String(), `"retryable":true`) { + t.Errorf("verify: exit %d, out %q; want a retryable remote_unavailable refusal", code, out.String()) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete.go b/seaweed-block/cmd/sw-block/chunk_volume_delete.go index 52e05da0cc..0413f1709f 100644 --- a/seaweed-block/cmd/sw-block/chunk_volume_delete.go +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete.go @@ -46,7 +46,7 @@ func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int { if volumeID == "" || master == "" || requestID == "" || timeout <= 0 { return chunkFail("volume-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "a volume, --master and --request-id are required; --timeout must be positive", false) } - cat, closeFn, exit := chunkCatalog("volume-delete", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("volume-delete", filer, base, true, timeout, stdout, stderr) if exit >= 0 { return exit } diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index 52633a9426..f1f9d8dc0c 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -83,7 +83,7 @@ func run(args []string, stdout, stderr io.Writer) int { return ops.VolumeStatusExitInvalid } if len(args) < 2 { - fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk|volume-unheld") + fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk|volume-unheld|workspace") usage(stderr) return ops.VolumeStatusExitInvalid } @@ -128,6 +128,8 @@ func run(args []string, stdout, stderr io.Writer) int { return runOpsChunk(args[2:], stdout, stderr) case "volume-unheld": return runOpsVolumeUnheld(args[2:], stdout, stderr) + case "workspace": + return runOpsWorkspace(args[2:], stdout, stderr) default: fmt.Fprintf(stderr, "sw-block: unknown ops subcommand %q\n", args[1]) usage(stderr) @@ -2295,7 +2297,11 @@ func usage(w io.Writer) { fmt.Fprintln(w, " sw-block ops chunk fork --chunk-filer [--chunk-path /swblock/chunks] --source --snapshot --target [--request-id ] [--label k=v]...") fmt.Fprintln(w, " sw-block ops chunk show --volume --chunk-filer [--chunk-path /swblock/chunks]") fmt.Fprintln(w, " sw-block ops chunk gc --chunk-filer --master [--chunk-path /swblock/chunks] [--apply] [--grace 1h] [--intent-ttl 1h] [--timeout 1m]") + fmt.Fprintln(w, " sw-block ops chunk verify --volume --chunk-filer [--chunk-path /swblock/chunks] [--snapshot |--all-snapshots] [--depth meta|bindings|data]") + fmt.Fprintln(w, " [--concurrency 2] [--bytes-per-sec 33554432] [--timeout ] (read-only; exit 0 clean, 3 findings, 1 incomplete; --depth data needs --timeout)") fmt.Fprintln(w, " sw-block ops volume-unheld --path (exit 0: no process on this host holds it; local filesystems only)") + fmt.Fprintln(w, " sw-block ops workspace force-move --master --volume --target-host --target-data --target-ctrl --request-id --confirm-forced @ [--dry-run]") + fmt.Fprintln(w, " sw-block ops workspace lost-range --master --volume [--request-id ] (authority only; no bypass: see `sw-block ops workspace help`)") } func emptyCLI(value string) string { diff --git a/seaweed-block/cmd/sw-block/workspace.go b/seaweed-block/cmd/sw-block/workspace.go new file mode 100644 index 0000000000..b1e7d1693f --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace.go @@ -0,0 +1,274 @@ +package main + +import ( + "context" + "flag" + "fmt" + "io" + "strings" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/wsclient" +) + +// Exit codes of `sw-block ops workspace`. +const ( + wsExitOK = 0 + wsExitRefused = 1 // the master refused; nothing moved + wsExitRefusedLocally = 2 // bad usage or confirmation; no RPC was sent + wsExitUnknown = 3 // outcome unknown: rerun with the SAME --request-id + wsExitReadoutUnproven = 4 // move issued (or ranges exist) but the lost range is not proven + wsDefaultTimeout = 30 * time.Second + workspaceForceMoveName = "sw-block ops workspace force-move" + workspaceLostRangeName = "sw-block ops workspace lost-range" +) + +const workspaceUsage = `usage: + sw-block ops workspace force-move --master ADDR --volume V --target-host H --target-data A --target-ctrl A + --request-id ID --confirm-forced V@EPOCH [--dry-run] [--timeout 30s] + sw-block ops workspace lost-range --master ADDR --volume V [--request-id ID] [--timeout 30s] + +force-move FORCES an RF1 workspace volume's authority off a holder that is gone, +abandoning what it wrote after the last published HEAD. It moves AUTHORITY only: +starting the volume on the target host is the next step, done separately. The +blockmaster admits it only once the holder's lease horizon and its granted or +restart deadline, each plus the clock-skew bound, have passed; before that it is +refused and this command says when it becomes admissible. There is NO bypass +flag. Clean (detached) moves are not offered here. + +--confirm-forced must be exactly @, retyped: the epoch +is the holder's epoch the move is sent against, and the master refuses it when +that is no longer current. --dry-run asks the master for an advisory preview +(nothing is written; admission is re-checked at the move); it is never a +confirmation. The lost range is stored before the move is issued and printed +from that record; the authority store and its lost-range files stay off the +volume hosts (layout rule). + +lost-range prints the stored lost ranges of the volume's issued forced moves, in +issue order (all of them, or the one of --request-id). It never prints "no loss" +for a forced move whose record is missing or fails its checks. + +exit: 0 done; 1 refused by the master (nothing moved); 2 refused locally (usage +or confirmation; nothing sent); 3 outcome unknown: rerun with the SAME +--request-id; 4 the move is issued but its lost range is not proven (or a +stored range is unreadable). +` + +// workspaceDial is swapped by tests. +var workspaceDial = wsclient.Dial + +// runOpsWorkspace is `sw-block ops workspace`. +func runOpsWorkspace(args []string, stdout, stderr io.Writer) int { + if len(args) == 0 { + fmt.Fprint(stderr, workspaceUsage) + return wsExitRefusedLocally + } + switch args[0] { + case "force-move": + return runWorkspaceForceMove(args[1:], stdout, stderr) + case "lost-range": + return runWorkspaceLostRange(args[1:], stdout, stderr) + case "-h", "--help", "help": + fmt.Fprint(stdout, workspaceUsage) + return wsExitOK + default: + fmt.Fprintf(stderr, "sw-block ops workspace: unknown subcommand %q\n", args[0]) + fmt.Fprint(stderr, workspaceUsage) + return wsExitRefusedLocally + } +} + +func workspaceExit(o wsclient.Outcome) int { + switch o { + case wsclient.OutcomeOK: + return wsExitOK + case wsclient.OutcomeRefusedLocally: + return wsExitRefusedLocally + case wsclient.OutcomeRefused: + return wsExitRefused + case wsclient.OutcomeReadoutUnproven: + return wsExitReadoutUnproven + } + return wsExitUnknown +} + +func runWorkspaceForceMove(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet(workspaceForceMoveName, flag.ContinueOnError) + fs.SetOutput(stderr) + fs.Usage = func() { fmt.Fprint(stderr, workspaceUsage) } + var m wsclient.ForcedMove + var master string + var dryRun bool + var timeout time.Duration + fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port") + fs.StringVar(&m.VolumeID, "volume", "", "volume id") + fs.StringVar(&m.TargetHost, "target-host", "", "target node server id") + fs.StringVar(&m.TargetDataAddr, "target-data", "", "target data address host:port") + fs.StringVar(&m.TargetCtrlAddr, "target-ctrl", "", "target control address host:port") + fs.StringVar(&m.RequestID, "request-id", "", "this move's id; a rerun with the same id returns the stored grant") + fs.StringVar(&m.Confirm, "confirm-forced", "", "exactly @") + fs.BoolVar(&dryRun, "dry-run", false, "advisory preview only; writes nothing") + fs.DurationVar(&timeout, "timeout", wsDefaultTimeout, "bound for the RPCs") + if err := fs.Parse(args); err != nil { + return wsExitRefusedLocally + } + if fs.NArg() != 0 || master == "" || m.VolumeID == "" || m.TargetHost == "" || m.TargetDataAddr == "" || m.TargetCtrlAddr == "" || m.RequestID == "" || timeout <= 0 { + fmt.Fprintf(stderr, "%s: --master, --volume, --target-host, --target-data, --target-ctrl, --request-id and --confirm-forced are required (refused locally; nothing sent)\n", workspaceForceMoveName) + return wsExitRefusedLocally + } + // Row Parse -> Refused: checked before any connection or RPC. + if _, err := wsclient.ParseConfirmation(m.Confirm, m.VolumeID); err != nil { + fmt.Fprintf(stderr, "%s: refused locally, nothing sent: %v\n", workspaceForceMoveName, err) + return wsExitRefusedLocally + } + c, err := workspaceDial(master) + if err != nil { + fmt.Fprintf(stderr, "%s: refused locally, nothing sent: master address: %v\n", workspaceForceMoveName, err) + return wsExitRefusedLocally + } + defer c.Close() + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + if dryRun { + return workspacePreview(ctx, c, m, stdout, stderr) + } + g, err := c.ForceMove(ctx, m) + switch o := wsclient.OutcomeOf(err); o { + case wsclient.OutcomeOK: + printForcedGrant(stdout, g) + fmt.Fprintln(stdout, wsclient.Readout(m.VolumeID, g.GetLostRange())) + fmt.Fprintf(stdout, "next: start volume %s on %s (this command moved authority only)\n", m.VolumeID, g.GetNewHost()) + return wsExitOK + case wsclient.OutcomeReadoutUnproven: + if g != nil { + printForcedGrant(stdout, g) + } + fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err) + fmt.Fprintf(stderr, "%s: the move IS issued; do not assume no loss. Check the master's load errors, and read the range with:\n", workspaceForceMoveName) + fmt.Fprintf(stderr, "%s%s\n", workspaceRecoveryPrefix, shellCommand("sw-block", "ops", "workspace", "lost-range", "--master", master, "--volume", m.VolumeID, "--request-id", m.RequestID)) + return wsExitReadoutUnproven + case wsclient.OutcomeRefused: + fmt.Fprintf(stderr, "%s: refused by the master (nothing moved): %v\n", workspaceForceMoveName, err) + if at, ok := c.AdmissibleAt(ctx, m); ok { + fmt.Fprintf(stderr, "%s: admissible at %s, master clock (the lease horizon plus clock skew); wait, there is no bypass\n", workspaceForceMoveName, wsclient.FormatTime(at.UnixNano())) + } + return wsExitRefused + case wsclient.OutcomeUnknown: + fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err) + fmt.Fprintf(stderr, "%s: outcome unknown: rerun with the SAME --request-id %s\n", workspaceForceMoveName, m.RequestID) + return wsExitUnknown + default: + fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err) + return workspaceExit(o) + } +} + +// workspaceRecoveryPrefix starts the line that carries a recovery command. +const workspaceRecoveryPrefix = " " + +// shellCommand joins args for a POSIX shell, single-quoting any argument +// that is not plainly safe, so a printed command can be pasted as is. +func shellCommand(args ...string) string { + out := make([]string, len(args)) + for i, a := range args { + out[i] = shellQuote(a) + } + return strings.Join(out, " ") +} + +func shellQuote(a string) string { + if a != "" && strings.Trim(a, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@%+=:,./_-") == "" { + return a + } + return "'" + strings.ReplaceAll(a, "'", `'\''`) + "'" +} + +func printForcedGrant(w io.Writer, g *control.WorkspaceGrant) { + fmt.Fprintf(w, "forced move issued: volume %s request %s: %s@%d on %s -> %s@%d on %s (kept HEAD gen %d, remote LSN %d)\n", + g.GetVolumeId(), g.GetRequestId(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetOldHost(), g.GetNewReplicaId(), g.GetNewEpoch(), g.GetNewHost(), g.GetHeadGen(), g.GetRemoteLsn()) +} + +// workspacePreview is the --dry-run row: advisory, writes nothing, exit 0 +// whatever the answer (a failed preview call is reported by its outcome). +func workspacePreview(ctx context.Context, c *wsclient.Client, m wsclient.ForcedMove, stdout, stderr io.Writer) int { + p, err := c.PreviewForcedMove(ctx, m) + if err != nil { + fmt.Fprintf(stderr, "%s --dry-run: %v\n", workspaceForceMoveName, err) + if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown { + fmt.Fprintf(stderr, "%s --dry-run: the preview failed; nothing was written\n", workspaceForceMoveName) + } + return workspaceExit(wsclient.OutcomeOf(err)) + } + verdict := "not admitted" + if p.GetAdmitted() { + verdict = "admitted" + } + fmt.Fprintf(stdout, "preview (advisory): at master time %s, may change; admission is re-checked at the move. Nothing was written; this is not a confirmation.\n", wsclient.FormatTime(p.GetMasterTimeNs())) + if p.GetReason() != "" { + fmt.Fprintf(stdout, "forced move %s: %s\n", verdict, p.GetReason()) + } else { + fmt.Fprintf(stdout, "forced move %s\n", verdict) + } + if !p.GetAdmitted() && p.GetLostUntilNs() > p.GetMasterTimeNs() { + fmt.Fprintf(stdout, "admissible at %s, master clock\n", wsclient.FormatTime(p.GetLostUntilNs())) + } + if p.GetHeadRead() { + at := "unknown" + if p.GetHeadTimeKnown() { + at = wsclient.FormatTime(p.GetHeadTimeNs()) + " " + wsclient.HeadTimeClock + } + fmt.Fprintf(stdout, "HEAD now: gen %d, epoch %d, holder %s, remote LSN %d, published at %s\n", p.GetHeadGen(), p.GetHeadEpoch(), p.GetHeadHolder(), p.GetHeadRemoteLsn(), at) + if p.GetAdmitted() { + fmt.Fprintf(stdout, "if moved now: writes with LSN <= %d are kept; writes acknowledged after that and before %s, master clock, may be lost\n", p.GetHeadRemoteLsn(), wsclient.FormatTime(p.GetLostUntilNs())) + } + } else if p.GetHeadError() != "" { + fmt.Fprintf(stdout, "HEAD read failed: %s\n", p.GetHeadError()) + } + return wsExitOK +} + +func runWorkspaceLostRange(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet(workspaceLostRangeName, flag.ContinueOnError) + fs.SetOutput(stderr) + fs.Usage = func() { fmt.Fprint(stderr, workspaceUsage) } + var master, volume, requestID string + var timeout time.Duration + fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port") + fs.StringVar(&volume, "volume", "", "volume id") + fs.StringVar(&requestID, "request-id", "", "only this forced move's range (default: all, in issue order)") + fs.DurationVar(&timeout, "timeout", wsDefaultTimeout, "bound for the RPC") + if err := fs.Parse(args); err != nil { + return wsExitRefusedLocally + } + if fs.NArg() != 0 || master == "" || volume == "" || timeout <= 0 { + fmt.Fprintf(stderr, "%s: --master and --volume are required\n", workspaceLostRangeName) + return wsExitRefusedLocally + } + c, err := workspaceDial(master) + if err != nil { + fmt.Fprintf(stderr, "%s: master address: %v\n", workspaceLostRangeName, err) + return wsExitRefusedLocally + } + defer c.Close() + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + ranges, err := c.LostRanges(ctx, volume, requestID) + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", workspaceLostRangeName, err) + if wsclient.OutcomeOf(err) == wsclient.OutcomeReadoutUnproven { + fmt.Fprintf(stderr, "%s: a forced move's lost range is missing or unreadable: the readout is NOT proven; do not assume no loss\n", workspaceLostRangeName) + } + return workspaceExit(wsclient.OutcomeOf(err)) + } + if len(ranges) == 0 { + fmt.Fprintf(stdout, "volume %s has no issued forced move\n", volume) + return wsExitOK + } + for i, r := range ranges { + fmt.Fprintf(stdout, "range %d of %d: request %s, %s@%d -> epoch %d, lost after LSN %d, until %s (master clock)\n", + i+1, len(ranges), r.GetRequestId(), r.GetOldReplicaId(), r.GetOldEpoch(), r.GetNewEpoch(), r.GetLostAfterLsn(), wsclient.FormatTime(r.GetLostUntilNs())) + fmt.Fprintf(stdout, " %s\n", wsclient.Readout(volume, r)) + } + return wsExitOK +} diff --git a/seaweed-block/cmd/sw-block/workspace_master_test.go b/seaweed-block/cmd/sw-block/workspace_master_test.go new file mode 100644 index 0000000000..d7c594913b --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_master_test.go @@ -0,0 +1,173 @@ +package main + +import ( + "context" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// seedForcedVolume makes r1 on node-a the holder of vol-f at epoch 1 (lease +// renewed once) with a prepared target binding on node-b. +func seedForcedVolume(t *testing.T, h *master.Host) { + t.Helper() + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + ws := control.NewWorkspaceServiceClient(conn) + for _, server := range []string{"node-a", "node-b"} { + if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + } + if _, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "vol-f", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + for _, b := range []*control.WorkspaceBinding{ + {VolumeId: "vol-f", ServerId: "node-a", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"}, + {VolumeId: "vol-f", ServerId: "node-b", DataAddr: "127.0.0.1:29200", CtrlAddr: "127.0.0.1:29100"}, + } { + if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + } + if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "vol-f", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + if _, err := control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "vol-f", ReplicaId: "r1", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"}}}); err != nil { + t.Fatal(err) + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + for deadline := time.Now().Add(3 * time.Second); ; time.Sleep(10 * time.Millisecond) { + if line, ok := h.Publisher().VolumeAuthorityLine("vol-f"); ok && line.Epoch == 1 { + break + } + if time.Now().After(deadline) { + t.Fatal("no authority line for vol-f") + } + } + if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}); err != nil { + t.Fatal(err) + } +} + +// The CLI against a real master: before the horizon the move is refused +// (exit 1) with when it becomes admissible, and the dry run writes nothing; +// after it the move is issued with the readout of the stored range; a rerun +// with the same request id prints the same; lost-range prints that range; +// after a restart with the range file damaged a rerun exits 4 (issued, +// readout unproven) and lost-range exits 4. A confirmation at another epoch +// is refused by the master's state (exit 1); a malformed one never leaves +// the CLI (exit 2). +func TestWorkspaceForceMoveAgainstRealMaster(t *testing.T) { + headTime := time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC) + authDir := t.TempDir() + cfg := master.Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: authDir, LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, FilerMtimeNS: headTime.UnixNano()}, nil + }} + h, stop := startDeleteMaster(t, cfg) + stopped := false + defer func() { + if !stopped { + stop() + } + }() + seedForcedVolume(t, h) + args := func(extra ...string) []string { + return append([]string{"ops", "workspace", "force-move", "--master", h.Addr(), "--volume", "vol-f", "--target-host", "node-b", "--target-data", "127.0.0.1:29200", + "--target-ctrl", "127.0.0.1:29100", "--request-id", "force-1"}, extra...) + } + + if code, _, errOut := runCLI(args("--confirm-forced", "vol-f@1x")); code != wsExitRefusedLocally { + t.Fatalf("malformed confirmation: exit %d %s", code, errOut) + } + if code, _, errOut := runCLI(args("--confirm-forced", "vol-f@2")); code != wsExitRefused || !strings.Contains(errOut, "no holder of volume") { + t.Fatalf("confirmation at another epoch: exit %d %s", code, errOut) + } + code, _, errOut := runCLI(args("--confirm-forced", "vol-f@1")) + if code != wsExitRefused || !strings.Contains(errOut, "has not elapsed") || !strings.Contains(errOut, "admissible at ") { + t.Fatalf("before the horizon: exit %d %s", code, errOut) + } + code, out, _ := runCLI(args("--confirm-forced", "vol-f@1", "--dry-run")) + if code != wsExitOK || !strings.Contains(out, "forced move not admitted") || !strings.Contains(out, "admissible at ") { + t.Fatalf("dry run before the horizon: exit %d\n%s", code, out) + } + if st := h.Publisher().WorkspaceState("vol-f"); len(st.Moves) != 0 { + t.Fatalf("refusal or dry run wrote a journal record: %+v", st.Moves) + } + + st := h.Publisher().WorkspaceState("vol-f") + skew := time.Duration(st.Lease.MaxClockSkewNS) + if skew < cfg.WorkspaceMaxClockSkew { + skew = cfg.WorkspaceMaxClockSkew + } + time.Sleep(time.Until(time.Unix(0, st.Lease.ExpiresAtNS).Add(skew)) + 100*time.Millisecond) + + code, out, errOut = runCLI(args("--confirm-forced", "vol-f@1")) + if code != wsExitOK || !strings.HasPrefix(out, "forced move issued: volume vol-f request force-1: r1@1 on node-a -> r1@2 on node-b (kept HEAD gen 9, remote LSN 42)\n") || + !strings.Contains(out, "volume vol-f restored to the last published image at 2026-11-21T01:02:03Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 9, LSN 42): writes with LSN <= 42 are preserved; writes acknowledged by r1@1 after that and before ") { + t.Fatalf("forced move: exit %d stderr %s\n%s", code, errOut, out) + } + code2, out2, _ := runCLI(args("--confirm-forced", "vol-f@1")) + if code2 != wsExitOK || out2 != out { + t.Fatalf("rerun with the same request id: exit %d\n%s\nwant\n%s", code2, out2, out) + } + readout := strings.Split(out, "\n")[1] + code, lr, _ := runCLI([]string{"ops", "workspace", "lost-range", "--master", h.Addr(), "--volume", "vol-f"}) + if code != wsExitOK || !strings.HasPrefix(lr, "range 1 of 1: request force-1, r1@1 -> epoch 2, lost after LSN 42") || !strings.Contains(lr, " "+readout+"\n") { + t.Fatalf("lost-range: exit %d\n%s\nwant readout %s", code, lr, readout) + } + + stop() + stopped = true + var files []string + _ = filepath.WalkDir(authDir, func(p string, d fs.DirEntry, err error) error { + if err == nil && !d.IsDir() && strings.HasSuffix(p, ".lostrange.json") { + files = append(files, p) + } + return err + }) + if len(files) != 1 { + t.Fatalf("lost range files %v", files) + } + raw, err := os.ReadFile(files[0]) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(files[0], []byte(strings.Replace(string(raw), `"LostAfterLSN":42`, `"LostAfterLSN":41`, 1)), 0o644); err != nil { + t.Fatal(err) + } + h2, stop2 := startDeleteMaster(t, cfg) + defer stop2() + args2 := func(extra ...string) []string { + a := args(extra...) + a[4] = h2.Addr() + return a + } + code, out, errOut = runCLI(args2("--confirm-forced", "vol-f@1")) + if code != wsExitReadoutUnproven || !strings.HasPrefix(out, "forced move issued: volume vol-f request force-1") || strings.Contains(out, "restored to") || !strings.Contains(errOut, "not proven") { + t.Fatalf("rerun with a damaged range: exit %d stdout %q stderr %s", code, out, errOut) + } + if code, _, errOut = runCLI([]string{"ops", "workspace", "lost-range", "--master", h2.Addr(), "--volume", "vol-f"}); code != wsExitReadoutUnproven { + t.Fatalf("lost-range with a damaged range: exit %d %s", code, errOut) + } +} diff --git a/seaweed-block/cmd/sw-block/workspace_postissue_test.go b/seaweed-block/cmd/sw-block/workspace_postissue_test.go new file mode 100644 index 0000000000..0be23f3bdc --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_postissue_test.go @@ -0,0 +1,83 @@ +package main + +import ( + "bytes" + "context" + "log" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/host/master" +) + +type lockedLog struct { + mu sync.Mutex + b bytes.Buffer +} + +func (l *lockedLog) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.Write(p) +} + +func (l *lockedLog) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.String() +} + +// A failure AFTER the forced move is issued (here the binding +// reconciliation, made to fail by moving the binding store's directory away) +// is reported through the RPC, the client and the CLI as an unknown outcome +// with the same-request-id recovery, never as a refusal ("nothing moved") +// and never with a fresh request id; the master's audit log records the +// issue; a rerun with the same id then returns the stored grant. +func TestWorkspaceForceMovePostIssueFailureKeepsTheOutcome(t *testing.T) { + logs := &lockedLog{} + lifecycleDir := t.TempDir() + cfg := master.Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: lifecycleDir, WorkspaceRPC: true, + Logger: log.New(logs, "", 0), + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42}, nil + }} + h, stop := startDeleteMaster(t, cfg) + defer stop() + seedForcedVolume(t, h) + st := h.Publisher().WorkspaceState("vol-f") + skew := time.Duration(st.Lease.MaxClockSkewNS) + if skew < cfg.WorkspaceMaxClockSkew { + skew = cfg.WorkspaceMaxClockSkew + } + time.Sleep(time.Until(time.Unix(0, st.Lease.ExpiresAtNS).Add(skew)) + 100*time.Millisecond) + + bindings := filepath.Join(lifecycleDir, "workspace-bindings") + if err := os.Rename(bindings, bindings+".aside"); err != nil { + t.Fatal(err) + } + args := []string{"ops", "workspace", "force-move", "--master", h.Addr(), "--volume", "vol-f", "--target-host", "node-b", "--target-data", "127.0.0.1:29200", + "--target-ctrl", "127.0.0.1:29100", "--request-id", "force-1", "--confirm-forced", "vol-f@1"} + code, out, errOut := runCLI(args) + if line, ok := h.Publisher().VolumeAuthorityLine("vol-f"); !ok || line.Epoch != 2 { + t.Fatalf("fixture: the forced move was not issued before the failure: %+v", line) + } + if code != wsExitUnknown || strings.Contains(errOut, "nothing moved") || strings.Contains(out, "nothing moved") || + !strings.Contains(errOut, "rerun with the SAME --request-id force-1") || strings.Contains(strings.ToLower(errOut), "new request id") { + t.Fatalf("post-issue failure: exit %d stdout %q stderr %s; want exit 3 with the same-id recovery and no refusal", code, out, errOut) + } + if !strings.Contains(logs.String(), `forced move issued volume="vol-f" request="force-1"`) { + t.Fatalf("issued forced move missing from the audit log:\n%s", logs.String()) + } + if err := os.Rename(bindings+".aside", bindings); err != nil { + t.Fatal(err) + } + code, out, errOut = runCLI(args) + if code != wsExitOK || !strings.HasPrefix(out, "forced move issued: volume vol-f request force-1: r1@1 on node-a -> r1@2 on node-b") { + t.Fatalf("rerun with the same id: exit %d stdout %q stderr %s", code, out, errOut) + } +} diff --git a/seaweed-block/cmd/sw-block/workspace_test.go b/seaweed-block/cmd/sw-block/workspace_test.go new file mode 100644 index 0000000000..31b73cceb9 --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_test.go @@ -0,0 +1,450 @@ +package main + +import ( + "bytes" + "context" + "net" + "strings" + "sync" + "testing" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/wsclient" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// fakeWorkspace is a workspace service with canned answers that records +// every call. +type fakeWorkspace struct { + control.UnimplementedWorkspaceServiceServer + mu sync.Mutex + calls map[string]int + moves []*control.WorkspaceMove + status *control.WorkspaceStatus + move func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) + preview *control.WorkspaceMovePreview + ranges []*control.WorkspaceLostRange + rangeErr error + lastLR *control.WorkspaceLostRangeQuery +} + +func (f *fakeWorkspace) count(m string) { + f.mu.Lock() + defer f.mu.Unlock() + if f.calls == nil { + f.calls = map[string]int{} + } + f.calls[m]++ +} + +func (f *fakeWorkspace) n(m string) int { + f.mu.Lock() + defer f.mu.Unlock() + return f.calls[m] +} + +func (f *fakeWorkspace) total() int { + f.mu.Lock() + defer f.mu.Unlock() + n := 0 + for _, c := range f.calls { + n += c + } + return n +} + +func (f *fakeWorkspace) QueryWorkspace(context.Context, *control.WorkspaceVolume) (*control.WorkspaceStatus, error) { + f.count("QueryWorkspace") + return f.status, nil +} + +func (f *fakeWorkspace) MoveWorkspace(_ context.Context, q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + f.count("MoveWorkspace") + f.mu.Lock() + f.moves = append(f.moves, q) + f.mu.Unlock() + return f.move(q) +} + +func (f *fakeWorkspace) PreviewWorkspaceMove(context.Context, *control.WorkspaceMove) (*control.WorkspaceMovePreview, error) { + f.count("PreviewWorkspaceMove") + if f.preview == nil { + return nil, status.Error(codes.Unavailable, "no preview") + } + return f.preview, nil +} + +func (f *fakeWorkspace) QueryWorkspaceLostRange(_ context.Context, q *control.WorkspaceLostRangeQuery) (*control.WorkspaceLostRanges, error) { + f.count("QueryWorkspaceLostRange") + f.mu.Lock() + f.lastLR = q + f.mu.Unlock() + if f.rangeErr != nil { + return nil, f.rangeErr + } + return &control.WorkspaceLostRanges{Ranges: f.ranges}, nil +} + +// startFakeWorkspace serves f; dials counts the CLI's connections. +func startFakeWorkspace(t *testing.T, f *fakeWorkspace) (addr string, dials *int) { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + control.RegisterWorkspaceServiceServer(srv, f) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + n := 0 + prev := workspaceDial + workspaceDial = func(a string) (*wsclient.Client, error) { n++; return wsclient.Dial(a) } + t.Cleanup(func() { workspaceDial = prev }) + return lis.Addr().String(), &n +} + +var ( + wsHeadTime = time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC) + wsLostUntil = time.Date(2026, 11, 21, 1, 5, 0, 0, time.UTC) +) + +func wsHolder() *control.WorkspaceStatus { + return &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3}} +} + +func wsGrant(q *control.WorkspaceMove) *control.WorkspaceGrant { + return &control.WorkspaceGrant{RequestId: q.RequestId, VolumeId: q.VolumeId, OldReplicaId: q.ExpectedReplicaId, NewReplicaId: q.TargetReplicaId, Kind: "forced", + OldEpoch: q.ExpectedEpoch, NewEpoch: q.ExpectedEpoch + 1, HeadGen: 9, RemoteLsn: 42, Issued: true, OldHost: "node-a", NewHost: q.TargetServerId, + LostRange: &control.WorkspaceLostRange{RequestId: q.RequestId, VolumeId: q.VolumeId, NewEpoch: q.ExpectedEpoch + 1, OldReplicaId: q.ExpectedReplicaId, OldEpoch: q.ExpectedEpoch, + LostAfterLsn: 42, LostUntilNs: wsLostUntil.UnixNano(), HeadGen: 9, HeadTimeNs: wsHeadTime.UnixNano(), HeadTimeKnown: true}} +} + +const wsReadout = "volume vol restored to the last published image at 2026-11-21T01:02:03Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 9, LSN 42): writes with LSN <= 42 are preserved; " + + "writes acknowledged by r1@3 after that and before 2026-11-21T01:05:00Z, master clock, may be lost; the upper bound is a time, not an LSN." + +func forceMoveArgs(addr string, extra ...string) []string { + return append([]string{"ops", "workspace", "force-move", "--master", addr, "--volume", "vol", "--target-host", "node-b", "--target-data", "10.0.0.2:3260", + "--target-ctrl", "10.0.0.2:9100", "--request-id", "req-1"}, extra...) +} + +func runCLI(args []string) (int, string, string) { + var out, errOut bytes.Buffer + code := run(args, &out, &errOut) + return code, out.String(), errOut.String() +} + +// Row Parse -> Refused (INV-WS-FORCED-CONFIRM-001): a confirmation that is +// absent or not exactly @ exits 2 with no +// connection and no RPC. +func TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { return wsGrant(q), nil }} + addr, dials := startFakeWorkspace(t, f) + for _, extra := range [][]string{nil, {"--confirm-forced", "other@3"}, {"--confirm-forced", "vol"}, {"--confirm-forced", "vol@x"}, {"--confirm-forced", "vol@0"}, + {"--confirm-forced", "vol@3", "--force"}, {"--dry-run"}} { + code, out, errOut := runCLI(forceMoveArgs(addr, extra...)) + if code != wsExitRefusedLocally || out != "" { + t.Fatalf("%v: exit %d stdout %q; want 2 and nothing", extra, code, out) + } + if len(extra) > 0 && extra[len(extra)-1] != "--force" && !strings.Contains(errOut, "refused locally") { + t.Fatalf("%v: stderr %q", extra, errOut) + } + } + if *dials != 0 || f.total() != 0 { + t.Fatalf("refused locally after %d dials and %d RPCs", *dials, f.total()) + } +} + +// Row Parse -> Preview: --dry-run calls only the preview, writes nothing, +// labels the answer advisory, says when a refused move becomes admissible, +// and exits 0 whatever the answer. +func TestWorkspaceForceMove_Row2_DryRunPreview(t *testing.T) { + master := time.Date(2026, 11, 21, 1, 4, 0, 0, time.UTC) + f := &fakeWorkspace{status: wsHolder(), move: func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) { panic("dry run moved") }, + preview: &control.WorkspaceMovePreview{Reason: "workspace forced move lease expiry plus clock-skew margin has not elapsed", LostUntilNs: wsLostUntil.UnixNano(), MasterTimeNs: master.UnixNano()}} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--dry-run")) + if code != wsExitOK || f.n("MoveWorkspace") != 0 || f.n("PreviewWorkspaceMove") != 1 { + t.Fatalf("exit %d, %v; stderr %s", code, f.calls, errOut) + } + for _, s := range []string{"preview (advisory): at master time 2026-11-21T01:04:00Z, may change; admission is re-checked at the move", "this is not a confirmation", + "forced move not admitted: workspace forced move lease expiry", "admissible at 2026-11-21T01:05:00Z, master clock"} { + if !strings.Contains(out, s) { + t.Fatalf("stdout lacks %q:\n%s", s, out) + } + } + f.preview = &control.WorkspaceMovePreview{Admitted: true, LostUntilNs: wsLostUntil.UnixNano(), MasterTimeNs: wsLostUntil.Add(time.Minute).UnixNano(), + HeadRead: true, HeadGen: 9, HeadEpoch: 3, HeadHolder: "node-a/r1", HeadRemoteLsn: 42, HeadTimeNs: wsHeadTime.UnixNano(), HeadTimeKnown: true} + code, out, _ = runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--dry-run")) + if code != wsExitOK || f.n("MoveWorkspace") != 0 || strings.Contains(out, "admissible at") || + !strings.Contains(out, "forced move admitted") || !strings.Contains(out, "HEAD now: gen 9, epoch 3, holder node-a/r1, remote LSN 42, published at 2026-11-21T01:02:03Z (publishing host clock as recorded in the filer, 1 s resolution)") { + t.Fatalf("admitted preview: exit %d\n%s", code, out) + } +} + +// Rows Parse -> Sent and Sent -> Granted: the move is sent as kind forced, +// force true, at the confirmed epoch with the request id; the grant and the +// readout from its stored range are printed, with the next step. +func TestWorkspaceForceMove_Row3and4_SentAndGranted(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { return wsGrant(q), nil }} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")) + if code != wsExitOK || errOut != "" { + t.Fatalf("exit %d stderr %s", code, errOut) + } + q := f.moves[0] + if len(f.moves) != 1 || q.Kind != "forced" || !q.Force || q.ExpectedEpoch != 3 || q.ExpectedReplicaId != "r1" || q.TargetReplicaId != "r1" || q.RequestId != "req-1" || + q.VolumeId != "vol" || q.TargetServerId != "node-b" || q.TargetDataAddr != "10.0.0.2:3260" || q.TargetCtrlAddr != "10.0.0.2:9100" { + t.Fatalf("sent %+v", f.moves) + } + want := "forced move issued: volume vol request req-1: r1@3 on node-a -> r1@4 on node-b (kept HEAD gen 9, remote LSN 42)\n" + wsReadout + "\n" + + "next: start volume vol on node-b (this command moved authority only)\n" + if out != want { + t.Fatalf("stdout\n got %q\nwant %q", out, want) + } +} + +// Row Sent -> Refused: a FailedPrecondition prints the master's reason and, +// before the horizon, when the move becomes admissible; exit 1. +func TestWorkspaceForceMove_Row5_MasterRefusal(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) { + return nil, status.Error(codes.FailedPrecondition, "workspace forced move lease expiry plus clock-skew margin has not elapsed") + }, preview: &control.WorkspaceMovePreview{LostUntilNs: wsLostUntil.UnixNano(), MasterTimeNs: wsLostUntil.Add(-time.Minute).UnixNano()}} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")) + if code != wsExitRefused || out != "" || !strings.Contains(errOut, "refused by the master (nothing moved)") || !strings.Contains(errOut, "has not elapsed") || + !strings.Contains(errOut, "admissible at 2026-11-21T01:05:00Z, master clock") || !strings.Contains(errOut, "there is no bypass") { + t.Fatalf("exit %d stdout %q stderr %s", code, out, errOut) + } + // Past the horizon (refused for another reason) no time is promised. + f.preview = &control.WorkspaceMovePreview{Admitted: true, LostUntilNs: wsLostUntil.UnixNano(), MasterTimeNs: wsLostUntil.Add(time.Minute).UnixNano()} + if code, _, errOut = runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")); code != wsExitRefused || strings.Contains(errOut, "admissible at") { + t.Fatalf("exit %d stderr %s", code, errOut) + } + // A confirmation at an epoch the master never had is refused before the move. + moves := f.n("MoveWorkspace") + if code, _, errOut = runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@7")); code != wsExitRefused || f.n("MoveWorkspace") != moves || !strings.Contains(errOut, "no holder of volume") { + t.Fatalf("stale epoch: exit %d stderr %s", code, errOut) + } +} + +// Row Sent -> Unknown: a transport error or the deadline leaves the outcome +// unknown; exit 3 with "rerun with the SAME --request-id". +func TestWorkspaceForceMove_Row6_OutcomeUnknown(t *testing.T) { + for name, move := range map[string]func(*control.WorkspaceMove) (*control.WorkspaceGrant, error){ + "unavailable": func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) { + return nil, status.Error(codes.Unavailable, "connection reset") + }, + "deadline": func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) { + time.Sleep(2 * time.Second) + return nil, status.Error(codes.Unavailable, "late") + }, + } { + t.Run(name, func(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: move} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--timeout", "500ms")) + if code != wsExitUnknown || out != "" || !strings.Contains(errOut, "outcome unknown: rerun with the SAME --request-id req-1") { + t.Fatalf("exit %d stdout %q stderr %s", code, out, errOut) + } + }) + } +} + +// Row Granted -> LostMissing: an issued forced grant without its stored +// range (or with another move's) exits 4: the move is issued, the readout is +// not proven, and "no loss" is never printed. lost-range with a missing or +// corrupt record (DataLoss) exits 4 too. +func TestWorkspaceForceMove_Row7_ReadoutUnproven(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + g := wsGrant(q) + g.LostRange, g.LostRangeError = nil, "workspace lost range missing or unreadable: forced move \"req-1\" has no loaded lost range record" + return g, nil + }, rangeErr: status.Error(codes.DataLoss, "workspace lost range missing or unreadable")} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")) + if code != wsExitReadoutUnproven || !strings.HasPrefix(out, "forced move issued: volume vol request req-1") || strings.Contains(out, "restored to") || + !strings.Contains(errOut, "lost range is not proven") || !strings.Contains(errOut, "the move IS issued; do not assume no loss") { + t.Fatalf("exit %d stdout %q stderr %s", code, out, errOut) + } + code, out, errOut = runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol"}) + if code != wsExitReadoutUnproven || out != "" || !strings.Contains(errOut, "NOT proven") { + t.Fatalf("lost-range: exit %d stdout %q stderr %s", code, out, errOut) + } +} + +// splitShellWords splits a POSIX shell line of plain words and +// single-quoted parts and backslash escapes (the forms shellCommand prints). +func splitShellWords(t *testing.T, line string) []string { + t.Helper() + var words []string + var cur strings.Builder + in, quoted, inQuote, escaped := false, false, false, false + for _, r := range line { + switch { + case escaped: + cur.WriteRune(r) + escaped, in = false, true + case inQuote && r == '\'': + inQuote = false + case inQuote: + cur.WriteRune(r) + case r == '\'': + inQuote, in, quoted = true, true, true + case r == '\\': + escaped = true + case r == ' ': + if in { + words = append(words, cur.String()) + cur.Reset() + in, quoted = false, false + } + default: + cur.WriteRune(r) + in = true + } + } + if inQuote { + t.Fatalf("unterminated quote in %q", line) + } + if in || quoted { + words = append(words, cur.String()) + } + return words +} + +// The exit-4 recovery command carries the master address and survives +// arguments that need quoting: the printed words parse back to the same +// values and run as a lost-range command against the same master. +func TestWorkspaceForceMoveRecoveryCommandRuns(t *testing.T) { + const reqID = "req 1'$x" + f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + g := wsGrant(q) + g.LostRange, g.LostRangeError = nil, "missing" + return g, nil + }, ranges: nil} + addr, _ := startFakeWorkspace(t, f) + args := forceMoveArgs(addr, "--confirm-forced", "vol@3") + args[len(args)-3] = reqID // --request-id value + code, _, errOut := runCLI(args) + if code != wsExitReadoutUnproven { + t.Fatalf("exit %d %s", code, errOut) + } + var line string + for _, l := range strings.Split(errOut, "\n") { + if strings.HasPrefix(l, workspaceRecoveryPrefix+"sw-block ") { + line = strings.TrimPrefix(l, workspaceRecoveryPrefix) + } + } + words := splitShellWords(t, line) + want := []string{"sw-block", "ops", "workspace", "lost-range", "--master", addr, "--volume", "vol", "--request-id", reqID} + if strings.Join(words, "\x00") != strings.Join(want, "\x00") { + t.Fatalf("recovery command %q parses to %q; want %q", line, words, want) + } + f.ranges = []*control.WorkspaceLostRange{{RequestId: reqID, VolumeId: "vol", NewEpoch: 4, OldReplicaId: "r1", OldEpoch: 3, LostAfterLsn: 42, LostUntilNs: wsLostUntil.UnixNano(), HeadGen: 9}} + if code, out, errOut := runCLI(words[1:]); code != wsExitOK || f.lastLR.RequestId != reqID || f.lastLR.VolumeId != "vol" || !strings.Contains(out, "range 1 of 1") { + t.Fatalf("recovery command run: exit %d %+v stdout %q stderr %s", code, f.lastLR, out, errOut) + } +} + +// A successful answer that does not match the request (here the target) +// is an unknown outcome, and one whose range disagrees with the kept HEAD +// is unproven: neither prints the preservation readout. +func TestWorkspaceForceMoveRejectsAMismatchedAnswer(t *testing.T) { + for name, tc := range map[string]struct { + fault func(*control.WorkspaceGrant) + exit int + }{ + "grant target": {func(g *control.WorkspaceGrant) { g.NewHost = "node-c" }, wsExitUnknown}, + "grant epoch": {func(g *control.WorkspaceGrant) { g.OldEpoch = 2 }, wsExitUnknown}, + "range volume": {func(g *control.WorkspaceGrant) { g.LostRange.VolumeId = "vol2" }, wsExitReadoutUnproven}, + "range frontier": {func(g *control.WorkspaceGrant) { g.LostRange.LostAfterLsn = 41 }, wsExitReadoutUnproven}, + "range head gen": {func(g *control.WorkspaceGrant) { g.LostRange.HeadGen = 8 }, wsExitReadoutUnproven}, + } { + t.Run(name, func(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + g := wsGrant(q) + tc.fault(g) + return g, nil + }} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")) + if code != tc.exit || strings.Contains(out, "restored to") || strings.Contains(out, "next: start") { + t.Fatalf("exit %d (want %d) stdout %q stderr %s", code, tc.exit, out, errOut) + } + if tc.exit == wsExitUnknown && !strings.Contains(errOut, "rerun with the SAME --request-id req-1") { + t.Fatalf("no same-id recovery: %s", errOut) + } + }) + } +} + +// Row Rerun same id -> Granted: the master replays the stored grant, and +// the output is the same, from the stored range. +func TestWorkspaceForceMove_Row8_RerunSameRequestID(t *testing.T) { + stored := map[string]*control.WorkspaceGrant{} + f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + if g, ok := stored[q.RequestId]; ok { + return g, nil + } + stored[q.RequestId] = wsGrant(q) + return nil, status.Error(codes.Unavailable, "reply lost") + }} + addr, _ := startFakeWorkspace(t, f) + if code, _, _ := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")); code != wsExitUnknown { + t.Fatalf("first run: exit %d; want unknown", code) + } + code, out, _ := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")) + code2, out2, _ := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")) + if code != wsExitOK || code2 != wsExitOK || out != out2 || !strings.Contains(out, wsReadout) { + t.Fatalf("reruns: exit %d/%d\n%s\n%s", code, code2, out, out2) + } + if len(f.moves) != 3 || f.moves[0].RequestId != f.moves[2].RequestId { + t.Fatalf("moves %+v", f.moves) + } +} + +// lost-range lists every stored range in issue order (or the one of +// --request-id), each with its readout; a volume without forced moves says +// so. +func TestWorkspaceLostRangeListsAllInOrder(t *testing.T) { + q := &control.WorkspaceMove{RequestId: "req-1", VolumeId: "vol", ExpectedReplicaId: "r1", TargetReplicaId: "r1", ExpectedEpoch: 3} + first := wsGrant(q).LostRange + second := &control.WorkspaceLostRange{RequestId: "req-2", VolumeId: "vol", NewEpoch: 5, OldReplicaId: "r1", OldEpoch: 4, LostAfterLsn: 42, + LostUntilNs: wsLostUntil.Add(time.Minute).UnixNano(), HeadGen: 9, HeadTimeNs: wsHeadTime.UnixNano(), HeadTimeKnown: true} + f := &fakeWorkspace{ranges: []*control.WorkspaceLostRange{first, second}} + addr, _ := startFakeWorkspace(t, f) + code, out, _ := runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol"}) + i1, i2 := strings.Index(out, "range 1 of 2: request req-1, r1@3 -> epoch 4"), strings.Index(out, "range 2 of 2: request req-2, r1@4 -> epoch 5") + if code != wsExitOK || i1 < 0 || i2 < i1 || !strings.Contains(out, " "+wsReadout+"\n") || !strings.Contains(out, "acknowledged by r1@4 after that and before 2026-11-21T01:06:00Z") { + t.Fatalf("exit %d\n%s", code, out) + } + if f.lastLR.RequestId != "" { + t.Fatalf("listed with request id %q", f.lastLR.RequestId) + } + f.ranges = []*control.WorkspaceLostRange{second} + if code, out, _ = runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol", "--request-id", "req-2"}); code != wsExitOK || f.lastLR.RequestId != "req-2" || !strings.Contains(out, "range 1 of 1: request req-2") { + t.Fatalf("by request id: exit %d %+v\n%s", code, f.lastLR, out) + } + f.ranges = nil + if code, out, _ = runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol"}); code != wsExitOK || out != "volume vol has no issued forced move\n" { + t.Fatalf("none: exit %d %q", code, out) + } + f.rangeErr = status.Error(codes.NotFound, "no issued forced move with that request id") + if code, _, _ = runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol", "--request-id", "x"}); code != wsExitRefused { + t.Fatalf("unknown request id: exit %d", code) + } +} + +// The help says authority only, the next step, and that no bypass exists. +func TestWorkspaceHelpText(t *testing.T) { + code, out, _ := runCLI([]string{"ops", "workspace", "help"}) + out = strings.Join(strings.Fields(out), " ") + for _, s := range []string{"AUTHORITY only", "starting the volume on the target host is the next step", "There is NO bypass", "never a confirmation", "@"} { + if code != wsExitOK || !strings.Contains(out, s) { + t.Fatalf("help lacks %q:\n%s", s, out) + } + } +} diff --git a/seaweed-block/cmd/sw-block/workspace_uncertain_test.go b/seaweed-block/cmd/sw-block/workspace_uncertain_test.go new file mode 100644 index 0000000000..d4e2c96043 --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_uncertain_test.go @@ -0,0 +1,90 @@ +package main + +import ( + "context" + "errors" + "log" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/host/master" +) + +// The issuing write of a forced move reaches the authority store (renamed +// into place) but the store reports an error (directory sync): the master +// cannot know whether the move is issued, and memory stays unissued. The +// CLI must report an unknown outcome with the same-request-id recovery, +// never "nothing moved", also on a rerun before the master restarts; after a +// restart the master reloads the issued record and a rerun with the same id +// gets the grant. +func TestWorkspaceForceMoveUncertainIssueWriteIsUnknown(t *testing.T) { + logs := &lockedLog{} + cfg := master.Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + Logger: log.New(logs, "", 0), + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42}, nil + }} + h, stop := startDeleteMaster(t, cfg) + stopped := false + defer func() { + if !stopped { + stop() + } + }() + seedForcedVolume(t, h) + st := h.Publisher().WorkspaceState("vol-f") + skew := time.Duration(st.Lease.MaxClockSkewNS) + if skew < cfg.WorkspaceMaxClockSkew { + skew = cfg.WorkspaceMaxClockSkew + } + time.Sleep(time.Until(time.Unix(0, st.Lease.ExpiresAtNS).Add(skew)) + 100*time.Millisecond) + + var faults atomic.Int32 + authority.SetPutAfterRenameFaultForTest(func(r authority.DurableRecord) error { + if r.Workspace == nil { + return nil + } + for _, m := range r.Workspace.Moves { + if m.RequestID == "force-1" && m.Issued && faults.Add(1) == 1 { + return errors.New("injected directory fsync failure after the rename") + } + } + return nil + }) + t.Cleanup(func() { authority.SetPutAfterRenameFaultForTest(nil) }) + + args := func(addr string) []string { + return []string{"ops", "workspace", "force-move", "--master", addr, "--volume", "vol-f", "--target-host", "node-b", "--target-data", "127.0.0.1:29200", + "--target-ctrl", "127.0.0.1:29100", "--request-id", "force-1", "--confirm-forced", "vol-f@1"} + } + for _, attempt := range []string{"first", "rerun before restart"} { + code, out, errOut := runCLI(args(h.Addr())) + if code != wsExitUnknown || strings.Contains(errOut+out, "nothing moved") || !strings.Contains(errOut, "rerun with the SAME --request-id force-1") { + t.Fatalf("%s: exit %d stdout %q stderr %s; want exit 3 with the same-id recovery and no refusal", attempt, code, out, errOut) + } + } + if faults.Load() != 1 { + t.Fatalf("fixture: the issuing write failed %d times; want once", faults.Load()) + } + if line, _ := h.Publisher().VolumeAuthorityLine("vol-f"); line.Epoch != 1 { + t.Fatalf("fixture: memory published the issue (epoch %d); this control needs it unpublished", line.Epoch) + } + if !strings.Contains(logs.String(), `MoveWorkspace outcome unknown volume="vol-f" request="force-1"`) || strings.Contains(logs.String(), "forced move issued") { + t.Fatalf("master log must record an unknown outcome, not an issue:\n%s", logs.String()) + } + + stop() + stopped = true + h2, stop2 := startDeleteMaster(t, cfg) + defer stop2() + if line, _ := h2.Publisher().VolumeAuthorityLine("vol-f"); line.Epoch != 2 { + t.Fatalf("fixture: the reloaded store does not hold the issued move (epoch %d)", line.Epoch) + } + code, out, errOut := runCLI(args(h2.Addr())) + if code != wsExitOK || !strings.HasPrefix(out, "forced move issued: volume vol-f request force-1: r1@1 on node-a -> r1@2 on node-b") || !strings.Contains(out, "restored to the last published image") { + t.Fatalf("rerun after restart: exit %d stdout %q stderr %s", code, out, errOut) + } +} diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index c6516119ec..c0fc650b39 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -469,6 +469,11 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr p.mu.Lock() if p.workspaceUncertain[ask.VolumeID] { p.mu.Unlock() + if grant != nil { + // An earlier workspace write may have landed (an issue among + // them): a move cannot be answered definitely until a reload. + return fmt.Errorf("authority: workspace persistence uncertain; restart required: %w", ErrWorkspaceOutcomeUncertain) + } return fmt.Errorf("authority: workspace persistence uncertain; restart required") } if p.workspace[ask.VolumeID] != nil && ask.Intent != IntentRefreshEndpoint && grant == nil { @@ -607,6 +612,12 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr p.refreshLeaseViewLocked(ask.VolumeID) } p.mu.Unlock() + if issuedWorkspace != nil { + // The store may have written the issuing record before + // failing (e.g. a directory sync after the rename): the + // move's outcome is unknown, not refused. + return fmt.Errorf("authority: durable Put of a workspace move issue failed: %w: %w", err, ErrWorkspaceOutcomeUncertain) + } return fmt.Errorf("authority: durable Put failed, rolling back mint: %w", err) } p.writeSeqByVolume[ask.VolumeID] = nextSeq diff --git a/seaweed-block/core/authority/authority_store_file.go b/seaweed-block/core/authority/authority_store_file.go index f14b0bc1db..e27dff65f2 100644 --- a/seaweed-block/core/authority/authority_store_file.go +++ b/seaweed-block/core/authority/authority_store_file.go @@ -6,8 +6,26 @@ import ( "path/filepath" "strings" "sync" + "sync/atomic" ) +// putAfterRenameFault, when set, runs in every FileAuthorityStore.Put after +// the record's rename (its bytes are in the final file) and before the +// directory sync; an error fails that Put as a failed sync would. +var putAfterRenameFault atomic.Pointer[func(DurableRecord) error] + +// SetPutAfterRenameFaultForTest installs (nil clears) that hook for every +// FileAuthorityStore in the process. Tests only: it models a durable write +// whose caller sees an error (directory sync or close failing after the +// rename). +func SetPutAfterRenameFaultForTest(hook func(DurableRecord) error) { + if hook == nil { + putAfterRenameFault.Store(nil) + return + } + putAfterRenameFault.Store(&hook) +} + // ============================================================ // P14 S5 — File-Per-Volume Authority Store // @@ -188,6 +206,11 @@ func (s *FileAuthorityStore) Put(record DurableRecord) error { _ = os.Remove(tempPath) return fmt.Errorf("authority_store: rename temp->final: %w", err) } + if h := putAfterRenameFault.Load(); h != nil { + if err := (*h)(record); err != nil { + return fmt.Errorf("authority_store: after rename: %w", err) + } + } // Best-effort fsync the directory so the rename is durable. // On Windows, opening directories as files for fsync is not diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 5b83779332..27f50cabe1 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -2,18 +2,29 @@ package authority import ( "context" + "errors" "fmt" "time" ) // WorkspaceHead is read from the configured HEAD source, never supplied as // operator evidence. Detached means the old holder's final cut is committed. +// FilerMtimeNS is the HEAD entry's modification time as the filer reports it +// with that same read (1 s resolution; the entry's mtime is set by the cut +// that wrote it); 0 means the source gave none (unknown, never invented). type WorkspaceHead struct { Gen, Epoch, RemoteLSN uint64 Holder string Detached bool + FilerMtimeNS int64 } +// ErrWorkspaceOutcomeUncertain marks a move whose outcome is unknown: its +// issuing write failed after it may have reached the store, or the volume's +// workspace persistence is already uncertain. Memory shows it unissued, but +// a reload may find it issued; a definite refusal must not be reported. +var ErrWorkspaceOutcomeUncertain = errors.New("workspace move outcome unknown: an authority write may have landed") + type WorkspaceLease struct { ReplicaID string Epoch uint64 @@ -350,19 +361,32 @@ func (p *Publisher) WorkspaceForcedMoveAdmitted(ctx context.Context, volume, req // forcedMoveAdmissionLocked returns the audit bound of the lost range when a // forced move is admitted. Caller holds p.mu. func (p *Publisher) forcedMoveAdmissionLocked(volume string, lease *WorkspaceLease) (int64, error) { - now := p.workspaceNow() + lostUntil, _, err := p.forcedMoveBarrierLocked(volume, lease) + if err != nil { + return 0, err + } + return lostUntil, nil +} + +// forcedMoveBarrierLocked evaluates forced admission at master time now. It +// returns the barrier (the audit bound of the lost range, wall time: the +// later of lease expiry and the granted or restart deadline, each plus +// skew) whether or not it has passed, and an error while it has not. +// Caller holds p.mu. +func (p *Publisher) forcedMoveBarrierLocked(volume string, lease *WorkspaceLease) (lostUntil int64, now time.Time, err error) { + now = p.workspaceNow() skew := p.workspaceSkew(lease) deadline := p.leaseDeadlineLocked(volume) - if now.Before(time.Unix(0, lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) { - return 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") - } - // The audit bound only, in wall time: the admission above keeps both + // The audit bound only, in wall time: the admission below keeps both // predicates (the deadline's monotonic reading included). - lostUntil := time.Unix(0, lease.ExpiresAtNS).Add(skew).UnixNano() + lostUntil = time.Unix(0, lease.ExpiresAtNS).Add(skew).UnixNano() if d := deadline.Add(skew).UnixNano(); d > lostUntil { lostUntil = d } - return lostUntil, nil + if now.Before(time.Unix(0, lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) { + return lostUntil, now, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") + } + return lostUntil, now, nil } // issueWorkspaceMove marks the move issued and starts the new holder's lease @@ -414,16 +438,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra return s, r.NewEpoch, now, nil } } - owned := h.Gen != 0 && h.Epoch == q.ExpectedEpoch && h.Holder == q.ExpectedHost+"/"+q.ExpectedReplicaID - if !owned && q.Kind == "forced" { - // Admitted (the expected holder's lease has expired) and HEAD read - // after that: a HEAD at an older epoch means the expected holder - // never claimed it, or an earlier holder's late claim landed. The - // lost range starts at this HEAD's RemoteLSN. A HEAD at the expected - // or a higher epoch that is not the expected holder's stays refused. - owned = h.Gen != 0 && h.Epoch < q.ExpectedEpoch - } - if !owned { + if !workspaceHeadAdmits(q, h) { return nil, 0, time.Time{}, fmt.Errorf("workspace move: HEAD not owned by expected holder") } if q.Kind == "clean" { @@ -443,7 +458,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra r := WorkspaceMoveRecord{RequestID: q.RequestID, VolumeID: q.VolumeID, OldHost: q.ExpectedHost, NewHost: q.TargetHost, OldReplicaID: q.ExpectedReplicaID, NewReplicaID: q.TargetReplicaID, Kind: q.Kind, OldEpoch: q.ExpectedEpoch, NewEpoch: max + 1, HeadGen: h.Gen, RemoteLSN: h.RemoteLSN, TargetDataAddr: q.TargetDataAddr, TargetCtrlAddr: q.TargetCtrlAddr} if q.Kind == "forced" { - lost := WorkspaceLostRange{RequestID: r.RequestID, NewEpoch: r.NewEpoch, OldReplicaID: r.OldReplicaID, OldEpoch: r.OldEpoch, LostAfterLSN: r.RemoteLSN, LostUntilNS: lostUntil} + lost := WorkspaceLostRange{RequestID: r.RequestID, NewEpoch: r.NewEpoch, OldReplicaID: r.OldReplicaID, OldEpoch: r.OldEpoch, LostAfterLSN: r.RemoteLSN, LostUntilNS: lostUntil, HeadTimeNS: h.FilerMtimeNS} if err := p.recordLostRangeLocked(q.VolumeID, lost); err != nil { return nil, 0, time.Time{}, err } @@ -456,3 +471,81 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra p.issueWorkspaceMove(s, len(s.Moves)-1, now) return s, r.NewEpoch, now, nil } + +// workspaceHeadAdmits is the HEAD rule of a move: HEAD is the expected +// holder's at the expected epoch, or, for a forced move only, any published +// HEAD at an older epoch. Admitted (the expected holder's lease has expired) +// and HEAD read after that: a HEAD at an older epoch means the expected +// holder never claimed it, or an earlier holder's late claim landed. The +// lost range starts at this HEAD's RemoteLSN. A HEAD at the expected or a +// higher epoch that is not the expected holder's stays refused. +func workspaceHeadAdmits(q WorkspaceMoveRequest, h WorkspaceHead) bool { + owned := h.Gen != 0 && h.Epoch == q.ExpectedEpoch && h.Holder == q.ExpectedHost+"/"+q.ExpectedReplicaID + if !owned && q.Kind == "forced" { + owned = h.Gen != 0 && h.Epoch < q.ExpectedEpoch + } + return owned +} + +// WorkspaceForcedMovePreview is a forced move's admission as the publisher +// would judge it now. It is advisory: MoveWorkspace checks again. +type WorkspaceForcedMovePreview struct { + Admitted bool + Reason string // why not admitted, or a note on an admitted replay + // LostUntilNS is the forced barrier (master wall time): the move is + // admissible from then on, and it bounds the lost range. 0 when there + // is no lease of the expected holder to judge. + LostUntilNS int64 + NowNS int64 // the master time of this judgement + Replay bool // the request id is an issued move: a move replays it +} + +// PreviewWorkspaceForcedMove runs the forced admission of req (request +// validation, journal replay, the expected line and lease, the barrier) +// without reserving, writing or minting anything. The HEAD rule is +// WorkspaceMoveHeadAdmits, applied by the caller to a HEAD read after an +// admitted preview, as for the move itself. +func (p *Publisher) PreviewWorkspaceForcedMove(req WorkspaceMoveRequest) WorkspaceForcedMovePreview { + p.mu.Lock() + defer p.mu.Unlock() + out := WorkspaceForcedMovePreview{NowNS: p.workspaceNow().UnixNano()} + if req.Kind != "forced" { + out.Reason = "workspace move preview: forced moves only" + return out + } + if err := validateWorkspaceMoveRequest(req); err != nil { + out.Reason = err.Error() + return out + } + if _, replay, err := p.issuedWorkspaceReplayLocked(req); err != nil { + out.Reason = err.Error() + return out + } else if replay { + out.Admitted, out.Replay = true, true + out.Reason = "request id already issued: a move with it returns the stored grant" + if lr, ok := p.lostRangeForRequestLocked(req.VolumeID, req.RequestID); ok { + out.LostUntilNS = lr.LostUntilNS + } + return out + } + _, line, ok := p.workspaceLineLocked(req.VolumeID) + s := p.workspace[req.VolumeID] + if !ok || line.info.Epoch != req.ExpectedEpoch || line.info.ReplicaID != req.ExpectedReplicaID || s == nil || s.Lease == nil { + out.Reason = "workspace move: missing or changed authority/lease" + return out + } + lostUntil, now, err := p.forcedMoveBarrierLocked(req.VolumeID, s.Lease) + out.LostUntilNS, out.NowNS = lostUntil, now.UnixNano() + if err != nil { + out.Reason = err.Error() + return out + } + out.Admitted = true + return out +} + +// WorkspaceMoveHeadAdmits reports whether head passes the HEAD rule of req +// (the same predicate a move applies). +func WorkspaceMoveHeadAdmits(req WorkspaceMoveRequest, head WorkspaceHead) bool { + return workspaceHeadAdmits(req, head) +} diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 7d35415762..ce19c81325 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "runtime" "strings" "sync" "sync/atomic" @@ -911,7 +912,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { case werr = <-writersDone: writersDone <- werr // keep it for the cleanup join case <-time.After(20 * time.Second): - t.Fatal("deadlock: writers did not finish after the release") + t.Fatal("deadlock: writers did not finish after the release", allGoroutineStacks()) } if werr != nil { t.Fatal("writer:", werr) @@ -919,7 +920,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { select { case <-closed: case <-time.After(20 * time.Second): - t.Fatal("deadlock: Close did not finish after the release") + t.Fatal("deadlock: Close did not finish after the release", allGoroutineStacks()) } time.Sleep(50 * time.Millisecond) // renewals continue after Close stopRenewers() @@ -928,7 +929,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { select { case <-settled: case <-time.After(20 * time.Second): - t.Fatal("deadlock: renewers did not finish") + t.Fatal("deadlock: renewers did not finish", allGoroutineStacks()) } if s := time.Duration(slowest.Load()); s >= 2*time.Second { @@ -1218,3 +1219,16 @@ func TestLeaseTestClockMonotonicAcrossFreezeResume(t *testing.T) { t.Fatal(e) } } + +// allGoroutineStacks returns the stack of every goroutine on a new line, so +// that a stall reported by a test shows where each party is blocked. +func allGoroutineStacks() string { + buf := make([]byte, 1<<20) + for { + n := runtime.Stack(buf, true) + if n < len(buf) { + return string('\n') + string(buf[:n]) + } + buf = make([]byte, 2*len(buf)) + } +} diff --git a/seaweed-block/core/authority/workspace_lost_range.go b/seaweed-block/core/authority/workspace_lost_range.go index 40d26cd5ae..74198aa17a 100644 --- a/seaweed-block/core/authority/workspace_lost_range.go +++ b/seaweed-block/core/authority/workspace_lost_range.go @@ -16,6 +16,11 @@ import ( // none of them was acknowledged later than LostUntilNS (master time: the // forced barrier, the lease horizon or restart deadline plus skew). The // lease carries no write frontier, so the upper bound is a time. +// +// HeadTimeNS is the kept HEAD entry's filer mtime, read with that HEAD at the +// move; 0 means unknown (the filer gave none, or the record predates the +// field). It is stored apart from the checksummed v1 range body (see +// lostRangeEnvelope) so the encoding of the ranges themselves is unchanged. type WorkspaceLostRange struct { RequestID string NewEpoch uint64 @@ -23,17 +28,82 @@ type WorkspaceLostRange struct { OldEpoch uint64 LostAfterLSN uint64 LostUntilNS int64 + HeadTimeNS int64 `json:"-"` } // lostRangeFileExtension does not end in storeFileExtension: authority // loaders, old and new, never read these files. const lostRangeFileExtension = ".lostrange.json" +// lostRangeEnvelope: Checksum covers VolumeID and Ranges exactly as before +// HEAD times existed, so a binary that predates them still verifies and +// loads the file (it ignores the two fields after it). HeadTimes carries the +// non-zero HEAD times; HeadTimesChecksum covers VolumeID, Ranges and +// HeadTimes together, and a file with HeadTimes but without a matching +// HeadTimesChecksum fails its checks. type lostRangeEnvelope struct { - Version int `json:"v"` - VolumeID string `json:"volume"` - Ranges []WorkspaceLostRange `json:"ranges"` - Checksum string `json:"checksum"` + Version int `json:"v"` + VolumeID string `json:"volume"` + Ranges []WorkspaceLostRange `json:"ranges"` + Checksum string `json:"checksum"` + HeadTimes []lostRangeHeadTime `json:"head_times,omitempty"` + HeadTimesChecksum string `json:"head_times_checksum,omitempty"` +} + +type lostRangeHeadTime struct { + RequestID string + NewEpoch uint64 + HeadTimeNS int64 +} + +func lostRangeHeadTimesChecksum(volumeID string, ranges []WorkspaceLostRange, times []lostRangeHeadTime) string { + body, err := json.Marshal(struct { + VolumeID string + Ranges []WorkspaceLostRange + HeadTimes []lostRangeHeadTime + }{volumeID, ranges, times}) + if err != nil { + return "" + } + sum := sha256.Sum256(body) + return hex.EncodeToString(sum[:]) +} + +func encodeLostRangeEnvelope(volumeID string, ranges []WorkspaceLostRange) lostRangeEnvelope { + env := lostRangeEnvelope{Version: 1, VolumeID: volumeID, Ranges: ranges, Checksum: lostRangeChecksum(volumeID, ranges)} + for _, r := range ranges { + if r.HeadTimeNS != 0 { + env.HeadTimes = append(env.HeadTimes, lostRangeHeadTime{RequestID: r.RequestID, NewEpoch: r.NewEpoch, HeadTimeNS: r.HeadTimeNS}) + } + } + if len(env.HeadTimes) > 0 { + env.HeadTimesChecksum = lostRangeHeadTimesChecksum(volumeID, ranges, env.HeadTimes) + } + return env +} + +// decodeLostRangeHeadTimes checks env's HEAD times and copies them onto its +// ranges. +func decodeLostRangeHeadTimes(env *lostRangeEnvelope) error { + if len(env.HeadTimes) == 0 && env.HeadTimesChecksum == "" { + return nil + } + if env.HeadTimesChecksum != lostRangeHeadTimesChecksum(env.VolumeID, env.Ranges, env.HeadTimes) { + return errors.New("head times checksum mismatch") + } + for _, t := range env.HeadTimes { + found := false + for i := range env.Ranges { + if env.Ranges[i].RequestID == t.RequestID && env.Ranges[i].NewEpoch == t.NewEpoch { + env.Ranges[i].HeadTimeNS = t.HeadTimeNS + found = true + } + } + if !found { + return fmt.Errorf("head time for unknown range %s/%d", t.RequestID, t.NewEpoch) + } + } + return nil } func lostRangeChecksum(volumeID string, ranges []WorkspaceLostRange) string { @@ -54,7 +124,7 @@ func (s *FileAuthorityStore) PutWorkspaceLostRanges(volumeID string, ranges []Wo if volumeID == "" { return fmt.Errorf("authority_store: lost range with empty VolumeID") } - payload, err := json.Marshal(lostRangeEnvelope{Version: 1, VolumeID: volumeID, Ranges: ranges, Checksum: lostRangeChecksum(volumeID, ranges)}) + payload, err := json.Marshal(encodeLostRangeEnvelope(volumeID, ranges)) if err != nil { return fmt.Errorf("authority_store: encode lost range: %w", err) } @@ -136,6 +206,8 @@ func (s *FileAuthorityStore) LoadWorkspaceLostRanges() (map[string][]WorkspaceLo err = errors.New("checksum mismatch") case encodeVolumeIDForFilename(env.VolumeID)+lostRangeFileExtension != name: err = fmt.Errorf("filename does not match VolumeID %q", env.VolumeID) + default: + err = decodeLostRangeHeadTimes(&env) } if err != nil { skips = append(skips, fmt.Errorf("%s: %w: lost range %v", name, ErrCorruptRecord, err)) @@ -189,6 +261,51 @@ func (p *Publisher) recordLostRangeLocked(volume string, r WorkspaceLostRange) e return nil } +// ErrWorkspaceLostRangeMissing: an issued forced move has no readable lost +// range (never written, or its file failed its checks at load and was +// skipped). The readout is unproven; it must never be reported as no loss. +var ErrWorkspaceLostRangeMissing = errors.New("workspace lost range missing or unreadable") + +// ErrWorkspaceNoForcedMove: the request id names no issued forced move. +var ErrWorkspaceNoForcedMove = errors.New("workspace: no issued forced move with that request id") + +// WorkspaceLostRangeReadout is one stored lost range with the stored move +// record it belongs to (the HEAD generation the move kept, and the hosts). +type WorkspaceLostRangeReadout struct { + WorkspaceLostRange + VolumeID string + HeadGen uint64 + OldHost, NewHost string +} + +// WorkspaceLostRangeReadouts returns the stored lost range of every issued +// forced move of volume, in journal (issue) order, or only requestID's when +// it is not empty. Nothing is recomputed. Any issued forced move in scope +// whose range is not loaded fails the whole read with +// ErrWorkspaceLostRangeMissing; an empty result means the volume has no +// issued forced move. +func (p *Publisher) WorkspaceLostRangeReadouts(volume, requestID string) ([]WorkspaceLostRangeReadout, error) { + p.mu.Lock() + defer p.mu.Unlock() + var out []WorkspaceLostRangeReadout + if s := p.workspace[volume]; s != nil { + for _, m := range s.Moves { + if !m.Issued || m.Kind != "forced" || (requestID != "" && m.RequestID != requestID) { + continue + } + r, ok := p.lostRangeLocked(volume, m.RequestID, m.NewEpoch) + if !ok { + return nil, fmt.Errorf("%w: forced move %q (epoch %d -> %d) of volume %q has no loaded lost range record", ErrWorkspaceLostRangeMissing, m.RequestID, m.OldEpoch, m.NewEpoch, volume) + } + out = append(out, WorkspaceLostRangeReadout{WorkspaceLostRange: r, VolumeID: volume, HeadGen: m.HeadGen, OldHost: m.OldHost, NewHost: m.NewHost}) + } + } + if requestID != "" && len(out) == 0 { + return nil, fmt.Errorf("%w: %q on volume %q", ErrWorkspaceNoForcedMove, requestID, volume) + } + return out, nil +} + // WorkspaceLostRanges returns the lost ranges of volume's issued forced // moves (an entry with no matching issued move is ignored). func (p *Publisher) WorkspaceLostRanges(volume string) []WorkspaceLostRange { @@ -209,3 +326,16 @@ func (p *Publisher) WorkspaceLostRanges(volume string) []WorkspaceLostRange { } return out } + +// lostRangeForRequestLocked returns the recorded range of requestID's +// journal record, if any. Called under p.mu. +func (p *Publisher) lostRangeForRequestLocked(volume, requestID string) (WorkspaceLostRange, bool) { + if s := p.workspace[volume]; s != nil { + for _, m := range s.Moves { + if m.RequestID == requestID { + return p.lostRangeLocked(volume, requestID, m.NewEpoch) + } + } + } + return WorkspaceLostRange{}, false +} diff --git a/seaweed-block/core/authority/workspace_lost_range_readout_test.go b/seaweed-block/core/authority/workspace_lost_range_readout_test.go new file mode 100644 index 0000000000..7dc5e6d5cb --- /dev/null +++ b/seaweed-block/core/authority/workspace_lost_range_readout_test.go @@ -0,0 +1,339 @@ +package authority + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" +) + +// The HEAD time a forced move kept, as the filer reported it with HEAD. +var headFilerTime = time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC) + +// pastBarrier moves now past the forced barrier of v's current lease. +func pastBarrier(t *testing.T, p *Publisher, now *time.Time) { + t.Helper() + st := p.WorkspaceState("v") + if st == nil || st.Lease == nil { + t.Fatal("no lease") + } + barrier := time.Unix(0, st.Lease.ExpiresAtNS) + if d := p.leaseDeadlineLockedForTest("v"); d.After(barrier) { + barrier = d + } + *now = barrier.Add(p.workspaceSkew(st.Lease)).Add(time.Second) +} + +// INV-WS-LOST-RANGE-READOUT-001: a forced move stores the kept HEAD's filer +// time with its range; the readout returns it, with the move record's HEAD +// generation, also after a reload. A range with a HEAD time keeps the v1 +// checksum over the ranges, so a binary that predates HEAD times still +// verifies the file; a range without one is written exactly as before. +func TestWorkspaceForcedMoveStoresHeadFilerTime(t *testing.T) { + for _, known := range []bool{true, false} { + t.Run(map[bool]string{true: "filer time known", false: "filer time unknown"}[known], func(t *testing.T) { + disk, dir := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, false) + *now = barrier.Add(time.Second) + head := forcedLostRangeHead + if known { + head.FilerMtimeNS = headFilerTime.UnixNano() + } + r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, head) + if err != nil { + t.Fatal(err) + } + want := WorkspaceLostRangeReadout{WorkspaceLostRange: WorkspaceLostRange{RequestID: "f", NewEpoch: r.NewEpoch, OldReplicaID: "old", OldEpoch: 1, LostAfterLSN: 42, LostUntilNS: barrier.UnixNano(), HeadTimeNS: head.FilerMtimeNS}, + VolumeID: "v", HeadGen: 7, OldHost: "old-node", NewHost: "new-node"} + for name, q := range map[string]*Publisher{"running": p, "reloaded": NewPublisher(nil, WithStore(disk))} { + got, err := q.WorkspaceLostRangeReadouts("v", "") + if err != nil || len(got) != 1 || got[0] != want { + t.Fatalf("%s: readout %+v %v; want [%+v]", name, got, err, want) + } + } + raw, err := os.ReadFile(filepath.Join(dir, "v"+lostRangeFileExtension)) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(raw), "head_times") != known { + t.Fatalf("head times present=%v in %s", !known, raw) + } + // What a binary that predates HEAD times reads and checks. + type oldRange struct { + RequestID string + NewEpoch uint64 + OldReplicaID string + OldEpoch uint64 + LostAfterLSN uint64 + LostUntilNS int64 + } + var old struct { + Version int `json:"v"` + VolumeID string `json:"volume"` + Ranges []oldRange `json:"ranges"` + Checksum string `json:"checksum"` + } + if err := json.Unmarshal(raw, &old); err != nil { + t.Fatal(err) + } + body, _ := json.Marshal(struct { + VolumeID string + Ranges []oldRange + }{old.VolumeID, old.Ranges}) + sum := sha256.Sum256(body) + if old.Version != 1 || old.Checksum != hex.EncodeToString(sum[:]) || len(old.Ranges) != 1 || old.Ranges[0].LostAfterLSN != 42 { + t.Fatalf("an older binary would not verify the file: %s", raw) + } + }) + } +} + +// A HEAD time changed on disk without its checksum fails the file's checks: +// the readout then fails, never "no loss" and never a wrong time. +func TestWorkspaceLostRangeHeadTimeTamperFailsClosed(t *testing.T) { + disk, dir := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, false) + *now = barrier.Add(time.Second) + head := forcedLostRangeHead + head.FilerMtimeNS = headFilerTime.UnixNano() + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, head); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "v"+lostRangeFileExtension) + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var env map[string]any + if err := json.Unmarshal(raw, &env); err != nil { + t.Fatal(err) + } + env["head_times"].([]any)[0].(map[string]any)["HeadTimeNS"] = float64(headFilerTime.Add(time.Hour).UnixNano()) + tampered, _ := json.Marshal(env) + if err := os.WriteFile(path, tampered, 0o644); err != nil { + t.Fatal(err) + } + reloaded := NewPublisher(nil, WithStore(disk)) + if _, err := reloaded.WorkspaceLostRangeReadouts("v", ""); !errors.Is(err, ErrWorkspaceLostRangeMissing) { + t.Fatalf("tampered head time: %v; want ErrWorkspaceLostRangeMissing", err) + } + if !loadErrorsMention(reloaded, "head times checksum mismatch") { + t.Fatalf("load errors %v do not name the failed check", reloaded.LoadErrors()) + } +} + +func loadErrorsMention(p *Publisher, s string) bool { + for _, e := range p.LoadErrors() { + if strings.Contains(e.Error(), s) { + return true + } + } + return false +} + +// Accumulation: a second forced move with no cut between (HEAD unchanged, +// still at the first holder's epoch) keeps the same LostAfterLSN with a +// later LostUntil; a forced move after a new cut starts at the new HEAD. The +// readout lists every range in issue order, or one by request id; replays +// return the stored ranges, never recomputed ones. +func TestWorkspaceLostRangeAccumulatesInIssueOrder(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, false) + *now = barrier.Add(time.Second) + h1 := forcedLostRangeHead + h1.FilerMtimeNS = headFilerTime.UnixNano() + f1, err := p.MoveWorkspace(ctx, forcedLostRangeReq, h1) // old-node -> new-node, epoch 1 -> 2 + if err != nil { + t.Fatal(err) + } + pastBarrier(t, p, now) + f2req := WorkspaceMoveRequest{RequestID: "f2", VolumeID: "v", ExpectedReplicaID: "old", TargetReplicaID: "old", ExpectedHost: "new-node", TargetHost: "third-node", + ExpectedEpoch: f1.NewEpoch, TargetDataAddr: "td", TargetCtrlAddr: "tc", Kind: "forced", Force: true} + f2, err := p.MoveWorkspace(ctx, f2req, h1) // the grantee never cut: HEAD unchanged + if err != nil { + t.Fatal(err) + } + pastBarrier(t, p, now) + h3 := WorkspaceHead{Gen: 8, Epoch: f2.NewEpoch, Holder: "third-node/old", RemoteLSN: 50, FilerMtimeNS: headFilerTime.Add(time.Minute).UnixNano()} + f3req := WorkspaceMoveRequest{RequestID: "f3", VolumeID: "v", ExpectedReplicaID: "old", TargetReplicaID: "old", ExpectedHost: "third-node", TargetHost: "old-node", + ExpectedEpoch: f2.NewEpoch, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} + if _, err := p.MoveWorkspace(ctx, f3req, h3); err != nil { + t.Fatal(err) + } + got, err := p.WorkspaceLostRangeReadouts("v", "") + if err != nil || len(got) != 3 { + t.Fatalf("readout %+v %v; want three ranges", got, err) + } + if got[0].RequestID != "f" || got[1].RequestID != "f2" || got[2].RequestID != "f3" { + t.Fatalf("not in issue order: %+v", got) + } + if got[1].LostAfterLSN != got[0].LostAfterLSN || got[1].LostUntilNS <= got[0].LostUntilNS || got[1].HeadGen != 7 || got[1].HeadTimeNS != h1.FilerMtimeNS { + t.Fatalf("no cut between: want the same LostAfterLSN, a later LostUntil and the same HEAD: %+v then %+v", got[0], got[1]) + } + if got[2].LostAfterLSN != 50 || got[2].HeadGen != 8 || got[2].HeadTimeNS != h3.FilerMtimeNS || got[2].LostUntilNS <= got[1].LostUntilNS { + t.Fatalf("after a cut: want a range from the new HEAD: %+v", got[2]) + } + one, err := p.WorkspaceLostRangeReadouts("v", "f2") + if err != nil || len(one) != 1 || one[0] != got[1] { + t.Fatalf("by request id: %+v %v; want [%+v]", one, err, got[1]) + } + if _, err := p.WorkspaceLostRangeReadouts("v", "nope"); !errors.Is(err, ErrWorkspaceNoForcedMove) { + t.Fatalf("unknown request id: %v", err) + } + // A replay much later, after a reload, returns the stored grant and the + // stored range: nothing is recomputed from the replay's clock or HEAD. + *now = now.Add(time.Hour) + q := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, func() time.Time { return *now })) + r2, err := q.MoveWorkspace(ctx, f2req, WorkspaceHead{Gen: 99, Epoch: 9, Holder: "x/y", RemoteLSN: 999, FilerMtimeNS: 1}) + if err != nil || r2 != f2 { + t.Fatalf("replay %+v %v; want the stored grant %+v", r2, err, f2) + } + again, err := q.WorkspaceLostRangeReadouts("v", "") + if err != nil || len(again) != 3 || again[0] != got[0] || again[1] != got[1] || again[2] != got[2] { + t.Fatalf("after reload and replay: %+v %v; want %+v", again, err, got) + } +} + +// Fail closed: an issued forced move whose range file is missing, or fails +// its checksum, makes the readout fail (all ranges, or its own); it never +// returns an empty "no loss". +func TestWorkspaceLostRangeReadoutFailsClosed(t *testing.T) { + for _, damage := range []string{"missing", "checksum"} { + t.Run(damage, func(t *testing.T) { + disk, dir := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, false) + *now = barrier.Add(time.Second) + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "v"+lostRangeFileExtension) + if damage == "missing" { + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + } else { + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(strings.Replace(string(raw), `"LostAfterLSN":42`, `"LostAfterLSN":43`, 1)), 0o644); err != nil { + t.Fatal(err) + } + } + reloaded := NewPublisher(nil, WithStore(disk)) + for _, id := range []string{"", "f"} { + got, err := reloaded.WorkspaceLostRangeReadouts("v", id) + if !errors.Is(err, ErrWorkspaceLostRangeMissing) || got != nil { + t.Fatalf("request %q: %+v %v; want ErrWorkspaceLostRangeMissing", id, got, err) + } + } + if damage == "checksum" && !loadErrorsMention(reloaded, "checksum mismatch") { + t.Fatalf("load errors %v", reloaded.LoadErrors()) + } + }) + } +} + +// skipRangeStore drops the lost range write but reports success: the +// mutant "grant issued, range write skipped". +type skipRangeStore struct{ *FileAuthorityStore } + +func (skipRangeStore) PutWorkspaceLostRanges(string, []WorkspaceLostRange) error { return nil } + +// The mutant "grant issued, range write skipped" is detected: the move +// issues (the store claimed the range durable), but the readout of a master +// that reloads from disk fails closed instead of reporting no loss. (The +// order itself, range before issue, is TestWorkspaceForcedMoveLostRangeOrdering.) +func TestWorkspaceLostRangeSkippedWriteIsDetected(t *testing.T) { + disk, _ := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, skipRangeStore{disk}, false) + *now = barrier.Add(time.Second) + if r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err != nil || !r.Issued { + t.Fatalf("fixture: %+v %v", r, err) + } + if _, err := NewPublisher(nil, WithStore(disk)).WorkspaceLostRangeReadouts("v", "f"); !errors.Is(err, ErrWorkspaceLostRangeMissing) { + t.Fatalf("skipped range write not detected: %v", err) + } +} + +// countWritesStore counts every durable write, authority and lost range. +type countWritesStore struct { + *FileAuthorityStore + writes atomic.Int64 +} + +func (s *countWritesStore) Put(r DurableRecord) error { + s.writes.Add(1) + return s.FileAuthorityStore.Put(r) +} + +func (s *countWritesStore) PutWorkspaceLostRanges(v string, rs []WorkspaceLostRange) error { + s.writes.Add(1) + return s.FileAuthorityStore.PutWorkspaceLostRanges(v, rs) +} + +// The preview runs the forced admission and writes nothing: before the +// barrier it is refused and names the barrier (when it becomes admissible); +// after it, it is admitted, and the move then records exactly that barrier +// as LostUntil. A replay previews as admitted with the stored bound. +func TestWorkspaceForcedMovePreviewWritesNothing(t *testing.T) { + disk, dir := newTempStore(t) + store := &countWritesStore{FileAuthorityStore: disk} + p, now, barrier := forcedLostRangeFixture(t, store, false) + before, state := store.writes.Load(), p.WorkspaceState("v") + *now = barrier.Add(-time.Nanosecond) + pv := p.PreviewWorkspaceForcedMove(forcedLostRangeReq) + if pv.Admitted || pv.LostUntilNS != barrier.UnixNano() || pv.NowNS != now.UnixNano() || !strings.Contains(pv.Reason, "has not elapsed") { + t.Fatalf("preview before the barrier: %+v", pv) + } + *now = barrier.Add(time.Second) + pv = p.PreviewWorkspaceForcedMove(forcedLostRangeReq) + if !pv.Admitted || pv.LostUntilNS != barrier.UnixNano() || pv.Replay { + t.Fatalf("preview after the barrier: %+v", pv) + } + bad := forcedLostRangeReq + bad.ExpectedEpoch = 5 + if pv := p.PreviewWorkspaceForcedMove(bad); pv.Admitted || !strings.Contains(pv.Reason, "missing or changed authority/lease") { + t.Fatalf("preview at a stale epoch: %+v", pv) + } + clean := forcedLostRangeReq + clean.Kind, clean.Force = "clean", false + if pv := p.PreviewWorkspaceForcedMove(clean); pv.Admitted { + t.Fatalf("preview of a clean move: %+v", pv) + } + if !WorkspaceMoveHeadAdmits(forcedLostRangeReq, forcedLostRangeHead) || WorkspaceMoveHeadAdmits(forcedLostRangeReq, WorkspaceHead{Gen: 9, Epoch: 1, Holder: "other/old"}) { + t.Fatal("the preview's HEAD rule differs from the move's") + } + if got := store.writes.Load(); got != before { + t.Fatalf("preview wrote %d times", got-before) + } + if after := p.WorkspaceState("v"); len(after.Moves) != len(state.Moves) || *after.Lease != *state.Lease { + t.Fatalf("preview changed state: %+v -> %+v", state, after) + } + if m, _ := filepath.Glob(filepath.Join(dir, "*"+lostRangeFileExtension)); len(m) != 0 { + t.Fatalf("preview wrote a lost range file: %v", m) + } + r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead) + if err != nil { + t.Fatal(err) + } + if got := p.WorkspaceLostRanges("v"); len(got) != 1 || got[0].LostUntilNS != pv.LostUntilNS { + t.Fatalf("move recorded %+v; the preview named %d", got, pv.LostUntilNS) + } + writes := store.writes.Load() + *now = now.Add(time.Hour) + if pv := p.PreviewWorkspaceForcedMove(forcedLostRangeReq); !pv.Admitted || !pv.Replay || pv.LostUntilNS != barrier.UnixNano() { + t.Fatalf("preview of the issued request %+v (grant %+v)", pv, r) + } + if store.writes.Load() != writes { + t.Fatal("replay preview wrote") + } +} diff --git a/seaweed-block/core/authority/workspace_outcome_uncertain_test.go b/seaweed-block/core/authority/workspace_outcome_uncertain_test.go new file mode 100644 index 0000000000..aab5f3ec8e --- /dev/null +++ b/seaweed-block/core/authority/workspace_outcome_uncertain_test.go @@ -0,0 +1,69 @@ +package authority + +import ( + "context" + "errors" + "testing" + "time" +) + +// An issuing write that lands in the store but reports an error (the +// directory sync after the rename) leaves the move's outcome unknown: +// MoveWorkspace fails with ErrWorkspaceOutcomeUncertain while memory shows +// it unissued, a retry before a reload fails the same way, and a reload finds +// it issued and replays it. Ordinary refusals (admission before the barrier, +// a failed lost-range write before the issue) are not marked uncertain. +func TestWorkspaceUncertainIssueWriteIsTyped(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, false) + req := forcedLostRangeReq + req.RequestID = "uncertain-1" + + *now = barrier.Add(-time.Nanosecond) + if _, err := p.MoveWorkspace(ctx, req, forcedLostRangeHead); err == nil || errors.Is(err, ErrWorkspaceOutcomeUncertain) { + t.Fatalf("admission refusal before the barrier: %v; want a plain refusal", err) + } + *now = barrier.Add(time.Second) + testLostRangeFaultHook = func(string) error { return errInjected } + t.Cleanup(func() { testLostRangeFaultHook = nil }) + if _, err := p.MoveWorkspace(ctx, req, forcedLostRangeHead); !errors.Is(err, errInjected) || errors.Is(err, ErrWorkspaceOutcomeUncertain) { + t.Fatalf("lost-range write failure before the issue: %v; want a plain refusal", err) + } + testLostRangeFaultHook = nil + + faults := 0 + SetPutAfterRenameFaultForTest(func(r DurableRecord) error { + if r.Workspace != nil { + for _, m := range r.Workspace.Moves { + if m.RequestID == req.RequestID && m.Issued { + faults++ + return errInjected + } + } + } + return nil + }) + t.Cleanup(func() { SetPutAfterRenameFaultForTest(nil) }) + if _, err := p.MoveWorkspace(ctx, req, forcedLostRangeHead); !errors.Is(err, ErrWorkspaceOutcomeUncertain) { + t.Fatalf("issuing write landed then failed: %v; want ErrWorkspaceOutcomeUncertain", err) + } + SetPutAfterRenameFaultForTest(nil) + if faults != 1 || p.IssuedWorkspaceMove(req) { + t.Fatalf("fixture: faults=%d issued in memory=%v; want one fault and memory unissued", faults, p.IssuedWorkspaceMove(req)) + } + if _, err := p.MoveWorkspace(ctx, req, forcedLostRangeHead); !errors.Is(err, ErrWorkspaceOutcomeUncertain) { + t.Fatalf("retry before a reload: %v; want ErrWorkspaceOutcomeUncertain", err) + } + reloaded := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, func() time.Time { return *now })) + if !reloaded.IssuedWorkspaceMove(req) { + t.Fatal("the reloaded store does not hold the issued move") + } + r, err := reloaded.MoveWorkspace(ctx, req, WorkspaceHead{}) + if err != nil || !r.Issued || r.RequestID != req.RequestID { + t.Fatalf("replay after reload: %+v %v", r, err) + } + if got, err := reloaded.WorkspaceLostRangeReadouts("v", req.RequestID); err != nil || len(got) != 1 || got[0].LostAfterLSN != 42 { + t.Fatalf("readout after reload: %+v %v", got, err) + } +} diff --git a/seaweed-block/core/engine/projection.go b/seaweed-block/core/engine/projection.go index b2df857375..01e1f41418 100644 --- a/seaweed-block/core/engine/projection.go +++ b/seaweed-block/core/engine/projection.go @@ -13,16 +13,16 @@ const ( // ReplicaProjection is the operator-facing view derived from state. // Intentionally descriptive. Must NEVER be reused as control truth. type ReplicaProjection struct { - Mode Mode - RecoveryDecision RecoveryDecision - SessionKind SessionKind - SessionPhase SessionPhase - Epoch uint64 - EndpointVersion uint64 - R uint64 - S uint64 - H uint64 - Reason string + Mode Mode // the engine mode (idle, recovering, healthy, degraded) + RecoveryDecision RecoveryDecision // the recovery class the R/S/H boundaries call for + SessionKind SessionKind // the kind of the current recovery session, if any + SessionPhase SessionPhase // its phase + Epoch uint64 // the authority epoch + EndpointVersion uint64 // the endpoint version within the epoch + R uint64 // the replica's durable boundary (LSN) + S uint64 // the primary's recoverable start boundary (WAL tail LSN) + H uint64 // the primary's target boundary (head LSN) + Reason string // why the engine is in this mode or decision } // DeriveProjection computes the projection from current state. diff --git a/seaweed-block/core/frontend/chunkstore/GC.md b/seaweed-block/core/frontend/chunkstore/GC.md index 8a3ad3bb9f..c3b5a5c883 100644 --- a/seaweed-block/core/frontend/chunkstore/GC.md +++ b/seaweed-block/core/frontend/chunkstore/GC.md @@ -103,3 +103,161 @@ This test requires the binary and fails rather than skips when it is absent. It It advances only the GC clock to exercise grace admission deterministically; network services, conditional metadata writes, authority RPC and blob deletion are real. It is not an elapsed-time soak or a lab qualification. + +## Single filer + +Every command that writes chunk metadata (`snapshot-delete`, `fork`, `retain` +without `--dry-run`, `volume-delete`, `gc --apply`) and `verify` make the same +start check as blockvolume before they read or write anything: it asks the +filer for its masters and filer group, and refuses unless a master lists +exactly one filer in that group and it is the `--chunk-filer` given. `verify` +writes nothing, but against a split filer view it would report false +findings. The other read-only commands and modes do not run the check. A +filer that is not the only one of its group exits 2 with code `bad_request`; +a check that cannot finish (a filer or master that does not answer) exits 1 +with code `remote_unavailable`, retryable. The check runs within the command's +`--timeout`. The masters the filer reports must be reachable from where the +command runs. + +## Verify + +`sw-block ops chunk verify` compares one volume's remote image with what its +HEAD, and optionally its snapshots, say. It is read-only: it writes no intent, +mark, tombstone or binding, and deletes nothing. + +```sh +sw-block ops chunk verify --volume v1 --chunk-filer 127.0.0.1:18888 \ + [--chunk-path /swblock/chunks] [--snapshot s1 | --all-snapshots] \ + [--depth meta|bindings|data] [--concurrency 2] [--bytes-per-sec 33554432] \ + [--timeout 10m] +``` + +HEAD is always checked. `--snapshot` adds one named snapshot; `--all-snapshots` +adds every published snapshot that is not being deleted. Each depth includes the +one before it: + +- `meta`: the HEAD root decodes and is self-consistent; its chunk size and chunk + indices fit the VOLUME geometry; every segment a checked root names is + readable, matches its SHA-256 and decodes strictly; the same for each checked + snapshot's embedded HEAD; a snapshot's document names the volume and the + snapshot it was found under (else `ROOT_INVALID`; the snapshot is still + checked under the name it was found under); references to one + chunk with different SHA-256s disagree (`CONTENT_MISMATCH`); for a fork, its + fork record's digest matches an attempt of the parent snapshot at the + recorded generation. +- `bindings` (the default): also, every chunk key a checked root references has + a binding in its owner's `keys/` (a fork's `@owner/key` resolves to the owner + volume), of the right kind, with a fid, without filer chunks, and not + tombstoned by GC. Each owner's `keys/` is listed once. GC's mark does not make + this check: it never looks up the bindings of the keys it roots. +- `data`: also, every distinct chunk (owner and key, across all checked roots) + is read once, and its SHA-256 must equal the reference and its length the + chunk size, the rule a guest read applies. `--depth data` requires an explicit + `--timeout`. Reads are bounded by `--concurrency` and paced by + `--bytes-per-sec` (0 leaves them unpaced). + +Old capture intents below HEAD's epoch that name no key HEAD references are +reported as `INTENT_STALE`. This is a hint only: whether GC may expire an intent +remains GC's decision, with blockmaster authority. + +The output is one JSON object: the HEAD generations and snapshots covered, +segments and chunks checked, distinct chunks and bytes read, the two counters +below, findings by class, and the findings, one per line. Each finding +names the volume, the root (`HEAD gen N`, `snapshot name/attempt`, an intent or +the VOLUME fork record), the chunk index or segment, the owner, key and fid, a +class and a detail. Classes: `ROOT_INVALID`, `GEOMETRY`, `SEGMENT_UNREADABLE`, +`BINDING_MISSING`, `BINDING_TOMBSTONED`, `NEEDLE_MISSING`, `CONTENT_MISMATCH`, +`SIZE_MISMATCH`, `FORK_RECORD_MISMATCH`, `INTENT_STALE`, `READ_ERROR`. + +`NEEDLE_MISSING` means the blob store answered that the needle does not exist +(for SeaweedFS: HTTP 404 from every location of a fresh volume lookup; when the +cached locations all answer 404, the volume is looked up again, since it may +have moved). Any other read failure, such as a +timeout, a refused or reset connection, or another HTTP status, is retried twice +with a short backoff. If it still fails, the chunk or segment is reported as +`READ_ERROR`, with the error in the detail. `READ_ERROR` is not evidence of +damage: it means that object was **not verified**. Re-run verify, after fixing +the store's reachability if needed. The summary counts these objects separately +in `chunksNotRead`, and `readRetries` counts the retried reads. The rule below +applies to `READ_ERROR` as to any other bad outcome. + +### Running beside a live owner and beside GC + +Segments and chunks are immutable and written before the root that names them, +so a root read once and the segments it names are a consistent view. But nothing +registers a reader with GC: a chunk that leaves a root can be collected once +GC's grace has passed, and a long pass can outlive that. So verify checks each +chunk once, records its outcome, and computes the findings only at the end, from +those outcomes and the roots at its final read: + +- HEAD is read again at least every 2 minutes during a long pass (a newer + generation replaces the view; only segments whose key changed are read again; + chunks it names that the pass has not seen are added and checked). +- When every chunk is checked, verify reads HEAD and each checked snapshot's state + once more. If that read names a chunk not seen, verify checks it and reads + again, at most 3 times; the read that names nothing new is the final read, and + no read follows it. Only a HEAD that decodes can be part of it: if that read + finds no HEAD, or one that does not decode, the final view has no HEAD root and + the pass is incomplete. +- Chunks and segments alike are read once per key, whatever reference names them, + and keep that one outcome: the content (a segment keeps its bytes), or binding + missing or tombstoned, needle missing, or a read error. +- At the end, each reference is judged against that one outcome, the same way + whatever the order the pass met them in: a bad outcome stays that outcome; a + reference with another hash is a `CONTENT_MISMATCH`; a chunk that matches its + reference but is not a chunk long is a `SIZE_MISMATCH`; a segment that does not + decode under that reference's own fields is `SEGMENT_UNREADABLE`; else it is + sound (and a sound segment reference gives that root its chunks). +- For each object and class a reference of the final read has, there is one + finding, under the first root having such a reference (HEAD, then the snapshots + still active, in order), at its first such index. +- A chunk or segment that had a problem under any reference the pass saw (or a bad + outcome) but has no finding, because no reference of the final read has one, is + counted once: in `rootDeletedDuringVerify` when a checked snapshot that was + deleted during the pass carried a problem reference, otherwise in + `supersededDuringVerify`. This includes an object still named, but only by sound + references. Deleted snapshots are listed in `snapshotsDeletedDuringVerify` as not + fully covered. The counters do not make a pass unclean. +- A key that an earlier HEAD read named, a later one did not, and the final HEAD + names again is a `ROOT_INVALID` finding ("HEAD names a key it had dropped"), + whatever its chunk's state: a key that left every root may have been collected, + and must not come back. + +A finding describes each chunk as it was when checked, for the roots at the final +read; a chunk damaged after its check is the next pass's finding. + +A pass that cannot finish is **incomplete**, never clean: `complete` is false and +`incomplete` gives the reason: `deadline`, `cancelled`, `error` (a filer or blob +store failure, a refused request, or a final read that returned an older HEAD), +`closing_rounds_exhausted` (each of the 3 final reads named new chunks: the volume +is too busy; re-run), `head_absent` (the final read found no HEAD) or +`head_invalid` (the final read's HEAD does not decode; also a `ROOT_INVALID` +finding). Its findings are those computed from the chunks it did check, for the +roots of its last view (none for HEAD in the last two cases). + +### What verify cannot check + +- Orphan needles: a needle uploaded whose binding was never written cannot be + enumerated. +- Which block inside a chunk is bad: there is one SHA-256 per chunk. +- A data chunk's size without reading it: bindings and references store no size. +- The HEAD root against an independent value: no checksum of the root is stored. +- Whether the image equals the volume's content at its remote LSN: only the + holder's local volume could say. +- Past HEAD generations, forced-move lost ranges (kept outside the filer), and + any verification history (nothing records it). +- Each replica of a needle: a read stops at the first replica that answers. + +### Exit codes + +- `0`: the pass completed with no finding. +- `3`: the pass completed with findings. This includes `READ_ERROR`: the pass + did not verify everything. +- `1`: the pass could not complete (the deadline passed, the filer failed, HEAD + kept naming new chunks, HEAD was gone or did not decode at the final read, or + the volume or snapshot does not exist). The error body + `{code,message,retryable}` is printed with the partial result, and its + `incomplete` reason, under `verify`. A single-filer start check that cannot + finish also exits 1 (`remote_unavailable`), before the pass, with no result. +- `2`: usage error, or the filer is not the only one of its group (`bad_request`, + before the pass, with no result). diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index eb6fd6f4eb..ade786fa78 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -36,7 +36,6 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/geometry" - "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "github.com/seaweedfs/seaweed-block/core/storage" @@ -70,9 +69,12 @@ const ( // SnapAbsent is DeleteSnapshot's answer for a snapshot that is not there. SnapAbsent = "absent" - // OriginCreate and OriginFork are a volume's origins. - OriginCreate = "create" - OriginFork = "fork" + // OriginCreate, OriginFork and OriginRestore are a volume's origins. A + // restore is a fork whose volume later becomes independent of its source + // (own chunks, restoreIndependentName written); until then it is a fork. + OriginCreate = "create" + OriginFork = "fork" + OriginRestore = "restore" // DefaultOpDeadline bounds a snapshot or fork from reading its source to // its final write (spec §2.3). @@ -250,6 +252,11 @@ type SnapshotRequest struct { // SourceReadAt is when the caller obtained the HEAD it snapshots (the // cut's return); OpDeadline counts from it. Zero means now. SourceReadAt time.Time + // ShareToken is the ShareGuard token of a caller that began the share + // before it obtained the HEAD (the owner's seal: Begin, then the cut). + // Empty: CreateSnapshot begins the share itself and refuses a HEAD that + // is no longer current. Unused without a guard; never stored. + ShareToken string } // ListOptions pages a snapshot listing. @@ -295,6 +302,8 @@ type Catalog struct { // retainHook, when set, runs at the named stages of a Retain pass (a // test seam for interleavings; see hookPlanned). retainHook func(stage, name string) + // guard, when set, is told about every share of a volume's chunks. + guard ShareGuard } // NewCatalog returns the catalog for the chunk base directory base (the @@ -395,10 +404,10 @@ func decodeVolume(p string, e *filerpb.Entry) (VolumeInfo, error) { if v.Format != volumeFormat { return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: format %d not supported", p, v.Format) } - if v.Origin != OriginCreate && v.Origin != OriginFork { + if v.Origin != OriginCreate && v.Origin != OriginFork && v.Origin != OriginRestore { return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: origin %q", p, v.Origin) } - if v.Origin == OriginFork && (v.Fork == nil || v.Fork.RequestID == "") { + if isForked(v.Origin) && (v.Fork == nil || v.Fork.RequestID == "") { return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: a fork without its fork record", p) } v.State = string(e.Extended[extVolState]) @@ -527,8 +536,10 @@ func (c *Catalog) EnsureVolume(ctx context.Context, vol string, g Geometry) (Vol return VolumeInfo{}, err } } - if v.Origin == OriginFork { + if isForked(v.Origin) { // One read of HEAD decides both: absent and aborted never attach. + // A restore reads only its own HEAD here, never its source: a source + // deleted meanwhile is a normal state, not a mismatch. h, has, err := c.ReadHead(ctx, vol) switch { case err != nil: @@ -748,11 +759,18 @@ func (c *Catalog) AbortSnapshot(ctx context.Context, vol, name, attempt string) // is confirmed or can never apply. It never touches another attempt's // intent, even under the same operation: an earlier attempt's create may // still be held by the server and land later (W5 rule). A failed delete -// leaves the intent, which only over-protects. +// leaves the intent, which only over-protects. The delete outlives the +// caller's cancellation (cleanup after a refused or cancelled request) but is +// bounded by dropIntentTimeout, so it can never hang on an unresponsive filer. func (c *Catalog) dropIntent(ctx context.Context, root, id string) { - _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(root, intentsDir), id, nil) + dctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dropIntentTimeout) + defer cancel() + _ = c.f.DeleteEntry(dctx, path.Join(root, intentsDir), id, nil) } +// dropIntentTimeout bounds one intent delete (a var so tests can shorten it). +var dropIntentTimeout = 30 * time.Second + type createOutcome int const ( @@ -859,6 +877,29 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe if !ok { return SnapshotInfo{}, catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", vol) } + if v.Origin == OriginRestore { + // A restore is independent only once its marker exists: a snapshot + // taken before would keep naming the source's chunks for its whole + // retention, so it is refused until then. + if _, independent, err := c.ReadIndependence(ctx, vol); err != nil { + return SnapshotInfo{}, err + } else if !independent { + return SnapshotInfo{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s is still being restored: snapshots are refused until it is independent", vol) + } + // The supplied image need not be the current HEAD: a cut taken before + // the marker may still name the source's chunks. Check the image itself. + if q, err := c.foreignRefsOf(ctx, vol, head); err != nil { + return SnapshotInfo{}, err + } else if q > 0 { + return SnapshotInfo{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s: snapshot image gen %d holds %d refs to another volume", vol, head.Gen, q) + } + } + shareToken := req.ShareToken + if shareToken == "" { + if shareToken, err = c.beginShare(ctx, vol, head); err != nil { + return SnapshotInfo{}, err + } + } // Take the name: this request's record, or an earlier attempt's of it. attempt, err := c.claimName(ctx, vol, root, req, head.Gen) @@ -919,6 +960,11 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe return SnapshotInfo{}, catErr(CodeDeadlineExceeded, true, nil, "snapshot %s/%s: %v since the cut, over the %v deadline; nothing written", vol, req.Name, c.now().Sub(readAt), c.deadline()) } dir := path.Join(root, snapsDir, req.Name) + if err := c.finishShare(ctx, vol, shareToken, head); err != nil { + // Clean abort: the snapshot entry was never sent. + c.dropIntent(ctx, root, id) + return SnapshotInfo{}, err + } pctx, cancel := c.publishCtx(ctx, deadline) outcome, got, cerr := c.createResolved(ctx, pctx, dir, e, attempt) cancel() @@ -1097,16 +1143,12 @@ func (c *Catalog) DeleteSnapshot(ctx context.Context, vol, name string) (string, } continue // re-read: the path now holds a tombstone or the late snapshot case ref.info.State == SnapActive: - // The one mark path shared with retention: a live fork claim - // refuses. - m, live, _, err := c.markDeleting(ctx, vol, name, ref.rec.Attempt) + // The one mark path shared with retention; forks do not hold it. + m, _, err := c.markDeleting(ctx, vol, name, ref.rec.Attempt) if err != nil { return "", err } - switch m { - case markClaimed: - return "", claimedErr(vol, name, live) - case markGone: + if m == markGone { continue } } @@ -1169,6 +1211,24 @@ func (c *Catalog) ListVolumes(ctx context.Context) ([]string, error) { // unsettled keeps its own intent (that create may still land); no attempt // or replay deletes another attempt's intent. func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) { + return c.fork(ctx, req, OriginFork) +} + +// Restore starts an independent restore of req.Source's snapshot into +// req.Target: the same steps as Fork (claim, qualified refs, HEAD), recorded +// with Origin restore. The target serves at once (lazy fill); the restore +// driver then hydrates every chunk, re-uploads the qualified ones under the +// target's own keys in bounded batch cuts, and MarkIndependent records the +// end of the lineage once HEAD holds no ref to another volume. +func (c *Catalog) Restore(ctx context.Context, req ForkRequest) (ForkResult, error) { + return c.fork(ctx, req, OriginRestore) +} + +// isForked reports whether origin made the volume from another volume's +// snapshot (a fork record exists and HEAD may hold qualified refs). +func isForked(origin string) bool { return origin == OriginFork || origin == OriginRestore } + +func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (ForkResult, error) { if _, err := c.volRoot(req.Source); err != nil { return ForkResult{}, err } @@ -1199,7 +1259,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, refuseDeleted(req.Target, "fork to a new volume id") } if ok { - if err := c.checkForkRecord(existing, req); err != nil { + if err := c.checkForkRecord(existing, req, origin); err != nil { return ForkResult{}, err } h, has, err := c.ReadHead(ctx, req.Target) @@ -1219,22 +1279,25 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) } } - // Claim the parent before using it (review of #142): one conditional - // write on the parent attempt's entry, which retention's delete mark - // is conditioned against (see retention.go). + // The deadline starts before the parent is read, and every attempt + // (a retry included) reads it again: a snapshot deleted before the read + // is refused, and one deleted after it stays rooted by GC's grace past + // readAt + deadline, the last moment this fork can publish + // (INV-SNAP-DELETE-ANY-ORDER-001). The parent is not claimed. readAt := c.now() - snap, err := c.claimForkParent(ctx, req) + var shareToken string + if c.guard != nil { // the shared HEAD is the snapshot's, read below + if shareToken, err = c.guard.Begin(ctx, req.Source); err != nil { + return ForkResult{}, remoteErr(err, "share guard for %s", req.Source) + } + } + snap, err := c.readForkParent(ctx, req) if err != nil { return ForkResult{}, err } - // Read after the claim: a delete of the source marks its HEAD deleting - // before it reads claims, so either it sees this claim (and gives its - // mark back) or this read sees the mark and the fork gives the claim - // back before installing anything. if gone, err := c.volumeGone(ctx, req.Source); err != nil { return ForkResult{}, err } else if gone { - c.dropForkClaim(ctx, req, snap.attempt) return ForkResult{}, refuseDeleted(req.Source, "its snapshots cannot be forked") } if snap.geo == (Geometry{}) { @@ -1271,7 +1334,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) req.Target, req.Source, req.Snapshot, existing.Fork.SourceGen, snap.HeadGen) } } else { - vol := VolumeInfo{Format: volumeFormat, VolumeID: req.Target, Geometry: snap.geo, Origin: OriginFork, CreatedNs: c.now().UnixNano(), + vol := VolumeInfo{Format: volumeFormat, VolumeID: req.Target, Geometry: snap.geo, Origin: origin, CreatedNs: c.now().UnixNano(), Parent: &Parent{VolumeID: req.Source, Snapshot: req.Snapshot, Gen: snap.HeadGen}, Fork: record} ve, err := volumeEntry(vol, req.RequestID) if err != nil { @@ -1285,7 +1348,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, catErr(CodeOutcomeUnknown, true, cerr, "fork %s: VOLUME create outcome unknown; retry with the same request id", req.Target) } v, err := decodeVolume(path.Join(dstRoot, volumeName), got) - if err != nil || c.checkForkRecord(v, req) != nil || v.Fork.HeadSHA256 != digest { + if err != nil || c.checkForkRecord(v, req, origin) != nil || v.Fork.HeadSHA256 != digest { return ForkResult{}, catErr(CodeTargetExists, false, nil, "volume %s exists (another request, or another image)", req.Target) } } @@ -1313,6 +1376,11 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) c.dropIntent(ctx, dstRoot, id) return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: %v since reading the snapshot, over the %v deadline; HEAD not written", req.Target, c.now().Sub(readAt), c.deadline()) } + if err := c.finishShare(ctx, req.Source, shareToken, src); err != nil { + // Clean abort: HEAD was never sent. + c.dropIntent(ctx, dstRoot, id) + return ForkResult{}, err + } // Under this request's VOLUME only this request's attempts write HEAD // (attach refuses a fork without HEAD), so a HEAD found there completes // the fork; if it is another attempt's and this create is unsettled, @@ -1335,115 +1403,33 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, err } if h.State == storage.ChunkHeadAborted || headDeletingOrDeleted(h) { - c.dropIntent(ctx, dstRoot, id) // the tombstone is permanent: this create never lands - c.dropForkClaim(ctx, req, snap.attempt) // and this fork never needs the parent again + c.dropIntent(ctx, dstRoot, id) // the tombstone is permanent: this create never lands return ForkResult{}, catErr(CodeTargetExists, false, nil, "fork %s lost to a sweep: its HEAD is an aborted tombstone; fork to a new volume id", req.Target) } if outcome != createUnsettled { c.dropIntent(ctx, dstRoot, id) // confirmed, or refused for good } - c.dropForkClaim(ctx, req, snap.attempt) // the fork has its HEAD: the parent is no longer needed for it return forkResult(existing, outcome != createdNow), nil } -// claimForkParent adds fork req's claim to the parent attempt its -// snapshot name resolves to, conditioned on the entry being active with -// the claims read, and returns that snapshot. A parent deleting is -// refused (snapshot_deleting); a claim already there is reused. -func (c *Catalog) claimForkParent(ctx context.Context, req ForkRequest) (SnapshotInfo, error) { - root, err := c.volRoot(req.Source) +// readForkParent returns the published snapshot fork req names. A parent +// deleting is refused (snapshot_deleting), an absent or aborted one +// (snapshot_not_found). +func (c *Catalog) readForkParent(ctx context.Context, req ForkRequest) (SnapshotInfo, error) { + ref, ok, err := c.resolveSnap(ctx, req.Source, req.Snapshot) if err != nil { return SnapshotInfo{}, err } - token := forkClaim(req.Target, req.RequestID) - dir := path.Join(root, snapsDir, req.Snapshot) - for try := 0; try < 5; try++ { - ref, ok, err := c.resolveSnap(ctx, req.Source, req.Snapshot) - if err != nil { - return SnapshotInfo{}, err - } - if !ok || ref.entry == nil || ref.info.State == SnapAborted { - return SnapshotInfo{}, catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", req.Source, req.Snapshot) - } - if ref.info.State == SnapDeleting { - return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot) - } - if ref.info.geo.BlockSize != 0 && ref.info.geo.NumBlocks > geometry.MaxVolumeBytes/uint64(ref.info.geo.BlockSize) { - return SnapshotInfo{}, catErr(CodeGeometryMismatch, false, nil, "fork size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes) - } - claims := decodeClaims(ref.entry) - for _, cl := range claims { - if cl == token { - return ref.info, nil - } - } - raw := ref.entry.Extended[extSnapClaims] - next := proto.Clone(ref.entry).(*filerpb.Entry) - setClaims(next, append(claims, token)) - err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: []byte(SnapActive), extSnapClaims: raw}) - if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { - continue // a mark, another claim or a delete landed: read again - } - if err != nil { - // The claim may have landed; a retry finds and reuses it. - return SnapshotInfo{}, catErr(CodeOutcomeUnknown, true, err, "fork %s: claim on %s/%s outcome unknown; retry with the same request id", req.Target, req.Source, req.Snapshot) - } - return ref.info, nil + if !ok || ref.entry == nil || ref.info.State == SnapAborted { + return SnapshotInfo{}, catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", req.Source, req.Snapshot) } - return SnapshotInfo{}, catErr(CodeOutcomeUnknown, true, nil, "fork %s: snapshot %s/%s kept changing; retry", req.Target, req.Source, req.Snapshot) -} - -// dropForkClaim removes fork req's claim from its parent attempt once the -// fork no longer needs it (best effort: retention treats a claim whose -// target has a HEAD as dead anyway). -func (c *Catalog) dropForkClaim(ctx context.Context, req ForkRequest, attempt string) { - _, _ = c.removeForkClaim(ctx, req, attempt) -} - -// removeForkClaim removes fork req's claim from its parent attempt and -// reports whether this call confirmed its removal (false with no error: -// the claim was not there). -func (c *Catalog) removeForkClaim(ctx context.Context, req ForkRequest, attempt string) (bool, error) { - root, err := c.volRoot(req.Source) - if err != nil || attempt == "" { - return false, err + if ref.info.State == SnapDeleting { + return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot) } - token := forkClaim(req.Target, req.RequestID) - dir := path.Join(root, snapsDir, req.Snapshot) - for try := 0; try < 3; try++ { - e, err := c.f.LookupEntry(ctx, dir, attempt) - if errors.Is(err, ErrNotFound) { - return false, nil - } - if err != nil { - return false, remoteErr(err, "read %s/%s attempt %s", req.Source, req.Snapshot, attempt) - } - claims := decodeClaims(e) - kept := claims[:0:0] - for _, cl := range claims { - if cl != token { - kept = append(kept, cl) - } - } - if len(kept) == len(claims) { - return false, nil - } - c.hook(hookClaimDrop, req.Snapshot) - // Conditioned on the state read too (review of f42e723): a - // delete that marked the entry meanwhile must never be undone by - // this stale copy. A lost condition re-reads a fresh copy. - raw := e.Extended[extSnapClaims] - next := proto.Clone(e).(*filerpb.Entry) - setClaims(next, kept) - err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: e.Extended[extSnapState], extSnapClaims: raw}) - if err == nil { - return true, nil - } - if !errors.Is(err, ErrPrecondition) { - return false, remoteErr(err, "remove the claim of %s on %s/%s", req.Target, req.Source, req.Snapshot) - } + if ref.info.geo.BlockSize != 0 && ref.info.geo.NumBlocks > geometry.MaxVolumeBytes/uint64(ref.info.geo.BlockSize) { + return SnapshotInfo{}, catErr(CodeGeometryMismatch, false, nil, "fork size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes) } - return false, remoteErr(nil, "claim of %s on %s/%s kept changing", req.Target, req.Source, req.Snapshot) + return ref.info, nil } // AbortFork settles a dead fork for a GC sweep (W5): it claims the @@ -1477,7 +1463,10 @@ func (c *Catalog) AbortFork(ctx context.Context, target string) (claimed bool, e } // checkForkRecord refuses a target VOLUME that is not this fork request's. -func (c *Catalog) checkForkRecord(v VolumeInfo, req ForkRequest) error { +func (c *Catalog) checkForkRecord(v VolumeInfo, req ForkRequest, origin string) error { + if v.Origin != origin { + return catErr(CodeTargetExists, false, nil, "volume %s exists (origin %s, not %s)", req.Target, v.Origin, origin) + } if v.Fork == nil || v.Fork.RequestID != req.RequestID { return catErr(CodeTargetExists, false, nil, "volume %s exists (another request)", req.Target) } diff --git a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go index 44b67dffaa..b3fe22a6f5 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go @@ -4,7 +4,6 @@ import ( "context" "crypto/sha256" "errors" - "path" "sort" "strings" "testing" @@ -166,22 +165,8 @@ func TestFork_IncompleteRetryBoundToOriginalImage(t *testing.T) { t.Fatalf("request id reused for another snapshot: %v, want target_exists", err) } - // The fork claims s1, so an explicit delete is refused. The image - // binding below still guards a - // fork made before claims existed: drop the claim as such a fork would - // never have written one. - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); CodeOf(err) != CodeSnapshotClaimed { - t.Fatalf("delete of a claimed parent: %v, want snapshot_claimed", err) - } - ref, _, err := c.resolveSnap(ctx, "v1", "s1") - if err != nil || ref.entry == nil { - t.Fatalf("read s1: %v", err) - } - delete(ref.entry.Extended, extSnapClaims) - if err := f.UpdateEntry(ctx, path.Join(catBase, "v1", snapsDir, "s1"), ref.entry, nil); err != nil { - t.Fatal(err) - } - + // Forks do not hold their parent: the delete goes through while the + // fork is incomplete, and the image binding below guards the retry. // s1 is deleted and recreated over a newer source image. if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { // frees the name t.Fatal(err) diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index a127f5a2d7..8462cfad23 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -236,6 +236,32 @@ func (r *ChunkRemote) Get(ctx context.Context, key string) ([]byte, error) { return r.b.Get(ctx, fid) } +// ReclaimKey deletes the needle bound to one of this volume's own keys +// with GC's step (reclaimBinding): the binding is tombstoned, the exact fid +// deleted, the binding kept for ever and marked done. It decides nothing: +// the caller must know that no HEAD, snapshot, fork or intent references +// key. An owner-qualified key is refused. +func (r *ChunkRemote) ReclaimKey(ctx context.Context, key string, blobs BlobDeleter) error { + if err := storage.ValidChunkKey(key); err != nil { + return fmt.Errorf("%w: %v", ErrInvalidKey, err) + } + if strings.HasPrefix(key, "@") { + return fmt.Errorf("%w: %q is owner-qualified; a volume reclaims only its own keys", ErrInvalidKey, key) + } + name, err := keyName(key) + if err != nil { + return err + } + e, err := r.f.LookupEntry(ctx, r.keyDir(), name) + if err != nil { + return fmt.Errorf("chunkstore: chunk key %q: %w", key, err) + } + if len(e.GetChunks()) != 0 || string(e.Extended[extKind]) != kindChunkKey || len(e.Extended[extFid]) == 0 { + return fmt.Errorf("chunkstore: chunk key %q: entry is not a chunk key binding", key) + } + return reclaimBinding(ctx, r.f, blobs, r.keyDir(), e) +} + // Delete is not supported; see ErrDeleteUnsupported. func (r *ChunkRemote) Delete(context.Context, string) error { return ErrDeleteUnsupported } diff --git a/seaweed-block/core/frontend/chunkstore/fake_test.go b/seaweed-block/core/frontend/chunkstore/fake_test.go index 9f3ddcfb15..adfcc42ed1 100644 --- a/seaweed-block/core/frontend/chunkstore/fake_test.go +++ b/seaweed-block/core/frontend/chunkstore/fake_test.go @@ -256,7 +256,7 @@ func (b *fakeBlobs) Get(_ context.Context, fid string) ([]byte, error) { b.gets++ d, ok := b.data[fid] if !ok { - return nil, errors.New("fake: no such fid " + fid) + return nil, fmt.Errorf("fake: no such fid %s: %w", fid, ErrBlobNotFound) } return append([]byte(nil), d...), nil } diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index 7e8bf522f5..2416e85f58 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -19,6 +19,15 @@ import ( const extGCDeleted = "swb.gc.deleted" +// ErrBlobDeleteRejected identifies a definite per-object refusal (HTTP400). +// It never proves the needle absent; GC retains its tombstone and reports it. +var ErrBlobDeleteRejected = errors.New("chunkstore: blob DELETE rejected") + +// DefaultGCClockSkew is the allowed pairwise difference between timestamp +// writers and collectors. Deployments with a larger bound must raise ClockSkew; +// no finite time-based grace can be safe with unbounded clock differences. +const DefaultGCClockSkew = time.Minute + // BlobDeleter deletes one immutable needle. Missing needles are success. // Implementations must not reuse a deleted fid. type BlobDeleter interface { @@ -30,8 +39,22 @@ type BlobDeleter interface { // lease expiry or a cached guess. Unknown authority retains the intent. type GCConfig struct { Grace, IntentTTL time.Duration - IssuedEpoch func(context.Context, string) (uint64, error) - Now func() time.Time + // ClockSkew bounds pairwise wall-clock differences. Zero uses the default. + // Binding creation timestamps additionally lose up to one second of precision. + ClockSkew time.Duration + // CASApplyBound is the margin for a publish applied after its fork's + // deadline check. Zero uses the catalog operation deadline. A publish + // known to have succeeded was applied before its context ended, and that + // context ends at readAt + deadline, so it is inside the deadline; an + // unknown outcome keeps the fork intent, which roots the keys until the + // target is resolved, with no time bound. This bound covers apply delay + // and clock-rate drift beyond those two. NewCollector requires + // Grace >= operation deadline + ClockSkew + CASApplyBound, so a snapshot + // deleted while a fork of it is in flight stays rooted until the fork can + // no longer publish (INV-SNAP-DELETE-ANY-ORDER-001). + CASApplyBound time.Duration + IssuedEpoch func(context.Context, string) (uint64, error) + Now func() time.Time } type GCRoot struct { @@ -47,10 +70,16 @@ type GCObject struct { Key string `json:"key"` FID string `json:"fid"` } +type GCDeleteFailure struct { + GCObject + Error string `json:"error"` +} + type GCResult struct { - Roots []GCRoot `json:"roots"` - WouldDelete []GCObject `json:"would_delete"` - WouldExpireIntents []string `json:"would_expire_intents"` + FailedDeletes []GCDeleteFailure `json:"failed_deletes"` + Roots []GCRoot `json:"roots"` + WouldDelete []GCObject `json:"would_delete"` + WouldExpireIntents []string `json:"would_expire_intents"` Volumes, Intents, ExpiredIntents, Candidates, Reclaimed int // Pre-binding needles cannot be enumerated by this API. They are retained; // UnknownUnbound is true rather than inventing a report-only count. @@ -77,6 +106,7 @@ type gcIntent struct { // Different collectors may duplicate idempotent blob deletes but cannot // shorten either collector's independent two-mark grace requirement. type Collector struct { + scope string // empty traces and reclaims the entire namespace cat *Catalog blobs BlobDeleter cfg GCConfig @@ -86,8 +116,25 @@ type Collector struct { } func NewCollector(cat *Catalog, blobs BlobDeleter, cfg GCConfig) (*Collector, error) { - if cat == nil || blobs == nil || cfg.Grace <= cat.deadline() || cfg.IntentTTL <= 0 || cfg.IssuedEpoch == nil { - return nil, errors.New("chunkstore: GC requires catalog, blob deletion, grace > operation deadline, positive intent TTL and epoch authority") + if cat == nil || blobs == nil || cfg.IntentTTL <= 0 || cfg.IssuedEpoch == nil { + return nil, errors.New("chunkstore: GC requires catalog, blob deletion, positive intent TTL and epoch authority") + } + if cfg.ClockSkew == 0 { + cfg.ClockSkew = DefaultGCClockSkew + } + if cfg.ClockSkew < 0 || cfg.ClockSkew > time.Duration(1<<63-1)-time.Second { + return nil, errors.New("chunkstore: invalid GC clock skew bound") + } + if cfg.CASApplyBound == 0 { + cfg.CASApplyBound = cat.deadline() + } + const maxDur = time.Duration(1<<63 - 1) + d := cat.deadline() + if cfg.CASApplyBound < 0 || cfg.CASApplyBound > maxDur-d-cfg.ClockSkew { + return nil, errors.New("chunkstore: invalid GC CAS apply bound") + } + if need := d + cfg.ClockSkew + cfg.CASApplyBound; cfg.Grace < need { + return nil, fmt.Errorf("chunkstore: GC grace %v is below operation deadline %v + clock skew %v + CAS apply bound %v = %v", cfg.Grace, d, cfg.ClockSkew, cfg.CASApplyBound, need) } if cfg.Now == nil { cfg.Now = time.Now @@ -112,6 +159,7 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e result.Roots = []GCRoot{} result.WouldDelete = []GCObject{} result.WouldExpireIntents = []string{} + result.FailedDeletes = []GCDeleteFailure{} defer func() { if err != nil && apply { g.candidates = map[string]gcCandidate{} @@ -119,7 +167,13 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e }() start := g.cfg.Now() if !g.last.IsZero() && start.Before(g.last) { - return result, errors.New("chunkstore: GC clock moved backwards") + // Discard coverage across a backward clock step; a fresh complete mark + // can still make progress without borrowing time from the future. + if apply { + g.candidates = map[string]gcCandidate{} + } + // Preview must also ignore the old coverage without mutating it. + // Candidate lookup below is guarded by this same condition. } roots := map[string]bool{} var bindings []gcBinding @@ -207,18 +261,18 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e } for _, in := range intents { result.Intents++ - if in.CreatedNs <= 0 || in.CreatedNs > start.UnixNano() { + if in.CreatedNs <= 0 { return result, errors.New("chunkstore: invalid intent creation time") } expire := false - if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") && start.Sub(time.Unix(0, in.CreatedNs)) > g.cfg.IntentTTL { + if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") && g.oldEnough(start, time.Unix(0, in.CreatedNs), g.cfg.IntentTTL, 0) { issued, authorityErr := g.cfg.IssuedEpoch(ctx, vol) // Catalog copy intents are retained: their exclusive creates // are not epoch-fenced. For a capture, both the authority // and the actual CAS domain must have // advanced. Mere lease loss, or issuance without takeover, // cannot authorize expiry of a paused publisher's intent. - expire = authorityErr == nil && issued > in.Epoch && h.Epoch > in.Epoch && h.Epoch <= issued + expire = (g.scope == "" || g.scope == vol) && authorityErr == nil && issued > in.Epoch && h.Epoch > in.Epoch && h.Epoch <= issued } if expire { expired = append(expired, gcIntent{r, in}) @@ -256,6 +310,10 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e } } } + // INV-MAINT-SCOPE: roots above remain catalog-wide; candidates are local. + if g.scope != "" && g.scope != vol { + continue + } pageAfter := "" for { page, e := g.cat.f.ListEntries(ctx, r.keyDir(), "", pageAfter, listPage) @@ -312,15 +370,18 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e continue } created := time.Unix(b.entry.Attributes.Crtime, 0) - if !start.After(created.Add(g.cfg.Grace)) { + if !g.oldEnough(start, created, g.cfg.Grace, time.Second) { continue } candidate, seen := g.candidates[p] + if !g.last.IsZero() && start.Before(g.last) { + seen = false + } if !seen || candidate.digest != b.digest { candidate = gcCandidate{start, b.digest} } result.Candidates++ - if start.Sub(candidate.since) < g.cfg.Grace { + if !g.oldEnough(start, candidate.since, g.cfg.Grace, 0) { nextCandidates[p] = candidate continue } @@ -331,23 +392,21 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e if err = ctx.Err(); err != nil { return result, err } - // Preserve the immutable binding forever: removing it would allow Put - // to rebind a key that once existed. The tombstone also permits retry - // after a failed physical delete without losing the fid. - if string(b.entry.Extended[extGCDeleted]) != "1" { - e := proto.Clone(b.entry).(*filerpb.Entry) - e.Extended[extGCDeleted] = []byte("1") - expected := map[string][]byte{extKind: []byte(kindChunkKey), extFid: b.entry.Extended[extFid], extGCDeleted: nil} - if err = g.cat.f.UpdateEntry(ctx, path.Dir(p), e, expected); err != nil { - return result, err - } + err = reclaimBinding(ctx, g.cat.f, g.blobs, path.Dir(p), b.entry) + if err != nil && ctx.Err() != nil { + err = ctx.Err() } - if err = g.blobs.DeleteBlob(ctx, string(b.entry.Extended[extFid])); err != nil { - return result, err + if errors.Is(err, ErrBlobDeleteRejected) { + // INV-GC-DELETE-PROGRESS-001: a confirmed object rejection + // must not starve later candidates or invalidate a complete mark. + // Keep the fid/tombstone and retry; never record this object done. + result.FailedDeletes = append(result.FailedDeletes, GCDeleteFailure{ + GCObject: GCObject{Volume: b.volume, Key: mustUnescapeGCKey(b.entry.Name), FID: string(b.entry.Extended[extFid])}, Error: err.Error(), + }) + nextCandidates[p] = candidate + continue } - e := proto.Clone(b.entry).(*filerpb.Entry) - e.Extended[extGCDeleted] = []byte("done") - if err = g.cat.f.UpdateEntry(ctx, path.Dir(p), e, map[string][]byte{extFid: b.entry.Extended[extFid], extGCDeleted: []byte("1")}); err != nil { + if err != nil { return result, err } result.Reclaimed++ @@ -388,3 +447,39 @@ func (b gcBlobReader) Get(ctx context.Context, fid string) ([]byte, error) { } return reader.Get(ctx, fid) } + +// reclaimBinding deletes the needle a key binding names, keeping the binding +// for ever: removing it would allow Put to rebind a key that once existed. +// The binding first gets a conditional swb.gc.deleted=1 tombstone (which +// also lets a failed physical delete be retried without losing the fid), +// then the exact fid is deleted, then the tombstone becomes done. A binding +// already done is left as it is. The caller decides that nothing references +// the key. +func reclaimBinding(ctx context.Context, f Filer, blobs BlobDeleter, dir string, entry *filerpb.Entry) error { + switch string(entry.Extended[extGCDeleted]) { + case "done": + return nil + case "1": + default: + e := proto.Clone(entry).(*filerpb.Entry) + e.Extended[extGCDeleted] = []byte("1") + expected := map[string][]byte{extKind: []byte(kindChunkKey), extFid: entry.Extended[extFid], extGCDeleted: nil} + if err := f.UpdateEntry(ctx, dir, e, expected); err != nil { + return err + } + } + if err := blobs.DeleteBlob(ctx, string(entry.Extended[extFid])); err != nil { + return err + } + e := proto.Clone(entry).(*filerpb.Entry) + e.Extended[extGCDeleted] = []byte("done") + return f.UpdateEntry(ctx, dir, e, map[string][]byte{extFid: entry.Extended[extFid], extGCDeleted: []byte("1")}) +} + +// INV-GC-CLOCK-SKEW-001: expiry uses a lower bound on elapsed time, +// never the raw difference of timestamps from different hosts. Subtracting +// separately avoids overflowing grace + skew for large configured durations. +func (g *Collector) oldEnough(now, stamp time.Time, grace, resolution time.Duration) bool { + age := now.Sub(stamp) + return age > grace && age-grace > g.cfg.ClockSkew+resolution +} diff --git a/seaweed-block/core/frontend/chunkstore/gc_clock_skew_test.go b/seaweed-block/core/frontend/chunkstore/gc_clock_skew_test.go new file mode 100644 index 0000000000..427d0596cc --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/gc_clock_skew_test.go @@ -0,0 +1,308 @@ +package chunkstore + +import ( + "context" + "encoding/json" + "github.com/seaweedfs/seaweed-block/core/storage" + "path" + "strings" + "testing" + "time" +) + +// Exercise the default one-minute pairwise budget independently of the +// implementation constant. Wider clock differences require a larger config. +const testedGCSkew = time.Minute + +func TestGCSkewSnapshotDeleteGraceBothDirections(t *testing.T) { + for _, offset := range []time.Duration{-testedGCSkew, testedGCSkew} { + t.Run(offset.String(), func(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + realDelete := *now + c.SetClock(func() time.Time { return realDelete.Add(offset) }) + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41)}) + snapshotDir(t, f, "v1", "s1") + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); err != nil { + t.Fatal(err) + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatal(err) + } + if offset < 0 { + *now = realDelete.Add(g.cfg.Grace - testedGCSkew/2) + } else { + *now = realDelete + } + roots, err := g.snapshotAttemptHeads(ctx, "v1", *now) + if err != nil || len(roots) != 1 { + t.Fatalf("skew shortened delete grace or blocked mark: roots=%d err=%v", len(roots), err) + } + *now = realDelete.Add(g.cfg.Grace + 2*testedGCSkew + time.Nanosecond) + roots, err = g.snapshotAttemptHeads(ctx, "v1", *now) + if err != nil || len(roots) != 0 { + t.Fatalf("old deleting attempt did not release: roots=%d err=%v", len(roots), err) + } + }) + } +} +func TestGCSkewIntentExpiryUsesConservativeAge(t *testing.T) { + f, b, _, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + id, err := r.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "old"}) + if err != nil { + t.Fatal(err) + } + ins, _ := r.ListIntents(ctx) + created := time.Unix(0, ins[0].CreatedNs) + head, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if _, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "new", Chunks: map[uint64]storage.ChunkRef{}}); err != nil { + t.Fatal(err) + } + g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { return 2, nil } + *now = created.Add(g.cfg.IntentTTL + testedGCSkew/2) + result, err := g.Run(ctx) + if err != nil || result.ExpiredIntents != 0 { + t.Fatalf("intent expired inside skew allowance: %+v %v", result, err) + } + *now = created.Add(g.cfg.IntentTTL + testedGCSkew + time.Nanosecond) + result, err = g.Run(ctx) + if err != nil || result.ExpiredIntents != 1 { + t.Fatalf("eligible intent %s retained: %+v %v", id, result, err) + } +} +func TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress(t *testing.T) { + f, b, _, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + for _, key := range []string{"rooted", "orphan"} { + if err := r.Put(ctx, key, []byte(key)); err != nil { + t.Fatal(err) + } + } + id, err := r.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "live", Keys: []string{"rooted"}}) + if err != nil { + t.Fatal(err) + } + dir := path.Join(catBase, "v1", intentsDir) + entry, err := f.LookupEntry(ctx, dir, id) + if err != nil { + t.Fatal(err) + } + var doc intentDoc + if err = json.Unmarshal(entry.Content, &doc); err != nil { + t.Fatal(err) + } + doc.CreatedNs = now.Add(testedGCSkew / 2).UnixNano() + entry.Content, _ = json.Marshal(doc) + if err = f.UpdateEntry(ctx, dir, entry, nil); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + out, err := g.Run(ctx) + if err != nil { + t.Fatalf("future intent blocked unrelated progress: %v", err) + } + if i == 1 && out.Reclaimed != 1 { + t.Fatalf("unrelated orphan did not progress: %+v", out) + } + *now = now.Add(2 * time.Hour) + } + if _, err = r.Get(ctx, "rooted"); err != nil { + t.Fatal("future root lost", err) + } +} +func TestGCSkewPersistedCoverageAcrossHosts(t *testing.T) { + for _, future := range []bool{false, true} { + t.Run(map[bool]string{false: "fast-reader", true: "future-writer"}[future], func(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil { + t.Fatal(err) + } + first := *now + if future { + *now = first.Add(testedGCSkew) + } + if _, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil { + t.Fatal(err) + } + if future { + *now = first + } else { + *now = first.Add(g.cfg.Grace + testedGCSkew/2) + } + out, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) + if err != nil || out.Reclaimed != 0 { + t.Fatalf("cross-host coverage shortened grace or blocked pass: %+v %v", out, err) + } + *now = now.Add(g.cfg.Grace + testedGCSkew + time.Nanosecond) + out, err = c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) + if err != nil || out.Reclaimed != 1 { + t.Fatalf("fresh safe coverage did not reclaim: %+v %v", out, err) + } + }) + } +} +func TestGCSkewBindingAgeIncludesSecondResolution(t *testing.T) { + f, b, _, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil { + t.Fatal(err) + } + born := time.Unix(now.Unix(), 900000000) + *now = born.Add(g.cfg.Grace) + dir := path.Join(catBase, "v1", keysDir) + entry, err := f.LookupEntry(ctx, dir, "orphan") + if err != nil { + t.Fatal(err) + } + entry.Attributes.Crtime = born.Add(-testedGCSkew).Unix() + if err = f.UpdateEntry(ctx, dir, entry, nil); err != nil { + t.Fatal(err) + } + out, err := g.Run(ctx) + if err != nil || out.Candidates != 0 { + t.Fatalf("binding age lost skew/second resolution: %+v %v", out, err) + } +} + +func TestGCSkewConfigAndMarkCoverage(t *testing.T) { + for _, skew := range []time.Duration{0, 2 * time.Minute} { + t.Run(skew.String(), func(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil { + t.Fatal(err) + } + cfg := g.cfg + cfg.ClockSkew = skew + if _, err := c.ExecuteVolumeGC(ctx, "v1", b, cfg, true); err != nil { + t.Fatal(err) + } + entry, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), gcMarkName) + if err != nil { + t.Fatal(err) + } + var mark savedGCMark + if err = json.Unmarshal(entry.Content, &mark); err != nil { + t.Fatal(err) + } + if mark.ClockSkewNs <= 0 { + t.Fatal("normalized clock policy absent from mark") + } + // A legacy mark, or one from another skew policy, cannot authorize deletion. + mark.ClockSkewNs = 0 + entry.Content, _ = json.Marshal(mark) + if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), entry, nil); err != nil { + t.Fatal(err) + } + *now = now.Add(2 * time.Hour) + out, err := c.ExecuteVolumeGC(ctx, "v1", b, cfg, true) + if err != nil || out.Reclaimed != 0 { + t.Fatalf("legacy coverage borrowed: %+v %v", out, err) + } + *now = now.Add(2 * time.Hour) + out, err = c.ExecuteVolumeGC(ctx, "v1", b, cfg, true) + if err != nil || out.Reclaimed != 1 { + t.Fatalf("matching normalized policy lost coverage: %+v %v", out, err) + } + }) + } + _, b, c, g, _ := gcFixture(t) + for _, bad := range []time.Duration{-1, time.Duration(1<<63 - 1)} { + cfg := g.cfg + cfg.ClockSkew = bad + if _, err := NewCollector(c, b, cfg); err == nil { + t.Fatalf("bad skew %s accepted", bad) + } + } +} + +func TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate(t *testing.T) { + f, b, _, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil { + t.Fatal(err) + } + if _, err := g.Run(ctx); err != nil { + t.Fatal(err) + } + first := g.last + *now = now.Add(-time.Second) + if out, err := g.Preview(ctx); err != nil || out.Reclaimed != 0 { + t.Fatalf("backward preview: %+v %v", out, err) + } + if !g.last.Equal(first) || len(g.candidates) != 1 { + t.Fatal("preview changed coverage") + } + if out, err := g.Run(ctx); err != nil || out.Reclaimed != 0 { + t.Fatalf("backward mark: %+v %v", out, err) + } + *now = now.Add(g.cfg.Grace + g.cfg.ClockSkew + time.Nanosecond) + if out, err := g.Run(ctx); err != nil || out.Reclaimed != 1 { + t.Fatalf("fresh coverage made no progress: %+v %v", out, err) + } +} + +func TestGCSkewFutureCopyDoesNotBlockOtherSettlement(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + c.SetClock(func() time.Time { return *now }) + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x55)}) + for _, name := range []string{"future", "expired"} { + snapshotDir(t, f, "v1", name) + holdFirst(f, path.Join(catBase, "v1", snapsDir, name)+"/") + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: name, RequestID: name}, h); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("held copy: %v", err) + } + } + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + ins, err := r.ListIntents(ctx) + if err != nil || len(ins) != 2 { + t.Fatalf("intents: %+v %v", ins, err) + } + *now = now.Add(DefaultOpDeadline + time.Second) + futureID := "" + for _, in := range ins { + if !strings.Contains(in.Holder, "/future/") { + continue + } + futureID = in.ID + dir := path.Join(catBase, "v1", intentsDir) + e, err := f.LookupEntry(ctx, dir, in.ID) + if err != nil { + t.Fatal(err) + } + var d intentDoc + if err = json.Unmarshal(e.Content, &d); err != nil { + t.Fatal(err) + } + d.CreatedNs = now.Add(testedGCSkew / 2).UnixNano() + e.Content, _ = json.Marshal(d) + if err = f.UpdateEntry(ctx, dir, e, nil); err != nil { + t.Fatal(err) + } + } + if futureID == "" { + t.Fatal("future copy fixture not found") + } + if count, err := g.SweepCopies(ctx); err != nil || count != 1 { + t.Fatalf("unrelated settlement blocked: %d %v", count, err) + } + left, err := r.ListIntents(ctx) + if err != nil || len(left) != 1 || left[0].ID != futureID { + t.Fatalf("future protection lost: %+v %v", left, err) + } + if out, err := g.Run(ctx); err != nil || len(out.Roots) == 0 { + t.Fatalf("future copy not rooted: %+v %v", out, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy.go b/seaweed-block/core/frontend/chunkstore/gc_copy.go index 2da07b132e..9d5e515dc5 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_copy.go +++ b/seaweed-block/core/frontend/chunkstore/gc_copy.go @@ -31,6 +31,9 @@ func (g *Collector) SweepCopies(ctx context.Context) (settled int, err error) { } var pending []copyAttempt for _, vol := range vols { + if g.scope != "" && g.scope != vol { + continue + } r, e := NewChunkRemote(g.cat.f, nilBlobs{}, path.Join(g.cat.base, vol)) if e != nil { return 0, e @@ -43,10 +46,13 @@ func (g *Collector) SweepCopies(ctx context.Context) (settled int, err error) { if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") { continue } - if in.CreatedNs <= 0 || in.CreatedNs > now.UnixNano() { + if in.CreatedNs <= 0 { return 0, errors.New("chunkstore: invalid copy intent creation time") } - if in.DeadlineNs <= 0 || now.UnixNano() <= in.DeadlineNs { + // A future creation stamp retains protection, without preventing + // unrelated copy attempts from settling. Deadline alone never + // releases roots: the permanent target claim below is still required. + if in.CreatedNs > now.UnixNano() || in.DeadlineNs <= 0 || now.UnixNano() <= in.DeadlineNs { continue } pending = append(pending, copyAttempt{vol, r, in}) @@ -86,7 +92,7 @@ func (g *Collector) SweepCopies(ctx context.Context) (settled int, err error) { if readErr != nil { return settled, readErr } - if !ok || v.Origin != OriginFork || v.Fork == nil || v.Fork.RequestID != parts[1] { + if !ok || !isForked(v.Origin) || v.Fork == nil || v.Fork.RequestID != parts[1] { return settled, errors.New("chunkstore: fork intent has no matching target VOLUME") } if _, err = g.cat.AbortFork(ctx, a.vol); err != nil { @@ -171,10 +177,10 @@ func (g *Collector) snapshotAttemptHeads(ctx context.Context, vol string, now ti } if info.State == SnapDeleting { ns, err := strconv.ParseInt(string(e.Extended[extSnapDeletedNs]), 10, 64) - if err != nil || ns <= 0 || ns > now.UnixNano() { + if err != nil || ns <= 0 { return nil, errors.New("chunkstore: invalid deleted snapshot timestamp") } - if now.Sub(time.Unix(0, ns)) > g.cfg.Grace { + if g.oldEnough(now, time.Unix(0, ns), g.cfg.Grace, 0) { continue } } diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go index 00789d6bf4..16e1994efa 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go @@ -163,7 +163,7 @@ func TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace(t *testing.T) { if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 { t.Fatalf("first unrooted mark: %+v %v", result, e) } - *now = now.Add(time.Hour) + *now = now.Add(time.Hour + g.cfg.ClockSkew + time.Nanosecond) if result, e := g.Run(ctx); e != nil || result.Reclaimed != 2 { t.Fatalf("deleted attempt retained chunks forever: %+v %v", result, e) } diff --git a/seaweed-block/core/frontend/chunkstore/gc_delete_progress_test.go b/seaweed-block/core/frontend/chunkstore/gc_delete_progress_test.go new file mode 100644 index 0000000000..0874adcddd --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/gc_delete_progress_test.go @@ -0,0 +1,97 @@ +package chunkstore + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "path" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestGCPermanentDeleteDoesNotStarveLaterBindings(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + for _, key := range []string{"a_bad", "b_later", "rooted"} { + if err := r.Put(ctx, key, []byte(key)); err != nil { + t.Fatal(err) + } + } + if _, err := r.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "live", Keys: []string{"rooted"}}); err != nil { + t.Fatal(err) + } + entry, err := f.LookupEntry(ctx, path.Join(catBase, "v1", keysDir), "a_bad") + if err != nil { + t.Fatal(err) + } + badFID := string(entry.Extended[extFid]) + calls := map[string]int{} + var callsMu sync.Mutex + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + fid := strings.TrimPrefix(req.URL.Path, "/") + callsMu.Lock() + calls[fid]++ + callsMu.Unlock() + if fid == badFID { + http.Error(w, "cookie mismatch", http.StatusBadRequest) + return + } + if err := b.DeleteBlob(req.Context(), fid); err != nil { + t.Error(err) + } + w.WriteHeader(http.StatusAccepted) + })) + defer server.Close() + deleter := &SWFS{http: server.Client(), vidCache: map[string][]string{"3": {strings.TrimPrefix(server.URL, "http://")}}} + if _, err := c.ExecuteVolumeGC(ctx, "v1", deleter, g.cfg, true); err != nil { + t.Fatal(err) + } + *now = now.Add(2 * time.Hour) + out, err := c.ExecuteVolumeGC(ctx, "v1", deleter, g.cfg, true) + if out.Reclaimed != 1 { + t.Fatalf("permanent DELETE starved later binding: %+v err=%v", out, err) + } + if len(out.FailedDeletes) != 1 || out.FailedDeletes[0].FID != badFID || out.FailedDeletes[0].Key != "a_bad" || out.FailedDeletes[0].Volume != "v1" || !strings.Contains(out.FailedDeletes[0].Error, "http 400") { + t.Fatalf("object refusal missing from result: %+v", out) + } + if !errors.Is(err, ErrBlobDeleteRejected) || !out.MarkSaved { + t.Fatalf("partial deletion must retain complete mark coverage: %+v %v", out, err) + } + badEntry, err := f.LookupEntry(ctx, path.Join(catBase, "v1", keysDir), "a_bad") + if err != nil || string(badEntry.Extended[extGCDeleted]) != "1" { + t.Fatalf("failed DELETE declared done: %+v %v", badEntry, err) + } + if _, err := r.Get(ctx, "rooted"); err != nil { + t.Fatal("protected root lost", err) + } + // A repeatedly rejected older object must not erase a younger object's + // first mark, including when each pass is a new collector process. + if err := r.Put(ctx, "c_new", []byte("c_new")); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + *now = now.Add(2 * time.Hour) + out, err = c.ExecuteVolumeGC(ctx, "v1", deleter, g.cfg, true) + if (err != nil && !errors.Is(err, ErrBlobDeleteRejected)) || !out.MarkSaved || ((len(out.FailedDeletes) > 0) != errors.Is(err, ErrBlobDeleteRejected)) { + t.Fatalf("repeated rejection stalled coverage: %+v %v", out, err) + } + if i == 1 && out.Reclaimed != 1 { + t.Fatalf("younger binding lost coverage: %+v", out) + } + } + callsMu.Lock() + badCalls := calls[badFID] + callsMu.Unlock() + if badCalls < 2 { + t.Fatal("failed binding was silently abandoned") + } + if err := r.Put(ctx, "a_bad", []byte("rebind")); err == nil { + t.Fatal("failed deletion permitted rebinding") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/gc_execution.go b/seaweed-block/core/frontend/chunkstore/gc_execution.go index 5d4b5ab560..98188a765c 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_execution.go +++ b/seaweed-block/core/frontend/chunkstore/gc_execution.go @@ -25,9 +25,11 @@ type savedGCCandidate struct { Digest string `json:"digest"` } type savedGCMark struct { + Scope string `json:"scope,omitempty"` Format int `json:"format"` Base string `json:"base"` GraceNs int64 `json:"grace_ns"` + ClockSkewNs int64 `json:"clock_skew_ns"` TTLNs int64 `json:"ttl_ns"` OpDeadlineNs int64 `json:"op_deadline_ns"` Ready bool `json:"ready"` @@ -53,6 +55,19 @@ type GCExecution struct { // and identify uncertain stages, rather than asserting remote absence. // The catalog namespace is the scope; permanent tombstones are untouched. func (c *Catalog) ExecuteGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig, apply bool) (out GCExecution, err error) { + return c.executeGC(ctx, blobs, cfg, apply, "") +} + +// ExecuteVolumeGC reclaims only volumeID's objects while tracing every volume's +// roots. Its persisted two-mark coverage never aliases namespace-wide coverage. +func (c *Catalog) ExecuteVolumeGC(ctx context.Context, volumeID string, blobs BlobDeleter, cfg GCConfig, apply bool) (GCExecution, error) { + if err := CheckVolumeID(volumeID); err != nil { + return GCExecution{GCResult: GCResult{UnknownUnbound: true}}, err + } + return c.executeGC(ctx, blobs, cfg, apply, volumeID) +} + +func (c *Catalog) executeGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig, apply bool, scope string) (out GCExecution, err error) { // Pre-binding needles remain unenumerable even if admission/readback fails. out.UnknownUnbound = true out.DryRun = !apply @@ -62,11 +77,12 @@ func (c *Catalog) ExecuteGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig if err != nil { return out, err } + g.scope = scope mark, previous, err := g.readMark(ctx) if err != nil { return out, err } - if mark != nil && mark.Ready && mark.GraceNs == int64(cfg.Grace) && mark.TTLNs == int64(cfg.IntentTTL) && mark.OpDeadlineNs == int64(c.deadline()) { + if mark != nil && mark.Ready && mark.GraceNs == int64(cfg.Grace) && mark.TTLNs == int64(g.cfg.IntentTTL) && mark.ClockSkewNs == int64(g.cfg.ClockSkew) && mark.OpDeadlineNs == int64(c.deadline()) { for p, candidate := range mark.Candidates { raw, _ := hex.DecodeString(candidate.Digest) var digest [32]byte @@ -105,11 +121,17 @@ func (c *Catalog) ExecuteGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig } out.MarkOutcome = "complete" out.MarkSaved = true + if len(out.FailedDeletes) != 0 { + // The mark completed and is reusable even though these tombstoned + // objects remain. Report partial failure after persisting coverage, + // so CLI/maintenance callers cannot mistake it for full reclamation. + return out, fmt.Errorf("%w: %d objects retained; complete GC mark saved", ErrBlobDeleteRejected, len(out.FailedDeletes)) + } return out, nil } func (g *Collector) mark(ready bool) savedGCMark { - m := savedGCMark{Format: 1, Base: g.cat.base, GraceNs: int64(g.cfg.Grace), TTLNs: int64(g.cfg.IntentTTL), OpDeadlineNs: int64(g.cat.deadline()), Ready: ready, Candidates: map[string]savedGCCandidate{}} + m := savedGCMark{Format: 1, Scope: g.scope, Base: g.cat.base, GraceNs: int64(g.cfg.Grace), TTLNs: int64(g.cfg.IntentTTL), ClockSkewNs: int64(g.cfg.ClockSkew), OpDeadlineNs: int64(g.cat.deadline()), Ready: ready, Candidates: map[string]savedGCCandidate{}} if ready { m.LastNs = g.last.UnixNano() for p, c := range g.candidates { @@ -119,8 +141,15 @@ func (g *Collector) mark(ready bool) savedGCMark { return m } +func (g *Collector) markDir() string { + if g.scope != "" { + return path.Join(g.cat.base, g.scope) + } + return g.cat.base +} + func (g *Collector) readMark(ctx context.Context) (*savedGCMark, string, error) { - e, err := g.cat.f.LookupEntry(ctx, g.cat.base, gcMarkName) + e, err := g.cat.f.LookupEntry(ctx, g.markDir(), gcMarkName) if errors.Is(err, ErrNotFound) { return nil, "", nil } @@ -141,20 +170,25 @@ func (g *Collector) readMark(ctx context.Context) (*savedGCMark, string, error) if err = d.Decode(&trailing); err != io.EOF { return nil, "", errors.New("chunkstore: trailing GC mark content") } - if m.Format != 1 || m.Base != g.cat.base || m.GraceNs <= 0 || m.TTLNs <= 0 || m.OpDeadlineNs <= 0 { + if m.Format != 1 || m.Scope != g.scope || m.Base != g.cat.base || m.GraceNs <= 0 || m.TTLNs <= 0 || m.OpDeadlineNs <= 0 || m.ClockSkewNs < 0 { return nil, "", errors.New("chunkstore: incompatible GC mark") } if m.Ready { now := g.cfg.Now().UnixNano() - if m.LastNs <= 0 || m.LastNs > now { - return nil, "", errors.New("chunkstore: invalid/future GC mark time") + if m.LastNs <= 0 { + return nil, "", errors.New("chunkstore: invalid GC mark time") } for p, c := range m.Candidates { digest, err := hex.DecodeString(c.Digest) - if err != nil || len(digest) != 32 || c.SinceNs <= 0 || c.SinceNs > m.LastNs || path.Clean(p) != p || !strings.HasPrefix(p, g.cat.base+"/") || !strings.Contains(p, "/"+keysDir+"/") { + if err != nil || len(digest) != 32 || c.SinceNs <= 0 || c.SinceNs > m.LastNs || path.Clean(p) != p || !strings.HasPrefix(p, g.markDir()+"/") || !strings.Contains(p, "/"+keysDir+"/") { return nil, "", errors.New("chunkstore: invalid GC candidate state") } } + if m.LastNs > now { + // A valid mark from a faster clock cannot supply elapsed coverage. + // Keep its token for the conditional replacement, but start afresh. + m.Ready, m.LastNs, m.Candidates = false, 0, nil + } } else if m.LastNs != 0 || len(m.Candidates) != 0 { return nil, "", errors.New("chunkstore: incomplete GC mark carries coverage") } @@ -176,9 +210,9 @@ func (g *Collector) writeMark(ctx context.Context, m savedGCMark, expected strin now := g.cfg.Now().Unix() e := &filerpb.Entry{Name: gcMarkName, Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Crtime: now, Mtime: now, FileMode: 0600}, Content: body, Extended: map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(token)}} if expected == "" { - err = g.cat.f.CreateEntry(ctx, g.cat.base, e, true) + err = g.cat.f.CreateEntry(ctx, g.markDir(), e, true) } else { - err = g.cat.f.UpdateEntry(ctx, g.cat.base, e, map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(expected)}) + err = g.cat.f.UpdateEntry(ctx, g.markDir(), e, map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(expected)}) } if err != nil { return "", fmt.Errorf("chunkstore: GC watermark changed or unavailable: %w", err) diff --git a/seaweed-block/core/frontend/chunkstore/gc_execution_test.go b/seaweed-block/core/frontend/chunkstore/gc_execution_test.go index 94da6e0517..84b089e9c9 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_execution_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_execution_test.go @@ -31,7 +31,7 @@ func TestGCExecution_PreviewAndIndependentApplyMarks(t *testing.T) { if e != nil || len(early.WouldDelete) != 0 { t.Fatalf("early independent preview: %+v %v", early, e) } - *now = now.Add(2 * time.Second) + *now = now.Add(2*time.Second + g.cfg.ClockSkew) before, _ := f.LookupEntry(ctx, catBase, gcMarkName) mature, e := c.ExecuteGC(ctx, b, g.cfg, false) if e != nil || len(mature.WouldDelete) != 1 || mature.Reclaimed != 0 { diff --git a/seaweed-block/core/frontend/chunkstore/gc_test.go b/seaweed-block/core/frontend/chunkstore/gc_test.go index 498a7f667f..70ff2d2eab 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_test.go @@ -142,7 +142,7 @@ func TestGC_UnreachableRequiresTwoMarksAndUploadAge(t *testing.T) { if _, e := r.Get(ctx, "orphan"); e != nil { t.Fatal("orphan deleted before grace", e) } - *now = now.Add(2 * time.Second) + *now = now.Add(2*time.Second + g.cfg.ClockSkew) result, e := g.Run(ctx) if e != nil || result.Reclaimed != 1 { t.Fatalf("old unreachable chunk was not reclaimed after grace-separated marks: %+v %v", result, e) @@ -181,7 +181,7 @@ func TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence(t *testing.T) { {"takeover-but-no-authority", 1, 2, 2 * time.Hour, false, false}, {"unknown-authority", 2, 2, 2 * time.Hour, true, false}, {"TTL-not-exceeded", 2, 2, time.Hour, false, false}, - {"higher-issued-and-fenced", 2, 2, time.Hour + time.Nanosecond, false, true}, + {"higher-issued-and-fenced", 2, 2, time.Hour + DefaultGCClockSkew + time.Nanosecond, false, true}, } { t.Run(tc.name, func(t *testing.T) { f, b, _, g, now := gcFixture(t) @@ -339,7 +339,7 @@ func TestGC_CopyIntentSurvivesTakeover(t *testing.T) { } func TestSWFS_DeleteBlobStatusesAndExactPath(t *testing.T) { - for _, status := range []int{200, 202, 204, 404, 401, 500} { + for _, status := range []int{200, 202, 204, 404, 400, 401, 500} { t.Run(http.StatusText(status), func(t *testing.T) { calls := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -355,6 +355,9 @@ func TestSWFS_DeleteBlobStatusesAndExactPath(t *testing.T) { if (e == nil) != (status == 200 || status == 202 || status == 204 || status == 404) { t.Fatalf("status %d: %v", status, e) } + if errors.Is(e, ErrBlobDeleteRejected) != (status == 400) { + t.Fatalf("wrong per-object refusal classification: status=%d err=%v", status, e) + } if calls != 1 { t.Fatalf("calls %d", calls) } diff --git a/seaweed-block/core/frontend/chunkstore/gc_volume_test.go b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go new file mode 100644 index 0000000000..ea5cfdc98f --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go @@ -0,0 +1,251 @@ +package chunkstore + +import ( + "context" + "errors" + "path" + "reflect" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestVolumeGC_ForeignIntentRootsAndLocalCandidates(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil { + t.Fatal(err) + } + v1, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + v2, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) + for _, key := range []string{"rooted-only-from-v2", "local-orphan"} { + if err := v1.Put(ctx, key, []byte(key)); err != nil { + t.Fatal(err) + } + } + if err := v2.Put(ctx, "foreign-orphan", []byte("foreign")); err != nil { + t.Fatal(err) + } + if _, err := v2.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "snapshot:v2/s1/req", Keys: []string{"@v1/rooted-only-from-v2"}}); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if _, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil { + t.Fatal(err) + } + *now = now.Add(2 * time.Hour) + } + if _, err := v1.Get(ctx, "local-orphan"); err == nil { + t.Error("local orphan not reclaimed") + } + if _, err := v1.Get(ctx, "rooted-only-from-v2"); err != nil { + t.Errorf("foreign root lost: %v", err) + } + if _, err := v2.Get(ctx, "foreign-orphan"); err != nil { + t.Errorf("scoped pass reclaimed foreign candidate: %v", err) + } +} + +// Grace must cover the operation deadline, the clock skew and the CAS apply +// bound (default: the deadline), so a snapshot deleted while a fork of it is +// in flight stays rooted until that fork can no longer publish. +func TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound(t *testing.T) { + _, b, c, g, _ := gcFixture(t) + need := c.deadline() + DefaultGCClockSkew + c.deadline() + for _, grace := range []time.Duration{0, c.deadline(), c.deadline() + DefaultGCClockSkew, need - time.Nanosecond} { + cfg := g.cfg + cfg.Grace, cfg.ClockSkew, cfg.CASApplyBound = grace, 0, 0 + if _, err := NewCollector(c, b, cfg); err == nil { + t.Errorf("accepted grace %s < deadline + skew + apply bound %s", grace, need) + } + } + cfg := g.cfg + cfg.Grace, cfg.ClockSkew, cfg.CASApplyBound = need, 0, 0 + if _, err := NewCollector(c, b, cfg); err != nil { + t.Fatalf("grace = deadline + skew + apply bound: %v", err) + } + cfg.Grace, cfg.CASApplyBound = need, time.Second // an explicit, smaller bound + if _, err := NewCollector(c, b, cfg); err != nil { + t.Fatal(err) + } + cfg.CASApplyBound = -1 + if _, err := NewCollector(c, b, cfg); err == nil { + t.Fatal("accepted a negative CAS apply bound") + } +} + +func TestVolumeGC_DoesNotImportGlobalMark(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err := r.Put(ctx, "orphan", []byte("bytes")); err != nil { + t.Fatal(err) + } + if _, err := c.ExecuteGC(ctx, b, g.cfg, true); err != nil { + t.Fatal(err) + } + *now = now.Add(2 * time.Hour) + // A separate scope must take its own first mark, even with mature global coverage. + result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) + if err != nil || result.Reclaimed != 0 { + t.Fatalf("scope imported namespace coverage: %+v %v", result, err) + } + if _, err = f.LookupEntry(ctx, path.Join(catBase, "v1"), gcMarkName); errors.Is(err, ErrNotFound) { + t.Fatal("scoped watermark absent") + } +} + +func TestVolumeGC_IncompletePassAndConfigChangeDiscardCoverage(t *testing.T) { + for _, mode := range []string{"incomplete", "config"} { + t.Run(mode, func(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err := r.Put(ctx, "orphan", []byte("bytes")); err != nil { + t.Fatal(err) + } + if _, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil { + t.Fatal(err) + } + *now = now.Add(2 * time.Hour) + if mode == "incomplete" { + g.scope = "v1" + _, token, err := g.readMark(ctx) + if err != nil { + t.Fatal(err) + } + if _, err = g.writeMark(ctx, g.mark(false), token); err != nil { + t.Fatal(err) + } + } else { + g.cfg.IntentTTL += time.Second + } + result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) + if err != nil || result.Reclaimed != 0 { + t.Fatalf("stale coverage used: %+v %v", result, err) + } + *now = now.Add(2 * time.Hour) + result, err = c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) + if err != nil || result.Reclaimed != 1 { + t.Fatalf("fresh coverage did not progress: %+v %v", result, err) + } + }) + } +} + +func TestVolumeGC_ForeignForkHeadIsSoleRoot(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x22)}) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { + t.Fatal(err) + } + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}}); err != nil { + t.Fatal(err) + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if out, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil || out.Reclaimed != 0 { + t.Fatalf("foreign-only fork root reclaimed: %+v %v", out, err) + } + *now = now.Add(2 * time.Hour) + } + for _, ref := range h.Chunks { + if _, err := r.Get(ctx, ref.Key); err != nil { + t.Fatal("fork bytes reclaimed", err) + } + } +} + +func TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil { + t.Fatal(err) + } + remotes := map[string]*ChunkRemote{} + for _, vol := range []string{"v1", "v2"} { + remote, _ := NewChunkRemote(f, b, path.Join(catBase, vol)) + remotes[vol] = remote + if err := remote.Put(ctx, "capture", []byte("protected")); err != nil { + t.Fatal(err) + } + if _, err := remote.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "old", Keys: []string{"capture"}}); err != nil { + t.Fatal(err) + } + cur, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "new", Chunks: map[uint64]storage.ChunkRef{}}); err != nil { + t.Fatal(err) + } + } + g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { return 2, nil } + *now = time.Now().Add(3 * time.Hour) + foreign, _ := remotes["v2"].ListIntents(ctx) + result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) + local, _ := remotes["v1"].ListIntents(ctx) + after, _ := remotes["v2"].ListIntents(ctx) + if err != nil || result.ExpiredIntents != 1 || len(local) != 0 || !reflect.DeepEqual(foreign, after) { + t.Fatalf("capture scope mutated foreign intent: %+v %v before=%+v after=%+v", result, err, foreign, after) + } + if _, err := remotes["v2"].Get(ctx, "capture"); err != nil { + t.Fatal("foreign protection lost", err) + } + result, err = c.ExecuteVolumeGC(ctx, "v2", b, g.cfg, true) + if err != nil || result.ExpiredIntents != 1 { + t.Fatalf("foreign positive eligibility not witnessed: %+v %v", result, err) + } +} +func TestVolumeGC_ForeignEligibleCopyIsNotSettled(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + c.SetClock(func() time.Time { return *now }) + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil { + t.Fatal(err) + } + for _, vol := range []string{"v1", "v2"} { + h := publishSource(t, f, b.fakeBlobs, vol, map[uint64][]byte{0: chunkBytes(0x55)}) + snapshotDir(t, f, vol, "held") + holdFirst(f, path.Join(catBase, vol, snapsDir, "held")+"/") + if _, err := c.CreateSnapshot(ctx, vol, SnapshotRequest{Name: "held", RequestID: "dead"}, h); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("copy not held: %v", err) + } + } + before := intentsOf(t, f, "v2") + foreignPath := snapPath(t, f, "v2", "held") + *now = now.Add(DefaultOpDeadline + time.Second) + result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) + after := intentsOf(t, f, "v2") + if err != nil || result.SettledCopies != 1 || len(intentsOf(t, f, "v1")) != 0 || !reflect.DeepEqual(before, after) { + t.Fatalf("copy scope changed foreign attempt: %+v %v", result, err) + } + if _, err := f.LookupEntry(ctx, path.Dir(foreignPath), path.Base(foreignPath)); !errors.Is(err, ErrNotFound) { + t.Fatalf("foreign pending copy claimed: %v", err) + } + result, err = c.ExecuteVolumeGC(ctx, "v2", b, g.cfg, true) + if err != nil || result.SettledCopies != 1 || len(intentsOf(t, f, "v2")) != 0 { + t.Fatalf("foreign positive settlement not witnessed: %+v %v", result, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/reclaim_key_test.go b/seaweed-block/core/frontend/chunkstore/reclaim_key_test.go new file mode 100644 index 0000000000..25acbb33d0 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/reclaim_key_test.go @@ -0,0 +1,47 @@ +package chunkstore + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// ReclaimKey is GC's step for one own key: the binding is tombstoned and +// kept, the needle deleted; repeating it is a no-op; a qualified key is +// refused. +func TestChunkRemote_ReclaimKey(t *testing.T) { + f, b := newFakeFiler(), newFakeBlobs() + r, err := NewChunkRemote(f, b, catBase+"/v1") + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if err := r.Put(ctx, "k1", []byte("payload")); err != nil { + t.Fatal(err) + } + fid := r.fids["k1"] + if err := r.ReclaimKey(ctx, "k1", gcBlobs{b}); err != nil { + t.Fatal(err) + } + e, err := f.LookupEntry(ctx, r.keyDir(), "k1") + if err != nil { + t.Fatalf("binding removed: %v", err) + } + if string(e.Extended[extGCDeleted]) != "done" || string(e.Extended[extFid]) != fid { + t.Fatalf("binding after reclaim: %q fid %q; want done, same fid", e.Extended[extGCDeleted], e.Extended[extFid]) + } + if _, err := b.Get(ctx, fid); err == nil { + t.Fatal("needle still readable after reclaim") + } + if err := r.ReclaimKey(ctx, "k1", gcBlobs{b}); err != nil { + t.Fatalf("repeated reclaim: %v", err) + } + if err := r.Put(ctx, "k1", []byte("again")); !errors.Is(err, storage.ErrChunkKeyExists) { + t.Fatalf("rebinding a reclaimed key: %v", err) + } + if err := r.ReclaimKey(ctx, "@v0/k1", gcBlobs{b}); err == nil { + t.Fatal("reclaim of an owner-qualified key accepted") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/remote.go b/seaweed-block/core/frontend/chunkstore/remote.go index 78dd8dd4b9..cd8e87f18a 100644 --- a/seaweed-block/core/frontend/chunkstore/remote.go +++ b/seaweed-block/core/frontend/chunkstore/remote.go @@ -40,7 +40,9 @@ type Blobs interface { // Put stores data as a new needle and returns its fid. A fid is never // reused, so a Put can never overwrite data another manifest references. Put(ctx context.Context, data []byte) (fid string, err error) - // Get returns the whole needle payload. + // Get returns the whole needle payload. When the store reports the + // needle absent (not merely unreachable), the error wraps + // ErrBlobNotFound. Get(ctx context.Context, fid string) ([]byte, error) } @@ -54,4 +56,8 @@ var ( // ErrInvalidKey: a chunk key is malformed, or names an owner that is // not a plain volume id, or is qualified where only own keys are allowed. ErrInvalidKey = errors.New("chunkstore: invalid chunk key") + // ErrBlobNotFound: the blob store answered that the needle does not + // exist (SWFS: HTTP 404 from every location). A timeout, a refused + // connection or any other status is not this error. + ErrBlobNotFound = errors.New("chunkstore: needle not found") ) diff --git a/seaweed-block/core/frontend/chunkstore/restore.go b/seaweed-block/core/frontend/chunkstore/restore.go new file mode 100644 index 0000000000..22a12d1f83 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/restore.go @@ -0,0 +1,163 @@ +package chunkstore + +import ( + "context" + "encoding/json" + "errors" + "path" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// restoreIndependentName is the write-once entry that ends a restore's +// lineage: written only when the restored volume's HEAD holds no qualified +// ref, so from then on nothing of the volume reaches its source's chunks. +const ( + restoreIndependentName = "RESTORE-INDEPENDENT" + kindRestoreIndependent = "chunkrestoreindependent" +) + +// Restore error codes. +const ( + // CodeNotRestore: the volume was not made by Restore. + CodeNotRestore = "not_restore" + // CodeRestoreIncomplete: HEAD still holds qualified refs (or no HEAD). + CodeRestoreIncomplete = "restore_incomplete" +) + +// RestoreIndependence is the content of restoreIndependentName. +type RestoreIndependence struct { + Format int `json:"format"` + VolumeID string `json:"volume_id"` + HeadGen uint64 `json:"head_gen"` + MarkedNs int64 `json:"marked_ns"` +} + +// ForeignRefs counts the refs of vol's HEAD h that name ANOTHER volume's +// chunks or segments: a "@/" key whose owner is not vol. A resolved +// HEAD writes every chunk key in owner-qualified form, vol's own included, +// so a bare "@" prefix does not make a ref foreign; an unqualified key is +// always vol's own. +func ForeignRefs(h storage.ChunkHead, vol string) int { + foreign := func(key string) bool { + if !strings.HasPrefix(key, "@") { + return false + } + owner, _, ok := strings.Cut(key[1:], "/") + return !ok || owner != vol + } + n := 0 + for _, ref := range h.Chunks { + if foreign(ref.Key) { + n++ + } + } + for _, seg := range h.Segments { + if foreign(seg.Key) { + n++ + } + } + return n +} + +// MarkIndependent records that restored volume vol no longer depends on its +// source: refused unless vol was made by Restore and its current HEAD holds +// no qualified ref. Write-once: an existing marker is a replay (ok). +func (c *Catalog) MarkIndependent(ctx context.Context, vol string) (RestoreIndependence, error) { + root, err := c.volRoot(vol) + if err != nil { + return RestoreIndependence{}, err + } + if m, ok, err := c.ReadIndependence(ctx, vol); err != nil || ok { + return m, err + } + v, ok, err := c.ReadVolume(ctx, vol) + if err != nil { + return RestoreIndependence{}, err + } + if !ok || v.Origin != OriginRestore { + return RestoreIndependence{}, catErr(CodeNotRestore, false, nil, "volume %s was not made by restore", vol) + } + h, has, err := c.ReadHead(ctx, vol) + if err != nil { + return RestoreIndependence{}, err + } + if !has || h.State == storage.ChunkHeadAborted || headDeletingOrDeleted(h) { + return RestoreIndependence{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s has no live HEAD", vol) + } + q, err := c.foreignRefsOf(ctx, vol, h) + if err != nil { + return RestoreIndependence{}, err + } + if q > 0 { + return RestoreIndependence{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s: HEAD gen %d still holds %d refs to another volume", vol, h.Gen, q) + } + m := RestoreIndependence{Format: volumeFormat, VolumeID: vol, HeadGen: h.Gen, MarkedNs: c.now().UnixNano()} + body, err := json.Marshal(m) + if err != nil { + return RestoreIndependence{}, err + } + now := time.Now().Unix() + e := &filerpb.Entry{ + Name: restoreIndependentName, + Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Mtime: now, Crtime: now, FileMode: 0o644, Mime: "application/json"}, + Extended: map[string][]byte{extKind: []byte(kindRestoreIndependent)}, + Content: body, + } + if err := c.f.CreateEntry(ctx, root, e, true); err != nil { + if !errors.Is(err, ErrExists) { + return RestoreIndependence{}, remoteErr(err, "create %s of %s", restoreIndependentName, vol) + } + m, ok, err := c.ReadIndependence(ctx, vol) + if err == nil && !ok { + err = remoteErr(nil, "re-read %s of %s", restoreIndependentName, vol) + } + return m, err + } + return m, nil +} + +// ReadIndependence returns vol's independence marker; ok is false when the +// restore has not ended (or vol is not a restore). +func (c *Catalog) ReadIndependence(ctx context.Context, vol string) (RestoreIndependence, bool, error) { + root, err := c.volRoot(vol) + if err != nil { + return RestoreIndependence{}, false, err + } + e, err := c.f.LookupEntry(ctx, root, restoreIndependentName) + if errors.Is(err, ErrNotFound) { + return RestoreIndependence{}, false, nil + } + if err != nil { + return RestoreIndependence{}, false, remoteErr(err, "read %s of %s", restoreIndependentName, vol) + } + if k := string(e.Extended[extKind]); k != kindRestoreIndependent { + return RestoreIndependence{}, false, remoteErr(nil, "%s of %s: kind %q", restoreIndependentName, vol, k) + } + var m RestoreIndependence + if err := json.Unmarshal(e.GetContent(), &m); err != nil || m.VolumeID != vol { + return RestoreIndependence{}, false, remoteErr(err, "decode %s of %s", restoreIndependentName, vol) + } + return m, true, nil +} + +// foreignRefsOf counts the refs to other volumes in image h of vol, resolved: +// the manifest segments name chunk refs too, so every segment key and every +// chunk ref inside is checked, as GC and usage resolve it. +func (c *Catalog) foreignRefsOf(ctx context.Context, vol string, h storage.ChunkHead) (int, error) { + if c.blobs == nil { + return 0, errors.New("chunkstore: restore independence needs the segment reader") + } + r, err := NewChunkRemote(c.f, c.blobs, path.Join(c.base, vol)) + if err != nil { + return 0, err + } + resolved, err := r.resolveManifest(ctx, h) + if err != nil { + return 0, remoteErr(err, "resolve gen %d of %s", h.Gen, vol) + } + return ForeignRefs(resolved, vol), nil +} diff --git a/seaweed-block/core/frontend/chunkstore/restore_test.go b/seaweed-block/core/frontend/chunkstore/restore_test.go new file mode 100644 index 0000000000..bcda46abf0 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/restore_test.go @@ -0,0 +1,392 @@ +package chunkstore + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "fmt" + "path" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// restoreFixture: v1 with snapshot s1, restored into v2. +func restoreFixture(t *testing.T) (*fakeFiler, *fakeBlobs, *Catalog, storage.ChunkHead) { + t.Helper() + f, b, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if _, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); err != nil { + t.Fatal(err) + } + return f, b, c, h +} + +// ownAll re-uploads every qualified chunk of vol under vol's own keys and +// publishes a HEAD with no qualified ref (what the restore's batch cuts do). +func ownAll(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string) storage.ChunkHead { + t.Helper() + ctx := context.Background() + r, err := NewChunkRemote(f, b, catBase+"/"+vol) + if err != nil { + t.Fatal(err) + } + h, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + // The batch cut's result in one step: every chunk under a fresh own key + // (chunks/e2/...), a new manifest, one HEAD CAS, intents dropped. + next := storage.ChunkHead{Epoch: 1, Holder: "h2", RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}} + for idx, ref := range h.Chunks { + data, err := r.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + key := fmt.Sprintf("chunks/e2/c%d/k", idx) + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + next.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + next, intents, err := r.PrepareManifest(ctx, h, next, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks)) + if err != nil { + t.Fatal(err) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next); err != nil { + t.Fatal(err) + } + for _, id := range intents { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + got, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + return got +} + +// allQualified reports whether every chunk ref and segment key of h names another volume. +func allQualified(h storage.ChunkHead) bool { + for _, ref := range h.Chunks { + if !strings.HasPrefix(ref.Key, "@") { + return false + } + } + for _, seg := range h.Segments { + if !strings.HasPrefix(seg.Key, "@") { + return false + } + } + return len(h.Chunks) > 0 +} + +func TestRestore_RecordsOriginForkRecordAndQualifiedHead(t *testing.T) { + f, b, c, h := restoreFixture(t) + ctx := context.Background() + v, ok, err := c.ReadVolume(ctx, "v2") + if err != nil || !ok || v.Origin != OriginRestore || v.Fork == nil || v.Fork.Source != "v1" || v.Parent == nil { + t.Fatalf("restored VOLUME %+v ok=%v err=%v: want Origin restore with a fork record and Parent", v, ok, err) + } + r2, _ := NewChunkRemote(f, b, catBase+"/v2") + h2, _ := r2.GetHead(ctx) + if !allQualified(h2) || len(h2.Chunks) != len(h.Chunks) { + t.Fatalf("restored HEAD %v: want all %d chunk refs (and segments) qualified", h2.Chunks, len(h.Chunks)) + } + if _, err := c.EnsureVolume(ctx, "v2", v.Geometry); err != nil { + t.Fatalf("a restored volume attaches like a fork: %v", err) + } +} + +func TestRestore_ReplayAndOriginMismatchRefused(t *testing.T) { + _, _, c, _ := restoreFixture(t) + ctx := context.Background() + if r, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); err != nil || !r.Replayed { + t.Fatalf("restore replay: %+v %v", r, err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); CodeOf(err) != CodeTargetExists { + t.Fatalf("a fork onto a restored volume with the same request id must be refused: %v", err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "f1"}); err != nil { + t.Fatal(err) + } + if _, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "f1"}); CodeOf(err) != CodeTargetExists { + t.Fatalf("a restore onto a fork volume with the same request id must be refused: %v", err) + } +} + +func TestRestore_MarkIndependentOnlyWithoutQualifiedRefs(t *testing.T) { + f, b, c, _ := restoreFixture(t) + ctx := context.Background() + if _, err := c.MarkIndependent(ctx, "v2"); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("marker while HEAD holds qualified refs: %v, want %s", err, CodeRestoreIncomplete) + } + if _, ok, err := c.ReadIndependence(ctx, "v2"); err != nil || ok { + t.Fatalf("no marker may exist after a refused mark: ok=%v err=%v", ok, err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "f1"}); err != nil { + t.Fatal(err) + } + if _, err := c.MarkIndependent(ctx, "v3"); CodeOf(err) != CodeNotRestore { + t.Fatalf("marker on a fork: %v, want %s", err, CodeNotRestore) + } + h := ownAll(t, f, b, "v2") + if ForeignRefs(h, "v2") != 0 { + t.Fatalf("fixture: %d foreign refs left", ForeignRefs(h, "v2")) + } + m, err := c.MarkIndependent(ctx, "v2") + if err != nil || m.HeadGen != h.Gen || m.VolumeID != "v2" { + t.Fatalf("marker: %+v %v (HEAD gen %d)", m, err, h.Gen) + } + if again, err := c.MarkIndependent(ctx, "v2"); err != nil || again != m { + t.Fatalf("marker is write-once (a replay returns it): %+v %v", again, err) + } + if got, ok, err := c.ReadIndependence(ctx, "v2"); err != nil || !ok || got != m { + t.Fatalf("read marker: %+v %v %v", got, ok, err) + } +} + +// Deleting the source mid-restore is a normal state for every reader of T's fork record. +func TestRestore_SourceGoneIsNormal(t *testing.T) { + f, b, c, _ := restoreFixture(t) + ctx := context.Background() + r2, _ := NewChunkRemote(f, b, catBase+"/v2") + h2, _ := r2.GetHead(ctx) + before := map[uint64][]byte{} + for idx, ref := range h2.Chunks { + data, err := r2.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + before[idx] = data + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatalf("after T has its HEAD the source snapshot may go: %v", err) + } + detachHead(t, f, b, "v1") + if _, err := c.DeleteVolume(ctx, "v1", nil); err != nil { + t.Fatalf("delete the source volume: %v", err) + } + v, _, _ := c.ReadVolume(ctx, "v2") + if _, err := c.EnsureVolume(ctx, "v2", v.Geometry); err != nil { + t.Fatalf("attach of a restore whose source is gone must be normal: %v", err) + } + if r, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); err != nil || !r.Replayed { + t.Fatalf("replay of a restore whose source is gone: %+v %v", r, err) + } + for idx, ref := range h2.Chunks { + data, err := r2.Get(ctx, ref.Key) + if err != nil || sha256.Sum256(data) != sha256.Sum256(before[idx]) || sha256.Sum256(data) != ref.SHA256 { + t.Fatalf("chunk %d unreadable or changed after the source was deleted: %v", idx, err) + } + } + h := ownAll(t, f, b, "v2") + if _, err := c.MarkIndependent(ctx, "v2"); err != nil { + t.Fatalf("the restore finishes with its source gone: %v (HEAD gen %d)", err, h.Gen) + } +} + +// Load-bearing (the claim ends at the first HEAD): after the restore's HEAD exists, the +// source snapshot and the source volume may both go; GC must keep every chunk T's HEAD names (qualified +// refs resolve to the owner's bindings) until T's own batch cuts replace them. +func TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x31), 3: chunkBytes(0x33)}) + if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); e != nil { + t.Fatal(e) + } + if e := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); e != nil { + t.Fatal(e) + } + if _, e := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs"}); e != nil { + t.Fatal(e) + } + if _, e := c.DeleteSnapshot(ctx, "v1", "s1"); e != nil { + t.Fatalf("retention/delete may retire S once T has a HEAD: %v", e) + } + detachHead(t, f, b.fakeBlobs, "v1") + if _, e := c.DeleteVolume(ctx, "v1", nil); e != nil { + t.Fatalf("delete the source volume: %v", e) + } + r2, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) + h2, e := r2.GetHead(ctx) + if e != nil { + t.Fatal(e) + } + for i := 0; i < 3; i++ { + if _, e := g.Run(ctx); e != nil { + t.Fatalf("gc: %v", e) + } + *now = now.Add(2 * time.Hour) + } + want := map[uint64][]byte{0: chunkBytes(0x31), 3: chunkBytes(0x33)} + for idx, ref := range h2.Chunks { + got, e := r2.Get(ctx, ref.Key) + if e != nil || !bytes.Equal(got, want[idx]) { + t.Fatalf("restored chunk %d lost after S and V were deleted and GC ran: %v", idx, e) + } + } +} + +// A restore whose HEAD is absent or an aborted tombstone never attaches, like a fork. +func TestRestore_WithoutLiveHeadNeverAttaches(t *testing.T) { + f, _, c, _ := catalogFixture(t) + ctx := context.Background() + v := VolumeInfo{Format: volumeFormat, VolumeID: "v9", Geometry: catGeo, Origin: OriginRestore, CreatedNs: 1, + Parent: &Parent{VolumeID: "v1", Snapshot: "s1", Gen: 1}, Fork: &ForkRecord{RequestID: "rq", Source: "v1", Snapshot: "s1"}} + e, err := volumeEntry(v, "rq") + if err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, catBase+"/v9", e, true); err != nil { + t.Fatal(err) + } + if _, err := c.EnsureVolume(ctx, "v9", catGeo); CodeOf(err) != CodeForkIncomplete { + t.Fatalf("restore without a HEAD attached: %v, want %s", err, CodeForkIncomplete) + } + if _, err := c.AbortFork(ctx, "v9"); err != nil { + t.Fatalf("abort the unpublished restore (sweep): %v", err) + } + if _, err := c.EnsureVolume(ctx, "v9", catGeo); CodeOf(err) != CodeForkIncomplete { + t.Fatalf("restore with an aborted HEAD attached: %v, want %s", err, CodeForkIncomplete) + } + if _, err := c.MarkIndependent(ctx, "v9"); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("marker on an aborted restore: %v, want %s", err, CodeRestoreIncomplete) + } +} + +// Snapshots of a restore are refused until it is independent. +func TestRestore_SnapshotsRefusedUntilIndependent(t *testing.T) { + f, b, c, _ := restoreFixture(t) + ctx := context.Background() + r2, _ := NewChunkRemote(f, b, catBase+"/v2") + h2, _ := r2.GetHead(ctx) + if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "early", RequestID: "e"}, h2); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("snapshot of a restore in progress: %v, want %s", err, CodeRestoreIncomplete) + } + if _, ok, err := c.SnapshotReplay(ctx, "v2", SnapshotRequest{Name: "early", RequestID: "e"}); err != nil || ok { + t.Fatalf("a refused snapshot must leave nothing: ok=%v err=%v", ok, err) + } + h := ownAll(t, f, b, "v2") + if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "late", RequestID: "l"}, h); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("own chunks but no marker yet: %v, want %s", err, CodeRestoreIncomplete) + } + if _, err := c.MarkIndependent(ctx, "v2"); err != nil { + t.Fatal(err) + } + s, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "late", RequestID: "l"}, h) + if err != nil { + t.Fatalf("snapshot after the marker: %v", err) + } + if ForeignRefs(s.Head(), "v2") != 0 { + t.Fatalf("a snapshot of an independent restore names %d foreign refs", ForeignRefs(s.Head(), "v2")) + } +} + +// hangingDeleteFiler blocks DeleteEntry until its ctx ends (or the test +// releases it). It reports whether that ctx carried a deadline and was live on +// entry, then how it ended. +type hangingDeleteFiler struct { + Filer + entered chan deleteEntry + ended chan error + release chan struct{} +} + +type deleteEntry struct { + hadDeadline bool + errAtEntry error +} + +func (h hangingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { + _, ok := ctx.Deadline() + h.entered <- deleteEntry{hadDeadline: ok, errAtEntry: ctx.Err()} + select { + case <-ctx.Done(): + h.ended <- ctx.Err() + return ctx.Err() + case <-h.release: + return errors.New("released by the test") + } +} + +// dropIntent outlives a cancelled caller, but one unresponsive delete must still be bounded. +func TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled(t *testing.T) { + old := dropIntentTimeout + dropIntentTimeout = 50 * time.Millisecond + t.Cleanup(func() { dropIntentTimeout = old }) + h := hangingDeleteFiler{Filer: newFakeFiler(), entered: make(chan deleteEntry, 1), ended: make(chan error, 1), release: make(chan struct{})} + c := &Catalog{f: h} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + done := make(chan struct{}) + t.Cleanup(func() { // an unbounded delete (the failing case) is released and joined + close(h.release) + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("cleanup: dropIntent did not return") + } + }) + go func() { c.dropIntent(ctx, "/vols/v1", "op-1"); close(done) }() + select { + case e := <-h.entered: + if e.errAtEntry != nil { + t.Fatalf("the intent delete inherited the caller's cancellation: %v", e.errAtEntry) + } + if !e.hadDeadline { + t.Fatal("the intent delete ran without any deadline") + } + case <-time.After(5 * time.Second): + t.Fatal("dropIntent never reached the filer") + } + select { + case err := <-h.ended: + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("the intent delete ended with %v, want its own deadline (context.DeadlineExceeded)", err) + } + case <-time.After(5 * time.Second): + t.Fatal("the intent delete never ended: it is unbounded") + } + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("dropIntent did not return: the delete is unbounded") + } +} + +// A cut image saved before the marker still names the source's chunks: the +// marker must not let it become a snapshot. +func TestRestore_SnapshotOfAStalePreIndependenceImageRefused(t *testing.T) { + f, b, c, _ := restoreFixture(t) + ctx := context.Background() + r2, _ := NewChunkRemote(f, b, catBase+"/v2") + stale, _ := r2.GetHead(ctx) + h := ownAll(t, f, b, "v2") + if _, err := c.MarkIndependent(ctx, "v2"); err != nil { + t.Fatal(err) + } + req := SnapshotRequest{Name: "stale", RequestID: "s"} + if _, err := c.CreateSnapshot(ctx, "v2", req, stale); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("stale foreign image after the marker: %v, want %s", err, CodeRestoreIncomplete) + } + if _, ok, err := c.SnapshotReplay(ctx, "v2", req); err != nil || ok { + t.Fatalf("a refused snapshot must leave nothing: ok=%v err=%v", ok, err) + } + if list, _, err := c.ListSnapshots(ctx, "v2", ListOptions{}); err != nil || len(list) != 0 { + t.Fatalf("snapshots after the refusal: %v %v", list, err) + } + if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "own", RequestID: "o"}, h); err != nil { + t.Fatalf("the own image must still be accepted: %v", err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index a714cb82bc..561a5fd06e 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -8,13 +8,11 @@ import ( "path" "sort" "strconv" - "strings" "time" "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" ) // Snapshot retention. @@ -34,7 +32,6 @@ import ( // + every snapshot younger than KeepYounger (a creation time in the // future, from clock skew, counts as young) // + the log-spaced keeps (below) -// + every snapshot a fork still needs // // and deletes every other snapshot. A pinned snapshot past its ExpiresAtNs // is treated as unpinned. GC reclaims the chunks. @@ -50,34 +47,18 @@ import ( // record is removed only while it still names that attempt, so a // same-name replacement made after planning is never touched. // -// Fork parents (design from the review of #142). Protection is -// one conditional write on the parent attempt's own entry, nothing else: -// -// - Fork, before it reads the parent, adds its claim (target/request) -// to the entry's claims, conditioned on {state active, claims as read}. -// A parent already deleting is refused. -// - Retain marks an attempt deleting only conditioned on {state active, -// gen, no claims}. A lost condition re-reads and decides again. -// -// The two writes hit the same entry, so one of them sees the other: either -// the claim landed first and retain keeps the snapshot (fork_held), or the -// mark landed first and the fork refuses before installing anything. -// -// A claim is removed by the fork once its HEAD is installed. Retain removes -// (conditionally) only claims that can never matter again: the target has -// a HEAD (the fork completed, or a sweep aborted it), or the target's -// VOLUME belongs to another request (this one can never publish there). -// Any other claim keeps the snapshot, however old: a fork that died before -// publishing its VOLUME holds it until the fork is retried to completion or -// settled by AbortFork. Forks published before claims existed are still -// found by the fork-record scan (forkParentsNeeded). -// -// An explicit DeleteSnapshot goes through the same check and mark -// (markDeleting): it refuses a live claim with snapshot_claimed. +// Forks and restores do not hold their parent (INV-SNAP-DELETE-ANY-ORDER-001). +// A snapshot is deleted by retention or DeleteSnapshot whatever forks read +// it: a fork reads the parent after taking its deadline start and publishes +// its HEAD only before readAt + deadline, and GC keeps a deleted attempt +// rooted for its grace, which exceeds deadline + clock skew + CAS apply +// bound (NewCollector). A fork that reads after the delete mark gets +// snapshot_deleting or snapshot_not_found, also on a retry. A claims +// xattr left by an older version is ignored. // // A pass stopped after a mark (e.g. a lost response) leaves the attempt // deleting with its name still held; the next pass (and its dry run) lists -// it and frees the name. A deleting attempt cannot gain claims. +// it and frees the name. const ( SnapshotClassSemantic = "semantic" @@ -85,18 +66,12 @@ const ( CodeInvalidClass = "invalid_class" CodeInvalidPolicy = "invalid_policy" - // CodeSnapshotClaimed: an explicit delete of a snapshot a fork still - // claims. Not retryable as such: it clears - // when the fork publishes its HEAD or is aborted. - CodeSnapshotClaimed = "snapshot_claimed" DefaultKeepNewest = 10 DefaultKeepYounger = time.Hour extRetention = "retention" extRetentionRev = "retention_rev" - - extSnapClaims = "swb.snap.claims" ) // ValidateSnapshotClass refuses a class other than "", "semantic" and @@ -116,11 +91,11 @@ func (s SnapshotInfo) Pinned() bool { // RetentionPolicy is a volume's snapshot retention policy. type RetentionPolicy struct { - KeepNewest int `json:"keepNewest"` - KeepYoungerNs int64 `json:"keepYoungerNs"` - KeepHourly int `json:"keepHourly"` - KeepDaily int `json:"keepDaily"` - KeepWeekly int `json:"keepWeekly"` + KeepNewest int `json:"keepNewest"` // keep the newest N unpinned snapshots + KeepYoungerNs int64 `json:"keepYoungerNs"` // keep every snapshot younger than this (ns) + KeepHourly int `json:"keepHourly"` // keep the newest snapshot of each of the last N hours + KeepDaily int `json:"keepDaily"` // keep the newest snapshot of each of the last N days + KeepWeekly int `json:"keepWeekly"` // keep the newest snapshot of each of the last N weeks } // DefaultRetentionPolicy is the policy of a volume that never set one. @@ -217,21 +192,20 @@ type RetentionDecision struct { // The reasons a snapshot is kept. const ( - keepNewest = "newest" - keepPinned = "pinned" - keepYoung = "younger_than_policy" - keepHourly = "hourly" - keepDaily = "daily" - keepWeekly = "weekly" - keepForkParent = "fork_parent" - reasonExpired = "expired" + keepNewest = "newest" + keepPinned = "pinned" + keepYoung = "younger_than_policy" + keepHourly = "hourly" + keepDaily = "daily" + keepWeekly = "weekly" + reasonExpired = "expired" ) // planRetention decides, from one listing, which snapshots policy keeps at -// now. needed names the snapshots a fork still needs. Unpinned snapshots +// now. Unpinned snapshots // are ranked newest first; equal creation times rank by name, so the plan // is deterministic. -func planRetention(p RetentionPolicy, snaps []SnapshotInfo, needed map[string]bool, now time.Time) []RetentionDecision { +func planRetention(p RetentionPolicy, snaps []SnapshotInfo, now time.Time) []RetentionDecision { ordered := append([]SnapshotInfo(nil), snaps...) sort.SliceStable(ordered, func(i, j int) bool { if ordered[i].CreatedNs != ordered[j].CreatedNs { @@ -280,9 +254,6 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, needed map[string]bo d.Reasons = append(d.Reasons, lk.reason) } } - if needed[s.Name] { - d.Reasons = append(d.Reasons, keepForkParent) - } d.Keep = len(d.Reasons) > 0 if !d.Keep { d.Reasons = []string{reasonExpired} @@ -314,7 +285,6 @@ type RetentionResult struct { Decisions []RetentionDecision `json:"decisions"` Deleted []string `json:"deleted"` // confirmed deleted (empty on a dry run) Replaced []string `json:"replaced"` // planned, but the name now holds another attempt: left alone - ForkHeld []string `json:"forkHeld"` // planned, but a fork took a hold meanwhile: kept Failed *RetentionFailure `json:"failed,omitempty"` // NotAttempted lists the expired snapshots not reached because the // pass stopped at Failed. @@ -350,13 +320,9 @@ func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (Retentio snaps = append(snaps, s) } } - needed, err := c.forkParentsNeeded(ctx, vol) - if err != nil { - return RetentionResult{}, err - } res := RetentionResult{VolumeID: vol, Policy: p, PolicySet: set, DryRun: dryRun, - Deleted: []string{}, Replaced: []string{}, ForkHeld: []string{}, NotAttempted: []string{}} - res.Decisions = planRetention(p, snaps, needed, c.now()) + Deleted: []string{}, Replaced: []string{}, NotAttempted: []string{}} + res.Decisions = planRetention(p, snaps, c.now()) var expired []RetentionDecision for _, d := range res.Decisions { if d.Keep { @@ -390,8 +356,6 @@ func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (Retentio res.Deleted = append(res.Deleted, d.Name) case retainReplaced: res.Replaced = append(res.Replaced, d.Name) - case retainForkHeld: - res.ForkHeld = append(res.ForkHeld, d.Name) } } return res, nil @@ -409,7 +373,6 @@ type retainOutcome int const ( retainDeleted retainOutcome = iota // marked deleting (or already gone) and the name freed retainReplaced // the planned attempt is gone; another attempt holds the name - retainForkHeld // a live fork claim is on the attempt: kept, nothing written ) // deleteRetainedAttempt deletes the planned attempt of vol/name and only @@ -420,13 +383,9 @@ func (c *Catalog) deleteRetainedAttempt(ctx context.Context, vol, name, attempt if err != nil { return 0, false, err } - m, _, uncertain, err := c.markDeleting(ctx, vol, name, attempt) - if err != nil { + if _, uncertain, err := c.markDeleting(ctx, vol, name, attempt); err != nil { return 0, uncertain, err } - if m == markClaimed { - return retainForkHeld, false, nil - } return c.freeName(ctx, root, name, attempt) } @@ -435,90 +394,56 @@ type markResult int const ( markDone markResult = iota // this call marked the attempt deleting markGone // the attempt's entry is gone - markSettled // already deleting or aborted (no fork can claim it) - markClaimed // a live fork claim is on it: nothing written + markSettled // already deleting or aborted ) -// markDeleting marks attempt of vol/name deleting under the fork-claim -// rule, the one path for retention and explicit delete: the mark is -// conditioned on {state active, gen, no claims}; dead claims are cleared -// conditionally first; a lost condition re-reads and decides again. live -// lists the live claims when the result is markClaimed. uncertain -// reports, with an error, a mutation whose outcome is unknown. -func (c *Catalog) markDeleting(ctx context.Context, vol, name, attempt string) (markResult, []string, bool, error) { +// markDeleting marks attempt of vol/name deleting, the one path for +// retention and explicit delete: the mark is conditioned on {state active, +// gen}; a lost condition re-reads and decides again. No fork claim is read +// (INV-SNAP-DELETE-ANY-ORDER-001). uncertain reports, with an error, a +// mutation whose outcome is unknown. +func (c *Catalog) markDeleting(ctx context.Context, vol, name, attempt string) (markResult, bool, error) { root, err := c.volRoot(vol) if err != nil { - return 0, nil, false, err + return 0, false, err } dir := path.Join(root, snapsDir, name) for try := 0; try < 5; try++ { e, err := c.f.LookupEntry(ctx, dir, attempt) if errors.Is(err, ErrNotFound) { - return markGone, nil, false, nil + return markGone, false, nil } if err != nil { - return 0, nil, false, remoteErr(err, "read snapshot %s/%s attempt %s", vol, name, attempt) + return 0, false, remoteErr(err, "read snapshot %s/%s attempt %s", vol, name, attempt) } if string(e.Extended[extSnapState]) != SnapActive { - return markSettled, nil, false, nil - } - raw := string(e.Extended[extSnapClaims]) - claims := decodeClaims(e) - live, err := c.liveClaims(ctx, vol, name, claims) - if err != nil { - return 0, nil, false, err - } - if len(live) > 0 { - return markClaimed, live, false, nil + return markSettled, false, nil } c.hook(hookChecked, name) next := proto.Clone(e).(*filerpb.Entry) - if len(claims) > 0 { - // Every claim is dead: clear them, then decide again. - delete(next.Extended, extSnapClaims) - err := c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: []byte(SnapActive), extSnapClaims: []byte(raw)}) - if err != nil && !errors.Is(err, ErrPrecondition) && !errors.Is(err, ErrNotFound) { - return 0, nil, true, remoteErr(err, "clear the dead fork claims of %s/%s attempt %s", vol, name, attempt) - } - continue - } next.Extended[extSnapState] = []byte(SnapDeleting) next.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10)) err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{ - extSnapState: []byte(SnapActive), - extSnapGen: e.Extended[extSnapGen], - extSnapClaims: nil, // no claims: a fork that claimed meanwhile wins + extSnapState: []byte(SnapActive), + extSnapGen: e.Extended[extSnapGen], }) if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { - continue // a claim, a delete or a replacement landed: decide again + continue // a delete or a replacement landed: decide again } if err != nil { - return 0, nil, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt) + return 0, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt) } c.hook(hookMarked, name) - return markDone, nil, false, nil + return markDone, false, nil } - return 0, nil, false, remoteErr(nil, "snapshot %s/%s attempt %s kept changing", vol, name, attempt) -} - -// claimedErr is snapshot_claimed naming the claiming fork volumes. -func claimedErr(vol, name string, live []string) error { - targets := make([]string, 0, len(live)) - for _, cl := range live { - t, _, _ := strings.Cut(cl, "/") - targets = append(targets, t) - } - return catErr(CodeSnapshotClaimed, false, nil, "snapshot %s/%s is the parent of incomplete fork %s; it can be deleted once that fork completes or is aborted", vol, name, strings.Join(targets, ", ")) + return 0, false, remoteErr(nil, "snapshot %s/%s attempt %s kept changing", vol, name, attempt) } // Test seams: hook stages in a Retain pass. const ( hookPlanned = "planned" // after planning, before any deletion - hookChecked = "checked" // an attempt's claims were read and none is live, before its mark + hookChecked = "checked" // an attempt was read active, before its mark hookMarked = "marked" // an attempt is marked deleting, before its name is freed - // hookClaimDrop: a completed fork read its parent entry to drop its - // claim, before the conditional write. - hookClaimDrop = "claim-drop" ) func (c *Catalog) hook(stage, name string) { @@ -539,61 +464,6 @@ func (c *Catalog) freeName(ctx context.Context, root, name, attempt string) (ret return 0, true, remoteErr(err, "remove the name record %s", name) } -// forkClaim is the claim a fork puts on its parent attempt. -func forkClaim(target, requestID string) string { return target + "/" + requestID } - -func decodeClaims(e *filerpb.Entry) []string { - raw := e.Extended[extSnapClaims] - if len(raw) == 0 { - return nil - } - var out []string - if json.Unmarshal(raw, &out) != nil { - return []string{string(raw)} // unreadable: kept as one live claim (safe) - } - return out -} - -func setClaims(e *filerpb.Entry, claims []string) { - if len(claims) == 0 { - delete(e.Extended, extSnapClaims) - return - } - sort.Strings(claims) - body, _ := json.Marshal(claims) - e.Extended[extSnapClaims] = body -} - -// liveClaims returns the claims on vol/name that a fork may still need: a -// claim is dead only when its target has a HEAD, or its target's VOLUME -// was made by another request (or from another parent). -func (c *Catalog) liveClaims(ctx context.Context, vol, name string, claims []string) ([]string, error) { - var live []string - for _, cl := range claims { - target, req, ok := strings.Cut(cl, "/") - if !ok || CheckVolumeID(target) != nil { - live = append(live, cl) // not ours to judge: keep the snapshot - continue - } - _, has, err := c.ReadHead(ctx, target) - if err != nil { - return nil, err - } - if has { - continue - } - v, ok, err := c.ReadVolume(ctx, target) - if err != nil { - return nil, err - } - if ok && (v.Fork == nil || v.Fork.RequestID != req || v.Fork.Source != vol || v.Fork.Snapshot != name) { - continue - } - live = append(live, cl) - } - return live, nil -} - // allSnapshots lists every published, not-deleting snapshot of vol, with // the attempt each name resolved to. func (c *Catalog) allSnapshots(ctx context.Context, vol string) ([]SnapshotInfo, error) { @@ -618,36 +488,3 @@ func (c *Catalog) listSnapshots(ctx context.Context, vol string, deleting bool) after = next } } - -// forkParentsNeeded names the snapshots of vol a fork still needs by its -// published fork record: a volume whose fork record names vol and the -// snapshot, and which has no real published HEAD yet (absent or aborted). -// It covers forks published before fork holds existed; a newer fork is -// also covered, atomically, by its hold (deleteRetainedAttempt). -func (c *Catalog) forkParentsNeeded(ctx context.Context, vol string) (map[string]bool, error) { - vols, err := c.ListVolumes(ctx) - if err != nil { - return nil, err - } - needed := map[string]bool{} - for _, other := range vols { - if other == vol { - continue - } - v, ok, err := c.ReadVolume(ctx, other) - if err != nil { - return nil, err - } - if !ok || v.Fork == nil || v.Fork.Source != vol { - continue - } - h, has, err := c.ReadHead(ctx, other) - if err != nil { - return nil, err - } - if !has || h.State == storage.ChunkHeadAborted { - needed[v.Fork.Snapshot] = true - } - } - return needed, nil -} diff --git a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go index 1570b55000..d04475e01c 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go @@ -143,7 +143,7 @@ func TestIntegration_RetainAndUsage(t *testing.T) { // deadline exceeded) keeps its parent, and completes on retry; (3) a fork // that claims between retention's claim check and its mark makes the // filer refuse the mark (conditioned on no claims), so the parent is kept. -func TestIntegration_RetainHeldSchedules(t *testing.T) { +func TestIntegration_RetainIgnoresIncompleteForks(t *testing.T) { c := startWeed(t) ctx := context.Background() const base = "/swblock/chunks" @@ -222,27 +222,18 @@ func TestIntegration_RetainHeldSchedules(t *testing.T) { t.Fatal(err) } cat.retainHook = nil - if len(res.Deleted) != 0 || fmt.Sprint(res.Replaced) != "[s00]" || fmt.Sprint(res.ForkHeld) != "[s02 s01]" { - t.Fatalf("retain: deleted=%v replaced=%v forkHeld=%v; want none / s00 / s02 s01", res.Deleted, res.Replaced, res.ForkHeld) + if fmt.Sprint(res.Deleted) != "[s02 s01]" || fmt.Sprint(res.Replaced) != "[s00]" { + t.Fatalf("retain: deleted=%v replaced=%v; want s02 s01 / s00 (forks do not hold their parent)", res.Deleted, res.Replaced) } b, err := cat.readSnap(ctx, "v1", "s00") if err != nil || b.attempt != pinnedAttempt || b.State != SnapActive || b.Class != SnapshotClassPinned { t.Fatalf("pinned replacement: %+v %v (attempt %s, want %s)", b, err, b.attempt, pinnedAttempt) } - // An explicit delete of a claimed parent is refused. - if _, err := cat.DeleteSnapshot(ctx, "v1", "s01"); CodeOf(err) != CodeSnapshotClaimed { - t.Fatalf("delete of the claimed s01: %v; want snapshot_claimed", err) - } + // A retry of either stopped fork reads its parent again and is refused. for _, fk := range []struct{ snap, target string }{{"s01", "v2"}, {"s02", "v3"}} { - if s, err := cat.readSnap(ctx, "v1", fk.snap); err != nil || s.State != SnapActive { - t.Fatalf("fork parent %s: %+v %v; want active", fk.snap, s, err) + _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: fk.snap, Target: fk.target, RequestID: "f"}) + if code := CodeOf(err); code != CodeSnapshotNotFound && code != CodeSnapshotDeleting { + t.Fatalf("fork %s retry after its parent was deleted: %v; want snapshot_not_found or snapshot_deleting", fk.target, err) } - if _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: fk.snap, Target: fk.target, RequestID: "f"}); err != nil { - t.Fatalf("fork %s retry: %v", fk.target, err) - } - } - res, err = cat.Retain(ctx, "v1", false) - if err != nil || fmt.Sprint(res.Deleted) != "[s02 s01]" { - t.Fatalf("after the forks completed: deleted=%v %v; want s02 s01 (s00 is pinned)", res.Deleted, err) } } diff --git a/seaweed-block/core/frontend/chunkstore/retention_review_test.go b/seaweed-block/core/frontend/chunkstore/retention_review_test.go index ab074525b3..0ebd5b8081 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_review_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_review_test.go @@ -3,7 +3,6 @@ package chunkstore import ( "context" "errors" - "path" "strings" "testing" "time" @@ -26,7 +25,7 @@ func TestPlanRetention_RollingWindows(t *testing.T) { for _, a := range ages { snaps = append(snaps, snapAt(nm(a), a, SnapshotClassSemantic, time.Time{}, nil)) } - return kept(planRetention(p, snaps, nil, now)) + return kept(planRetention(p, snaps, now)) } now := at(10*time.Hour + 30*time.Minute) if k := plan(RetentionPolicy{KeepHourly: 1}, now, at(10*time.Hour+20*time.Minute), at(9*time.Hour+50*time.Minute)); len(k) != 1 || k[nm(at(10*time.Hour+20*time.Minute))] == nil { @@ -104,51 +103,6 @@ func forkFixture(t *testing.T) (*fakeFiler, *Catalog) { return f, c } -// A fork that starts after the retention scan (its VOLUME published, its -// HEAD not yet) has claimed the parent: retention keeps it, and the fork -// completes on retry. -func TestCatalog_RetainKeepsAParentForkedAfterTheScan(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - c.retainHook = func(stage, _ string) { - if stage != hookPlanned { - return - } - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork with a held HEAD create: %v", err) - } - } - res, err := c.Retain(ctx, "v1", false) - if err != nil { - t.Fatal(err) - } - if strings.Join(res.ForkHeld, ",") != "s01" || strings.Join(res.Deleted, ",") != "s02,s00" { - t.Fatalf("deleted=%v forkHeld=%v; want s01 kept for the fork", res.Deleted, res.ForkHeld) - } - if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive { - t.Fatalf("parent after retain: %+v %v; want active", s, err) - } - c.retainHook = nil - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork retry: %v", err) - } - // Completed: the hold is gone and the parent is no longer needed. - res, err = c.Retain(ctx, "v1", false) - if err != nil || strings.Join(res.Deleted, ",") != "s01" { - t.Fatalf("after the fork completed: deleted=%v %v; want s01", res.Deleted, err) - } -} - -func claimsOf(t *testing.T, c *Catalog, name string) []string { - t.Helper() - ref, ok, err := c.resolveSnap(context.Background(), "v1", name) - if err != nil || !ok || ref.entry == nil { - t.Fatalf("read %s: ok=%t %v", name, ok, err) - } - return decodeClaims(ref.entry) -} - // A fork arriving after the mark finds the parent deleting and refuses // before installing anything (and leaves no claim). func TestCatalog_ForkAfterTheMarkRefuses(t *testing.T) { @@ -176,105 +130,6 @@ func TestCatalog_ForkAfterTheMarkRefuses(t *testing.T) { } } -// Schedule 1: retention read no claims, then a fork claims before the -// mark. The mark's condition (no claims) fails; retention reads again, -// sees the live claim and keeps the parent. -func TestCatalog_ClaimBetweenCheckAndMarkWins(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - c.retainHook = func(stage, name string) { - if stage != hookChecked || name != "s01" { - return - } - c.retainHook = nil - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork with a held HEAD create: %v", err) - } - } - res, err := c.Retain(ctx, "v1", false) - if err != nil { - t.Fatal(err) - } - if strings.Join(res.ForkHeld, ",") != "s01" || strings.Join(res.Deleted, ",") != "s02,s00" { - t.Fatalf("deleted=%v forkHeld=%v; want s01 kept", res.Deleted, res.ForkHeld) - } - if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive { - t.Fatalf("parent: %+v %v; want active", s, err) - } - if got := claimsOf(t, c, "s01"); strings.Join(got, ",") != "v2/f" { - t.Fatalf("claims %v; want v2/f", got) - } -} - -// Schedule 2: a fork that claimed and died before publishing its VOLUME -// keeps the parent however much later retention runs (no lifetimes); the -// fork retried to completion releases it. -func TestCatalog_DeadForkClaimKeepsTheParent(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - f.failCreate = func(p string) error { - if p == catBase+"/v2/"+volumeName { - return errors.New("filer unavailable") - } - return nil - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err == nil { - t.Fatal("fork with a failing VOLUME create succeeded") - } - f.failCreate = nil - if _, ok, _ := c.ReadVolume(ctx, "v2"); ok { - t.Fatal("VOLUME published") - } - saved := c.now - c.SetClock(func() time.Time { return saved().Add(30 * 24 * time.Hour) }) - res, err := c.Retain(ctx, "v1", false) - if err != nil || strings.Join(res.ForkHeld, ",") != "s01" { - t.Fatalf("30 days later: forkHeld=%v %v; want s01 still kept", res.ForkHeld, err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork retry: %v", err) - } - if got := claimsOf(t, c, "s01"); len(got) != 0 { - t.Fatalf("claims after the fork completed: %v; want none", got) - } - res, err = c.Retain(ctx, "v1", false) - if err != nil || strings.Join(res.Deleted, ",") != "s01" { - t.Fatalf("after completion: deleted=%v %v; want s01", res.Deleted, err) - } -} - -// Schedule 3: a second request for the same target is refused without -// touching the first request's claim (claims are per target AND request, -// and a fork drops only its own, only once its HEAD exists). -func TestCatalog_RefusedSameTargetForkLeavesTheOtherClaim(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "a"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork a: %v", err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "b"}); CodeOf(err) != CodeTargetExists { - t.Fatalf("fork b (same target, other request): %v; want target_exists", err) - } - if _, err := c.Retain(ctx, "v1", false); err != nil { - t.Fatal(err) - } - if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive { - t.Fatalf("parent after retain: %+v %v; want kept for request a", s, err) - } - if got := claimsOf(t, c, "s01"); strings.Join(got, ",") != "v2/a" { - t.Fatalf("claims %v; want only a's, intact", got) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "a"}); err != nil { - t.Fatalf("fork a retry: %v", err) - } - res, err := c.Retain(ctx, "v1", false) - if err != nil || strings.Join(res.Deleted, ",") != "s01" { - t.Fatalf("after a completed: deleted=%v %v; want s01 (b's claim dead)", res.Deleted, err) - } -} - // A failure part way reports the confirmed deletions, the failing // snapshot (uncertain: the mark's outcome is unknown) and what was not // attempted; a lost response leaves the snapshot deleting and the next @@ -355,84 +210,3 @@ func TestCatalog_UsageCountsForkHolders(t *testing.T) { t.Fatalf("s1 after v1's HEAD moved, v2 forked from it: %+v; want 0 exclusive (v2 holds both chunks)", u.Snapshots) } } - -// An explicit delete of a snapshot an -// incomplete fork claims is refused (snapshot_claimed, not retryable, -// naming the fork); once the fork completes or is aborted the delete goes -// through. Retention and delete share the check (markDeleting). -func TestCatalog_DeleteRefusesAClaimedParent(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork v2: %v", err) - } - holdFirst(f, catBase+"/v3/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s02", Target: "v3", RequestID: "g"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork v3: %v", err) - } - for _, tc := range []struct{ snap, target string }{{"s01", "v2"}, {"s02", "v3"}} { - _, err := c.DeleteSnapshot(ctx, "v1", tc.snap) - var ce *CatalogError - if !errors.As(err, &ce) || ce.Code != CodeSnapshotClaimed || ce.Retryable || !strings.Contains(ce.Detail(), tc.target) { - t.Fatalf("delete %s claimed by %s: %v; want snapshot_claimed, not retryable, naming %s", tc.snap, tc.target, err, tc.target) - } - if s, err := c.readSnap(ctx, "v1", tc.snap); err != nil || s.State != SnapActive { - t.Fatalf("%s after the refused delete: %+v %v; want active", tc.snap, s, err) - } - } - // Completed fork: its claim no longer blocks. - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork v2 retry: %v", err) - } - if got, err := c.DeleteSnapshot(ctx, "v1", "s01"); err != nil || got != SnapDeleting { - t.Fatalf("delete after the fork completed: %q %v", got, err) - } - // Aborted fork (a sweep's tombstone): neither does its claim. - if claimed, err := c.AbortFork(ctx, "v3"); err != nil || !claimed { - t.Fatalf("abort v3: claimed=%t %v", claimed, err) - } - if got, err := c.DeleteSnapshot(ctx, "v1", "s02"); err != nil || got != SnapDeleting { - t.Fatalf("delete after the fork was aborted: %q %v", got, err) - } -} - -// Review of f42e723: a completed fork's claim cleanup that read the parent -// entry, then paused while an explicit delete marked it, must not write -// its stale copy back (resurrecting an unnamed snapshot as a GC root). -func TestCatalog_ClaimCleanupNeverUndoesADelete(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork: %v", err) - } - parent, err := c.readSnap(ctx, "v1", "s01") - if err != nil { - t.Fatal(err) - } - ran := false - c.retainHook = func(stage, name string) { - if stage != hookClaimDrop || name != "s01" || ran { - return - } - ran = true // the fork's HEAD exists now: its claim is dead - if _, err := c.DeleteSnapshot(ctx, "v1", "s01"); err != nil { - t.Fatalf("delete during the claim cleanup: %v", err) - } - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork retry: %v", err) - } - c.retainHook = nil - e, err := f.LookupEntry(ctx, path.Join(catBase, "v1", snapsDir, "s01"), parent.attempt) - if err != nil { - t.Fatal(err) - } - if !ran || string(e.Extended[extSnapState]) != SnapDeleting || len(e.Extended[extSnapDeletedNs]) == 0 { - t.Fatalf("ran=%t state=%q deleted_ns=%q; want the delete mark kept", ran, e.Extended[extSnapState], e.Extended[extSnapDeletedNs]) - } - if _, ok, err := c.resolveSnap(ctx, "v1", "s01"); ok || err != nil { - t.Fatalf("s01's name is back (%v)", err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/retention_test.go b/seaweed-block/core/frontend/chunkstore/retention_test.go index 10109d3916..f329ed96be 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_test.go @@ -9,7 +9,6 @@ import ( "testing" "time" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -45,7 +44,7 @@ func TestPlanRetention_NewestNWithNameTieBreak(t *testing.T) { for i := 0; i < 15; i++ { snaps = append(snaps, snapAt(fmt.Sprintf("s%02d", i), retBase.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) } - k := kept(planRetention(noYoung(), snaps, nil, now)) + k := kept(planRetention(noYoung(), snaps, now)) if len(k) != 10 { t.Fatalf("kept %d, want 10: %v", len(k), k) } @@ -55,7 +54,7 @@ func TestPlanRetention_NewestNWithNameTieBreak(t *testing.T) { } } tie := []SnapshotInfo{snapAt("b", retBase, "", time.Time{}, nil), snapAt("a", retBase, "", time.Time{}, nil)} - if k := kept(planRetention(RetentionPolicy{KeepNewest: 1}, tie, nil, now)); len(k) != 1 || k["a"] == nil { + if k := kept(planRetention(RetentionPolicy{KeepNewest: 1}, tie, now)); len(k) != 1 || k["a"] == nil { t.Fatalf("tie: kept %v, want only a (name order)", k) } } @@ -71,7 +70,7 @@ func TestPlanRetention_PinnedSemanticAndLabels(t *testing.T) { snapAt("semantic-old", retBase, SnapshotClassSemantic, time.Time{}, nil), snapAt("labeled-old", retBase, "", time.Time{}, map[string]string{"agent.step": "npm-ci"}), } - k := kept(planRetention(RetentionPolicy{}, snaps, nil, now)) + k := kept(planRetention(RetentionPolicy{}, snaps, now)) if len(k) != 2 || k["pinned-old"] == nil || k["pinned-by-expiry"] == nil { t.Fatalf("kept %v; want exactly pinned-old and pinned-by-expiry", k) } @@ -87,7 +86,7 @@ func TestPlanRetention_YoungAndClockSkew(t *testing.T) { snapAt("future", now.Add(10*time.Minute), SnapshotClassSemantic, time.Time{}, nil), snapAt("old", now.Add(-2*time.Hour), SnapshotClassSemantic, time.Time{}, nil), } - k := kept(planRetention(p, snaps, nil, now)) + k := kept(planRetention(p, snaps, now)) if len(k) != 2 || k["young"] == nil || k["future"] == nil { t.Fatalf("kept %v; want young and future", k) } @@ -100,7 +99,7 @@ func TestPlanRetention_HourlyBuckets(t *testing.T) { for i := 0; i < 12; i++ { // every 30 min over the last 6 hours snaps = append(snaps, snapAt(fmt.Sprintf("s%02d", i), now.Add(-time.Duration(i)*30*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) } - k := kept(planRetention(RetentionPolicy{KeepHourly: 3}, snaps, nil, now)) + k := kept(planRetention(RetentionPolicy{KeepHourly: 3}, snaps, now)) if len(k) != 3 { t.Fatalf("kept %d, want 3 (one per hour for the last 3 hours): %v", len(k), k) } @@ -111,16 +110,6 @@ func TestPlanRetention_HourlyBuckets(t *testing.T) { } } -// A snapshot a fork still needs is kept whatever the policy says. -func TestPlanRetention_ForkParentKept(t *testing.T) { - now := retBase.Add(48 * time.Hour) - snaps := []SnapshotInfo{snapAt("parent", retBase, SnapshotClassSemantic, time.Time{}, nil)} - k := kept(planRetention(RetentionPolicy{}, snaps, map[string]bool{"parent": true}, now)) - if len(k) != 1 || k["parent"][0] != keepForkParent { - t.Fatalf("kept %v; want parent (fork_parent)", k) - } -} - // An agent that checkpoints every step stays bounded: one semantic // snapshot a minute for a day keeps at most N + T/step + hourly buckets. func TestPlanRetention_AgentCheckpointingEveryStepStaysBounded(t *testing.T) { @@ -132,14 +121,14 @@ func TestPlanRetention_AgentCheckpointingEveryStepStaysBounded(t *testing.T) { } now := start.Add(24 * time.Hour) bound := p.KeepNewest + int(DefaultKeepYounger/time.Minute) + p.KeepHourly - if k := kept(planRetention(p, snaps, nil, now)); len(k) > bound { + if k := kept(planRetention(p, snaps, now)); len(k) > bound { t.Fatalf("kept %d of %d step checkpoints; want at most %d", len(k), len(snaps), bound) } // The bound holds however long the agent runs. for i := 24 * 60; i < 7*24*60; i++ { snaps = append(snaps, snapAt(fmt.Sprintf("step-%05d", i), start.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) } - if k := kept(planRetention(p, snaps, nil, start.Add(7*24*time.Hour))); len(k) > bound { + if k := kept(planRetention(p, snaps, start.Add(7*24*time.Hour))); len(k) > bound { t.Fatalf("after a week: kept %d; want at most %d", len(k), bound) } } @@ -283,41 +272,6 @@ func TestCatalog_SnapshotClass(t *testing.T) { } } -// A fork whose HEAD is not yet written still needs its parent snapshot: -// retain keeps it; once the fork's HEAD is published it no longer does. -func TestCatalog_RetainKeepsParentOfAnIncompleteFork(t *testing.T) { - f, c, _, clock := retentionFixture(t, 3) - ctx := context.Background() - if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy - t.Fatal(err) - } - // The fake filer lists only directory entries it holds; a real filer - // has them for every volume directory. - for _, vol := range []string{"v1", "v2"} { - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - } - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork with a held HEAD create: %v", err) - } - res, err := c.Retain(ctx, "v1", true) - if err != nil { - t.Fatal(err) - } - if k := kept(res.Decisions); len(k) != 1 || k["s01"] == nil || k["s01"][0] != keepForkParent { - t.Fatalf("incomplete fork: kept %v; want only s01 (fork_parent)", k) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork retry: %v", err) - } - _ = clock - if res, err := c.Retain(ctx, "v1", true); err != nil || res.Kept != 0 { - t.Fatalf("published fork: kept %d (%v); want 0", res.Kept, err) - } -} - // publishTagged installs a HEAD for vol with chunks under keys tagged tag. func publishTagged(t *testing.T, f *fakeFiler, b *fakeBlobs, vol, tag string, chunks map[uint64][]byte) storage.ChunkHead { t.Helper() diff --git a/seaweed-block/core/frontend/chunkstore/share_guard.go b/seaweed-block/core/frontend/chunkstore/share_guard.go new file mode 100644 index 0000000000..1f4ba19c7c --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/share_guard.go @@ -0,0 +1,61 @@ +package chunkstore + +import ( + "context" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// ShareGuard is told about every sharer of a volume's chunks. A snapshot or +// fork calls Begin before it obtains the HEAD it will reference, and Finish, +// with that HEAD, right before it activates its result; an error from either +// aborts the share before anything is activated. A token Begin returned and +// nobody finished is the guard's to expire. +// +// No guard (the default) changes nothing: no call is made and no check is +// added. +type ShareGuard interface { + Begin(ctx context.Context, vol string) (token string, err error) + Finish(ctx context.Context, vol, token string, head storage.ChunkHead) error +} + +// SetShareGuard installs g (nil removes it). Set it before the catalog is +// used. +func (c *Catalog) SetShareGuard(g ShareGuard) { c.guard = g } + +// ShareGuard returns the installed guard, or nil. +func (c *Catalog) ShareGuard() ShareGuard { return c.guard } + +// beginShare starts a share of vol's chunks for a caller that passes the +// HEAD in: with a guard, it begins the share, then refuses unless head is +// still vol's current HEAD (a share that obtained an older HEAD could +// reference chunks superseded meanwhile). token is "" without a guard. +func (c *Catalog) beginShare(ctx context.Context, vol string, head storage.ChunkHead) (token string, err error) { + if c.guard == nil { + return "", nil + } + token, err = c.guard.Begin(ctx, vol) + if err != nil { + return "", remoteErr(err, "share guard for %s", vol) + } + cur, ok, err := c.ReadHead(ctx, vol) + if err != nil { + return "", err + } + if !ok || cur.Gen != head.Gen || cur.Epoch != head.Epoch { + return "", catErr(CodeOutcomeUnknown, true, nil, "volume %s: the HEAD to share (gen %d) is no longer current (gen %d); retry", vol, head.Gen, cur.Gen) + } + return token, nil +} + +// finishShare finishes a share before its result is activated; no-op +// without a guard. +func (c *Catalog) finishShare(ctx context.Context, vol, token string, head storage.ChunkHead) error { + if c.guard == nil { + return nil + } + if err := c.guard.Finish(ctx, vol, token, head); err != nil { + return remoteErr(err, "share guard for %s refused the share", vol) + } + return nil +} diff --git a/seaweed-block/core/frontend/chunkstore/share_guard_test.go b/seaweed-block/core/frontend/chunkstore/share_guard_test.go new file mode 100644 index 0000000000..a0f7661520 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/share_guard_test.go @@ -0,0 +1,204 @@ +package chunkstore + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// recGuard records Begin and Finish; onFinish runs inside Finish. +type recGuard struct { + mu sync.Mutex + events []string + n int + finishErr error + beginErr error + onFinish func() +} + +func (g *recGuard) Begin(_ context.Context, vol string) (string, error) { + g.mu.Lock() + defer g.mu.Unlock() + g.n++ + g.events = append(g.events, "begin:"+vol) + if g.beginErr != nil { + return "", g.beginErr + } + return fmt.Sprintf("tok-%d", g.n), nil +} + +func (g *recGuard) Finish(_ context.Context, vol, token string, head storage.ChunkHead) error { + if g.onFinish != nil { + g.onFinish() + } + g.mu.Lock() + defer g.mu.Unlock() + g.events = append(g.events, fmt.Sprintf("finish:%s:%s:%d", vol, token, head.Gen)) + return g.finishErr +} + +func (g *recGuard) list() []string { + g.mu.Lock() + defer g.mu.Unlock() + return append([]string(nil), g.events...) +} + +func countUnder(f *fakeFiler, prefix string) int { + f.mu.Lock() + defer f.mu.Unlock() + n := 0 + for k := range f.entries { + if strings.HasPrefix(k, prefix) { + n++ + } + } + return n +} + +// A snapshot of a passed-in HEAD begins the share, checks the HEAD is still +// current, and finishes it before the snapshot entry is written. +func TestShareGuard_SnapshotFinishesBeforeActivation(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + g := &recGuard{} + g.onFinish = func() { + if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { + t.Errorf("snapshot entry written before Finish (%d entries)", n) + } + } + c.SetShareGuard(g) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + want := []string{"begin:v1", fmt.Sprintf("finish:v1:tok-1:%d", h.Gen)} + if got := g.list(); len(got) != 2 || got[0] != want[0] || got[1] != want[1] { + t.Fatalf("guard events %v; want %v", got, want) + } + if countUnder(f, catBase+"/v1/snaps/s1/") == 0 { + t.Fatal("snapshot not written after a successful Finish") + } +} + +// A refused Finish aborts the snapshot: nothing activated, its intent dropped. +func TestShareGuard_RefusedFinishAbortsTheSnapshot(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + intents := countUnder(f, catBase+"/v1/intents/") + c.SetShareGuard(&recGuard{finishErr: errors.New("token expired")}) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err == nil { + t.Fatal("snapshot activated after a refused Finish") + } + if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { + t.Fatalf("%d snapshot entries after a refused Finish", n) + } + if n := countUnder(f, catBase+"/v1/intents/"); n != intents { + t.Fatalf("intents %d -> %d; want the snapshot's intent dropped", intents, n) + } +} + +// A passed-in HEAD that is no longer current is refused before Finish. +func TestShareGuard_StaleHeadIsRefused(t *testing.T) { + f, b, c, h := catalogFixture(t) + ctx := context.Background() + publishSource(t, f, b, "v1", map[uint64][]byte{5: chunkBytes(0x20)}) // HEAD moves on + g := &recGuard{} + c.SetShareGuard(g) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err == nil { + t.Fatal("snapshot of a superseded HEAD accepted with a guard") + } + for _, e := range g.list() { + if strings.HasPrefix(e, "finish:") { + t.Fatalf("Finish called for a refused share: %v", g.list()) + } + } + if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { + t.Fatalf("%d snapshot entries for a refused share", n) + } +} + +// A caller that began the share itself passes its token: no second Begin. +func TestShareGuard_CallerToken(t *testing.T) { + _, _, c, h := catalogFixture(t) + g := &recGuard{} + c.SetShareGuard(g) + if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "s1", RequestID: "r", ShareToken: "owner-tok"}, h); err != nil { + t.Fatal(err) + } + if got := g.list(); len(got) != 1 || got[0] != fmt.Sprintf("finish:v1:owner-tok:%d", h.Gen) { + t.Fatalf("guard events %v; want only Finish with the caller's token", got) + } +} + +// A fork begins the share before reading the snapshot and finishes it with +// the snapshot's HEAD before writing the child's HEAD; a refused Finish +// writes no child HEAD. +func TestShareGuard_Fork(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + g := &recGuard{} + g.onFinish = func() { + if countUnder(f, catBase+"/v2/HEAD") != 0 { + t.Error("child HEAD written before Finish") + } + } + c.SetShareGuard(g) + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork-1"}); err != nil { + t.Fatal(err) + } + want := []string{"begin:v1", fmt.Sprintf("finish:v1:tok-1:%d", h.Gen)} + if got := g.list(); len(got) != 2 || got[0] != want[0] || got[1] != want[1] { + t.Fatalf("guard events %v; want %v", got, want) + } + + c.SetShareGuard(&recGuard{finishErr: errors.New("token expired")}) + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "fork-2"}); err == nil { + t.Fatal("fork activated after a refused Finish") + } + if countUnder(f, catBase+"/v3/HEAD") != 0 { + t.Fatal("child HEAD written after a refused Finish") + } + if n := countUnder(f, catBase+"/v3/intents/"); n != 0 { + t.Fatalf("%d intents left for the refused fork; want its new intent dropped", n) + } +} + +// A refused Begin stops the snapshot and the fork before anything is +// written: no Finish, no snapshot entry, no child HEAD, no intent left. +func TestShareGuard_BeginRefused(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s0", RequestID: "r0"}, h); err != nil { + t.Fatal(err) + } + intents := countUnder(f, catBase+"/v1/intents/") + g := &recGuard{beginErr: errors.New("share refused")} + c.SetShareGuard(g) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err == nil { + t.Fatal("snapshot after a refused Begin") + } + if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { + t.Fatalf("%d snapshot entries after a refused Begin", n) + } + if n := countUnder(f, catBase+"/v1/intents/"); n != intents { + t.Fatalf("intents %d -> %d after a refused Begin", intents, n) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s0", Target: "v4", RequestID: "fork-b"}); err == nil { + t.Fatal("fork after a refused Begin") + } + if countUnder(f, catBase+"/v4/HEAD") != 0 || countUnder(f, catBase+"/v4/intents/") != 0 { + t.Fatal("a fork refused at Begin wrote a child HEAD or an intent") + } + for _, e := range g.list() { + if strings.HasPrefix(e, "finish:") { + t.Fatalf("Finish after a refused Begin: %v", g.list()) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go new file mode 100644 index 0000000000..35b05e3ed0 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go @@ -0,0 +1,204 @@ +package chunkstore + +import ( + "bytes" + "context" + "fmt" + "path" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// INV-SNAP-DELETE-ANY-ORDER-001: forks and restores do not hold their parent. + +// A fork stopped past its deadline does not keep its parent: the snapshot is +// deleted, and a retry of the same request reads the parent again and is +// refused; it never publishes from its first read. +func TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"} + clock := time.Now() + c.SetClock(func() time.Time { clock = clock.Add(time.Second); return clock }) // every read advances + c.OpDeadline = time.Nanosecond + if _, err := c.Fork(ctx, req); CodeOf(err) != CodeDeadlineExceeded { + t.Fatalf("fork past its deadline: %v, want deadline_exceeded", err) + } + c.OpDeadline = 0 + if _, ok, err := c.ReadVolume(ctx, "v2"); !ok || err != nil { + t.Fatalf("the stopped fork's VOLUME: ok=%v %v", ok, err) + } + if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { + t.Fatalf("delete the parent of an incomplete fork: %q %v, want deleting", got, err) + } + _, err := c.Fork(ctx, req) + if code := CodeOf(err); code != CodeSnapshotNotFound && code != CodeSnapshotDeleting { + t.Fatalf("retry after the parent was deleted: %v, want snapshot_not_found or snapshot_deleting", err) + } + if _, err := f.LookupEntry(ctx, catBase+"/v2", headName); err == nil { + t.Fatal("the retry published a HEAD from its first read of a deleted parent") + } +} + +// A delete that lands between a fork's read of its parent and its HEAD +// publish succeeds; the fork still publishes inside its deadline, and the +// target keeps every chunk after the source snapshot and volume are gone and +// GC has run past its grace. +func TestSnapshotDelete_DeleteDuringAForkInFlight(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + want := map[uint64][]byte{0: chunkBytes(0x41), 2: chunkBytes(0x42)} + h := publishSource(t, f, b.fakeBlobs, "v1", want) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + deleted := false + f.stallCreate = func(p string) bool { // runs before the fake takes its lock + if p == catBase+"/v2/"+headName && !deleted { + deleted = true + if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { + t.Errorf("delete while the fork is in flight: %q %v", got, err) + } + } + return false + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); err != nil { + t.Fatalf("fork whose parent was deleted after its read: %v", err) + } + f.stallCreate = nil + if !deleted { + t.Fatal("the delete never ran inside the fork") + } + detachHead(t, f, b.fakeBlobs, "v1") + if _, err := c.DeleteVolume(ctx, "v1", nil); err != nil { + t.Fatalf("delete the source volume: %v", err) + } + for i := 0; i < 3; i++ { + if _, err := g.Run(ctx); err != nil { + t.Fatalf("gc: %v", err) + } + *now = now.Add(2 * time.Hour) + } + r2, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) + h2, err := r2.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + requireChunks(t, ctx, r2, h2, want, "fork") +} + +// An unknown publish outcome keeps the fork's intent, and that intent roots +// the parent's keys with no time bound: the snapshot deleted, the source +// volume deleted, GC run well past its grace, the keys survive while the +// intent exists. +func TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + want := map[uint64][]byte{0: chunkBytes(0x51), 1: chunkBytes(0x52)} + h := publishSource(t, f, b.fakeBlobs, "v1", want) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + f.failCreate = func(p string) error { + if p == catBase+"/v2/"+headName { + return errTransport + } + return nil + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("fork with an unknown HEAD create: %v", err) + } + f.failCreate = nil + if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { + t.Fatalf("delete the parent: %q %v", got, err) + } + detachHead(t, f, b.fakeBlobs, "v1") + if _, err := c.DeleteVolume(ctx, "v1", nil); err != nil { + t.Fatalf("delete the source volume: %v", err) + } + intents := func() int { + list, err := f.ListEntries(ctx, path.Join(catBase, "v2", intentsDir), "", "", 0) + if err != nil { + t.Fatal(err) + } + return len(list) + } + if intents() == 0 { + t.Fatal("the unknown publish left no intent") + } + for i := 0; i < 4; i++ { + if _, err := g.Run(ctx); err != nil { + t.Fatalf("gc: %v", err) + } + *now = now.Add(2 * time.Hour) // far past the grace + } + if intents() == 0 { + t.Fatal("GC settled the fork intent without the target being resolved") + } + r1, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + requireChunks(t, ctx, r1, h, want, "parent (fork intent still present)") +} + +// requireChunks fails unless h names exactly the indexes of want and each one +// reads back want's bytes (a missing index cannot pass by iterating h alone). +func requireChunks(t *testing.T, ctx context.Context, r *ChunkRemote, h storage.ChunkHead, want map[uint64][]byte, what string) { + t.Helper() + if err := chunksMismatch(ctx, r, h, want); err != nil { + t.Fatalf("%s: %v", what, err) + } +} + +func chunksMismatch(ctx context.Context, r *ChunkRemote, h storage.ChunkHead, want map[uint64][]byte) error { + if len(h.Chunks) != len(want) { + return fmt.Errorf("HEAD names %d chunks, want %d", len(h.Chunks), len(want)) + } + for idx, data := range want { + ref, ok := h.Chunks[idx] + if !ok { + return fmt.Errorf("HEAD lost chunk %d", idx) + } + if got, err := r.Get(ctx, ref.Key); err != nil || !bytes.Equal(got, data) { + return fmt.Errorf("chunk %d unreadable or changed: %v", idx, err) + } + } + return nil +} + +// The check refuses a HEAD that lost an index, even when every chunk it +// still names reads back correctly. +func TestSnapshotDelete_ChunkCheckCatchesAMissingIndex(t *testing.T) { + f, b, _, h := catalogFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + want := map[uint64][]byte{} + missing := uint64(0) + for idx, ref := range h.Chunks { + data, err := r.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + want[idx] = data + if idx >= missing { + missing = idx + 1 + } + } + if err := chunksMismatch(ctx, r, h, want); err != nil { + t.Fatalf("the matching HEAD failed the check: %v", err) + } + want[missing] = chunkBytes(0x62) // an index the HEAD does not name + if err := chunksMismatch(ctx, r, h, want); err == nil { + t.Fatal("a HEAD missing an expected chunk passed the check") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/swfs.go b/seaweed-block/core/frontend/chunkstore/swfs.go index 3c2102b004..067c9e9850 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs.go +++ b/seaweed-block/core/frontend/chunkstore/swfs.go @@ -224,30 +224,77 @@ func (c *SWFS) Put(ctx context.Context, data []byte) (string, error) { } // Get implements Blobs: resolve the fid's volume through the filer, then GET -// the needle from each location until one answers. +// the needle from each location until one answers. The needle is reported +// absent (ErrBlobNotFound) only when every location of a fresh lookup +// answers 404: cached locations can be stale after a volume moves, so their +// 404s are followed by one fresh lookup. func (c *SWFS) Get(ctx context.Context, fid string) ([]byte, error) { vid, _, ok := strings.Cut(fid, ",") if !ok { return nil, fmt.Errorf("chunkstore: bad fid %q", fid) } - urls, err := c.lookupVolume(ctx, vid) + urls, cached, err := c.lookupVolume(ctx, vid) if err != nil { return nil, err } - var lastErr error - for _, host := range urls { - b, err := c.getFrom(ctx, host, fid) - if err == nil { - return b, nil - } - lastErr = err + b, allNotFound, lastErr := c.getFromAll(ctx, urls, fid) + if lastErr == nil { + return b, nil } c.mu.Lock() delete(c.vidCache, vid) c.mu.Unlock() + if allNotFound && cached { + if urls, _, err = c.lookupVolume(ctx, vid); err != nil { + return nil, err + } + if b, allNotFound, lastErr = c.getFromAll(ctx, urls, fid); lastErr == nil { + return b, nil + } + c.mu.Lock() + delete(c.vidCache, vid) + c.mu.Unlock() + } + if allNotFound { + lastErr = &blobNotFoundError{lastErr} + } return nil, fmt.Errorf("chunkstore: read %s: %w", fid, lastErr) } +// getFromAll tries each location in turn. On failure lastErr is the last +// location's error and allNotFound whether every location answered 404. +func (c *SWFS) getFromAll(ctx context.Context, urls []string, fid string) (b []byte, allNotFound bool, lastErr error) { + allNotFound = true + for _, host := range urls { + b, err := c.getFrom(ctx, host, fid) + if err == nil { + return b, false, nil + } + lastErr = err + var se *blobStatusError + if !errors.As(err, &se) || se.code != http.StatusNotFound { + allNotFound = false + } + } + return nil, allNotFound && lastErr != nil, lastErr +} + +// blobStatusError is a volume server's non-200 answer to a needle GET. +type blobStatusError struct { + code int + host string +} + +func (e *blobStatusError) Error() string { return fmt.Sprintf("http %d from %s", e.code, e.host) } + +// blobNotFoundError marks a read every location answered 404: it reads as +// the last location's error and matches ErrBlobNotFound. +type blobNotFoundError struct{ err error } + +func (e *blobNotFoundError) Error() string { return e.err.Error() } +func (e *blobNotFoundError) Unwrap() error { return e.err } +func (e *blobNotFoundError) Is(target error) bool { return target == ErrBlobNotFound } + func (c *SWFS) getFrom(ctx context.Context, host, fid string) ([]byte, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+host+"/"+fid, nil) if err != nil { @@ -259,21 +306,23 @@ func (c *SWFS) getFrom(ctx context.Context, host, fid string) ([]byte, error) { } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("http %d from %s", resp.StatusCode, host) + return nil, &blobStatusError{code: resp.StatusCode, host: host} } return io.ReadAll(resp.Body) } -func (c *SWFS) lookupVolume(ctx context.Context, vid string) ([]string, error) { +// lookupVolume returns vid's locations; cached reports that they came from +// the cache rather than a lookup made now. +func (c *SWFS) lookupVolume(ctx context.Context, vid string) (urls []string, cached bool, err error) { c.mu.Lock() urls, ok := c.vidCache[vid] c.mu.Unlock() if ok && len(urls) > 0 { - return urls, nil + return urls, true, nil } resp, err := c.fc.LookupVolume(ctx, &filerpb.LookupVolumeRequest{VolumeIds: []string{vid}}) if err != nil { - return nil, fmt.Errorf("chunkstore: lookup volume %s: %w", vid, err) + return nil, false, fmt.Errorf("chunkstore: lookup volume %s: %w", vid, err) } for _, l := range resp.GetLocationsMap()[vid].GetLocations() { if l.GetUrl() != "" { @@ -281,12 +330,12 @@ func (c *SWFS) lookupVolume(ctx context.Context, vid string) ([]string, error) { } } if len(urls) == 0 { - return nil, fmt.Errorf("chunkstore: volume %s has no locations", vid) + return nil, false, fmt.Errorf("chunkstore: volume %s has no locations", vid) } c.mu.Lock() c.vidCache[vid] = urls c.mu.Unlock() - return urls, nil + return urls, false, nil } var ( @@ -303,7 +352,7 @@ func (c *SWFS) DeleteBlob(ctx context.Context, fid string) error { if !ok || vid == "" || needle == "" || strings.ContainsAny(fid, "/\\?#% \r\n") { return fmt.Errorf("chunkstore: bad deletion fid %q", fid) } - urls, err := c.lookupVolume(ctx, vid) + urls, _, err := c.lookupVolume(ctx, vid) if err != nil { return err } @@ -317,6 +366,9 @@ func (c *SWFS) DeleteBlob(ctx context.Context, fid string) error { return err } resp.Body.Close() + if resp.StatusCode == http.StatusBadRequest { + return fmt.Errorf("%w: delete %s: http %d", ErrBlobDeleteRejected, fid, resp.StatusCode) + } if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound { return fmt.Errorf("chunkstore: delete %s: http %d", fid, resp.StatusCode) } diff --git a/seaweed-block/core/frontend/chunkstore/swfs_test.go b/seaweed-block/core/frontend/chunkstore/swfs_test.go index 748681e3a8..b26eedeafa 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs_test.go +++ b/seaweed-block/core/frontend/chunkstore/swfs_test.go @@ -32,6 +32,7 @@ type fakeFilerGRPC struct { lookupErr error assignResp *filerpb.AssignVolumeResponse lookupVol *filerpb.LookupVolumeResponse + volLookups int // LookupVolume calls lastCreate *filerpb.CreateEntryRequest lastUpdate *filerpb.UpdateEntryRequest @@ -80,6 +81,7 @@ func (f *fakeFilerGRPC) AssignVolume(_ context.Context, r *filerpb.AssignVolumeR func (f *fakeFilerGRPC) LookupVolume(_ context.Context, r *filerpb.LookupVolumeRequest) (*filerpb.LookupVolumeResponse, error) { f.mu.Lock() defer f.mu.Unlock() + f.volLookups++ return f.lookupVol, nil } diff --git a/seaweed-block/core/frontend/chunkstore/usage.go b/seaweed-block/core/frontend/chunkstore/usage.go index d8ec500960..472c1ed877 100644 --- a/seaweed-block/core/frontend/chunkstore/usage.go +++ b/seaweed-block/core/frontend/chunkstore/usage.go @@ -38,28 +38,28 @@ import ( // SnapshotUsage is one snapshot's share of a volume's space. type SnapshotUsage struct { - Name string `json:"name"` - CreatedNs int64 `json:"createdNs"` - Class string `json:"class"` - Pinned bool `json:"pinned"` - Chunks int `json:"chunks"` - ExclusiveBytes uint64 `json:"exclusiveBytes"` + Name string `json:"name"` // the snapshot name + CreatedNs int64 `json:"createdNs"` // when it was created (Unix ns) + Class string `json:"class"` // its retention class + Pinned bool `json:"pinned"` // retention never deletes it + Chunks int `json:"chunks"` // chunks its manifest references + ExclusiveBytes uint64 `json:"exclusiveBytes"` // bytes no other holder references: what deleting it makes eligible for GC } // VolumeUsage is a volume's space accounting. type VolumeUsage struct { - VolumeID string `json:"volumeID"` - ChunkBytes uint64 `json:"chunkBytes"` // one full chunk - LiveChunks int `json:"liveChunks"` - LiveBytes uint64 `json:"liveBytes"` - Snapshots []SnapshotUsage `json:"snapshots"` - ManifestBindings int `json:"manifestBindings"` - ManifestBytes uint64 `json:"manifestBytes"` - StoredBindings int `json:"storedBindings"` - StoredBytes uint64 `json:"storedBytes"` - StoredUpperBound bool `json:"storedUpperBound"` - Policy RetentionPolicy `json:"policy"` - PolicySet bool `json:"policySet"` + VolumeID string `json:"volumeID"` // the volume + ChunkBytes uint64 `json:"chunkBytes"` // one full chunk + LiveChunks int `json:"liveChunks"` // chunks HEAD references + LiveBytes uint64 `json:"liveBytes"` // their bytes (the last chunk clipped) + Snapshots []SnapshotUsage `json:"snapshots"` // one entry per live snapshot + ManifestBindings int `json:"manifestBindings"` // stored chunk-key bindings some manifest references + ManifestBytes uint64 `json:"manifestBytes"` // their exact bytes + StoredBindings int `json:"storedBindings"` // all chunk-key bindings in the filer, referenced or not + StoredBytes uint64 `json:"storedBytes"` // their bytes; unreferenced ones counted at full chunk size + StoredUpperBound bool `json:"storedUpperBound"` // StoredBytes is an upper bound (some bindings are unreferenced) + Policy RetentionPolicy `json:"policy"` // the snapshot retention policy in force + PolicySet bool `json:"policySet"` // the volume set its own policy (else the default applies) } // chunkSize is the byte size of chunk index idx under g. diff --git a/seaweed-block/core/frontend/chunkstore/verify.go b/seaweed-block/core/frontend/chunkstore/verify.go new file mode 100644 index 0000000000..0c11116d75 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/verify.go @@ -0,0 +1,1633 @@ +package chunkstore + +// Verify: a read-only check of one volume's remote image against what its +// HEAD (and, on request, its snapshots) say. It writes nothing to the filer +// or the blob store: no intent, no mark, no tombstone, no binding. +// +// Depths, each including the one before: +// +// - meta: the HEAD root decodes and is self-consistent; its geometry +// matches VOLUME; a snapshot's document names the volume and the +// snapshot it was found under; every segment a selected root names is +// readable and passes its SHA-256 and strict decode; a fork's record +// matches the parent snapshot it was made from. References to one +// chunk with different SHA-256s disagree (CONTENT_MISMATCH). +// - bindings (the default): every chunk key a selected root references +// has a sound binding in its owner's keys/ (one listing per owner), +// not tombstoned by GC. +// - data: every distinct chunk (owner + key, across all selected roots) +// is fetched once; its length must be the chunk size and its SHA-256 +// each reference's (the rule the chunk layer applies on a read miss). +// +// The pass runs beside a live owner and beside GC, so what it reports about +// chunks comes from a small automaton (the V.* names on the functions): +// +// - V.Discover: an object (a chunk or a segment, by owner and key) a root +// view names that the pass has not seen is queued for one check; every +// reference met is recorded as seen, with nothing judged about it. +// - V.Settle: the check records the object's one outcome (its content, or +// binding missing or tombstoned, needle missing, read error) and reports +// nothing; a settled object is never checked again. +// - V.Refresh: HEAD is read again at least every RefreshInterval; a newer +// generation replaces the HEAD view (an older one is ignored), the keys +// the old view named and the new one does not are marked dropped, and +// its new keys are discovered. +// - V.Round: once every queued chunk is settled, one closing read of HEAD +// and of each selected snapshot's state; if it names a chunk not seen, +// the pass checks it and reads again, at most ClosingRounds times +// (V.GiveUp: then the pass is incomplete). +// - V.Close: a closing read that names no chunk not seen is the final view. +// Only a decodable HEAD, not older than the view, can close a pass as +// complete: a closing read that finds no HEAD, or one that does not +// decode (ROOT_INVALID), leaves no HEAD root and the pass incomplete. +// - V.Reconcile: the findings and counters are computed from the outcomes, +// the references seen and the final view alone, nowhere else. Judge, a +// pure function of an object's outcome and one reference, gives the +// outcome when it is bad, else CONTENT_MISMATCH (another hash), +// SIZE_MISMATCH (a chunk not a chunk long) or SEGMENT_UNREADABLE (a +// segment that does not decode under that reference's fields), else +// sound. Per object and class Judge gives a final reference: one finding, +// under the first final root having one (HEAD, then the snapshots not +// gone, in order) at its first such index. An object with a problem +// under any reference seen, and no finding, is counted once. A key HEAD +// dropped and names again is ROOT_INVALID, whatever its outcome. +// +// The pass therefore reports the state of each named chunk at its check, +// for the roots at the final read; a chunk damaged after its check is the +// next pass's finding. A chunk that left HEAD can be collected after GC's +// grace, and a deleted snapshot's chunks are kept only for the grace, so an +// object that no root names at the final read is not a finding. +// +// A needle is NEEDLE_MISSING only when the store reports it absent +// (ErrBlobNotFound). Any other read failure is retried; if it persists it is +// READ_ERROR, which means "not verified", not "damaged". +// +// A finding never stops the pass. Only an inability to continue does (the +// context ended, the filer failed) or a HEAD that keeps naming new chunks: +// Verify then returns the result with Complete false and the reason in +// Incomplete, the findings computed from what was checked, and the error. + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "path" + "sort" + "strings" + "sync" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// VerifyDepth selects how far Verify checks. +type VerifyDepth string + +const ( + VerifyMeta VerifyDepth = "meta" + VerifyBindings VerifyDepth = "bindings" + VerifyData VerifyDepth = "data" +) + +const ( + // DefaultVerifyConcurrency bounds the chunk reads in flight. + DefaultVerifyConcurrency = 2 + // DefaultVerifyBytesPerSecond paces chunk reads. + DefaultVerifyBytesPerSecond int64 = 32 << 20 + // DefaultVerifyRefresh is the longest a pass works from one HEAD view; + // it stays below the operation deadline, the shortest time a chunk + // that just left HEAD is still guaranteed to be kept by GC. + DefaultVerifyRefresh = 2 * time.Minute + // DefaultVerifyIntentStaleAge is the age past which a capture intent + // below HEAD's epoch is reported as stale (the gc --intent-ttl default). + DefaultVerifyIntentStaleAge = time.Hour + // DefaultVerifyClosingRounds is the default ClosingRounds. + DefaultVerifyClosingRounds = 3 +) + +// Finding classes. +const ( + FindingRootInvalid = "ROOT_INVALID" + FindingGeometry = "GEOMETRY" + FindingSegmentUnreadable = "SEGMENT_UNREADABLE" + FindingBindingMissing = "BINDING_MISSING" + FindingBindingTombstoned = "BINDING_TOMBSTONED" + FindingNeedleMissing = "NEEDLE_MISSING" + FindingContentMismatch = "CONTENT_MISMATCH" + FindingSizeMismatch = "SIZE_MISMATCH" + FindingForkRecordMismatch = "FORK_RECORD_MISMATCH" + FindingIntentStale = "INTENT_STALE" + // FindingReadError is not proof of damage: a needle (chunk or segment) + // could not be read for a reason other than the store reporting it + // absent, after retries. That object was not verified; re-run. + FindingReadError = "READ_ERROR" +) + +// A read the store does not answer with "not found" is tried this many +// times in all, the retries spaced by verifyRetryBackoff times the attempt. +const verifyReadAttempts = 3 + +var verifyRetryBackoff = 50 * time.Millisecond + +// VerifyOptions configures a Verify pass. Zero values take the defaults. +type VerifyOptions struct { + // Depth is meta, bindings (default) or data. + Depth VerifyDepth + // Snapshot adds the named snapshot to the roots checked; AllSnapshots + // adds every published snapshot not marked deleting. HEAD is always + // checked. At most one of the two may be set. + Snapshot string + AllSnapshots bool + // Concurrency bounds the chunk reads in flight (depth data). + Concurrency int + // BytesPerSecond paces chunk reads: 0 is the default, a negative value + // leaves them unpaced. + BytesPerSecond int64 + // RefreshInterval is the longest the pass works from one HEAD view. + RefreshInterval time.Duration + // IntentStaleAge is the age past which a capture intent below HEAD's + // epoch that names no key HEAD references is reported (a hint only). + IntentStaleAge time.Duration + // ClosingRounds bounds the closing reads that may name chunks not seen + // before; past it the pass is incomplete. + ClosingRounds int + + // hook, when set, runs at the named stages of a pass (a test seam). + hook func(stage string) +} + +// Verify stages passed to the hook. +const ( + verifyHookHeadWalked = "head-walked" // the first HEAD view has been read and walked + verifyHookRootsWalked = "roots-walked" // the selected snapshots have been read and walked too + verifyHookBatchChecked = "batch-checked" // a batch of checks has settled + verifyHookClosingRead = "closing-read" // a closing read is about to be made + verifyHookClosed = "closed" // the quiet closing read was made: the final view is fixed +) + +// VerifyIncomplete is why a pass did not complete. +type VerifyIncomplete string + +const ( + VerifyIncompleteDeadline VerifyIncomplete = "deadline" // the caller's deadline passed + VerifyIncompleteCancelled VerifyIncomplete = "cancelled" // the caller cancelled + VerifyIncompleteRounds VerifyIncomplete = "closing_rounds_exhausted" // every closing read named new chunks + VerifyIncompleteHeadAbsent VerifyIncomplete = "head_absent" // the closing read found no HEAD + VerifyIncompleteHeadInvalid VerifyIncomplete = "head_invalid" // the closing read's HEAD does not decode + VerifyIncompleteError VerifyIncomplete = "error" // a filer or blob store failure, or a refused request +) + +// CodeVerifyIncomplete: the closing reads could not close the pass (each +// named chunks not seen before, or the last found no usable HEAD). +const CodeVerifyIncomplete = "verify_incomplete" + +// VerifyFinding is one problem found. Segment is set for a segment's own +// problem, Index for a chunk's. +type VerifyFinding struct { + Volume string `json:"volume"` + Root string `json:"root"` + Segment *uint64 `json:"segment,omitempty"` + Index *uint64 `json:"index,omitempty"` + Owner string `json:"owner,omitempty"` + Key string `json:"key,omitempty"` + FID string `json:"fid,omitempty"` + Class string `json:"class"` + Detail string `json:"detail"` +} + +// VerifyResult is a pass's summary and findings. Complete is false when the +// pass could not finish (Incomplete says why); the counters and findings +// then cover what it checked. +type VerifyResult struct { + VolumeID string `json:"volumeID"` + Depth VerifyDepth `json:"depth"` + Complete bool `json:"complete"` + // Incomplete is why the pass did not complete ("" when it did). + Incomplete VerifyIncomplete `json:"incomplete,omitempty"` + // HeadGens are the HEAD generations the pass read, in order; the last + // is the final view's. + HeadGens []uint64 `json:"headGens"` + // Snapshots are the snapshots checked, as name/attempt. + Snapshots []string `json:"snapshots"` + // SegmentsChecked counts segment references checked (per root walked); + // SegmentReads the segment objects actually read. + SegmentsChecked int `json:"segmentsChecked"` + SegmentReads int `json:"segmentReads"` + // ChunksChecked counts the chunk references (root, index) of the final + // view; DistinctChunks the distinct chunks (owner, key) the pass saw. + ChunksChecked int `json:"chunksChecked"` + DistinctChunks int `json:"distinctChunks"` + // DistinctChunksRead and BytesRead count the chunk data read. + DistinctChunksRead int `json:"distinctChunksRead"` + BytesRead int64 `json:"bytesRead"` + // SupersededDuringVerify counts the chunks and segments that had a bad + // outcome or a problem under a reference seen during the pass, yet yield + // no finding (no final reference has a problem), once each; + // RootDeletedDuringVerify counts instead those whose problem reference + // was carried by a selected snapshot deleted during the pass. + SupersededDuringVerify int `json:"supersededDuringVerify"` + RootDeletedDuringVerify int `json:"rootDeletedDuringVerify"` + // SnapshotsDeletedDuringVerify lists, as name/attempt, the checked + // snapshots gone at the final read: they are not fully covered. + SnapshotsDeletedDuringVerify []string `json:"snapshotsDeletedDuringVerify"` + // ForkSourceGone: this volume is a fork whose source volume no longer + // exists, so its fork record could not be compared with the parent + // snapshot. Not a finding. + ForkSourceGone bool `json:"forkSourceGone,omitempty"` + // ChunksNotRead counts the READ_ERROR findings: chunks or segments that + // could not be read, so were not verified. ReadRetries counts the + // retried reads. + ChunksNotRead int `json:"chunksNotRead"` + ReadRetries int `json:"readRetries"` + FindingsByClass map[string]int `json:"findingsByClass"` + Findings []VerifyFinding `json:"findings"` +} + +// Verify checks vol's remote image at opts.Depth; see the top of this file. +func (c *Catalog) Verify(ctx context.Context, vol string, opts VerifyOptions) (VerifyResult, error) { + res := VerifyResult{VolumeID: vol, HeadGens: []uint64{}, Snapshots: []string{}, SnapshotsDeletedDuringVerify: []string{}, + FindingsByClass: map[string]int{}, Findings: []VerifyFinding{}} + refuse := func(err error) (VerifyResult, error) { + res.Incomplete = VerifyIncompleteError + return res, err + } + if opts.Depth == "" { + opts.Depth = VerifyBindings + } + res.Depth = opts.Depth + if opts.Depth != VerifyMeta && opts.Depth != VerifyBindings && opts.Depth != VerifyData { + return refuse(catErr(CodeInvalidName, false, nil, "verify depth %q: meta, bindings or data", opts.Depth)) + } + if opts.Snapshot != "" && opts.AllSnapshots { + return refuse(catErr(CodeInvalidName, false, nil, "verify: a named snapshot and all snapshots do not combine")) + } + if opts.Snapshot != "" { + if err := CheckSnapshotName(opts.Snapshot); err != nil { + return refuse(err) + } + } + if opts.Concurrency <= 0 { + opts.Concurrency = DefaultVerifyConcurrency + } + if opts.BytesPerSecond == 0 { + opts.BytesPerSecond = DefaultVerifyBytesPerSecond + } + if opts.RefreshInterval <= 0 { + opts.RefreshInterval = DefaultVerifyRefresh + } + if opts.IntentStaleAge <= 0 { + opts.IntentStaleAge = DefaultVerifyIntentStaleAge + } + if opts.ClosingRounds <= 0 { + opts.ClosingRounds = DefaultVerifyClosingRounds + } + root, err := c.volRoot(vol) + if err != nil { + return refuse(err) + } + v := &verifier{c: c, vol: vol, root: root, opts: opts, res: &res, blobs: c.blobs, + segs: map[string]*verifySegment{}, chunks: map[string]*verifyChunk{}, dropped: map[string]bool{}, + seenChunks: map[string]map[seenChunk]bool{}, seenSegs: map[string]map[seenSeg]bool{}, + pacer: &verifyPacer{rate: opts.BytesPerSecond}} + err = v.run(ctx) + v.reconcile() + sort.SliceStable(res.Findings, func(i, j int) bool { return findingLess(res.Findings[i], res.Findings[j]) }) + for _, f := range res.Findings { + res.FindingsByClass[f.Class]++ + } + res.DistinctChunks = len(v.chunks) + if err != nil { + switch { + case errors.Is(err, errVerifyHeadAbsent): + res.Incomplete = VerifyIncompleteHeadAbsent + case errors.Is(err, errVerifyHeadInvalid): + res.Incomplete = VerifyIncompleteHeadInvalid + case CodeOf(err) == CodeVerifyIncomplete: + res.Incomplete = VerifyIncompleteRounds + case errors.Is(err, context.DeadlineExceeded): + res.Incomplete = VerifyIncompleteDeadline + case errors.Is(err, context.Canceled): + res.Incomplete = VerifyIncompleteCancelled + default: + res.Incomplete = VerifyIncompleteError + } + return res, err + } + res.Complete = true + return res, nil +} + +// Why a closing read leaves no HEAD root (wrapped in CodeVerifyIncomplete). +var ( + errVerifyHeadAbsent = errors.New("chunkstore: verify: the closing read found no HEAD") + errVerifyHeadInvalid = errors.New("chunkstore: verify: the closing read's HEAD does not decode") +) + +// verifySegment is one segment object (owner, key): read once, like a chunk +// (keys are never rebound). Its one outcome is a bad one (class and detail: +// binding missing, needle missing, read error) or its content (sum, body: +// a segment keeps its bytes). A reference to it is judged at need +// (judgeSegment); nothing about a reference is kept but the decode memo. +type verifySegment struct { + owner, key string + fid string + tombstoned bool + class, detail string + sum [32]byte + body []byte + memo map[segRef]segJudged // decodes by the full reference (every input of the decode) +} + +// segRef is one root's reference to a segment, with every root field its +// decode depends on. +type segRef struct { + group, chunkBytes, remoteLSN uint64 + ref storage.ChunkSegment +} + +// segJudged is Judge's answer for a segment reference: a class (and detail) +// when it is not sound, else this root's chunk references. +type segJudged struct { + class, detail string + chunks map[uint64]storage.ChunkRef +} + +// segID is a segment's identity: its owner and key. +func segID(vol string, ref storage.ChunkSegment) string { return chunkIdentity(vol, ref.Key) } + +// Seen references, per object: the root (HEAD, or a snapshot's label), the +// index (a chunk's) or the reference with its root fields (a segment's). +type seenChunk struct { + root string + idx uint64 + sha [32]byte +} + +type seenSeg struct { + root string + ref segRef +} + +const headRoot = "HEAD" // the root of every HEAD generation's references + +// verifyChunk is one distinct chunk (owner volume + the owner's own key): +// unseen while absent from the verifier's map, then queued, then settled. +type verifyChunk struct { + id string + owner, key string + fid string + bound bool // a sound, untombstoned binding was found + + // The outcome, under the verifier's lock until the checks are joined: + // class and detail of a bad outcome (binding missing or tombstoned, + // needle missing, read error), or the content read (read: its SHA-256 + // and length). + settled bool + class, detail string + read bool + digest [32]byte + length int +} + +// verifyView is one root as last read: its references by index, and its +// root document (for the segments it names). +type verifyView struct { + label string + h storage.ChunkHead + chunks map[uint64]storage.ChunkRef + // snapshots only: the identity they were found under, and whether the + // final round read them gone. + name, attempt string + gone bool +} + +type verifier struct { + c *Catalog + vol string + root string + opts VerifyOptions + blobs Blobs + pacer *verifyPacer + + geo Geometry + chunkBytes uint64 + nChunks uint64 + + mu sync.Mutex + res *VerifyResult + segs map[string]*verifySegment // the segments read, by identity + chunks map[string]*verifyChunk // the chunks seen, by identity + pending []*verifyChunk // queued, not yet checked + listed bool // the owners' keys/ were listed once + + head *verifyView // the HEAD view; nil without a usable HEAD + dropped map[string]bool // keys a HEAD view named and a later one did not + snaps []*verifyView // the selected snapshots, in order + lastRefresh time.Time + + seenChunks map[string]map[seenChunk]bool // the references seen, per chunk + seenSegs map[string]map[seenSeg]bool // the references seen, per segment +} + +func (v *verifier) hook(stage string) { + if v.opts.hook != nil { + v.opts.hook(stage) + } +} + +func (v *verifier) finding(f VerifyFinding) { + f.Volume = v.vol + v.mu.Lock() + v.res.Findings = append(v.res.Findings, f) + if f.Class == FindingReadError { + v.res.ChunksNotRead++ + } + v.mu.Unlock() +} + +func isContextErr(ctx context.Context, err error) bool { + return ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) +} + +// fetch reads one needle. A needle the store reports absent (ErrBlobNotFound) +// and a context error are returned at once; any other failure is retried, +// up to verifyReadAttempts reads in all, before it is returned. +func (v *verifier) fetch(ctx context.Context, fid string) ([]byte, error) { + for attempt := 1; ; attempt++ { + data, err := v.blobs.Get(ctx, fid) + if err == nil || errors.Is(err, ErrBlobNotFound) || isContextErr(ctx, err) || attempt == verifyReadAttempts { + return data, err + } + v.mu.Lock() + v.res.ReadRetries++ + v.mu.Unlock() + t := time.NewTimer(verifyRetryBackoff * time.Duration(attempt)) + select { + case <-t.C: + case <-ctx.Done(): + t.Stop() + return nil, ctx.Err() + } + } +} + +// readErrorDetail describes a read that failed for a reason other than "not found". +func readErrorDetail(err error) string { + return fmt.Sprintf("not verified: could not read the needle in %d attempts (re-run): %v", verifyReadAttempts, err) +} + +// verifyPrefetched serves one needle already read, so the shared segment +// decoder verifies exactly the bytes fetch returned. +type verifyPrefetched struct { + fid string + body []byte +} + +func (p verifyPrefetched) Put(context.Context, []byte) (string, error) { + return "", errors.New("chunkstore: verify is read-only") +} + +func (p verifyPrefetched) Get(_ context.Context, fid string) ([]byte, error) { + if fid != p.fid { + return nil, fmt.Errorf("chunkstore: verify: unexpected needle %s", fid) + } + return p.body, nil +} + +// abortErr turns a failure that stops the pass into its error: a context +// error stays one (the CLI reports deadline_exceeded), anything else from +// the filer is remote_unavailable. +func abortErr(ctx context.Context, err error, format string, a ...any) error { + if ctx.Err() != nil { + return fmt.Errorf("chunkstore: verify: %s: %w", fmt.Sprintf(format, a...), ctx.Err()) + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return fmt.Errorf("chunkstore: verify: %s: %w", fmt.Sprintf(format, a...), err) + } + if CodeOf(err) != "" { + return err + } + return remoteErr(err, format, a...) +} + +func headLabel(gen uint64) string { return fmt.Sprintf("HEAD gen %d", gen) } + +func (v *verifier) run(ctx context.Context) error { + vi, ok, err := v.c.ReadVolume(ctx, v.vol) + if err != nil { + if CodeOf(err) == CodeRemoteUnavailable || ctx.Err() != nil { + return abortErr(ctx, err, "read VOLUME of %s", v.vol) + } + v.finding(VerifyFinding{Root: "VOLUME", Class: FindingRootInvalid, Detail: err.Error()}) + return nil + } + if !ok { + return catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", v.vol) + } + v.geo = vi.Geometry + v.chunkBytes = uint64(v.geo.ChunkBlocks) * uint64(v.geo.BlockSize) + if v.geo.ChunkBlocks > 0 { + v.nChunks = (v.geo.NumBlocks + uint64(v.geo.ChunkBlocks) - 1) / uint64(v.geo.ChunkBlocks) + } + if v.chunkBytes == 0 { + v.finding(VerifyFinding{Root: "VOLUME", Class: FindingGeometry, Detail: fmt.Sprintf("VOLUME geometry %+v has no chunk size", v.geo)}) + } + if err := v.forkRecord(ctx, vi); err != nil { + return err + } + + // HEAD: the root once, then the segments it names. + e, err := v.c.f.LookupEntry(ctx, v.root, headName) + switch { + case errors.Is(err, ErrNotFound): + v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: "the volume has a VOLUME entry but no HEAD"}) + case err != nil: + return abortErr(ctx, err, "read HEAD of %s", v.vol) + default: + h, derr := decodeHead(path.Join(v.root, headName), e) + if derr != nil { + v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: derr.Error()}) + break + } + v.lastRefresh = v.c.now() + if _, err := v.refresh(ctx, h); err != nil { + return err + } + if err := v.intents(ctx, h, v.head.chunks); err != nil { + return err + } + } + v.hook(verifyHookHeadWalked) + + if err := v.snapshots(ctx); err != nil { + return err + } + v.hook(verifyHookRootsWalked) + for rounds := 0; ; { + if err := v.drain(ctx); err != nil { + return err + } + named, err := v.round(ctx) + if err != nil { + return err + } + if !named { + v.hook(verifyHookClosed) + return nil // V.Close: this read is the final view + } + if rounds++; rounds == v.opts.ClosingRounds { + return catErr(CodeVerifyIncomplete, true, nil, // V.GiveUp + "verify of %s: each of %d closing reads of HEAD named chunks not seen before; the pass is incomplete (re-run when the volume is quieter)", + v.vol, rounds) + } + } +} + +// drain checks every queued chunk, batch by batch, refreshing HEAD between +// batches (a refresh can queue more). +func (v *verifier) drain(ctx context.Context) error { + for len(v.pending) > 0 { + batch := v.pending + v.pending = nil + if err := v.checkBindings(ctx, batch, !v.listed); err != nil { + return err + } + v.listed = true + if v.opts.Depth == VerifyData { + if err := v.checkData(ctx, batch); err != nil { + return err + } + } + v.hook(verifyHookBatchChecked) + if err := v.maybeRefresh(ctx); err != nil { + return err + } + } + return nil +} + +// V.Round: once every queued chunk is settled, read HEAD and each selected snapshot's state once; report whether HEAD named a chunk not seen. +func (v *verifier) round(ctx context.Context) (bool, error) { + v.hook(verifyHookClosingRead) + named := false + if v.head != nil { + var err error + if named, err = v.readHead(ctx, true); err != nil { + return false, err + } + } + for _, s := range v.snaps { + active, err := v.snapshotActive(ctx, s) + if err != nil { + return false, err + } + s.gone = !active + } + return named, nil +} + +// ---- roots and segments ---- + +// V.Discover and V.Settle (segments): the segment ref names, read once per (owner, key) by this pass, its outcome kept. An error stops the pass. +func (v *verifier) segment(ctx context.Context, ref storage.ChunkSegment) (*verifySegment, error) { + id := segID(v.vol, ref) + if s := v.segs[id]; s != nil { + return s, nil + } + s, err := v.readSegment(ctx, ref) + if err != nil { + return nil, err + } + v.segs[id] = s + return s, nil +} + +func (v *verifier) readSegment(ctx context.Context, ref storage.ChunkSegment) (*verifySegment, error) { + if v.blobs == nil { + return nil, errors.New("chunkstore: verify needs a blob reader for segmented roots") + } + r, err := NewChunkRemote(v.c.f, v.blobs, v.root) + if err != nil { + return nil, err + } + s := &verifySegment{owner: ref.Owner, key: ref.Key, memo: map[segRef]segJudged{}} + dir, name, err := r.keyLocation(ref.Key) + if err != nil { + s.class, s.detail = FindingBindingMissing, "segment binding: "+err.Error() + return s, nil + } + e, err := v.c.f.LookupEntry(ctx, dir, name) + if errors.Is(err, ErrNotFound) { + s.class, s.detail = FindingBindingMissing, "segment binding not found" + return s, nil + } + if err != nil { + return nil, abortErr(ctx, err, "read segment binding %s/%s", dir, name) + } + s.fid = string(e.Extended[extFid]) + if bad := bindingProblem(e); bad != "" { + s.class, s.detail = FindingBindingMissing, "invalid segment binding: "+bad + return s, nil + } + s.tombstoned = len(e.Extended[extGCDeleted]) != 0 + v.mu.Lock() + v.res.SegmentReads++ + v.mu.Unlock() + body, err := v.fetch(ctx, s.fid) + switch { + case err == nil: + case isContextErr(ctx, err): + return nil, abortErr(ctx, err, "read segment %s", ref.Key) + case errors.Is(err, ErrBlobNotFound): + s.class, s.detail = FindingNeedleMissing, "segment needle not found: "+err.Error() + return s, nil + default: + s.class, s.detail = FindingReadError, readErrorDetail(err) + return s, nil + } + s.sum, s.body = sha256.Sum256(body), body + return s, nil +} + +// V.Reconcile's Judge for a segment reference (also used to walk a root): the segment's bad outcome; a hash mismatch; bytes that do not decode under this reference's own fields (SEGMENT_UNREADABLE); else this root's chunk references. +func (v *verifier) judgeSegment(ctx context.Context, s *verifySegment, k segRef) segJudged { + switch { + case s.class != "": + return segJudged{class: s.class, detail: s.detail} + case k.ref.SHA256 != s.sum: + return segJudged{class: FindingContentMismatch, detail: fmt.Sprintf("segment SHA-256 %s, reference %s", hex.EncodeToString(s.sum[:]), hex.EncodeToString(k.ref.SHA256[:]))} + } + // A memo of the decode, keyed by the full reference: the decode is a + // function of the bytes and of k alone, so the memo cannot change an + // answer; it only saves decoding a segment again at each walk. + if j, ok := s.memo[k]; ok { + return j + } + j := segJudged{} + r, err := NewChunkRemote(v.c.f, verifyPrefetched{s.fid, s.body}, v.root) + if err == nil { + r.mu.Lock() + r.fids[k.ref.Key] = s.fid + r.mu.Unlock() + one := storage.ChunkHead{Segments: map[uint64]storage.ChunkSegment{k.group: k.ref}, ChunkBytes: k.chunkBytes, + ManifestChunkCount: k.ref.Count, RemoteLSN: k.remoteLSN, State: storage.ChunkHeadActive} + var resolved storage.ChunkHead + if resolved, err = r.resolveManifest(ctx, one); err == nil { + j.chunks = resolved.Chunks + } + } + if err != nil { + j = segJudged{class: FindingSegmentUnreadable, detail: err.Error()} + } + s.memo[k] = j + return j +} + +// bindingProblem is what makes e unusable as a chunk key binding, or "". +func bindingProblem(e *filerpb.Entry) string { + switch { + case e.GetIsDirectory(): + return "is a directory" + case len(e.GetChunks()) != 0: + return fmt.Sprintf("carries %d filer chunks", len(e.GetChunks())) + case string(e.Extended[extKind]) != kindChunkKey: + return fmt.Sprintf("kind %q, want %q", e.Extended[extKind], kindChunkKey) + case len(e.Extended[extFid]) == 0: + return "no fid" + } + return "" +} + +// walk reads the segments root h (of root, HEAD or a snapshot's label) names +// and returns its chunk references by index, and the segment groups whose +// reference Judge does not find sound (their chunks are unknown). Every +// reference met is recorded as seen. +func (v *verifier) walk(ctx context.Context, root string, h storage.ChunkHead) (map[uint64]storage.ChunkRef, map[uint64]bool, error) { + out := map[uint64]storage.ChunkRef{} + unusable := map[uint64]bool{} + if h.Segments == nil { + for idx, ref := range h.Chunks { + out[idx] = ref + } + } + for _, g := range sortedGroups(h.Segments) { + v.mu.Lock() + v.res.SegmentsChecked++ + v.mu.Unlock() + s, err := v.segment(ctx, h.Segments[g]) + if err != nil { + return out, unusable, err + } + k := segRef{group: g, chunkBytes: h.ChunkBytes, remoteLSN: h.RemoteLSN, ref: h.Segments[g]} + see(v.seenSegs, segID(v.vol, k.ref), seenSeg{root, k}) + j := v.judgeSegment(ctx, s, k) + if j.class != "" { + unusable[g] = true + continue + } + for idx, cr := range j.chunks { + out[idx] = cr + } + } + for idx, ref := range out { + see(v.seenChunks, chunkIdentity(v.vol, ref.Key), seenChunk{root, idx, ref.SHA256}) + } + return out, unusable, nil +} + +// see records a reference to object id as seen. +func see[R comparable](seen map[string]map[R]bool, id string, r R) { + if seen[id] == nil { + seen[id] = map[R]bool{} + } + seen[id][r] = true +} + +// geometry reports a root's chunk size and chunk indices against VOLUME. +func (v *verifier) geometry(label string, h storage.ChunkHead, chunks map[uint64]storage.ChunkRef) { + if h.Segments != nil && h.ChunkBytes != v.chunkBytes { + v.finding(VerifyFinding{Root: label, Class: FindingGeometry, + Detail: fmt.Sprintf("root chunk_bytes %d, VOLUME chunk size %d", h.ChunkBytes, v.chunkBytes)}) + } + for _, idx := range sortedIndexes(chunks) { + if idx >= v.nChunks { + i := idx + owner, key := splitIdentity(chunkIdentity(v.vol, chunks[idx].Key)) + v.finding(VerifyFinding{Root: label, Index: &i, Owner: owner, Key: key, Class: FindingGeometry, + Detail: fmt.Sprintf("chunk index %d outside the volume (%d chunks)", idx, v.nChunks)}) + } + } +} + +// V.Discover: queue one check of each chunk the references name that this pass has not seen; report whether there was one. +func (v *verifier) discover(chunks map[uint64]storage.ChunkRef) bool { + found := false + for _, idx := range sortedIndexes(chunks) { + id := chunkIdentity(v.vol, chunks[idx].Key) + if v.chunks[id] != nil { + continue + } + owner, key := splitIdentity(id) + w := &verifyChunk{id: id, owner: owner, key: key} + v.chunks[id] = w + found = true + if v.opts.Depth == VerifyMeta { + w.settled = true // nothing to check at this depth + continue + } + v.pending = append(v.pending, w) + } + return found +} + +// V.Settle: record w's outcome (a bad outcome's class and detail, or none); report nothing. +func (v *verifier) settle(w *verifyChunk, class, detail string) { + v.mu.Lock() + w.settled, w.class, w.detail = true, class, detail + v.mu.Unlock() +} + +// snapshotActive reads snapshot s's state again (part of V.Round): its name +// record must still name s's attempt, and the attempt entry must still +// exist, neither aborted nor marked deleting (the attempt path is never +// reused, so a snapshot read gone stays gone). +func (v *verifier) snapshotActive(ctx context.Context, s *verifyView) (bool, error) { + ne, err := v.c.f.LookupEntry(ctx, path.Join(v.root, snapNamesDir), s.name) + if errors.Is(err, ErrNotFound) { + return false, nil + } + if err != nil { + return false, abortErr(ctx, err, "re-read snapshot name %s/%s", v.vol, s.name) + } + if rec, err := decodeNameRecord(path.Join(v.root, snapNamesDir, s.name), ne); err == nil && rec.Attempt != s.attempt { + return false, nil + } + e, err := v.c.f.LookupEntry(ctx, path.Join(v.root, snapsDir, s.name), s.attempt) + if errors.Is(err, ErrNotFound) { + return false, nil + } + if err != nil { + return false, abortErr(ctx, err, "re-read snapshot %s/%s/%s", v.vol, s.name, s.attempt) + } + st := string(e.Extended[extSnapState]) + return st != SnapAborted && st != SnapDeleting && len(e.Extended[extSnapDeletedNs]) == 0, nil +} + +func sortedIndexes(m map[uint64]storage.ChunkRef) []uint64 { + out := make([]uint64, 0, len(m)) + for idx := range m { + out = append(out, idx) + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// splitIdentity splits a chunkIdentity into the owner volume and its key. +func splitIdentity(id string) (owner, key string) { + owner, key, _ = strings.Cut(id, "\x00") + return owner, key +} + +// ---- snapshots and fork record ---- + +func (v *verifier) snapshots(ctx context.Context) error { + if v.opts.Snapshot != "" { + ref, ok, err := v.c.resolveSnap(ctx, v.vol, v.opts.Snapshot) + if err != nil { + if CodeOf(err) == CodeRemoteUnavailable || ctx.Err() != nil { + return abortErr(ctx, err, "read snapshot %s/%s", v.vol, v.opts.Snapshot) + } + v.finding(VerifyFinding{Root: "snapshot " + v.opts.Snapshot, Class: FindingRootInvalid, Detail: err.Error()}) + return nil + } + if !ok || ref.entry == nil || ref.info.State == SnapAborted { + return catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", v.vol, v.opts.Snapshot) + } + if ref.info.State == SnapDeleting { + return catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted; GC may already reclaim its chunks", v.vol, v.opts.Snapshot) + } + return v.snapshot(ctx, v.opts.Snapshot, ref) + } + if !v.opts.AllSnapshots { + return nil + } + dir := path.Join(v.root, snapNamesDir) + after := "" + for { + page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) + if err != nil { + return abortErr(ctx, err, "list snapshots of %s", v.vol) + } + for _, e := range page { + if e.GetName() <= after { + return remoteErr(nil, "non-advancing snapshot listing of %s", v.vol) + } + after = e.GetName() + ref, ok, err := v.c.resolveSnap(ctx, v.vol, e.GetName()) + if err != nil { + if CodeOf(err) == CodeRemoteUnavailable || ctx.Err() != nil { + return abortErr(ctx, err, "read snapshot %s/%s", v.vol, e.GetName()) + } + v.finding(VerifyFinding{Root: "snapshot " + e.GetName(), Class: FindingRootInvalid, Detail: err.Error()}) + continue + } + if !ok || ref.entry == nil || ref.info.State == SnapAborted || ref.info.State == SnapDeleting { + continue + } + if err := v.snapshot(ctx, e.GetName(), ref); err != nil { + return err + } + } + if len(page) < listPage { + return nil + } + } +} + +// snapshot selects the snapshot found under name, at the attempt its name +// record names: that path is its identity (label, state reads), and a +// document naming another volume or snapshot is ROOT_INVALID. Its +// references are fixed; its chunks are discovered (V.Discover). +func (v *verifier) snapshot(ctx context.Context, name string, ref snapRef) error { + s := &verifyView{label: "snapshot " + name + "/" + ref.rec.Attempt, h: ref.info.Head(), name: name, attempt: ref.rec.Attempt} + v.res.Snapshots = append(v.res.Snapshots, name+"/"+s.attempt) + v.snaps = append(v.snaps, s) + if ref.info.VolumeID != v.vol || ref.info.Name != name { + v.finding(VerifyFinding{Root: s.label, Class: FindingRootInvalid, + Detail: fmt.Sprintf("snapshot document names %s/%s, found as %s/%s", ref.info.VolumeID, ref.info.Name, v.vol, name)}) + } + if ref.info.geo != (Geometry{}) && ref.info.geo != v.geo { + v.finding(VerifyFinding{Root: s.label, Class: FindingGeometry, Detail: fmt.Sprintf("snapshot geometry %+v, VOLUME %+v", ref.info.geo, v.geo)}) + } + chunks, _, err := v.walk(ctx, s.label, s.h) + if err != nil { + return err + } + s.chunks = chunks + v.geometry(s.label, s.h, chunks) + v.discover(chunks) + return nil +} + +// forkRecord checks a fork's record against the parent snapshot it names: +// some attempt of that snapshot, at the recorded source generation, must +// have exactly the recorded HEAD digest (attempt entries are never +// removed, so a parent snapshot deleted or renamed since still answers). +func (v *verifier) forkRecord(ctx context.Context, vi VolumeInfo) error { + fr := vi.Fork + if vi.Origin != OriginFork || fr == nil { + return nil + } + const label = "VOLUME fork record" + mismatch := func(format string, a ...any) error { + v.finding(VerifyFinding{Root: label, Owner: fr.Source, Class: FindingForkRecordMismatch, Detail: fmt.Sprintf(format, a...)}) + return nil + } + if CheckVolumeID(fr.Source) != nil || CheckSnapshotName(fr.Snapshot) != nil { + return mismatch("fork record names source %q snapshot %q", fr.Source, fr.Snapshot) + } + dir := path.Join(v.c.base, fr.Source, snapsDir, fr.Snapshot) + after := "" + sawGen := false + for { + page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) + if err != nil { + return abortErr(ctx, err, "list attempts of %s/%s", fr.Source, fr.Snapshot) + } + for _, e := range page { + if e.GetName() <= after { + return remoteErr(nil, "non-advancing attempt listing of %s/%s", fr.Source, fr.Snapshot) + } + after = e.GetName() + info, _, err := decodeSnap(path.Join(dir, e.GetName()), e) + if err != nil || info.State == SnapAborted || info.HeadGen != fr.SourceGen { + continue + } + sawGen = true + if info.digest == fr.HeadSHA256 { + return nil + } + } + if len(page) < listPage { + break + } + } + if sawGen { + return mismatch("no attempt of snapshot %s/%s at gen %d has HEAD digest %s", fr.Source, fr.Snapshot, fr.SourceGen, fr.HeadSHA256) + } + // The source volume itself may have been deleted since the fork: its + // snapshot records went with it and there is nothing to compare with. + // That is not damage to this volume, whose chunks are checked through + // its own roots. + if _, ok, err := v.c.ReadVolume(ctx, fr.Source); err != nil { + return abortErr(ctx, err, "read fork source %s", fr.Source) + } else if !ok { + v.res.ForkSourceGone = true + return nil + } + return mismatch("no attempt of snapshot %s/%s at gen %d found", fr.Source, fr.Snapshot, fr.SourceGen) +} + +// ---- intents ---- + +// intents reports capture intents that look stale: below HEAD's epoch, +// older than IntentStaleAge, and naming no key HEAD references. It is a +// hint; whether GC may expire one is GC's decision, with blockmaster +// authority. An intent that does not decode is an invalid GC root. +func (v *verifier) intents(ctx context.Context, h storage.ChunkHead, chunks map[uint64]storage.ChunkRef) error { + named := map[string]bool{} + for _, ref := range chunks { + named[chunkIdentity(v.vol, ref.Key)] = true + } + for _, ref := range h.Segments { + named[chunkIdentity(v.vol, ref.Key)] = true + } + now := v.c.now() + dir := path.Join(v.root, intentsDir) + after := "" + for { + page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) + if err != nil { + return abortErr(ctx, err, "list intents of %s", v.vol) + } + for _, e := range page { + if e.GetName() <= after { + return remoteErr(nil, "non-advancing intent listing of %s", v.vol) + } + after = e.GetName() + in, err := decodeIntent(path.Join(dir, e.GetName()), e) + if err != nil { + v.finding(VerifyFinding{Root: "intent " + e.GetName(), Class: FindingRootInvalid, Detail: err.Error()}) + continue + } + if strings.HasPrefix(in.Holder, "snapshot:") || strings.HasPrefix(in.Holder, "fork:") { + continue // copy intents never expire by epoch + } + age := now.Sub(time.Unix(0, in.CreatedNs)) + if in.Epoch >= h.Epoch || age <= v.opts.IntentStaleAge { + continue + } + bound := false + for _, k := range in.Keys { + if named[chunkIdentity(v.vol, k)] { + bound = true + break + } + } + if bound { + continue + } + v.finding(VerifyFinding{Root: "intent " + in.ID, Class: FindingIntentStale, + Detail: fmt.Sprintf("capture intent of %q at epoch %d below HEAD epoch %d, %s old, naming %d keys HEAD does not reference", + in.Holder, in.Epoch, h.Epoch, age.Round(time.Second), len(in.Keys))}) + } + if len(page) < listPage { + return nil + } + } +} + +// ---- refresh ---- + +// maybeRefresh reads HEAD again (V.Refresh) once RefreshInterval has passed since the last read. +func (v *verifier) maybeRefresh(ctx context.Context) error { + if v.head == nil || v.c.now().Sub(v.lastRefresh) < v.opts.RefreshInterval { + return nil + } + _, err := v.readHead(ctx, false) + return err +} + +// readHead reads HEAD and applies it (V.Refresh); it reports whether HEAD +// named a chunk not seen. A periodic read that finds no HEAD, one that does +// not decode, or an older generation changes nothing: the closing read +// decides. At the closing read (closing set) every answer decides the final +// view: no HEAD leaves no HEAD root and the pass incomplete (HEAD absent); +// an undecodable one is ROOT_INVALID, no HEAD root, incomplete (HEAD +// invalid); an older generation than the view cannot be the final view and +// cannot keep the earlier one, so the pass is incomplete (an error). +func (v *verifier) readHead(ctx context.Context, closing bool) (bool, error) { + v.lastRefresh = v.c.now() + e, err := v.c.f.LookupEntry(ctx, v.root, headName) + if errors.Is(err, ErrNotFound) { + if !closing { + return false, nil + } + v.head = nil + return false, catErr(CodeVerifyIncomplete, true, errVerifyHeadAbsent, "verify of %s: the closing read found no HEAD; the pass has no HEAD to report against", v.vol) + } + if err != nil { + return false, abortErr(ctx, err, "refresh HEAD of %s", v.vol) + } + h, err := decodeHead(path.Join(v.root, headName), e) + if err != nil { + if !closing { + return false, nil + } + v.head = nil + v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: "HEAD at the closing read: " + err.Error()}) + return false, catErr(CodeVerifyIncomplete, true, errVerifyHeadInvalid, "verify of %s: the HEAD of the closing read does not decode", v.vol) + } + if closing && v.head != nil && h.Gen < v.head.h.Gen { + return false, remoteErr(nil, "verify of %s: the closing read returned HEAD gen %d, older than gen %d already read", v.vol, h.Gen, v.head.h.Gen) + } + return v.refresh(ctx, h) +} + +// V.Refresh: replace the HEAD view with h unless h is older (or the same); mark the keys it drops; discover its new keys. +func (v *verifier) refresh(ctx context.Context, h storage.ChunkHead) (bool, error) { + if v.head != nil && (h.Gen < v.head.h.Gen || h.Gen == v.head.h.Gen && h.Epoch == v.head.h.Epoch) { + return false, nil + } + chunks, unusable, err := v.walk(ctx, headRoot, h) + if err != nil { + return false, err + } + if v.head != nil { + // A key the old view named that h does not is dropped, unless its + // old index lies in a segment of h that could not be read. + perSeg := uint64(0) + if h.ChunkBytes > 0 { + perSeg = manifestSegmentBytes / h.ChunkBytes + } + now := map[string]bool{} + for _, ref := range chunks { + now[chunkIdentity(v.vol, ref.Key)] = true + } + for idx, ref := range v.head.chunks { + if id := chunkIdentity(v.vol, ref.Key); !now[id] && (perSeg == 0 || !unusable[idx/perSeg]) { + v.dropped[id] = true + } + } + } + v.head = &verifyView{label: headLabel(h.Gen), h: h, chunks: chunks} + v.res.HeadGens = append(v.res.HeadGens, h.Gen) + return v.discover(chunks), nil +} + +// ---- bindings ---- + +// checkBindings checks the binding of every chunk in batch. The first batch +// lists each owner's keys/ once; chunks not found in a listing (bound after +// it, or queued by a refresh) are looked up one by one. +func (v *verifier) checkBindings(ctx context.Context, batch []*verifyChunk, list bool) error { + found := map[*verifyChunk]*filerpb.Entry{} + if list { + byOwner := map[string]map[string]*verifyChunk{} + var owners []string + for _, w := range batch { + name, err := keyName(w.key) + if err != nil { + continue + } + if byOwner[w.owner] == nil { + byOwner[w.owner] = map[string]*verifyChunk{} + owners = append(owners, w.owner) + } + byOwner[w.owner][name] = w + } + sort.Strings(owners) + for _, owner := range owners { + if err := v.maybeRefresh(ctx); err != nil { + return err + } + if CheckVolumeID(owner) != nil { + continue + } + want := byOwner[owner] + dir := path.Join(v.c.base, owner, keysDir) + after := "" + for { + page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) + if err != nil { + return abortErr(ctx, err, "list the chunk keys of %s", owner) + } + for _, e := range page { + if e.GetName() <= after { + return remoteErr(nil, "non-advancing chunk key listing of %s", owner) + } + after = e.GetName() + if w := want[e.GetName()]; w != nil { + found[w] = e + } + } + if len(page) < listPage { + break + } + } + } + } + for _, w := range batch { + e := found[w] + if e == nil { + var err error + if e, err = v.lookupBinding(ctx, w); err != nil { + return err + } + } + v.evaluateBinding(w, e) + } + return nil +} + +// lookupBinding reads w's binding directly; nil when it does not exist. +func (v *verifier) lookupBinding(ctx context.Context, w *verifyChunk) (*filerpb.Entry, error) { + if CheckVolumeID(w.owner) != nil { + return nil, nil + } + name, err := keyName(w.key) + if err != nil { + return nil, nil + } + dir := path.Join(v.c.base, w.owner, keysDir) + e, err := v.c.f.LookupEntry(ctx, dir, name) + if errors.Is(err, ErrNotFound) { + return nil, nil + } + if err != nil { + return nil, abortErr(ctx, err, "read chunk key binding %s/%s", dir, name) + } + return e, nil +} + +// V.Settle (bindings): a missing, invalid or tombstoned binding is w's outcome; a sound one settles it at depth bindings. +func (v *verifier) evaluateBinding(w *verifyChunk, e *filerpb.Entry) { + if e == nil { + v.settle(w, FindingBindingMissing, fmt.Sprintf("no binding in %s/keys", w.owner)) + return + } + w.fid = string(e.Extended[extFid]) + switch bad := bindingProblem(e); { + case bad != "": + v.settle(w, FindingBindingMissing, "invalid binding: "+bad) + case len(e.Extended[extGCDeleted]) != 0: + v.settle(w, FindingBindingTombstoned, fmt.Sprintf("binding tombstoned by GC (%s=%s)", extGCDeleted, e.Extended[extGCDeleted])) + default: + w.bound = true + if v.opts.Depth != VerifyData { + v.settle(w, "", "") + } + } +} + +// ---- data ---- + +// checkData fetches every bound chunk of batch once, at bounded concurrency +// and paced. +func (v *verifier) checkData(ctx context.Context, batch []*verifyChunk) error { + if v.blobs == nil { + return errors.New("chunkstore: verify needs a blob reader for depth data") + } + jobs := make(chan *verifyChunk) + var ( + wg sync.WaitGroup + errMu sync.Mutex + firstEr error + ) + setErr := func(err error) { + errMu.Lock() + if firstEr == nil { + firstEr = err + } + errMu.Unlock() + } + getErr := func() error { + errMu.Lock() + defer errMu.Unlock() + return firstEr + } + wctx, cancel := context.WithCancel(ctx) + defer cancel() + for i := 0; i < v.opts.Concurrency; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for w := range jobs { + if err := v.readChunk(wctx, w); err != nil { + setErr(err) + cancel() + } + } + }() + } + dispatch := func() error { + for _, w := range batch { + if !w.bound { + continue + } + if err := getErr(); err != nil { + return err + } + if err := v.maybeRefresh(ctx); err != nil { + return err + } + if err := v.pacer.wait(wctx, int64(v.chunkBytes)); err != nil { + if werr := getErr(); werr != nil { + return werr + } + return abortErr(ctx, err, "pace chunk reads") + } + select { + case jobs <- w: + case <-wctx.Done(): + if err := getErr(); err != nil { + return err + } + return abortErr(ctx, wctx.Err(), "read chunks of %s", v.vol) + } + } + return nil + } + if err := dispatch(); err != nil { + // Stop the reads in flight before waiting for them, so a known + // failure is not held up by a read that would end only with the + // caller's deadline. The failure that stopped the pass is the one + // returned, not the cancellation it caused in the readers. + setErr(err) + cancel() + } + close(jobs) + wg.Wait() + return getErr() +} + +// V.Settle (data): read w's needle once and record the outcome (missing, read error, wrong size, or the content's SHA-256). +func (v *verifier) readChunk(ctx context.Context, w *verifyChunk) error { + data, err := v.fetch(ctx, w.fid) + switch { + case err == nil: + case isContextErr(ctx, err): + return abortErr(ctx, err, "read chunk %s", w.fid) + case errors.Is(err, ErrBlobNotFound): + v.settle(w, FindingNeedleMissing, err.Error()) + return nil + default: + v.settle(w, FindingReadError, readErrorDetail(err)) + return nil + } + sum := sha256.Sum256(data) + v.mu.Lock() + defer v.mu.Unlock() + v.res.DistinctChunksRead++ + v.res.BytesRead += int64(len(data)) + w.settled, w.read, w.digest, w.length = true, true, sum, len(data) + return nil +} + +// ---- reconcile ---- + +// V.Reconcile's Judge for a chunk reference: the chunk's bad outcome; a hash mismatch; a wrong length; else sound (""). +func (v *verifier) judgeChunk(w *verifyChunk, sha [32]byte) (string, string) { + switch { + case w.class != "": + return w.class, w.detail + case !w.read: // checked to its binding (depth bindings), or not checked (depth meta) + return "", "" + case sha != w.digest: + return FindingContentMismatch, fmt.Sprintf("needle SHA-256 %s, reference %s", hex.EncodeToString(w.digest[:]), hex.EncodeToString(sha[:])) + case uint64(w.length) != v.chunkBytes: + return FindingSizeMismatch, fmt.Sprintf("needle holds %d bytes, chunk size %d", w.length, v.chunkBytes) + } + return "", "" +} + +// judged is Judge's answer for one final reference: its root (position +// among the final roots), its index (a chunk's) or group (a segment's), the +// SHA-256 it expects, and its class ("" when sound) and detail. +type judged struct { + root int + at uint64 + sha [32]byte + class, detail string +} + +// V.Reconcile: every finding and counter, from the settled outcomes, the references seen and the final view alone (an incomplete pass: its last view); root deleted takes precedence over superseded. +func (v *verifier) reconcile() { + // The final roots: the HEAD view, then each selected snapshot not gone, + // in order. Per object and class Judge gives a final reference: one + // finding (byClass). An object with a bad outcome or a problem under any + // reference seen, and no finding, is counted once (count). Objects never + // settled (an incomplete pass) are not judged. + var roots []*verifyView + gone := map[string]bool{} + if v.head != nil { + roots = append(roots, v.head) + v.geometry(v.head.label, v.head.h, v.head.chunks) + } + for _, s := range v.snaps { + if s.gone { + gone[s.label] = true + v.res.SnapshotsDeletedDuringVerify = append(v.res.SnapshotsDeletedDuringVerify, s.name+"/"+s.attempt) + } else { + roots = append(roots, s) + } + } + finalChunks := map[string][]judged{} + for ri, r := range roots { + for _, idx := range sortedIndexes(r.chunks) { + ref := r.chunks[idx] + id := chunkIdentity(v.vol, ref.Key) + finalChunks[id] = append(finalChunks[id], judged{root: ri, at: idx, sha: ref.SHA256}) + v.res.ChunksChecked++ + } + } + for _, id := range sortedKeys(v.chunks) { + w := v.chunks[id] + if !w.settled { + continue + } + refs := finalChunks[id] + for i := range refs { + refs[i].class, refs[i].detail = v.judgeChunk(w, refs[i].sha) + } + mk := func(j judged) VerifyFinding { + idx := j.at + return VerifyFinding{Root: roots[j.root].label, Index: &idx, Owner: w.owner, Key: w.key, FID: w.fid, Class: j.class, Detail: j.detail} + } + reported := v.byClass(roots, refs, mk) + if v.opts.Depth != VerifyData { + // Below depth data no content was read: final references to one + // chunk with different SHA-256s disagree with each other. + for _, r := range refs[min(1, len(refs)):] { + if r.sha != refs[0].sha { + v.finding(mk(judged{root: r.root, at: r.at, class: FindingContentMismatch, detail: fmt.Sprintf( + "references to this chunk disagree: SHA-256 %s here, %s under %s at index %d (depth data reads the chunk)", + hex.EncodeToString(r.sha[:]), hex.EncodeToString(refs[0].sha[:]), roots[refs[0].root].label, refs[0].at)})) + reported = true + break + } + } + } + if !reported { + var problem []string + for r := range v.seenChunks[id] { + if c, _ := v.judgeChunk(w, r.sha); c != "" { + problem = append(problem, r.root) + } + } + v.count(problem, w.class != "", gone) + } + } + if v.head != nil { + reported := map[string]bool{} + for _, idx := range sortedIndexes(v.head.chunks) { + id := chunkIdentity(v.vol, v.head.chunks[idx].Key) + if v.dropped[id] && !reported[id] { + reported[id] = true + i := idx + owner, key := splitIdentity(id) + fid := "" + if w := v.chunks[id]; w != nil { + fid = w.fid + } + v.finding(VerifyFinding{Root: v.head.label, Index: &i, Owner: owner, Key: key, FID: fid, Class: FindingRootInvalid, + Detail: "HEAD names a key it had dropped earlier in this pass; a key that left every root must not be named again"}) + } + } + } + for _, id := range sortedKeys(v.segs) { + s := v.segs[id] + var refs []judged + for ri, r := range roots { + for _, g := range sortedGroups(r.h.Segments) { + if ref := r.h.Segments[g]; segID(v.vol, ref) == id { + j := v.judgeSegment(context.Background(), s, segRef{group: g, chunkBytes: r.h.ChunkBytes, remoteLSN: r.h.RemoteLSN, ref: ref}) + refs = append(refs, judged{root: ri, at: g, class: j.class, detail: j.detail}) + } + } + } + mk := func(j judged) VerifyFinding { + g := j.at + return VerifyFinding{Root: roots[j.root].label, Segment: &g, Owner: s.owner, Key: s.key, FID: s.fid, Class: j.class, Detail: j.detail} + } + reported := v.byClass(roots, refs, mk) + // A tombstoned segment binding is reported beside the segment's + // outcome, at depths that check bindings. + tomb := s.tombstoned && v.opts.Depth != VerifyMeta + if tomb && len(refs) > 0 { + v.finding(mk(judged{root: refs[0].root, at: refs[0].at, class: FindingBindingTombstoned, detail: "segment binding tombstoned by GC"})) + reported = true + } + if !reported { + var problem []string + for r := range v.seenSegs[id] { + if tomb || v.judgeSegment(context.Background(), s, r.ref).class != "" { + problem = append(problem, r.root) + } + } + v.count(problem, s.class != "" || tomb, gone) + } + } +} + +// byClass reports one finding per class among refs (in final-root order): +// under the first reference of that class, its detail counting the others +// of that class and naming the next root carrying one. It reports whether it +// made one. +func (v *verifier) byClass(roots []*verifyView, refs []judged, mk func(judged) VerifyFinding) bool { + var order []string + first, more, next := map[string]int{}, map[string]int{}, map[string]string{} + for i, j := range refs { + if j.class == "" { + continue + } + f, ok := first[j.class] + if !ok { + first[j.class] = i + order = append(order, j.class) + continue + } + more[j.class]++ + if next[j.class] == "" && j.root != refs[f].root { + next[j.class] = roots[j.root].label + } + } + for _, c := range order { + j := refs[first[c]] + if n := more[c]; n > 0 { + j.detail += fmt.Sprintf("; %d more final reference(s) of this class", n) + if next[c] != "" { + j.detail += ", next under " + next[c] + } + } + v.finding(mk(j)) + } + return len(order) > 0 +} + +// count counts an object that yields no finding but had a bad outcome (bad) +// or a problem under a reference seen (problem: those references' roots), +// once: root deleted when a snapshot that is gone carried such a reference, +// otherwise superseded. +func (v *verifier) count(problem []string, bad bool, gone map[string]bool) { + if len(problem) == 0 && !bad { + return + } + for _, r := range problem { + if gone[r] { + v.res.RootDeletedDuringVerify++ + return + } + } + v.res.SupersededDuringVerify++ +} + +func sortedKeys[T any](m map[string]T) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} + +func sortedGroups(m map[uint64]storage.ChunkSegment) []uint64 { + out := make([]uint64, 0, len(m)) + for g := range m { + out = append(out, g) + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// verifyPacer spaces reads so they average at most rate bytes per second. +type verifyPacer struct { + mu sync.Mutex + rate int64 // <= 0: unpaced + next time.Time +} + +func (p *verifyPacer) wait(ctx context.Context, n int64) error { + if p == nil || p.rate <= 0 || n <= 0 { + return ctx.Err() + } + p.mu.Lock() + now := time.Now() + if p.next.Before(now) { + p.next = now + } + start := p.next + p.next = p.next.Add(time.Duration(float64(n) / float64(p.rate) * float64(time.Second))) + p.mu.Unlock() + d := time.Until(start) + if d <= 0 { + return ctx.Err() + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-t.C: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func findingLess(a, b VerifyFinding) bool { + if a.Root != b.Root { + return a.Root < b.Root + } + if (a.Index == nil) != (b.Index == nil) { + return a.Index == nil // a root's and its segments' findings first + } + if as, bs := ptrOr(a.Segment), ptrOr(b.Segment); as != bs { + return as < bs + } + if ai, bi := ptrOr(a.Index), ptrOr(b.Index); ai != bi { + return ai < bi + } + if a.Key != b.Key { + return a.Key < b.Key + } + return a.Class < b.Class +} + +func ptrOr(p *uint64) uint64 { + if p == nil { + return 0 + } + return *p +} diff --git a/seaweed-block/core/frontend/chunkstore/verify_test.go b/seaweed-block/core/frontend/chunkstore/verify_test.go new file mode 100644 index 0000000000..407b223b36 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/verify_test.go @@ -0,0 +1,2036 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "path" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A geometry with three segments' worth of chunks (one segment covers a +// logical GiB: 32768 chunks of 32 KiB), so a test can damage one segment +// and see the others still checked. +var verifyGeo = Geometry{NumBlocks: 3 * 32768 * 8, BlockSize: 4096, ChunkBlocks: 8} + +const ( + verifyChunkBytes = 8 * 4096 + verifyPer = 32768 // chunks per segment at verifyGeo +) + +// countingBlobs counts reads per fid, and fails reads of a fid on request +// with a transient (not "not found") error. +type countingBlobs struct { + gcBlobs + mu sync.Mutex + gets map[string]int + fail map[string]int // reads of fid still to fail; negative: every read +} + +var errTransient = errors.New("read tcp 127.0.0.1:8080: connection reset by peer") + +func (b *countingBlobs) Get(ctx context.Context, fid string) ([]byte, error) { + b.mu.Lock() + b.gets[fid]++ + n := b.fail[fid] + if n > 0 { + b.fail[fid] = n - 1 + } + b.mu.Unlock() + if n != 0 { + return nil, fmt.Errorf("chunkstore: read %s: %w", fid, errTransient) + } + return b.gcBlobs.Get(ctx, fid) +} + +// failReads makes the next n reads of fid fail (n < 0: all of them). +func (b *countingBlobs) failReads(fid string, n int) { + b.mu.Lock() + defer b.mu.Unlock() + b.fail[fid] = n +} + +func (b *countingBlobs) reads(fid string) int { + b.mu.Lock() + defer b.mu.Unlock() + return b.gets[fid] +} + +type verifyFixture struct { + t *testing.T + f *fakeFiler + b gcBlobs + cb *countingBlobs + c *Catalog + tag int +} + +func newVerifyFixture(t *testing.T, vols ...string) *verifyFixture { + t.Helper() + fx := &verifyFixture{t: t, f: newFakeFiler(), b: gcBlobs{newFakeBlobs()}} + fx.cb = &countingBlobs{gcBlobs: fx.b, gets: map[string]int{}, fail: map[string]int{}} + c, err := NewCatalog(manifestFilerBlobs{fx.f, fx.cb}, catBase) + if err != nil { + t.Fatal(err) + } + fx.c = c + for _, vol := range vols { + if err := fx.f.CreateEntry(context.Background(), catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + if _, err := c.EnsureVolume(context.Background(), vol, verifyGeo); err != nil { + t.Fatal(err) + } + } + return fx +} + +func verifyData(fill byte) []byte { + b := make([]byte, verifyChunkBytes) + for i := range b { + b[i] = fill + byte(i%7) + } + return b +} + +// publish installs a new HEAD for vol: the current chunks when keep is set, +// with set written under fresh keys over them. +func (fx *verifyFixture) publish(vol string, set map[uint64][]byte, keep bool) storage.ChunkHead { + fx.t.Helper() + ctx := context.Background() + r, err := NewChunkRemote(fx.f, fx.b, path.Join(catBase, vol)) + if err != nil { + fx.t.Fatal(err) + } + cur, err := r.GetHead(ctx) + if err != nil { + fx.t.Fatal(err) + } + next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: max(cur.RemoteLSN, 42) + 1, Chunks: map[uint64]storage.ChunkRef{}} + if keep { + for idx, ref := range cur.Chunks { + next.Chunks[idx] = ref + } + } + for idx, data := range set { + fx.tag++ + key := fmt.Sprintf("chunks/t%d/c%d", fx.tag, idx) + if err := r.Put(ctx, key, data); err != nil { + fx.t.Fatal(err) + } + next.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + next, ids, err := r.PrepareManifest(ctx, cur, next, verifyChunkBytes) + if err != nil { + fx.t.Fatal(err) + } + gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next) + if err != nil { + fx.t.Fatal(err) + } + next.Gen = gen + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + fx.t.Fatal(err) + } + } + return next +} + +// binding returns the directory and name of a qualified key's binding. +func bindingOf(t *testing.T, qkey string) (string, string) { + t.Helper() + owner, own, ok := strings.Cut(strings.TrimPrefix(qkey, "@"), "/") + if !ok || !strings.HasPrefix(qkey, "@") { + t.Fatalf("key %q is not owner-qualified", qkey) + } + return path.Join(catBase, owner, keysDir), url.PathEscape(own) +} + +func (fx *verifyFixture) fid(qkey string) string { + fx.t.Helper() + dir, name := bindingOf(fx.t, qkey) + e, err := fx.f.LookupEntry(context.Background(), dir, name) + if err != nil { + fx.t.Fatalf("binding of %s: %v", qkey, err) + } + return string(e.Extended[extFid]) +} + +func (fx *verifyFixture) deleteBinding(qkey string) { + fx.t.Helper() + dir, name := bindingOf(fx.t, qkey) + if err := fx.f.DeleteEntry(context.Background(), dir, name, nil); err != nil { + fx.t.Fatal(err) + } +} + +func (fx *verifyFixture) tombstone(qkey string) { + fx.t.Helper() + dir, name := bindingOf(fx.t, qkey) + fx.f.bumpExtended(path.Join(dir, name), extGCDeleted, "done") +} + +// needle edits the stored bytes of fid (nil deletes the needle). +func (fx *verifyFixture) needle(fid string, edit func([]byte) []byte) { + fx.t.Helper() + fx.b.mu.Lock() + defer fx.b.mu.Unlock() + d, ok := fx.b.data[fid] + if !ok { + fx.t.Fatalf("no needle %s", fid) + } + if out := edit(append([]byte(nil), d...)); out == nil { + delete(fx.b.data, fid) + } else { + fx.b.data[fid] = out + } +} + +func flipByte(d []byte) []byte { d[len(d)/2] ^= 0xff; return d } +func truncate(d []byte) []byte { return d[:len(d)-4096] } +func dropNeedle([]byte) []byte { return nil } + +func (fx *verifyFixture) verify(vol string, opts VerifyOptions) VerifyResult { + fx.t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + res, err := fx.c.Verify(ctx, vol, opts) + if err != nil { + fx.t.Fatalf("verify %s %+v: %v", vol, opts, err) + } + if !res.Complete { + fx.t.Fatalf("verify %s: incomplete without an error: %+v", vol, res) + } + return res +} + +// classes renders findings as "CLASS@index" (or "CLASS@seg"), in order. +func classes(res VerifyResult) []string { + var out []string + for _, f := range res.Findings { + switch { + case f.Index != nil: + out = append(out, fmt.Sprintf("%s@%d", f.Class, *f.Index)) + case f.Segment != nil: + out = append(out, fmt.Sprintf("%s@seg%d", f.Class, *f.Segment)) + default: + out = append(out, f.Class) + } + } + return out +} + +func wantClasses(t *testing.T, what string, res VerifyResult, want ...string) { + t.Helper() + got := classes(res) + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("%s: findings %v, want %v\n%+v", what, got, want, res.Findings) + } + n := 0 + for _, c := range res.FindingsByClass { + n += c + } + if n != len(res.Findings) { + t.Fatalf("%s: findingsByClass %v does not count %d findings", what, res.FindingsByClass, len(res.Findings)) + } +} + +func allDepths() []VerifyDepth { return []VerifyDepth{VerifyMeta, VerifyBindings, VerifyData} } + +// A healthy volume with three segments and a snapshot verifies clean at +// every depth; the shared segments are read once. +func TestVerify_CleanVolumeAllDepths(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2), 2 * verifyPer: verifyData(3)}, false) + if _, err := fx.c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + for _, d := range allDepths() { + res := fx.verify("v1", VerifyOptions{Depth: d, AllSnapshots: true}) + wantClasses(t, string(d), res) + if len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen || len(res.Snapshots) != 1 || !strings.HasPrefix(res.Snapshots[0], "s1/") || + res.SegmentsChecked != 6 || res.SegmentReads != 3 || res.ChunksChecked != 6 || res.DistinctChunks != 3 { + t.Fatalf("%s: summary %+v", d, res) + } + wantRead := 0 + if d == VerifyData { + wantRead = 3 + } + if res.DistinctChunksRead != wantRead || res.BytesRead != int64(wantRead*verifyChunkBytes) { + t.Fatalf("%s: read %d chunks, %d bytes; want %d chunks", d, res.DistinctChunksRead, res.BytesRead, wantRead) + } + } +} + +// The gap the default depth closes: GC's mark never looks a rooted key up, +// so a HEAD key whose binding is missing passes it; verify reports it. +func TestVerify_MissingBindingGCPassesVerifyReports(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.deleteBinding(h.Chunks[1].Key) + + now := time.Now().Add(24 * time.Hour) + g, err := NewCollector(fx.c, fx.b, GCConfig{Grace: time.Hour, IntentTTL: time.Hour, Now: func() time.Time { return now }, + IssuedEpoch: func(context.Context, string) (uint64, error) { return 1, nil }}) + if err != nil { + t.Fatal(err) + } + if _, err := g.Preview(context.Background()); err != nil { + t.Fatalf("GC mark: %v; the gap is that it passes", err) + } + + wantClasses(t, "meta", fx.verify("v1", VerifyOptions{Depth: VerifyMeta})) + res := fx.verify("v1", VerifyOptions{}) + wantClasses(t, "default depth", res, "BINDING_MISSING@1") + f := res.Findings[0] + if res.Depth != VerifyBindings || f.Volume != "v1" || f.Root != headLabel(h.Gen) || f.Owner != "v1" || !strings.HasPrefix(h.Chunks[1].Key, "@v1/"+f.Key) { + t.Fatalf("finding %+v (depth %s)", f, res.Depth) + } +} + +// A flipped byte is invisible to metadata; depth data catches it. +func TestVerify_FlippedByteDataOnly(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.needle(fx.fid(h.Chunks[0].Key), flipByte) + wantClasses(t, "bindings", fx.verify("v1", VerifyOptions{Depth: VerifyBindings})) + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "data", res, "CONTENT_MISMATCH@0") + if res.Findings[0].FID != fx.fid(h.Chunks[0].Key) { + t.Fatalf("finding fid %q", res.Findings[0].FID) + } +} + +// A reference is judged by its hash first: a needle truncated in the store +// no longer matches its reference (CONTENT_MISMATCH); a needle that matches +// its reference but is not a chunk long is SIZE_MISMATCH. +func TestVerify_TruncatedNeedleSizeMismatch(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.needle(fx.fid(h.Chunks[1].Key), truncate) + wantClasses(t, "truncated in the store", fx.verify("v1", VerifyOptions{Depth: VerifyData}), "CONTENT_MISMATCH@1") + + fx = newVerifyFixture(t, "v1") + fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)[:verifyChunkBytes-4096]}, false) + wantClasses(t, "short but as referenced", fx.verify("v1", VerifyOptions{Depth: VerifyData}), "SIZE_MISMATCH@1") +} + +func TestVerify_MissingNeedle(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + wantClasses(t, "bindings", fx.verify("v1", VerifyOptions{Depth: VerifyBindings})) + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "data", res, "NEEDLE_MISSING@0") + // The store said "not found": that answer is not retried. + if res.ReadRetries != 0 || res.ChunksNotRead != 0 || fx.cb.reads(fx.fid(h.Chunks[0].Key)) != 1 { + t.Fatalf("not-found needle: %d retries, %d not read, %d reads; want 0, 0, 1", + res.ReadRetries, res.ChunksNotRead, fx.cb.reads(fx.fid(h.Chunks[0].Key))) + } +} + +// A read that fails once with an error other than "not found" is retried +// and then verifies: no finding. +func TestVerify_TransientReadIsRetried(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + chunk, seg := fx.fid(h.Chunks[0].Key), fx.fid(h.Segments[0].Key) + fx.cb.failReads(chunk, 1) + fx.cb.failReads(seg, 1) + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "transient", res) + if res.ReadRetries != 2 || res.ChunksNotRead != 0 || res.DistinctChunksRead != 2 || fx.cb.reads(chunk) != 2 || fx.cb.reads(seg) != 2 { + t.Fatalf("transient errors: %d retries, %d not read, %d chunks read, reads chunk %d segment %d; want 2, 0, 2, 2, 2", + res.ReadRetries, res.ChunksNotRead, res.DistinctChunksRead, fx.cb.reads(chunk), fx.cb.reads(seg)) + } +} + +// A read that keeps failing with an error other than "not found" is +// READ_ERROR (not verified), never NEEDLE_MISSING or SEGMENT_UNREADABLE. +func TestVerify_PersistentReadErrorIsNotAMissingNeedle(t *testing.T) { + t.Run("chunk", func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fid := fx.fid(h.Chunks[0].Key) + fx.cb.failReads(fid, -1) + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "chunk read error", res, "READ_ERROR@0") + f := res.Findings[0] + if res.ChunksNotRead != 1 || res.ReadRetries != 2 || fx.cb.reads(fid) != 3 || f.FID != fid || + !strings.Contains(f.Detail, "not verified") || !strings.Contains(f.Detail, errTransient.Error()) { + t.Fatalf("chunk read error: %d not read, %d retries, %d reads, finding %+v", res.ChunksNotRead, res.ReadRetries, fx.cb.reads(fid), f) + } + }) + t.Run("segment", func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2)}, false) + fx.cb.failReads(fx.fid(h.Segments[0].Key), -1) + res := fx.verify("v1", VerifyOptions{}) + wantClasses(t, "segment read error", res, "READ_ERROR@seg0") + if res.ChunksNotRead != 1 || res.ChunksChecked != 1 { + t.Fatalf("segment read error: %+v", res) + } + }) +} + +// SWFS reports a needle absent (ErrBlobNotFound) only when every location +// answers 404; the error text is what it was before. +func TestSWFS_GetNotFoundIsErrBlobNotFound(t *testing.T) { + server := func(status int) string { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(status) })) + t.Cleanup(s.Close) + return strings.TrimPrefix(s.URL, "http://") + } + missing, broken := server(http.StatusNotFound), server(http.StatusInternalServerError) + // dropped closes every connection without an answer: a transport error. + dropped := func() string { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + conn, _, err := w.(http.Hijacker).Hijack() + if err == nil { + _ = conn.Close() + } + })) + t.Cleanup(s.Close) + return strings.TrimPrefix(s.URL, "http://") + }() + statusOf := map[string]int{missing: http.StatusNotFound, broken: http.StatusInternalServerError} + for _, tc := range []struct { + name string + hosts []string + notFound bool + }{ + {"every location 404", []string{missing, missing}, true}, + {"one location 500", []string{missing, broken}, false}, + {"only 500", []string{broken}, false}, + // Only the last answer is 404: still not proof of absence. + {"500 then 404", []string{broken, missing}, false}, + {"transport error then 404", []string{dropped, missing}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + var locs []*filerpb.Location + for _, h := range tc.hosts { + locs = append(locs, &filerpb.Location{Url: h}) + } + c := startFakeFiler(t, &fakeFilerGRPC{lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: locs}}}}) + _, err := c.Get(context.Background(), "7,0000dead") + last := tc.hosts[len(tc.hosts)-1] + status := statusOf[last] + if err == nil || errors.Is(err, ErrBlobNotFound) != tc.notFound || err.Error() != fmt.Sprintf("chunkstore: read 7,0000dead: http %d from %s", status, last) { + t.Fatalf("Get: %v (not found %v), want not found %v", err, errors.Is(err, ErrBlobNotFound), tc.notFound) + } + }) + } +} + +// volumeAt is a LookupVolume answer placing volume vid at hosts. +func volumeAt(vid string, hosts ...string) *filerpb.LookupVolumeResponse { + var locs []*filerpb.Location + for _, h := range hosts { + locs = append(locs, &filerpb.Location{Url: h}) + } + return &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{vid: {Locations: locs}}} +} + +func (f *fakeFilerGRPC) volumeLookups() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.volLookups +} + +// Cached locations can be stale (the volume moved): 404 from every cached +// location is not proof of absence. Get looks the volume up again and reads +// from the fresh locations; only 404 from every fresh location is +// ErrBlobNotFound. A read the cache serves makes no lookup. +func TestSWFS_GetStaleCachedLocationLooksUpAgain(t *testing.T) { + body := []byte("needle bytes") + server := func(status int) string { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(status) + if status == http.StatusOK { + _, _ = w.Write(body) + } + })) + t.Cleanup(s.Close) + return strings.TrimPrefix(s.URL, "http://") + } + oldLoc, newLoc, alsoMissing := server(http.StatusNotFound), server(http.StatusOK), server(http.StatusNotFound) + const fid = "7,0000dead" + for _, tc := range []struct { + name string + cached []string // nil: nothing cached + fresh string + wantBody bool + wantLookups int + }{ + {"cached location 404, fresh location has it", []string{oldLoc}, newLoc, true, 1}, + {"cached and fresh locations 404", []string{oldLoc}, alsoMissing, false, 1}, + {"warm cache", []string{newLoc}, newLoc, true, 0}, + {"nothing cached, fresh location 404", nil, alsoMissing, false, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + f := &fakeFilerGRPC{lookupVol: volumeAt("7", tc.fresh)} + c := startFakeFiler(t, f) + if tc.cached != nil { + c.mu.Lock() + c.vidCache["7"] = tc.cached + c.mu.Unlock() + } + b, err := c.Get(context.Background(), fid) + if n := f.volumeLookups(); n != tc.wantLookups { + t.Fatalf("Get made %d volume lookups, want %d (err %v)", n, tc.wantLookups, err) + } + if tc.wantBody { + if err != nil || string(b) != string(body) { + t.Fatalf("Get: %q, %v; want the needle from %s", b, err, tc.fresh) + } + return + } + if !errors.Is(err, ErrBlobNotFound) || err.Error() != "chunkstore: read "+fid+": http 404 from "+tc.fresh { + t.Fatalf("Get: %v (not found %v); want ErrBlobNotFound from the fresh location %s", err, errors.Is(err, ErrBlobNotFound), tc.fresh) + } + }) + } +} + +// A volume that moved after its location was cached is not missing: depth +// data through SWFS reads every needle from the new location, no finding. +func TestVerify_MovedVolumeIsNotAMissingNeedle(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + var mu sync.Mutex + moved := false + serve := func(old bool) string { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + gone := old && moved + mu.Unlock() + fx.b.mu.Lock() + d, ok := fx.b.data[strings.TrimPrefix(r.URL.Path, "/")] + fx.b.mu.Unlock() + if gone || !ok { + w.WriteHeader(http.StatusNotFound) + return + } + _, _ = w.Write(d) + })) + t.Cleanup(s.Close) + return strings.TrimPrefix(s.URL, "http://") + } + oldLoc, newLoc := serve(true), serve(false) + vid, _, _ := strings.Cut(fx.fid(h.Chunks[0].Key), ",") + f := &fakeFilerGRPC{lookupVol: volumeAt(vid, oldLoc)} + sw := startFakeFiler(t, f) + ctx := context.Background() + // Warm the location cache at the old location, then move the volume. + if _, err := sw.Get(ctx, fx.fid(h.Chunks[0].Key)); err != nil { + t.Fatal(err) + } + mu.Lock() + moved = true + mu.Unlock() + f.mu.Lock() + f.lookupVol = volumeAt(vid, newLoc) + f.mu.Unlock() + + cat, err := NewCatalog(manifestFilerBlobs{fx.f, sw}, catBase) + if err != nil { + t.Fatal(err) + } + res, err := cat.Verify(ctx, "v1", VerifyOptions{Depth: VerifyData, BytesPerSecond: -1}) + if err != nil || !res.Complete { + t.Fatalf("verify: %v, %+v", err, res) + } + wantClasses(t, "moved volume", res) + if res.DistinctChunksRead != 2 || res.SegmentReads != 1 { + t.Fatalf("read %d chunks, %d segments; want 2, 1", res.DistinctChunksRead, res.SegmentReads) + } +} + +// A root that names a binding GC tombstoned: the chunk is gone or going. +func TestVerify_TombstonedBinding(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.tombstone(h.Chunks[0].Key) + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + wantClasses(t, "bindings", fx.verify("v1", VerifyOptions{}), "BINDING_TOMBSTONED@0") + // No read of a tombstoned binding's needle: one finding, not two. + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "data", res, "BINDING_TOMBSTONED@0") + if res.DistinctChunksRead != 1 { + t.Fatalf("read %d chunks, want only the sound one", res.DistinctChunksRead) + } +} + +// A corrupt segment (its content no longer matches the root's reference: a +// mismatch for that root) and a segment whose binding is gone are each a +// finding; the pass goes on to the other segments and their chunks. +func TestVerify_UnreadableSegmentContinues(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2), 2 * verifyPer: verifyData(3)}, false) + fx.needle(fx.fid(h.Segments[0].Key), flipByte) + fx.deleteBinding(h.Segments[1].Key) + fx.deleteBinding(h.Chunks[2*verifyPer].Key) + res := fx.verify("v1", VerifyOptions{}) + wantClasses(t, "bindings", res, "CONTENT_MISMATCH@seg0", "BINDING_MISSING@seg1", fmt.Sprintf("BINDING_MISSING@%d", 2*verifyPer)) + if res.SegmentsChecked != 3 || res.ChunksChecked != 1 { + t.Fatalf("summary %+v", res) + } + if !strings.Contains(res.Findings[0].Detail, "SHA-256") || res.Findings[0].Key != h.Segments[0].Key { + t.Fatalf("corrupt segment finding %+v", res.Findings[0]) + } +} + +// A chunk that leaves HEAD and is collected while the pass runs is not a +// finding when no root names it at the final read (a bad outcome is then +// counted as superseded during verify; read content has no reference left +// to compare with); under a snapshot that still names it, it is one. +func TestVerify_SupersededDuringPass(t *testing.T) { + type damage struct { + name string + depth VerifyDepth + apply func(fx *verifyFixture, qkey string) + class string + } + cases := []damage{ + {"binding deleted", VerifyBindings, func(fx *verifyFixture, k string) { + fid := fx.fid(k) + fx.deleteBinding(k) + fx.needle(fid, dropNeedle) + }, FindingBindingMissing}, + {"binding tombstoned", VerifyBindings, func(fx *verifyFixture, k string) { + fx.tombstone(k) + fx.needle(fx.fid(k), dropNeedle) + }, FindingBindingTombstoned}, + {"needle deleted", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), dropNeedle) }, FindingNeedleMissing}, + {"needle overwritten", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), flipByte) }, FindingContentMismatch}, + {"needle unreadable", VerifyData, func(fx *verifyFixture, k string) { fx.cb.failReads(fx.fid(k), -1) }, FindingReadError}, + } + for _, tc := range cases { + for _, withSnap := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/snapshot=%v", tc.name, withSnap), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if withSnap { + if _, err := fx.c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + } + old := h.Chunks[0].Key + hooked := 0 + opts := VerifyOptions{Depth: tc.depth, AllSnapshots: withSnap} + opts.hook = func(stage string) { + if stage != verifyHookHeadWalked { + return + } + hooked++ + // After verify read HEAD: the owner replaces chunk 0 and GC + // collects the old one. + fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) + tc.apply(fx, old) + } + res := fx.verify("v1", opts) + if !withSnap { + wantClasses(t, "HEAD only", res) + } else { + wantClasses(t, "with the snapshot", res, tc.class+"@0") + if !strings.HasPrefix(res.Findings[0].Root, "snapshot s1/") { + t.Fatalf("finding root %q, want the snapshot", res.Findings[0].Root) + } + } + superseded := 0 + if !withSnap { + superseded = 1 // a problem under a reference seen, and no finding + } + // The closing read sees the owner's new HEAD: it is the final view. + if hooked != 1 || res.SupersededDuringVerify != superseded || len(res.HeadGens) != 2 || res.HeadGens[0] != h.Gen { + t.Fatalf("hooked %d, superseded %d, gens %v; want 1, %d, [%d next]", hooked, res.SupersededDuringVerify, res.HeadGens, superseded, h.Gen) + } + }) + } + } +} + +// A miss under a snapshot is a finding only while that attempt is still +// active at the final read: a snapshot deleted during the pass, whose chunk +// is then collected, is listed as not fully covered, its bad chunk counted +// as root deleted during verify, not reported. +func TestVerify_SnapshotDeletedDuringPass(t *testing.T) { + cases := []struct { + name string + depth VerifyDepth + apply func(fx *verifyFixture, qkey string) + class string + }{ + {"binding deleted", VerifyBindings, func(fx *verifyFixture, k string) { + fid := fx.fid(k) + fx.deleteBinding(k) + fx.needle(fid, dropNeedle) + }, FindingBindingMissing}, + {"needle overwritten", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), flipByte) }, FindingContentMismatch}, + {"needle truncated", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), truncate) }, FindingContentMismatch}, + {"needle unreadable", VerifyData, func(fx *verifyFixture, k string) { fx.cb.failReads(fx.fid(k), -1) }, FindingReadError}, + } + for _, tc := range cases { + for _, deleteSnap := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/deleted=%v", tc.name, deleteSnap), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + s, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h) + if err != nil { + t.Fatal(err) + } + // HEAD moves on before the pass: only the snapshot names the old chunk 0. + fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) + old := h.Chunks[0].Key + opts := VerifyOptions{Depth: tc.depth, AllSnapshots: true} + opts.hook = func(stage string) { + if stage != verifyHookRootsWalked { + return + } + if deleteSnap { + if st, err := fx.c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapDeleting { + t.Errorf("delete s1: %q %v", st, err) + } + } + tc.apply(fx, old) + } + res := fx.verify("v1", opts) + if len(res.Snapshots) != 1 { + t.Fatalf("snapshots checked %v", res.Snapshots) + } + if !deleteSnap { + wantClasses(t, "active snapshot", res, tc.class+"@0") + if res.RootDeletedDuringVerify != 0 || len(res.SnapshotsDeletedDuringVerify) != 0 || !strings.HasPrefix(res.Findings[0].Root, "snapshot s1/") { + t.Fatalf("active snapshot: %+v", res) + } + return + } + wantClasses(t, "deleted snapshot", res) + // The gone snapshot carried the only problem reference. + if res.RootDeletedDuringVerify != 1 || res.SupersededDuringVerify != 0 || + len(res.SnapshotsDeletedDuringVerify) != 1 || res.SnapshotsDeletedDuringVerify[0] != res.Snapshots[0] { + t.Fatalf("deleted snapshot: root deleted %d, superseded %d, deleted list %v (checked %v, created %+v)", + res.RootDeletedDuringVerify, res.SupersededDuringVerify, res.SnapshotsDeletedDuringVerify, res.Snapshots, s.Name) + } + }) + } + } +} + +// A chunk named by HEAD (superseded during the pass) and by a snapshot that +// is still active is one finding, under the snapshot (and not counted as +// superseded: a root still names it). +func TestVerify_SharedChunkReportedUnderStillNamingRoot(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + opts := VerifyOptions{Depth: VerifyData, AllSnapshots: true} + opts.hook = func(stage string) { + if stage == verifyHookRootsWalked { + fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + } + } + res := fx.verify("v1", opts) + wantClasses(t, "shared chunk", res, "NEEDLE_MISSING@0") + if !strings.HasPrefix(res.Findings[0].Root, "snapshot s1/") || res.SupersededDuringVerify != 0 || res.RootDeletedDuringVerify != 0 { + t.Fatalf("finding under %q, superseded %d, root deleted %d; want the snapshot, 0, 0", + res.Findings[0].Root, res.SupersededDuringVerify, res.RootDeletedDuringVerify) + } +} + +// A HEAD that advances mid-pass: the result lists both generations, only +// the segment whose key changed is read again, and the references checked +// are the final view's. +func TestVerify_HeadRefreshRewalksChangedSegments(t *testing.T) { + for _, d := range []VerifyDepth{VerifyBindings, VerifyData} { + t.Run(string(d), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2), 2 * verifyPer: verifyData(3)}, false) + var h2 storage.ChunkHead + opts := VerifyOptions{Depth: d, RefreshInterval: time.Minute} + opts.hook = func(stage string) { + if stage == verifyHookHeadWalked { + h2 = fx.publish("v1", map[uint64][]byte{verifyPer: verifyData(7)}, true) + } + } + fx.c.SetClock(tickingClock(time.Minute)) // past the refresh interval at every read + res := fx.verify("v1", opts) + wantClasses(t, "refresh", res) + if len(res.HeadGens) != 2 || res.HeadGens[0] != h1.Gen || res.HeadGens[1] != h2.Gen { + t.Fatalf("covered gens %v, want [%d %d]", res.HeadGens, h1.Gen, h2.Gen) + } + if h2.Segments[0] != h1.Segments[0] || h2.Segments[2] != h1.Segments[2] || h2.Segments[1] == h1.Segments[1] { + t.Fatal("fixture: the new HEAD should change only segment 1") + } + if res.SegmentReads != 4 || res.SegmentsChecked != 6 { + t.Fatalf("segment reads %d (checked %d); want 3 + 1 changed", res.SegmentReads, res.SegmentsChecked) + } + if res.DistinctChunks != 4 || res.ChunksChecked != 3 { + t.Fatalf("chunks %d distinct, %d checked; want the 3 first and the 1 new, 3 final references", res.DistinctChunks, res.ChunksChecked) + } + if d == VerifyData && (res.DistinctChunksRead != 4 || fx.cb.reads(fx.fid(h2.Chunks[verifyPer].Key)) != 1) { + t.Fatalf("read %d chunks; want 4, the new one included", res.DistinctChunksRead) + } + }) + } +} + +// A chunk shared by HEAD and two snapshots is fetched once. +func TestVerify_DedupSharedChunkReadOnce(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + for _, n := range []string{"s1", "s2"} { + if _, err := fx.c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: n, RequestID: "r-" + n}, h); err != nil { + t.Fatal(err) + } + } + res := fx.verify("v1", VerifyOptions{Depth: VerifyData, AllSnapshots: true}) + wantClasses(t, "dedup", res) + if res.ChunksChecked != 6 || res.DistinctChunks != 2 || res.DistinctChunksRead != 2 || len(res.Snapshots) != 2 { + t.Fatalf("summary %+v", res) + } + for _, idx := range []uint64{0, 1} { + if n := fx.cb.reads(fx.fid(h.Chunks[idx].Key)); n != 1 { + t.Fatalf("chunk %d read %d times, want once", idx, n) + } + } + // One named snapshot works the same way. + res = fx.verify("v1", VerifyOptions{Depth: VerifyBindings, Snapshot: "s2"}) + if len(res.Snapshots) != 1 || !strings.HasPrefix(res.Snapshots[0], "s2/") || res.ChunksChecked != 4 { + t.Fatalf("named snapshot: %+v", res) + } + if _, err := fx.c.Verify(context.Background(), "v1", VerifyOptions{Snapshot: "nope"}); CodeOf(err) != CodeSnapshotNotFound { + t.Fatalf("missing snapshot: %v", err) + } +} + +// A fork's qualified keys are checked in the owner volume's keys/, and its +// fork record against the parent snapshot. +func TestVerify_ForkQualifiedKeysAndRecord(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { + t.Fatal(err) + } + if _, err := fx.c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { + t.Fatal(err) + } + for _, d := range allDepths() { + wantClasses(t, "clean fork "+string(d), fx.verify("v2", VerifyOptions{Depth: d})) + } + // The fork wrote no binding of its own: every chunk resolves to v1. + fx.deleteBinding(h.Chunks[1].Key) + res := fx.verify("v2", VerifyOptions{}) + wantClasses(t, "fork, parent binding gone", res, "BINDING_MISSING@1") + if res.Findings[0].Owner != "v1" || res.Findings[0].Volume != "v2" { + t.Fatalf("finding %+v, want owner v1 in volume v2", res.Findings[0]) + } + + // A fork record whose digest is not the parent snapshot's. + e, err := fx.f.LookupEntry(ctx, path.Join(catBase, "v2"), volumeName) + if err != nil { + t.Fatal(err) + } + var vi VolumeInfo + if err := json.Unmarshal(e.Content, &vi); err != nil { + t.Fatal(err) + } + vi.Fork.HeadSHA256 = strings.Repeat("0", 64) + if e.Content, err = json.Marshal(vi); err != nil { + t.Fatal(err) + } + if err := fx.f.UpdateEntry(ctx, path.Join(catBase, "v2"), e, nil); err != nil { + t.Fatal(err) + } + res = fx.verify("v2", VerifyOptions{Depth: VerifyMeta}) + wantClasses(t, "tampered fork record", res, "FORK_RECORD_MISMATCH") + if res.Findings[0].Owner != "v1" || !strings.Contains(res.Findings[0].Detail, "s1") { + t.Fatalf("finding %+v", res.Findings[0]) + } +} + +// A fork whose source volume was deleted afterwards has nothing to compare +// its fork record with. That is not damage: no finding, and the result +// says the source is gone. While the source volume still exists, a missing +// parent snapshot attempt is a finding. +func TestVerify_ForkSourceVolumeDeleted(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { + t.Fatal(err) + } + if _, err := fx.c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { + t.Fatal(err) + } + // The parent's snapshot attempts vanish, the source volume remains. + dir := path.Join(catBase, "v1", snapsDir, "s1") + es, err := fx.f.ListEntries(ctx, dir, "", "", 100) + if err != nil || len(es) == 0 { + t.Fatalf("attempts of s1: %d, %v", len(es), err) + } + for _, e := range es { + if err := fx.f.DeleteEntry(ctx, dir, e.GetName(), nil); err != nil { + t.Fatal(err) + } + } + res := fx.verify("v2", VerifyOptions{Depth: VerifyMeta}) + wantClasses(t, "attempts gone, source present", res, "FORK_RECORD_MISMATCH") + if res.ForkSourceGone { + t.Fatal("ForkSourceGone set while the source volume exists") + } + // Now the source volume record goes too. + if err := fx.f.DeleteEntry(ctx, path.Join(catBase, "v1"), volumeName, nil); err != nil { + t.Fatal(err) + } + res = fx.verify("v2", VerifyOptions{Depth: VerifyMeta}) + wantClasses(t, "source volume deleted", res) + if !res.ForkSourceGone { + t.Fatal("ForkSourceGone not set") + } +} + +// Intent bookkeeping: an old capture intent below HEAD's epoch naming keys +// HEAD does not reference is reported; one naming a key HEAD binds, a +// current one and a copy intent are not. +func TestVerify_IntentStale(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1)}, false) + root := path.Join(catBase, "v1") + headKey := strings.TrimPrefix(h.Chunks[0].Key, "@v1/") + stale, err := putIntent(ctx, fx.f, root, storage.ChunkIntent{Gen: 1, Epoch: 0, Holder: "old/r1", Keys: []string{"chunks/lost/k"}}) + if err != nil { + t.Fatal(err) + } + for _, in := range []storage.ChunkIntent{ + {Gen: 1, Epoch: 0, Holder: "old/r1", Keys: []string{headKey}}, // HEAD binds its key + {Gen: 2, Epoch: 1, Holder: "h1", Keys: []string{"chunks/next/k"}}, // the current epoch + {Gen: 0, Epoch: 0, Holder: "snapshot:v1/s9/1-0000000000000000", Keys: []string{"x/y"}}, // a copy intent + } { + if _, err := putIntent(ctx, fx.f, root, in); err != nil { + t.Fatal(err) + } + } + wantClasses(t, "young intents", fx.verify("v1", VerifyOptions{})) + fx.c.SetClock(func() time.Time { return time.Now().Add(2 * time.Hour) }) + res := fx.verify("v1", VerifyOptions{Depth: VerifyMeta}) + wantClasses(t, "old intents", res, "INTENT_STALE") + if res.Findings[0].Root != "intent "+stale { + t.Fatalf("stale intent finding %+v, want intent %s", res.Findings[0], stale) + } +} + +// recordingStore counts every write the catalog makes through it. +type recordingStore struct { + Filer + blobs *countingBlobs + mu sync.Mutex + creates, updates, deletes int + blobPuts, blobDeletes, reads int +} + +func (r *recordingStore) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, o bool) error { + r.mu.Lock() + r.creates++ + r.mu.Unlock() + return r.Filer.CreateEntry(ctx, dir, e, o) +} +func (r *recordingStore) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, x map[string][]byte) error { + r.mu.Lock() + r.updates++ + r.mu.Unlock() + return r.Filer.UpdateEntry(ctx, dir, e, x) +} +func (r *recordingStore) DeleteEntry(ctx context.Context, dir, name string, x map[string][]byte) error { + r.mu.Lock() + r.deletes++ + r.mu.Unlock() + return r.Filer.DeleteEntry(ctx, dir, name, x) +} +func (r *recordingStore) Put(ctx context.Context, d []byte) (string, error) { + r.mu.Lock() + r.blobPuts++ + r.mu.Unlock() + return r.blobs.Put(ctx, d) +} +func (r *recordingStore) Get(ctx context.Context, fid string) ([]byte, error) { + r.mu.Lock() + r.reads++ + r.mu.Unlock() + return r.blobs.Get(ctx, fid) +} +func (r *recordingStore) DeleteBlob(ctx context.Context, fid string) error { + r.mu.Lock() + r.blobDeletes++ + r.mu.Unlock() + return r.blobs.DeleteBlob(ctx, fid) +} + +// Verify writes nothing, at any depth, also on the miss, superseded and +// refresh paths and for a fork. +func TestVerify_ReadOnlyAtEveryDepth(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2), verifyPer: verifyData(3)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { + t.Fatal(err) + } + if _, err := fx.c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { + t.Fatal(err) + } + if _, err := putIntent(ctx, fx.f, path.Join(catBase, "v1"), storage.ChunkIntent{Gen: 1, Holder: "old", Keys: []string{"k/old"}}); err != nil { + t.Fatal(err) + } + fx.needle(fx.fid(h.Chunks[1].Key), flipByte) + rec := &recordingStore{Filer: fx.f, blobs: fx.cb} + cat, err := NewCatalog(rec, catBase) + if err != nil { + t.Fatal(err) + } + cat.SetClock(func() time.Time { return time.Now().Add(2 * time.Hour) }) + for _, d := range allDepths() { + for _, vol := range []string{"v1", "v2"} { + opts := VerifyOptions{Depth: d, AllSnapshots: true, RefreshInterval: time.Millisecond} + opts.hook = func(stage string) { + if vol == "v1" && stage == verifyHookHeadWalked { + // Writes by the owner (through the fixture, not the + // recorder): a new HEAD, and the old chunk 0 collected. + r, _ := NewChunkRemote(fx.f, fx.b, path.Join(catBase, "v1")) + cur, err := r.GetHead(ctx) + if err != nil { + t.Error(err) + return + } + oldFid := fx.fid(cur.Chunks[0].Key) + fx.publish("v1", map[uint64][]byte{0: verifyData(byte(10 + len(d)))}, true) + fx.needle(oldFid, dropNeedle) + time.Sleep(3 * time.Millisecond) + } + } + res, err := cat.Verify(ctx, vol, opts) + if err != nil || !res.Complete { + t.Fatalf("%s %s: %v", d, vol, err) + } + if d == VerifyData && rec.reads == 0 { + t.Fatalf("%s %s: no blob reads recorded; the recorder is not in the path", d, vol) + } + } + } + if rec.creates+rec.updates+rec.deletes+rec.blobPuts+rec.blobDeletes != 0 { + t.Fatalf("verify wrote: %d creates, %d updates, %d deletes, %d blob puts, %d blob deletes", + rec.creates, rec.updates, rec.deletes, rec.blobPuts, rec.blobDeletes) + } +} + +// A chunk index past the end of VOLUME's geometry is a GEOMETRY finding. +func TestVerify_GeometryOutsideVolume(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + fx.publish("v1", map[uint64][]byte{0: verifyData(1), 2 * verifyPer: verifyData(2)}, false) + e, err := fx.f.LookupEntry(ctx, path.Join(catBase, "v1"), volumeName) + if err != nil { + t.Fatal(err) + } + var vi VolumeInfo + if err := json.Unmarshal(e.Content, &vi); err != nil { + t.Fatal(err) + } + vi.NumBlocks = 2 * verifyPer * 8 + if e.Content, err = json.Marshal(vi); err != nil { + t.Fatal(err) + } + if err := fx.f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { + t.Fatal(err) + } + wantClasses(t, "meta", fx.verify("v1", VerifyOptions{Depth: VerifyMeta}), fmt.Sprintf("GEOMETRY@%d", 2*verifyPer)) +} + +// A HEAD that does not decode is a finding, not a failure to run. +func TestVerify_InvalidHeadRoot(t *testing.T) { + fx := newVerifyFixture(t, "v1") + fx.publish("v1", map[uint64][]byte{0: verifyData(1)}, false) + fx.f.bumpExtended(path.Join(catBase, "v1", headName), extGen, "999") + res := fx.verify("v1", VerifyOptions{}) + wantClasses(t, "bad HEAD", res, "ROOT_INVALID") + if len(res.HeadGens) != 0 { + t.Fatalf("covered gens %v of an invalid HEAD", res.HeadGens) + } +} + +// Only an inability to continue stops the pass: the result then says it is +// incomplete and keeps what was covered. +func TestVerify_ContextEndedIsIncomplete(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + opts := VerifyOptions{Depth: VerifyData} + opts.hook = func(stage string) { cancel() } + res, err := fx.c.Verify(ctx, "v1", opts) + if !errors.Is(err, context.Canceled) || res.Complete || len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen { + t.Fatalf("cancelled pass: %v, %+v", err, res) + } + if _, err := fx.c.Verify(context.Background(), "nope", VerifyOptions{}); CodeOf(err) != CodeNotChunkVolume { + t.Fatalf("missing volume: %v", err) + } +} + +// heldReads holds the read of one needle open until the reader's context +// ends (or the test releases it), and counts the reads in progress. +type heldReads struct { + Blobs + fid string + onEnter func() // runs once, when the held read has started + entered chan struct{} // closed when the held read has started + once sync.Once + + released chan struct{} // closed by release: the escape when cancellation fails + releaseOnce sync.Once + + mu sync.Mutex + active int + ended error // the held read's context error, once its context ended +} + +func newHeldReads(b Blobs, fid string) *heldReads { + return &heldReads{Blobs: b, fid: fid, entered: make(chan struct{}), released: make(chan struct{})} +} + +func (h *heldReads) release() { h.releaseOnce.Do(func() { close(h.released) }) } + +// verifyEscape bounds a test's wait for a Verify that should return at +// once; it only turns a hang into a failure, it is not a success criterion. +const verifyEscape = 30 * time.Second + +type verifyOutcome struct { + res VerifyResult + err error +} + +// verifyBounded runs cat.Verify in a goroutine and returns its result, or +// fails the test when it has not returned within verifyEscape. The cleanup, +// registered before the launch, releases the held read and joins the call. +func verifyBounded(t *testing.T, cat *Catalog, ctx context.Context, opts VerifyOptions, held *heldReads) (VerifyResult, error) { + t.Helper() + done := make(chan verifyOutcome, 1) + t.Cleanup(func() { + held.release() + select { + case out := <-done: + done <- out + case <-time.After(verifyEscape): + t.Error("Verify did not return even after its held read was released") + } + }) + go func() { + res, err := cat.Verify(ctx, "v1", opts) + done <- verifyOutcome{res, err} + }() + select { + case out := <-done: + done <- out // for the cleanup's join + return out.res, out.err + case <-time.After(verifyEscape): + t.Fatalf("Verify did not return within %s: the read in progress was not cancelled and joined", verifyEscape) + return VerifyResult{}, nil + } +} + +func (h *heldReads) Get(ctx context.Context, fid string) ([]byte, error) { + h.mu.Lock() + h.active++ + h.mu.Unlock() + defer func() { + h.mu.Lock() + h.active-- + h.mu.Unlock() + }() + if fid != h.fid { + return h.Blobs.Get(ctx, fid) + } + h.once.Do(func() { + close(h.entered) + if h.onEnter != nil { + h.onEnter() + } + }) + select { + case <-ctx.Done(): + case <-h.released: + return nil, fmt.Errorf("chunkstore: read %s: released by the test", fid) + } + h.mu.Lock() + h.ended = ctx.Err() + h.mu.Unlock() + return nil, fmt.Errorf("chunkstore: read %s: %w", fid, ctx.Err()) +} + +func (h *heldReads) state() (active int, ended error) { + h.mu.Lock() + defer h.mu.Unlock() + return h.active, h.ended +} + +var errFilerDown = errors.New("filer: connection refused") + +// tickingClock advances by step at every reading: with a refresh interval +// of step, a pass refreshes HEAD at every opportunity, without waiting. +func tickingClock(step time.Duration) func() time.Time { + var mu sync.Mutex + now := time.Now() + return func() time.Time { + mu.Lock() + defer mu.Unlock() + now = now.Add(step) + return now + } +} + +// headFailsDuringRead fails HEAD reads made while the held read is in +// progress. The first HEAD read after the chunk key listing passes (it is +// the refresh before the first chunk, the held one, is handed to a reader); +// later ones wait until the held read has started, then fail. +type headFailsDuringRead struct { + Filer + root, keys string + entered <-chan struct{} + released <-chan struct{} // the test's escape + + mu sync.Mutex + listed bool + after int // HEAD reads since the listing +} + +func (f *headFailsDuringRead) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { + if dir == f.keys { + f.mu.Lock() + f.listed = true + f.mu.Unlock() + } + return f.Filer.ListEntries(ctx, dir, prefix, after, limit) +} + +func (f *headFailsDuringRead) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if dir == f.root && name == headName { + f.mu.Lock() + n := 0 + if f.listed { + f.after++ + n = f.after + } + f.mu.Unlock() + if n >= 2 { + select { + case <-f.entered: + return nil, errFilerDown + case <-ctx.Done(): + return nil, ctx.Err() + case <-f.released: + return nil, errors.New("released by the test") + } + } + } + return f.Filer.LookupEntry(ctx, dir, name) +} + +// A HEAD refresh that fails while a chunk read is in progress stops that +// read at once: Verify returns the filer's error (not the cancellation it +// caused in the reader), incomplete, with no read left running, and long +// before the caller's own deadline. +func TestVerify_FailedRefreshCancelsReadInProgress(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + held := newHeldReads(fx.cb, fx.fid(h.Chunks[0].Key)) + filer := &headFailsDuringRead{Filer: fx.f, root: path.Join(catBase, "v1"), keys: path.Join(catBase, "v1", keysDir), + entered: held.entered, released: held.released} + cat, err := NewCatalog(manifestFilerBlobs{filer, held}, catBase) + if err != nil { + t.Fatal(err) + } + cat.SetClock(tickingClock(time.Minute)) + // The caller's deadline tells a read cancelled by the failed refresh + // from one that ran into it: Verify must end well before it. + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + res, err := verifyBounded(t, cat, ctx, VerifyOptions{Depth: VerifyData, RefreshInterval: time.Minute, BytesPerSecond: -1}, held) + active, ended := held.state() + if !errors.Is(err, errFilerDown) || !strings.Contains(err.Error(), "refresh HEAD") { + t.Fatalf("verify: %v; want the HEAD refresh error", err) + } + if ctx.Err() != nil || !errors.Is(ended, context.Canceled) { + t.Fatalf("held read ended with %v (caller context %v); want cancelled by the failed refresh", ended, ctx.Err()) + } + if res.Complete || active != 0 { + t.Fatalf("complete %v, %d reads still running; want incomplete, none", res.Complete, active) + } +} + +// Cancelling the caller's context while a chunk read is in progress ends +// that read and the pass: incomplete, the cancellation reported, no read +// left running. +func TestVerify_CancelDuringReadJoinsReaders(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + held := newHeldReads(fx.cb, fx.fid(h.Chunks[0].Key)) + cat, err := NewCatalog(manifestFilerBlobs{fx.f, held}, catBase) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + held.onEnter = cancel + res, err := verifyBounded(t, cat, ctx, VerifyOptions{Depth: VerifyData, BytesPerSecond: -1}, held) + active, ended := held.state() + select { + case <-held.entered: + default: + t.Fatal("the held read never started") + } + if !errors.Is(err, context.Canceled) || res.Complete || !errors.Is(ended, context.Canceled) || active != 0 { + t.Fatalf("verify: %v, complete %v; held read ended with %v, %d reads still running", err, res.Complete, ended, active) + } + if len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen { + t.Fatalf("covered gens %v, want [%d]", res.HeadGens, h.Gen) + } +} + +// republish installs a new HEAD for vol with the current chunk references +// as edit leaves them (keys are not uploaded again). +func (fx *verifyFixture) republish(vol string, edit func(map[uint64]storage.ChunkRef)) storage.ChunkHead { + fx.t.Helper() + ctx := context.Background() + r, err := NewChunkRemote(fx.f, fx.b, path.Join(catBase, vol)) + if err != nil { + fx.t.Fatal(err) + } + cur, err := r.GetHead(ctx) + if err != nil { + fx.t.Fatal(err) + } + next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: cur.RemoteLSN + 1, Chunks: map[uint64]storage.ChunkRef{}} + for idx, ref := range cur.Chunks { + next.Chunks[idx] = ref + } + edit(next.Chunks) + next, ids, err := r.PrepareManifest(ctx, cur, next, verifyChunkBytes) + if err != nil { + fx.t.Fatal(err) + } + gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next) + if err != nil { + fx.t.Fatal(err) + } + next.Gen = gen + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + fx.t.Fatal(err) + } + } + return next +} + +// wrongHash flips the reference SHA-256 of chunk idx, keeping its key. +func wrongHash(idx uint64) func(map[uint64]storage.ChunkRef) { + return func(c map[uint64]storage.ChunkRef) { + ref := c[idx] + ref.SHA256[0] ^= 0xff + c[idx] = ref + } +} + +// beforeRead runs fn once, before the first read of fid. +type beforeRead struct { + Blobs + fid string + fn func() + once sync.Once +} + +func (b *beforeRead) Get(ctx context.Context, fid string) ([]byte, error) { + if fid == b.fid { + b.once.Do(b.fn) + } + return b.Blobs.Get(ctx, fid) +} + +// A final reference to a chunk under the same key but with another SHA-256 +// is a finding: at depth data it is compared with the content read once for +// that chunk (the chunk is not read again), below data with the other final +// references. A reference only an earlier HEAD view carried is not compared +// (detail "": no finding). +func TestVerify_SameKeyWithAnotherHashIsAFinding(t *testing.T) { + for _, tc := range []struct { + name string + depth VerifyDepth + when string // "walked": HEAD changes once the first view is walked; "read": once chunk 0 was read; "snapshot": before the pass + detail string + }{ + {"refreshed HEAD, data, before the read", VerifyData, "walked", "needle SHA-256"}, + {"refreshed HEAD, data, after the read", VerifyData, "read", "needle SHA-256"}, + {"refreshed HEAD, bindings", VerifyBindings, "walked", ""}, + {"snapshot, data", VerifyData, "snapshot", "needle SHA-256"}, + {"snapshot, bindings", VerifyBindings, "snapshot", "disagree"}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fid0 := fx.fid(h1.Chunks[0].Key) + var h2 storage.ChunkHead + opts := VerifyOptions{Depth: tc.depth, BytesPerSecond: -1, RefreshInterval: time.Minute, Concurrency: 1} + cat := fx.c + switch tc.when { + case "walked": + opts.hook = func(stage string) { + if stage == verifyHookHeadWalked { + h2 = fx.republish("v1", wrongHash(0)) + } + } + case "read": + // One reader: chunk 0 is read completely before chunk 1 is + // handed out, so its content is known when HEAD changes. + br := &beforeRead{Blobs: fx.cb, fid: fx.fid(h1.Chunks[1].Key), fn: func() { h2 = fx.republish("v1", wrongHash(0)) }} + var err error + if cat, err = NewCatalog(manifestFilerBlobs{fx.f, br}, catBase); err != nil { + t.Fatal(err) + } + case "snapshot": + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h1); err != nil { + t.Fatal(err) + } + h2 = fx.republish("v1", wrongHash(0)) + opts.AllSnapshots = true + } + cat.SetClock(tickingClock(time.Minute)) + res, err := cat.Verify(ctx, "v1", opts) + if err != nil || !res.Complete { + t.Fatalf("verify: %v, %+v", err, res) + } + if tc.detail == "" { + wantClasses(t, tc.name, res) + return + } + wantClasses(t, tc.name, res, "CONTENT_MISMATCH@0") + f := res.Findings[0] + wantRoot := headLabel(h2.Gen) + if tc.when == "snapshot" && tc.depth != VerifyData { + // HEAD is walked first; the snapshot's reference is the one + // that disagrees with it. + wantRoot = "snapshot s1/" + } + if !strings.HasPrefix(f.Root, wantRoot) || !strings.Contains(f.Detail, tc.detail) || f.Key == "" { + t.Fatalf("finding %+v; want under %q, detail with %q", f, wantRoot, tc.detail) + } + if tc.when != "snapshot" && (len(res.HeadGens) != 2 || res.HeadGens[0] != h1.Gen || res.HeadGens[1] != h2.Gen) { + t.Fatalf("covered gens %v, want [%d %d]", res.HeadGens, h1.Gen, h2.Gen) + } + if tc.depth == VerifyData && (res.DistinctChunksRead != 2 || fx.cb.reads(fid0) != 1) { + t.Fatalf("read %d chunks, chunk 0 %d times; want 2, chunk 0 once", res.DistinctChunksRead, fx.cb.reads(fid0)) + } + }) + } +} + +// A chunk read once whose final references (HEAD and an active snapshot) +// carry two different wrong SHA-256s is one CONTENT_MISMATCH, under HEAD, +// whose detail counts the other differing reference and names its root. +func TestVerify_TwoWrongReferencesAreOneFinding(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + h2 := fx.republish("v1", wrongHash(0)) // the snapshot keeps this wrong hash + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h2); err != nil { + t.Fatal(err) + } + h3 := fx.republish("v1", func(c map[uint64]storage.ChunkRef) { // HEAD: another wrong hash, same key + ref := c[0] + ref.SHA256[1] ^= 0xff + c[0] = ref + }) + if h3.Chunks[0].Key != h1.Chunks[0].Key || h3.Chunks[0].SHA256 == h2.Chunks[0].SHA256 || h2.Chunks[0].SHA256 == h1.Chunks[0].SHA256 { + t.Fatal("fixture: one key, three different reference hashes") + } + res := fx.verify("v1", VerifyOptions{Depth: VerifyData, AllSnapshots: true, BytesPerSecond: -1}) + wantClasses(t, "two wrong references", res, "CONTENT_MISMATCH@0") + f := res.Findings[0] + if f.Root != headLabel(h3.Gen) || !strings.Contains(f.Detail, "1 more") || !strings.Contains(f.Detail, "snapshot s1/") { + t.Fatalf("finding %+v; want under %q, detail counting 1 more differing reference under the snapshot", f, headLabel(h3.Gen)) + } + if n := fx.cb.reads(fx.fid(h1.Chunks[0].Key)); n != 1 { + t.Fatalf("chunk read %d times, want once", n) + } +} + +// A schedule point: where a world event lands relative to the pass. +type schedPoint string + +const ( + atWalked schedPoint = "walked" // after the first HEAD view, before any check + atChecked schedPoint = "checked" // after the first batch of checks has settled + atClosing schedPoint = "closing" // just before the first closing read + atDuring schedPoint = "during" // while chunk K's read is in progress +) + +// verifyFixture.schedule runs a data-depth pass over v1 whose owner applies +// steps[i] at points[i] (several steps at one point run in order). HEAD is +// re-read at every opportunity; fidK is the chunk whose read is "during". +func (fx *verifyFixture) schedule(fidK string, steps []func(), points []schedPoint) VerifyResult { + fx.t.Helper() + var mu sync.Mutex + pending := map[schedPoint][]func(){} + for i, p := range points { + pending[p] = append(pending[p], steps[i]) + } + fire := func(p schedPoint) { + mu.Lock() + fs := pending[p] + delete(pending, p) + mu.Unlock() + for _, f := range fs { + f() + } + } + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1, RefreshInterval: time.Minute, Concurrency: 1} + opts.hook = func(stage string) { + switch stage { + case verifyHookHeadWalked: + fire(atWalked) + case verifyHookBatchChecked: + fire(atChecked) + case verifyHookClosingRead: + fire(atClosing) + } + } + during := &beforeRead{Blobs: fx.cb, fid: fidK, fn: func() { fire(atDuring) }} + cat, err := NewCatalog(manifestFilerBlobs{fx.f, during}, catBase) + if err != nil { + fx.t.Fatal(err) + } + cat.SetClock(tickingClock(time.Minute)) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + res, err := cat.Verify(ctx, "v1", opts) + if err != nil || !res.Complete { + fx.t.Fatalf("verify: %v, %+v", err, res) + } + if len(pending) != 0 { + fx.t.Fatalf("schedule points never reached: %v", pending) + } + return res +} + +// The same owner events in different interleavings with the pass's checks +// and HEAD reads give the same findings: the findings are computed at the +// end, from each chunk's one outcome and the roots at the final read. K is +// chunk 0 (index 0), L chunk 1; "bad" means K's needle is missing. +func TestVerify_SchedulesGiveTheSameFindings(t *testing.T) { + moveK := func(c map[uint64]storage.ChunkRef) { c[1] = c[0]; delete(c, 0) } + addK1 := func(c map[uint64]storage.ChunkRef) { c[1] = c[0] } + dropK := func(c map[uint64]storage.ChunkRef) { delete(c, 0) } + type edit = func(c map[uint64]storage.ChunkRef) + for _, tc := range []struct { + name string + bad bool + edits []edit // the owner's publishes, in order (nil: restore K at index 0) + interleave [][]schedPoint + want []string + superseded int + finalGenStep int // findings are under the HEAD this many publishes after the first (all of them) + }{ + {"K moves from index 0 to 1, its check fails", true, []edit{moveK}, + [][]schedPoint{{atWalked}, {atChecked}, {atClosing}}, []string{"NEEDLE_MISSING@1"}, 0, 1}, + {"a reference to K arrives after K settled bad", true, []edit{addK1, dropK}, + [][]schedPoint{{atWalked, atWalked}, {atWalked, atChecked}, {atChecked, atClosing}}, []string{"NEEDLE_MISSING@1"}, 0, 2}, + {"K is bad, a refresh keeps index 0 and adds index 1", true, []edit{addK1}, + [][]schedPoint{{atWalked}, {atChecked}, {atClosing}}, []string{"NEEDLE_MISSING@0"}, 0, 1}, + {"settlement and refresh overlap", true, []edit{moveK}, + [][]schedPoint{{atDuring}, {atWalked}}, []string{"NEEDLE_MISSING@1"}, 0, 1}, + {"K is named, not named, named again (bad)", true, []edit{dropK, nil}, + [][]schedPoint{{atWalked, atChecked}, {atChecked, atClosing}}, []string{"NEEDLE_MISSING@0", "ROOT_INVALID@0"}, 0, 2}, + {"K is named, not named, named again (good)", false, []edit{dropK, nil}, + [][]schedPoint{{atWalked, atChecked}, {atChecked, atClosing}}, []string{"ROOT_INVALID@0"}, 0, 2}, + {"K is bad and the final view does not name it", true, []edit{dropK}, + [][]schedPoint{{atWalked}, {atChecked}, {atClosing}}, nil, 1, 1}, + } { + for _, points := range tc.interleave { + t.Run(fmt.Sprintf("%s/%v", tc.name, points), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + k := h1.Chunks[0] + fidK := fx.fid(k.Key) + if tc.bad { + fx.needle(fidK, dropNeedle) + } + var last storage.ChunkHead + steps := make([]func(), len(tc.edits)) + for i, e := range tc.edits { + if e == nil { + e = func(c map[uint64]storage.ChunkRef) { c[0] = k } + } + steps[i] = func() { last = fx.republish("v1", e) } + } + res := fx.schedule(fidK, steps, points) + wantClasses(t, tc.name, res, tc.want...) + for _, f := range res.Findings { + if f.Root != headLabel(last.Gen) || f.Key == "" { + t.Fatalf("finding %+v; want under %q (the final HEAD view)", f, headLabel(last.Gen)) + } + } + if res.SupersededDuringVerify != tc.superseded || res.RootDeletedDuringVerify != 0 { + t.Fatalf("superseded %d, root deleted %d; want %d, 0", res.SupersededDuringVerify, res.RootDeletedDuringVerify, tc.superseded) + } + if res.HeadGens[len(res.HeadGens)-1] != last.Gen { + t.Fatalf("covered gens %v; want the last one %d", res.HeadGens, last.Gen) + } + // One check per chunk, however often HEAD names it again. + if n := fx.cb.reads(fidK); n != 1 { + t.Fatalf("chunk K read %d times, want once", n) + } + }) + } + } +} + +// A publish that lands while the pass makes its closing read is not missed: +// the read names a chunk not seen before, so the pass checks it and reads +// again; a bad new chunk is a finding, not a clean pass. +func TestVerify_PublishDuringClosingReadIsChecked(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + var h2 storage.ChunkHead + steps := []func(){func() { + h2 = fx.publish("v1", map[uint64][]byte{2: verifyData(3)}, true) + fx.needle(fx.fid(h2.Chunks[2].Key), dropNeedle) + }} + res := fx.schedule(fx.fid(h1.Chunks[0].Key), steps, []schedPoint{atClosing}) + wantClasses(t, "publish during the closing read", res, "NEEDLE_MISSING@2") + if res.Findings[0].Root != headLabel(h2.Gen) || fx.cb.reads(fx.fid(h2.Chunks[2].Key)) != 1 { + t.Fatalf("finding %+v, new chunk read %d times; want under %q, read once", res.Findings[0], fx.cb.reads(fx.fid(h2.Chunks[2].Key)), headLabel(h2.Gen)) + } + if len(res.HeadGens) != 2 || res.HeadGens[1] != h2.Gen { + t.Fatalf("covered gens %v, want [%d %d]", res.HeadGens, h1.Gen, h2.Gen) + } +} + +// An owner that publishes a new chunk before every closing read keeps the +// pass from closing: after ClosingRounds such reads the result is +// incomplete (never clean), with its reason and the findings computed from +// what was checked. +func TestVerify_ClosingRoundsExhaustedIsIncomplete(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + reads := 0 + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} + opts.hook = func(stage string) { + if stage == verifyHookClosingRead { + reads++ + fx.publish("v1", map[uint64][]byte{uint64(2 + reads): verifyData(byte(10 + reads))}, true) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + res, err := fx.c.Verify(ctx, "v1", opts) + if CodeOf(err) != CodeVerifyIncomplete || res.Complete || res.Incomplete != VerifyIncompleteRounds { + t.Fatalf("verify: %v, complete %v, incomplete %q; want %s, incomplete for the closing rounds", err, res.Complete, res.Incomplete, CodeVerifyIncomplete) + } + if reads != DefaultVerifyClosingRounds { + t.Fatalf("%d closing reads, want %d", reads, DefaultVerifyClosingRounds) + } + wantClasses(t, "partial findings", res, "NEEDLE_MISSING@0") +} + +// retagSnapshot rewrites one field of the document of the attempt snapshot +// name resolves to, leaving it otherwise valid. +func (fx *verifyFixture) retagSnapshot(vol, name, field, value string) string { + fx.t.Helper() + ctx := context.Background() + ref, ok, err := fx.c.resolveSnap(ctx, vol, name) + if err != nil || !ok || ref.entry == nil { + fx.t.Fatalf("snapshot %s/%s: %v %v", vol, name, ok, err) + } + dir := path.Join(catBase, vol, snapsDir, name) + e, err := fx.f.LookupEntry(ctx, dir, ref.rec.Attempt) + if err != nil { + fx.t.Fatal(err) + } + var doc map[string]json.RawMessage + if err := json.Unmarshal(e.Content, &doc); err != nil { + fx.t.Fatal(err) + } + if doc[field], err = json.Marshal(value); err != nil { + fx.t.Fatal(err) + } + if e.Content, err = json.Marshal(doc); err != nil { + fx.t.Fatal(err) + } + if err := fx.f.UpdateEntry(ctx, dir, e, nil); err != nil { + fx.t.Fatal(err) + } + return ref.rec.Attempt +} + +// A snapshot is checked under the name and volume it was found at. A +// document that names another snapshot or volume is ROOT_INVALID, and a +// miss under that still published attempt is reported under the name it +// was found at, never excused as a snapshot deleted during the pass. +func TestVerify_SnapshotDocumentNamingAnotherSnapshot(t *testing.T) { + for _, tc := range []struct { + name, field, value string + opts VerifyOptions + }{ + {"named, another name", "name", "s2", VerifyOptions{Snapshot: "s1"}}, + {"all, another name", "name", "s2", VerifyOptions{AllSnapshots: true}}, + {"named, another volume", "volume_id", "v9", VerifyOptions{Snapshot: "s1"}}, + {"all, another volume", "volume_id", "v9", VerifyOptions{AllSnapshots: true}}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + // HEAD moves on: only the snapshot names the old chunk 0, whose binding goes. + fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) + attempt := fx.retagSnapshot("v1", "s1", tc.field, tc.value) + fx.deleteBinding(h.Chunks[0].Key) + res := fx.verify("v1", tc.opts) + wantClasses(t, tc.name, res, "ROOT_INVALID", "BINDING_MISSING@0") + label := "snapshot s1/" + attempt + if res.Findings[0].Root != label || res.Findings[1].Root != label || !strings.Contains(res.Findings[0].Detail, tc.value) { + t.Fatalf("findings %+v; want both under %q", res.Findings, label) + } + if len(res.Snapshots) != 1 || res.Snapshots[0] != "s1/"+attempt || res.RootDeletedDuringVerify != 0 || len(res.SnapshotsDeletedDuringVerify) != 0 { + t.Fatalf("snapshots %v, root deleted %d, deleted %v; want [s1/%s], 0, none", + res.Snapshots, res.RootDeletedDuringVerify, res.SnapshotsDeletedDuringVerify, attempt) + } + }) + } +} + +// The closing read decides the final view: a HEAD that is gone, or that +// does not decode, leaves no HEAD root and makes the pass incomplete; it +// never closes on an earlier view. A bad chunk only that HEAD named is then +// counted as superseded, not reported. +func TestVerify_ClosingReadWithoutUsableHeadIsIncomplete(t *testing.T) { + for _, tc := range []struct { + name string + bad bool // chunk 0's needle is missing + undecoded bool // the closing read finds a HEAD that does not decode (else none) + want []string + reason VerifyIncomplete + superseded int + }{ + {"HEAD gone, bad chunk", true, false, nil, VerifyIncompleteHeadAbsent, 1}, + {"HEAD gone, good chunks", false, false, nil, VerifyIncompleteHeadAbsent, 0}, + {"HEAD does not decode", true, true, []string{"ROOT_INVALID"}, VerifyIncompleteHeadInvalid, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if tc.bad { + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + } + done := false + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} + opts.hook = func(stage string) { + if stage != verifyHookClosingRead || done { + return + } + done = true + if tc.undecoded { + fx.f.bumpExtended(path.Join(catBase, "v1", headName), extGen, "999") + } else if err := fx.f.DeleteEntry(ctx, path.Join(catBase, "v1"), headName, nil); err != nil { + t.Error(err) + } + } + res, err := fx.c.Verify(ctx, "v1", opts) + if CodeOf(err) != CodeVerifyIncomplete || res.Complete || res.Incomplete != tc.reason { + t.Fatalf("verify: %v, complete %v, incomplete %q; want incomplete %q", err, res.Complete, res.Incomplete, tc.reason) + } + wantClasses(t, tc.name, res, tc.want...) + for _, f := range res.Findings { + if f.Root == headLabel(h.Gen) { + t.Fatalf("finding %+v under the HEAD the closing read no longer returned", f) + } + } + if res.SupersededDuringVerify != tc.superseded { + t.Fatalf("superseded %d, want %d", res.SupersededDuringVerify, tc.superseded) + } + }) + } +} + +// casHead installs a HEAD whose segment references edit changes, without +// writing segments (the current HEAD is read without resolving them, so it +// may already carry a wrong reference). +func (fx *verifyFixture) casHead(vol string, edit func(segs map[uint64]storage.ChunkSegment)) storage.ChunkHead { + fx.t.Helper() + ctx := context.Background() + r, err := NewChunkRemote(fx.f, fx.b, path.Join(catBase, vol)) + if err != nil { + fx.t.Fatal(err) + } + cur, ok, err := fx.c.ReadHead(ctx, vol) + if err != nil || !ok { + fx.t.Fatalf("HEAD of %s: %v %v", vol, ok, err) + } + next := cur + next.Chunks = nil + next.RemoteLSN = cur.RemoteLSN + 1 + next.Segments = map[uint64]storage.ChunkSegment{} + for g, s := range cur.Segments { + next.Segments[g] = s + } + edit(next.Segments) + next.ManifestChunkCount = 0 + for _, s := range next.Segments { + next.ManifestChunkCount += s.Count + } + if next.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next); err != nil { + fx.t.Fatal(err) + } + return next +} + +// A segment is one object per (owner, key), read once: HEAD and an active +// snapshot naming one segment key with different reference hashes share its +// one outcome. A failed read is one READ_ERROR, under HEAD, counted once; a +// readable segment is used by the root whose reference matches its content, +// and the other root gets one mismatch finding. +func TestVerify_SegmentIsOneObjectPerKey(t *testing.T) { + for _, readFails := range []bool{true, false} { + t.Run(fmt.Sprintf("read fails=%v", readFails), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + // HEAD names the same segment key with another reference hash. + h2 := fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { + s := segs[0] + s.SHA256[0] ^= 0xff + segs[0] = s + }) + segFid := fx.fid(h.Segments[0].Key) + if readFails { + fx.cb.failReads(segFid, -1) + } + res := fx.verify("v1", VerifyOptions{Depth: VerifyBindings, AllSnapshots: true}) + wantReads := 1 + if readFails { + wantClasses(t, "segment read fails", res, "READ_ERROR@seg0") + wantReads = verifyReadAttempts // one read, with its retries + if res.ChunksNotRead != 1 { + t.Fatalf("chunksNotRead %d, want 1", res.ChunksNotRead) + } + } else { + wantClasses(t, "segment matches the snapshot only", res, "CONTENT_MISMATCH@seg0") + // The snapshot's reference matches: its chunks are walked and checked. + if res.ChunksChecked != 2 || res.DistinctChunks != 2 { + t.Fatalf("chunks checked %d, distinct %d; want the snapshot's 2", res.ChunksChecked, res.DistinctChunks) + } + } + if f := res.Findings[0]; f.Root != headLabel(h2.Gen) || f.Key != h.Segments[0].Key { + t.Fatalf("finding %+v; want under %q for the segment key", f, headLabel(h2.Gen)) + } + if n := fx.cb.reads(segFid); n != wantReads { + t.Fatalf("segment read %d times, want %d", n, wantReads) + } + }) + } +} + +// headLookups counts the HEAD reads a pass makes. +type headLookups struct { + Filer + root string + mu sync.Mutex + n int +} + +func (f *headLookups) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if dir == f.root && name == headName { + f.mu.Lock() + f.n++ + f.mu.Unlock() + } + return f.Filer.LookupEntry(ctx, dir, name) +} + +func (f *headLookups) count() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.n +} + +// The quiet closing read is the final view: no HEAD read follows it, and a +// publication that lands right after it is not part of this pass. +func TestVerify_QuietClosingReadIsTheFinalView(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + filer := &headLookups{Filer: fx.f, root: path.Join(catBase, "v1")} + cat, err := NewCatalog(manifestFilerBlobs{filer, fx.cb}, catBase) + if err != nil { + t.Fatal(err) + } + beforeRound, atClose := -1, -1 + var h2 storage.ChunkHead + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} + opts.hook = func(stage string) { + switch stage { + case verifyHookClosingRead: + if beforeRound < 0 { + beforeRound = filer.count() // before the closing round reads anything + } + case verifyHookClosed: + atClose = filer.count() + h2 = fx.publish("v1", map[uint64][]byte{2: verifyData(3)}, true) + fx.needle(fx.fid(h2.Chunks[2].Key), dropNeedle) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + res, err := cat.Verify(ctx, "v1", opts) + if err != nil || !res.Complete { + t.Fatalf("verify: %v, %+v", err, res) + } + if beforeRound < 0 || atClose < 0 { + t.Fatal("the quiet closing read was never reached") + } + // The closing round reads HEAD exactly once, and nothing reads it after. + if n := filer.count(); n-beforeRound != 1 { + t.Fatalf("%d HEAD reads from the start of the closing round to the end of the pass, want 1", n-beforeRound) + } + wantClasses(t, "publication after the quiet read", res) + if res.HeadGens[len(res.HeadGens)-1] != h.Gen || h2.Gen <= h.Gen { + t.Fatalf("covered gens %v (published %d after the close); want the quiet read's %d last", res.HeadGens, h2.Gen, h.Gen) + } +} + +// HEAD and an active snapshot name one segment key; the snapshot's reference +// is valid, HEAD's is changed by edit. Whichever reference the pass meets +// first, the findings are the same: each reference is judged against the +// segment's one outcome at the end, nothing about a reference is kept. +func TestVerify_SegmentFindingsDoNotDependOnOrder(t *testing.T) { + for _, tc := range []struct { + name string + edit func(s *storage.ChunkSegment) + want string + }{ + {"HEAD's reference has the right hash and wrong fields", func(s *storage.ChunkSegment) { s.Count++ }, "SEGMENT_UNREADABLE@seg0"}, + {"HEAD's reference has a wrong hash", func(s *storage.ChunkSegment) { s.SHA256[0] ^= 0xff }, "CONTENT_MISMATCH@seg0"}, + } { + for _, headFirst := range []bool{true, false} { + t.Run(fmt.Sprintf("%s/HEAD's reference first=%v", tc.name, headFirst), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + var bad storage.ChunkHead + breakHead := func() { + bad = fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { + s := segs[0] + tc.edit(&s) + segs[0] = s + }) + } + opts := VerifyOptions{Depth: VerifyData, AllSnapshots: true, BytesPerSecond: -1} + if headFirst { + breakHead() // the pass starts on HEAD's changed reference + } else { + // The pass first meets the valid reference (HEAD and the + // snapshot share it); the changed one comes at the closing read. + opts.hook = func(stage string) { + if stage == verifyHookRootsWalked { + breakHead() + } + } + } + res := fx.verify("v1", opts) + wantClasses(t, tc.name, res, tc.want) + if f := res.Findings[0]; f.Root != headLabel(bad.Gen) || f.Key != h.Segments[0].Key { + t.Fatalf("finding %+v; want under %q", f, headLabel(bad.Gen)) + } + // The snapshot's valid reference is used: its chunks are checked. + if res.ChunksChecked != 2 || res.DistinctChunks != 2 || res.DistinctChunksRead != 2 { + t.Fatalf("chunks checked %d, distinct %d, read %d; want the snapshot's 2", res.ChunksChecked, res.DistinctChunks, res.DistinctChunksRead) + } + if n := fx.cb.reads(fx.fid(h.Segments[0].Key)); n != 1 { + t.Fatalf("segment read %d times, want once", n) + } + }) + } + } +} + +// A problem under a reference that the final view no longer carries is not +// a finding, but it is counted once (superseded): the segment HEAD named +// with a wrong hash and then dropped; the segment HEAD named with a wrong +// hash and then named again soundly; a chunk read whose content a dropped +// reference did not match. +func TestVerify_DroppedReferenceProblemIsCounted(t *testing.T) { + wrongSegHash := func(segs map[uint64]storage.ChunkSegment) { s := segs[0]; s.SHA256[0] ^= 0xff; segs[0] = s } + for _, tc := range []struct { + name string + setup func(fx *verifyFixture) (before, during func()) + }{ + {"segment with a wrong hash, then dropped", func(fx *verifyFixture) (func(), func()) { + fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2)}, false) + return func() { fx.casHead("v1", wrongSegHash) }, + func() { fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { delete(segs, 0) }) } + }}, + {"segment with a wrong hash, then named soundly", func(fx *verifyFixture) (func(), func()) { + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + return func() { fx.casHead("v1", wrongSegHash) }, + func() { fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { segs[0] = h.Segments[0] }) } + }}, + {"chunk read, a dropped reference did not match it", func(fx *verifyFixture) (func(), func()) { + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + return func() { fx.republish("v1", wrongHash(0)) }, + func() { fx.republish("v1", func(c map[uint64]storage.ChunkRef) { c[0] = h.Chunks[0] }) } + }}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + before, during := tc.setup(fx) + before() + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} + opts.hook = func(stage string) { + if stage == verifyHookHeadWalked { + during() + } + } + res := fx.verify("v1", opts) + wantClasses(t, tc.name, res) + if res.SupersededDuringVerify != 1 || res.RootDeletedDuringVerify != 0 { + t.Fatalf("superseded %d, root deleted %d; want 1, 0", res.SupersededDuringVerify, res.RootDeletedDuringVerify) + } + }) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go b/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go index b1f4501a4d..28cc7b0e09 100644 --- a/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go @@ -120,7 +120,7 @@ func TestIntegration_DeleteVolumeThenGC(t *testing.T) { // GC: two marks past grace reclaim exactly A (only S1 and w2 reached // it) and D (only w2); B and C (w1's HEAD and S2) stay. - grace := 2 * DefaultOpDeadline + grace := 3 * DefaultOpDeadline // >= deadline + skew + CAS apply bound at := time.Now().Add(3 * grace) g, err := NewCollector(cat, cl, GCConfig{Grace: grace, IntentTTL: time.Hour, Now: func() time.Time { return at }, IssuedEpoch: func(context.Context, string) (uint64, error) { return 1, nil }}) diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete_test.go b/seaweed-block/core/frontend/chunkstore/volume_delete_test.go index 0bb854fa48..c554bb76f0 100644 --- a/seaweed-block/core/frontend/chunkstore/volume_delete_test.go +++ b/seaweed-block/core/frontend/chunkstore/volume_delete_test.go @@ -331,7 +331,7 @@ func TestCatalog_InFlightSnapshotRefusesTheDelete(t *testing.T) { } } -// A fork that claims during the delete mark sees the deleting source and +// A fork that reads during the delete mark sees the deleting source and // refuses before installing anything; the delete refuses too (the forked // snapshot exists) and reverts. func TestCatalog_ForkDuringTheDeleteMarkRefuses(t *testing.T) { @@ -355,9 +355,6 @@ func TestCatalog_ForkDuringTheDeleteMarkRefuses(t *testing.T) { if _, ok, _ := c.ReadVolume(ctx, "w2"); ok { t.Fatal("the refused fork published its VOLUME") } - if got := claimsOf(t, c, "s1"); len(got) != 0 { - t.Fatalf("the refused fork left claims %v", got) - } } // P2 (incarnation): D1 checks under deleting generation G and pauses @@ -504,14 +501,14 @@ func TestCatalog_DeleteVolumeTombstonesAndRefusesReuse(t *testing.T) { if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "w3", RequestID: "f3"}); CodeOf(err) != CodeOutcomeUnknown { t.Fatalf("fork w3: %v", err) } - if _, err := c.DeleteSnapshot(ctx, "v1", "s2"); CodeOf(err) != CodeSnapshotClaimed { - t.Fatalf("delete s2 under the incomplete fork: %v; want snapshot_claimed", err) + if got, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil || got != SnapDeleting { + t.Fatalf("delete s2 under the incomplete fork: %q %v; forks do not hold their parent", got, err) } if res, err := c.DeleteVolume(ctx, "w3", nil); err != nil || !res.Completed { t.Fatalf("delete w3: %+v %v", res, err) } - if _, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil { - t.Fatalf("delete s2 after w3 was deleted (its claim is dead): %v", err) + if got, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil || got != SnapAbsent { + t.Fatalf("delete s2 again: %q %v; want absent", got, err) } } diff --git a/seaweed-block/core/frontend/durable/attach_ready_fail_fast_test.go b/seaweed-block/core/frontend/durable/attach_ready_fail_fast_test.go new file mode 100644 index 0000000000..fee3162129 --- /dev/null +++ b/seaweed-block/core/frontend/durable/attach_ready_fail_fast_test.go @@ -0,0 +1,102 @@ +package durable + +import ( + "context" + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +// TestAttachReadinessWaitFailsFastOnTerminalState pins that an I/O waiting for +// chunk attachment returns at once, without another readiness wait, when an +// observer install failed, readiness was withdrawn or a fence is seen. +func TestAttachReadinessWaitFailsFastOnTerminalState(t *testing.T) { + for _, tc := range []struct { + name string + // before runs before the read; afterRefusal runs between the first gate + // refusal and the wait; whileWaiting runs once the read is waiting. + before func(t *testing.T, b *StorageBackend) + afterRefusal func(b *StorageBackend) + whileWaiting func(b *StorageBackend) + want error + wantWaits int32 + }{ + { + name: "observer install failed", + before: func(t *testing.T, b *StorageBackend) { + if err := b.SetWriteObserver(refusingRebaser{}); err == nil { + t.Fatal("refused observer install reported success") + } + }, + want: frontend.ErrNotReady, + }, + { + name: "fence seen after the attach refusal", + afterRefusal: func(b *StorageBackend) { + b.mu.Lock() + b.chunkFenced = func() bool { return true } + b.mu.Unlock() + }, + want: frontend.ErrStalePrimary, + }, + { + name: "readiness withdrawn while waiting", + whileWaiting: func(b *StorageBackend) { b.SetOperational(false, "host drain") }, + want: frontend.ErrNotReady, + wantWaits: 1, + }, + } { + t.Run(tc.name, func(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + b.setChunkAttachPending("attachment pending") + if tc.before != nil { + tc.before(t, b) + } + if tc.afterRefusal != nil { + b.testAfterAttachRefusal = func() { tc.afterRefusal(b) } + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var waits atomic.Int32 + waiting, resume := make(chan struct{}), make(chan struct{}) + b.testBeforeReadReadyWait = func() { + if waits.Add(1) == 1 && tc.whileWaiting != nil { + close(waiting) + <-resume + return + } + // A wait the rule forbids: end it now instead of after 3 s. + cancel() + } + result := make(chan error, 1) + go func() { + _, err := b.Read(ctx, 0, make([]byte, 4096)) + result <- err + }() + if tc.whileWaiting != nil { + select { + case <-waiting: + case <-time.After(3 * time.Second): + t.Fatal("read never waited for attachment readiness") + } + tc.whileWaiting(b) + close(resume) + } + var err error + select { + case err = <-result: + case <-time.After(5 * time.Second): + t.Fatal("read did not return") + } + if got := waits.Load(); got != tc.wantWaits { + t.Fatalf("read waited %d times for readiness, want %d (err=%v)", got, tc.wantWaits, err) + } + if !errors.Is(err, tc.want) { + t.Fatalf("err=%v, want %v", err, tc.want) + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/frozen_validation_before_access_test.go b/seaweed-block/core/frontend/durable/frozen_validation_before_access_test.go new file mode 100644 index 0000000000..88f6dfbb2b --- /dev/null +++ b/seaweed-block/core/frontend/durable/frozen_validation_before_access_test.go @@ -0,0 +1,22 @@ +package durable + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestFrozenValidationPrecedesAnyProviderAccess(t *testing.T) { + // Deliberately poisoned receiver: validation must return before touching + // even the provider mutex/volume map, much less StopIO, capture or HEAD. + var p *DurableProvider + for _, at := range []time.Time{{}, time.Unix(0, -1), time.Now().Add(time.Hour)} { + result, last, err := p.DetachVolumeFrozen(context.Background(), "v1", storage.FrozenDetachOptions{StartedAt: at}) + if !errors.Is(err, storage.ErrInvalidFreezeBudget) || result.Head.Gen != 0 || last != 0 { + t.Fatalf("invalid input accessed provider or returned an applied point: %+v %d %v", result, last, err) + } + } +} diff --git a/seaweed-block/core/frontend/durable/maintenance_lineage_test.go b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go new file mode 100644 index 0000000000..d6020247f2 --- /dev/null +++ b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go @@ -0,0 +1,92 @@ +package durable + +import ( + "context" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" + "testing" + "time" +) + +type maintenanceStubLayer struct{ storage.ChunkLayer } + +func (maintenanceStubLayer) Fenced() bool { return false } +func TestMaintenanceRejectsForeignLineageBeforeAdmission(t *testing.T) { + for _, field := range []string{"epoch", "replica", "endpoint", "handle", "layer"} { + t.Run(field, func(t *testing.T) { + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1} + lin := chunkLineage{"v1", "r1", 3, 1} + layer := &maintenanceStubLayer{} + h := &volHandle{chunk: layer} + p := &DurableProvider{volumes: map[string]*volHandle{"v1": h}, view: precopyQueueView{id}} + if !p.maintenanceCurrent("v1", h, layer, lin) { + t.Fatal("healthy same attachment refused") + } + switch field { + case "epoch": + id.Epoch++ + case "replica": + id.ReplicaID = "r2" + case "endpoint": + id.EndpointVersion++ + case "handle": + p.volumes["v1"] = &volHandle{chunk: layer} + case "layer": + h.chunk = &maintenanceStubLayer{} + } + p.view = precopyQueueView{id} + p.cfg.ChunkMaintenanceInterval = time.Nanosecond + calls := 0 + p.cfg.ChunkMaintenance = func(context.Context, string) error { calls++; return nil } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return p.maintenanceCurrent("v1", h, layer, lin) }) + if calls != 0 { + t.Fatalf("foreign attachment admitted %d passes", calls) + } + }) + } +} +func TestMaintenanceSameHandleRearmsAfterJoinedStop(t *testing.T) { + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1} + layer := &maintenanceStubLayer{} + h := &volHandle{chunk: layer, chunkLineage: chunkLineage{"v1", "r1", 3, 1}} + entered := make(chan struct{}, 2) + p := &DurableProvider{volumes: map[string]*volHandle{"v1": h}, view: precopyQueueView{id}, cfg: ProviderConfig{ChunkMaintenanceInterval: time.Nanosecond, ChunkMaintenance: func(ctx context.Context, _ string) error { entered <- struct{}{}; <-ctx.Done(); return ctx.Err() }}} + var stopperDone chan struct{} + t.Cleanup(func() { + p.mu.Lock() + stop, ownerDone := h.chunkStop, h.chunkDone + p.mu.Unlock() + if stop != nil { + stop() + } + for _, done := range []<-chan struct{}{stopperDone, ownerDone} { + if done != nil { + select { + case <-done: + case <-time.After(time.Second): + t.Error("cleanup did not join outstanding maintenance stopper/owner") + } + } + } + }) + for i := 0; i < 2; i++ { + p.mu.Lock() + p.startChunkLoop("v1", h, layer) + p.mu.Unlock() + select { + case <-entered: + case <-time.After(time.Second): + t.Fatal("same handle did not arm") + } + done := make(chan struct{}) + stopperDone = done + go func() { p.stopChunkLoop(h); close(done) }() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("stopped owner did not join") + } + } +} diff --git a/seaweed-block/core/frontend/durable/maintenance_policy_test.go b/seaweed-block/core/frontend/durable/maintenance_policy_test.go new file mode 100644 index 0000000000..734e5b89e6 --- /dev/null +++ b/seaweed-block/core/frontend/durable/maintenance_policy_test.go @@ -0,0 +1,60 @@ +package durable + +import ( + "context" + "fmt" + "sync" + "testing" + "testing/synctest" + "time" +) + +func TestMaintenanceVolumePhasesDoNotAlign(t *testing.T) { + interval := 15 * time.Minute + seen := map[time.Duration]bool{} + for i := 0; i < 200; i++ { + s := initialCutSchedule(fmt.Sprintf("volume-%d", i), interval, t0, true) + offset := s.firstDue.Sub(t0) + if offset <= 0 || offset >= interval { + t.Fatalf("phase outside interval: %s", offset) + } + seen[offset] = true + if _, due := testPolicy().due(s, s.firstDue.Add(-time.Nanosecond), false); due { + t.Fatal("published before own phase") + } + } + if len(seen) < 190 { + t.Fatalf("200 volumes collapsed into %d phases", len(seen)) + } +} + +// Virtual quiescence observes the join boundary directly, so a slow storage +// Close cannot accidentally make an omitted scheduler join look correct. +func TestMaintenanceStopJoinsBeforeRelease(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done, release, cancelled := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once sync.Once + finish := func() { once.Do(func() { close(release) }) } + defer finish() + p := &DurableProvider{} + h := &volHandle{chunkStop: cancel, chunkDone: done} + go func() { <-ctx.Done(); close(cancelled); <-release; close(done) }() + returned1, returned2 := make(chan struct{}), make(chan struct{}) + go func() { p.stopChunkLoop(h); close(returned1) }() + <-cancelled + go func() { p.stopChunkLoop(h); close(returned2) }() + synctest.Wait() + for _, returned := range []chan struct{}{returned1, returned2} { + select { + case <-returned: + t.Error("stop released before worker join") + default: + } + } + finish() + <-returned1 + <-returned2 + }) +} diff --git a/seaweed-block/core/frontend/durable/plain_detach_closed_test.go b/seaweed-block/core/frontend/durable/plain_detach_closed_test.go new file mode 100644 index 0000000000..07740f2329 --- /dev/null +++ b/seaweed-block/core/frontend/durable/plain_detach_closed_test.go @@ -0,0 +1,20 @@ +package durable + +import ( + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +// TestPlainDetachStopRefusesClosedBackend pins that the plain-detach stop of a +// closed backend returns ErrBackendClosed instead of reporting a clean stop. +func TestPlainDetachStopRefusesClosedBackend(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + if err := b.Close(); err != nil { + t.Fatal(err) + } + if err := b.stopPlainDetachIfIdle(); !errors.Is(err, frontend.ErrBackendClosed) { + t.Fatalf("plain-detach stop of a closed backend: %v", err) + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_admission.go b/seaweed-block/core/frontend/durable/precopy_admission.go index 9e58424413..6b2ea197c5 100644 --- a/seaweed-block/core/frontend/durable/precopy_admission.go +++ b/seaweed-block/core/frontend/durable/precopy_admission.go @@ -12,8 +12,12 @@ import ( const precopyQueueBudget = 5 * time.Second +var errPrecopyPaused = fmt.Errorf("%w: %w: pre-copy admission paused", frontend.ErrNotReady, frontend.ErrBackendBusy) + type precopyWaiter struct { ready chan struct{} + deadline time.Time + err error signaled bool } type precopyAdmission struct { @@ -48,7 +52,7 @@ func (b *StorageBackend) BeginPrecopyPause(ctx context.Context) (func(), error) once.Do(func() { b.mu.Lock() if b.precopy == p { - b.finishPrecopyLocked(b.operational.Load() && !b.closed) + b.finishPrecopyLocked() } b.mu.Unlock() }) @@ -73,30 +77,26 @@ func (b *StorageBackend) BeginPrecopyPause(ctx context.Context) (func(), error) } } -func signalPrecopy(w *precopyWaiter) { - if !w.signaled { - close(w.ready) - w.signaled = true - } -} - -// Caller owns mu. Resume admits the old queue serially; a terminal stop wakes -// every command to observe the terminal gate, without issuing storage I/O. -func (b *StorageBackend) finishPrecopyLocked(resume bool) { +// Caller owns mu. INV-CUT-PRECOPY-001: ending the pause releases every +// waiter in FIFO admission order in this one lock hold, then normal gate checks +// and completion run independently. New arrivals cannot join the ended pause. +func (b *StorageBackend) finishPrecopyLocked() { p := b.precopy if p == nil { return } p.active = false - if !resume { - for _, w := range p.waiters { - signalPrecopy(w) + b.precopy = nil + for _, w := range p.waiters { + // INV-CUT-PRECOPY-001: expiry versus grant is decided under mu. + if !time.Now().Before(w.deadline) { + w.err = context.DeadlineExceeded + } + w.signaled = true + close(w.ready) + if hook := b.testPrecopyGranted; hook != nil && w.err == nil { + hook(w) } - b.precopy = nil - } else if len(p.waiters) == 0 { - b.precopy = nil - } else { - signalPrecopy(p.waiters[0]) } } @@ -112,69 +112,67 @@ func (b *StorageBackend) removePrecopyWaiter(p *precopyAdmission, w *precopyWait break } } - if !p.active { - if len(p.waiters) == 0 { - b.precopy = nil - } else { - signalPrecopy(p.waiters[0]) - } - } } // An unqueued caller races the pause only at admit's final registration check. // Waiting callers own no I/O lock and execute no storage/observer operation. func (b *StorageBackend) admitPrecopy(ctx context.Context, admit func() (func(), error)) (func(), error) { + arrival := time.Now() // INV-CUT-PRECOPY-001: one command-owned wait budget. for { b.mu.Lock() p := b.precopy - if p == nil { - b.mu.Unlock() - release, err := admit() - if err != nil { - b.mu.Lock() - pending := b.precopy != nil - b.mu.Unlock() - if pending { - continue - } + + b.mu.Unlock() + if p != nil { + if err := b.readyCheck(); err != nil && !errors.Is(err, frontend.ErrBackendBusy) { + return nil, err } - return release, err - } - b.mu.Unlock() - if err := b.readyCheck(); err != nil && !errors.Is(err, frontend.ErrBackendBusy) { - return nil, err - } - b.mu.Lock() - if b.precopy != p { + b.mu.Lock() + if b.precopy != p { + b.mu.Unlock() + continue + } + deadline := arrival.Add(precopyQueueBudget) + if d, ok := ctx.Deadline(); ok && d.Before(deadline) { + deadline = d + } + w := &precopyWaiter{ready: make(chan struct{}), deadline: deadline} + p.waiters = append(p.waiters, w) b.mu.Unlock() - continue - } - w := &precopyWaiter{ready: make(chan struct{})} - p.waiters = append(p.waiters, w) - if !p.active && len(p.waiters) == 1 { - signalPrecopy(w) - } - deadline := p.started.Add(precopyQueueBudget) - b.mu.Unlock() - if hook := b.testPrecopyQueued; hook != nil { - hook() - } - waitCtx, cancel := context.WithDeadline(ctx, deadline) - select { - case <-w.ready: - case <-waitCtx.Done(): - } - cause := waitCtx.Err() - cancel() - if cause != nil { - b.removePrecopyWaiter(p, w) - return nil, b.attachReadyTimeout(cause) + if hook := b.testPrecopyQueued; hook != nil { + hook() + } + waitCtx, cancel := context.WithDeadline(ctx, deadline) + select { + case <-w.ready: + case <-waitCtx.Done(): + } + b.mu.Lock() + cause := waitCtx.Err() + if w.signaled { + cause = w.err + } + b.mu.Unlock() + // A timely queue grant cannot outlive the command's own deadline. + if cause == nil { + cause = ctx.Err() + } + cancel() + if cause != nil { + b.removePrecopyWaiter(p, w) + return nil, b.attachReadyTimeout(cause) + } } release, err := admit() - if err != nil { - b.removePrecopyWaiter(p, w) - return nil, err + // INV-CUT-PRECOPY-001 / INV-FE-LINEAGE-GATE-001: retry only the pause. + if errors.Is(err, errPrecopyPaused) { + b.mu.Lock() + pending := b.precopy != nil + b.mu.Unlock() + if pending { + continue + } } - return func() { release(); b.removePrecopyWaiter(p, w) }, nil + return release, err } } diff --git a/seaweed-block/core/frontend/durable/precopy_arrival_test.go b/seaweed-block/core/frontend/durable/precopy_arrival_test.go new file mode 100644 index 0000000000..c3da43764f --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_arrival_test.go @@ -0,0 +1,314 @@ +package durable + +import ( + "context" + "errors" + "sync" + "testing" + "testing/synctest" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +// INV-CUT-PRECOPY-001: an active pause may predate this command. Its queue +// allowance is measured once from this command's arrival, capped by its caller. +func TestPrecopyQueueBoundStartsAtCommandArrival(t *testing.T) { + for _, caller := range []time.Duration{2 * time.Second, 10 * time.Second} { + t.Run(caller.String(), func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + b := precopyMemoryBackend(t) + resume, err := b.BeginPrecopyPause(context.Background()) + if err != nil { + t.Fatal(err) + } + defer resume() + // Let the active pause get older than five seconds before this arrival. + time.Sleep(6 * time.Second) + ctx, cancel := context.WithTimeout(context.Background(), caller) + defer cancel() + queued, done := make(chan struct{}), make(chan error, 1) + b.testPrecopyQueued = func() { close(queued) } + observed := make(chan struct{}, 1) + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(context.Context) error { observed <- struct{}{}; return nil }}); err != nil { + t.Fatal(err) + } + joined := false + t.Cleanup(func() { + cancel() + resume() + if !joined { + select { + case <-done: + case <-time.After(time.Second): + t.Error("arrival-bounded waiter did not join") + } + } + }) + go func() { done <- b.Sync(ctx) }() + select { + case <-queued: + case err := <-done: + joined = true + t.Fatalf("command ended before queue registration: %v", err) + case <-time.After(time.Second): + t.Fatal("initial queue registration timed out") + } + synctest.Wait() + bound := 5 * time.Second + if caller < bound { + bound = caller + } + time.Sleep(bound - time.Nanosecond) + synctest.Wait() + select { + case err := <-done: + joined = true + t.Fatalf("fresh waiter inherited old pause deadline: %v", err) + default: + } + time.Sleep(time.Nanosecond) + synctest.Wait() + select { + case err := <-done: + joined = true + if !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expiry classification: %v", err) + } + default: + t.Fatal("arrival/caller deadline did not bound the waiter") + } + select { + case <-observed: + t.Fatal("expired paused waiter reached physical Sync") + default: + } + }) + }) + } +} + +// The queue grant and its deadline have one decision boundary even when a +// descheduled waiter cannot run until after its queue timer would have expired. +func TestPrecopyResumeGrantVersusExpiry(t *testing.T) { + for _, outcome := range []string{"grant-before-queue-expiry", "expiry-before-grant", "caller-expiry", "close-after-grant"} { + t.Run(outcome, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + b := precopyMemoryBackend(t) + caller := 10 * time.Second + if outcome == "caller-expiry" { + caller = 4 * time.Second + } + ctx, cancel := context.WithTimeout(context.Background(), caller) + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + queued, proceed := make(chan struct{}), make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(proceed) }) } + b.testPrecopyQueued = func() { close(queued); <-proceed } + observed := make(chan struct{}, 1) + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(context.Context) error { observed <- struct{}{}; return nil }}); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + joined := false + t.Cleanup(func() { + release() + cancel() + resume() + if !joined { + select { + case <-done: + case <-time.After(time.Second): + t.Error("boundary waiter did not join") + } + } + }) + go func() { done <- b.Sync(ctx) }() + select { + case <-queued: + case err := <-done: + joined = true + t.Fatalf("command ended before queue registration: %v", err) + case <-time.After(time.Second): + t.Fatal("initial queue registration timed out") + } + synctest.Wait() + if outcome == "expiry-before-grant" { + time.Sleep(6 * time.Second) + } + resume() + if outcome != "expiry-before-grant" { + time.Sleep(6 * time.Second) + } + if outcome == "close-after-grant" { + _ = b.Close() + } + release() + synctest.Wait() + var result error + select { + case result = <-done: + joined = true + case <-time.After(time.Second): + t.Fatal("grant boundary did not settle") + } + switch outcome { + case "grant-before-queue-expiry": + if result != nil { + t.Fatalf("timely grant lost to later queue expiry: %v", result) + } + case "close-after-grant": + if !errors.Is(result, frontend.ErrBackendClosed) { + t.Fatalf("Close did not retain terminal precedence: %v", result) + } + default: + if !errors.Is(result, frontend.ErrBackendBusy) || !errors.Is(result, context.DeadlineExceeded) { + t.Fatalf("expiry not refused as typed busy: %v", result) + } + } + select { + case <-observed: + if result != nil { + t.Fatal("refused waiter performed Sync") + } + default: + if result == nil { + t.Fatal("successful grant did not perform Sync") + } + } + }) + }) + } +} + +func TestPrecopyGrantedWaiterFollowsReplacementPause(t *testing.T) { + for _, outcome := range []string{"resume", "caller-cancel", "close", "original-deadline"} { + t.Run(outcome, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + resumeA, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + queued, proceedA := make(chan int, 2), make(chan struct{}) + calls := 0 + var once sync.Once + releaseA := func() { once.Do(func() { close(proceedA) }) } + b.testPrecopyQueued = func() { + calls++ + queued <- calls + if calls == 1 { + <-proceedA + } + } + observed := make(chan struct{}, 1) + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(context.Context) error { observed <- struct{}{}; return nil }}); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + joined := false + resumeB := func() {} + t.Cleanup(func() { + releaseA() + cancel() + resumeA() + resumeB() + if !joined { + select { + case <-done: + case <-time.After(time.Second): + t.Error("replacement-pause waiter did not join") + } + } + }) + go func() { done <- b.Sync(ctx) }() + select { + case n := <-queued: + if n != 1 { + t.Fatal("first pause registration missing") + } + case err := <-done: + joined = true + t.Fatalf("command ended before first pause registration: %v", err) + case <-time.After(time.Second): + t.Fatal("initial queue registration timed out") + } + synctest.Wait() + time.Sleep(2 * time.Second) + resumeA() + resumeB, err = b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + releaseA() + synctest.Wait() + select { + case n := <-queued: + if n != 2 { + t.Fatalf("requeue=%d", n) + } + case err := <-done: + joined = true + t.Fatalf("granted waiter returned replacement pause Busy instead of requeueing: %v", err) + default: + t.Fatal("waiter did not join replacement pause") + } + select { + case <-observed: + t.Fatal("waiter crossed replacement pause") + default: + } + switch outcome { + case "resume": + resumeB() + case "caller-cancel": + cancel() + case "close": + _ = b.Close() + case "original-deadline": + time.Sleep(3 * time.Second) + } + synctest.Wait() + var result error + select { + case result = <-done: + joined = true + case <-time.After(time.Second): + t.Fatal("replacement boundary did not settle") + } + switch outcome { + case "resume": + if result != nil { + t.Fatal(result) + } + case "close": + if !errors.Is(result, frontend.ErrBackendClosed) { + t.Fatalf("Close priority: %v", result) + } + case "caller-cancel": + if !errors.Is(result, frontend.ErrBackendBusy) || !errors.Is(result, context.Canceled) { + t.Fatalf("caller priority: %v", result) + } + case "original-deadline": + if !errors.Is(result, frontend.ErrBackendBusy) || !errors.Is(result, context.DeadlineExceeded) || ctx.Err() != nil { + t.Fatalf("requeue reset command allowance: %v ctx=%v", result, ctx.Err()) + } + } + select { + case <-observed: + if result != nil { + t.Fatal("refused replacement waiter performed Sync") + } + default: + if result == nil { + t.Fatal("resumed replacement waiter did not Sync") + } + } + }) + }) + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_drain_admitted_io_test.go b/seaweed-block/core/frontend/durable/precopy_drain_admitted_io_test.go new file mode 100644 index 0000000000..541e1feb39 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_drain_admitted_io_test.go @@ -0,0 +1,162 @@ +package durable + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// heldReadStore parks each ReadContext call on its LBA until the test releases +// that LBA, so every Read stays an admitted I/O for as long as the test needs. +type heldReadStore struct { + storage.LogicalStorage + entered chan uint32 + release map[uint32]chan struct{} +} + +func newHeldReadStore(lbas ...uint32) *heldReadStore { + s := &heldReadStore{entered: make(chan uint32, len(lbas)), release: make(map[uint32]chan struct{}, len(lbas))} + for _, lba := range lbas { + s.release[lba] = make(chan struct{}) + } + return s +} + +func (s *heldReadStore) ReadContext(ctx context.Context, lba uint32) ([]byte, error) { + s.entered <- lba + select { + case <-s.release[lba]: + return make([]byte, 4096), nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func (s *heldReadStore) Read(lba uint32) ([]byte, error) { + return s.ReadContext(context.Background(), lba) +} + +func (s *heldReadStore) NextLSN() uint64 { return 1 } + +// precopyTestBackend is an operational backend over store with a matching +// healthy projection, so admission depends only on the state under test. +func precopyTestBackend(store storage.LogicalStorage) *StorageBackend { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + b := &StorageBackend{storage: store, blockSize: 4096, id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}} + b.SetOperational(true, "serving") + return b +} + +// startHeldReads starts one Read per LBA and returns once every one of them is +// admitted and parked inside storage. Cleanup releases and joins them. +func startHeldReads(t *testing.T, b *StorageBackend, store *heldReadStore, lbas ...uint32) <-chan error { + t.Helper() + done := make(chan error, len(lbas)) + for _, lba := range lbas { + go func(off int64) { + _, err := b.Read(context.Background(), off, make([]byte, 4096)) + done <- err + }(int64(lba) * 4096) + } + t.Cleanup(func() { + for _, ch := range store.release { + select { + case <-ch: + default: + close(ch) + } + } + _ = b.Close() + }) + for range lbas { + select { + case <-store.entered: + case <-time.After(3 * time.Second): + t.Fatal("read never reached storage") + } + } + return done +} + +// installedPause waits until BeginPrecopyPause has installed its pause and +// returns the pause's drain channel. +func installedPause(t *testing.T, b *StorageBackend) <-chan struct{} { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for { + b.mu.Lock() + p := b.precopy + b.mu.Unlock() + if p != nil { + return p.drained + } + if time.Now().After(deadline) { + t.Fatal("pre-copy pause was never installed") + } + time.Sleep(time.Millisecond) + } +} + +type pauseResult struct { + resume func() + err error +} + +func beginPauseAsync(ctx context.Context, b *StorageBackend) <-chan pauseResult { + out := make(chan pauseResult, 1) + go func() { + resume, err := b.BeginPrecopyPause(ctx) + out <- pauseResult{resume, err} + }() + return out +} + +// TestPrecopyDrainWaitsForEveryAdmittedIO pins that a pre-copy pause reports +// its drain done only after every I/O admitted before it has finished, not +// when the first of several completes. +func TestPrecopyDrainWaitsForEveryAdmittedIO(t *testing.T) { + store := newHeldReadStore(0, 1) + b := precopyTestBackend(store) + reads := startHeldReads(t, b, store, 0, 1) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + pause := beginPauseAsync(ctx, b) + drained := installedPause(t, b) + + close(store.release[0]) + if err := <-reads; err != nil { + t.Fatalf("first admitted read: %v", err) + } + // The first read has returned, so its admission release has run. + select { + case <-drained: + t.Fatal("drain reported done while a second admitted I/O is still in flight") + default: + } + select { + case r := <-pause: + t.Fatalf("pause returned while a second admitted I/O is still in flight: err=%v", r.err) + default: + } + + close(store.release[1]) + if err := <-reads; err != nil { + t.Fatalf("second admitted read: %v", err) + } + select { + case r := <-pause: + if r.err != nil { + t.Fatalf("drain after the last admitted I/O: %v", r.err) + } + r.resume() + case <-time.After(3 * time.Second): + t.Fatal("drain not reported done after the last admitted I/O finished") + } + if _, err := b.Read(context.Background(), 0, nil); err != nil { + t.Fatalf("resume did not reopen admission: %v", err) + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_drain_readiness_loss_test.go b/seaweed-block/core/frontend/durable/precopy_drain_readiness_loss_test.go new file mode 100644 index 0000000000..1acde5c023 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_drain_readiness_loss_test.go @@ -0,0 +1,80 @@ +package durable + +import ( + "context" + "testing" + "time" +) + +// TestPrecopyDrainEndsWithErrorOnReadinessLossOrClose pins that a pre-copy +// drain still pending when the backend loses readiness or is closed ends with +// an error and never reports a clean drain. +func TestPrecopyDrainEndsWithErrorOnReadinessLossOrClose(t *testing.T) { + for _, tc := range []struct { + name string + // bound is the drain's caller context, as the pre-copy caller gives it. + bound time.Duration + spoil func(b *StorageBackend) + }{ + {"readiness lost", 3 * time.Second, func(b *StorageBackend) { b.SetOperational(false, "host drain") }}, + // Close does not signal the drain; the waiter ends at its own bound. + {"closed", 200 * time.Millisecond, func(b *StorageBackend) { _ = b.Close() }}, + } { + t.Run(tc.name, func(t *testing.T) { + store := newHeldReadStore(0) + b := precopyTestBackend(store) + reads := startHeldReads(t, b, store, 0) + ctx, cancel := context.WithTimeout(context.Background(), tc.bound) + defer cancel() + pause := beginPauseAsync(ctx, b) + installedPause(t, b) + + tc.spoil(b) + close(store.release[0]) + <-reads + select { + case r := <-pause: + if r.err == nil { + r.resume() + t.Fatal("drain reported clean after the backend became unusable") + } + case <-time.After(tc.bound + 3*time.Second): + t.Fatal("drain waiter did not end") + } + b.mu.Lock() + left := b.precopy + b.mu.Unlock() + if left != nil { + t.Fatal("failed drain left its pause installed") + } + }) + } +} + +// TestPrecopyFinalStopRefusedAfterReadinessLossOrClose pins that the final +// pre-copy stop refuses to commit a freeze when the backend lost readiness or +// was closed after the drain completed. +func TestPrecopyFinalStopRefusedAfterReadinessLossOrClose(t *testing.T) { + for _, tc := range []struct { + name string + spoil func(b *StorageBackend) + }{ + {"readiness lost", func(b *StorageBackend) { b.SetOperational(false, "host drain") }}, + {"closed", func(b *StorageBackend) { _ = b.Close() }}, + } { + t.Run(tc.name, func(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + defer resume() + tc.spoil(b) + if b.TryStopIO("chunk pre-copy: final detached cut") { + t.Fatal("final stop committed a freeze on an unusable backend") + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_fifo_test.go b/seaweed-block/core/frontend/durable/precopy_fifo_test.go index 7b41c5f2fe..ce8644ad14 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifo_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifo_test.go @@ -83,100 +83,6 @@ func TestPrecopyHostDrainDoesNotCompleteHeldGuestIO(t *testing.T) { } } -func TestPrecopyQueueResumesInFIFOOrder(t *testing.T) { - b := precopyMemoryBackend(t) - ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) - queued := make(chan struct{}, 4) - b.testPrecopyQueued = func() { queued <- struct{}{} } - first, release := make(chan struct{}), make(chan struct{}) - var once sync.Once - unpark := func() { once.Do(func() { close(release) }) } - seen := make(chan byte, 4) - if err := b.SetWriteObserver(precopyQueueObserver{observe: func(v byte) { - seen <- v - if v == 1 { - close(first) - select { - case <-release: - case <-ctx.Done(): - } - } - }}); err != nil { - t.Fatal(err) - } - resume, err := b.BeginPrecopyPause(ctx) - if err != nil { - t.Fatal(err) - } - var wg sync.WaitGroup - joined := make(chan struct{}) - errs := make(chan error, 4) - t.Cleanup(func() { - cancel() - unpark() - resume() - _ = b.Close() - go func() { wg.Wait(); close(joined) }() - select { - case <-joined: - case <-time.After(3 * time.Second): - t.Error("queue workers did not join") - } - }) - start := func(v byte) { - wg.Add(1) - go func() { defer wg.Done(); _, err := b.Write(ctx, 0, bytes.Repeat([]byte{v}, 4096)); errs <- err }() - select { - case <-queued: - case <-ctx.Done(): - t.Fatal("command was not queued") - } - } - start(1) - start(2) - start(3) - resume() - select { - case <-first: - case <-ctx.Done(): - t.Fatal("first queued write did not enter") - } - start(4) // New arrivals cannot bypass the old queue during an aborted cut. - if v := <-seen; v != 1 { - t.Fatalf("first write=%d", v) - } - select { - case v := <-seen: - t.Fatalf("write %d bypassed held FIFO head", v) - case <-time.After(30 * time.Millisecond): - } - unpark() - for _, want := range []byte{2, 3, 4} { - select { - case got := <-seen: - if got != want { - t.Fatalf("write=%d want%d", got, want) - } - case <-ctx.Done(): - t.Fatal("FIFO queue did not drain") - } - } - for i := 0; i < 4; i++ { - select { - case err := <-errs: - if err != nil { - t.Fatal(err) - } - case <-ctx.Done(): - t.Fatal("queued write did not finish") - } - } - data := make([]byte, 4096) - if _, err := b.Read(ctx, 0, data); err != nil || data[0] != 4 { - t.Fatalf("ordered final bytes=%d err=%v", data[0], err) - } -} - func TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture(t *testing.T) { b := precopyMemoryBackend(t) entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{}) @@ -258,7 +164,7 @@ func TestPrecopyQueueUsesFiveSecondCutoverBudget(t *testing.T) { // Releasing that lock before the fallback must not replace the pause identity. func TestPrecopyStopFallbackPreservesQueuedPause(t *testing.T) { for _, terminal := range []bool{false, true} { - name := "resume_fifo" + name := "resume_all" if terminal { name = "close" } @@ -365,12 +271,14 @@ func TestPrecopyStopFallbackPreservesQueuedPause(t *testing.T) { default: } } else { - for _, want := range []byte{1, 2} { + seenWrites := map[byte]bool{} + for i := 0; i < 2; i++ { select { case got := <-seen: - if got != want { - t.Fatalf("FIFO got %d want %d", got, want) + if got < 1 || got > 2 || seenWrites[got] { + t.Fatalf("unexpected resumed write %d", got) } + seenWrites[got] = true case <-ctx.Done(): t.Fatal("missing write") } diff --git a/seaweed-block/core/frontend/durable/precopy_pause_entry_checks_test.go b/seaweed-block/core/frontend/durable/precopy_pause_entry_checks_test.go new file mode 100644 index 0000000000..fb8b5b3bb2 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_pause_entry_checks_test.go @@ -0,0 +1,81 @@ +package durable + +import ( + "context" + "errors" + "testing" + "time" +) + +type refusingRebaser struct{} + +func (refusingRebaser) Observe(context.Context, uint32, uint64, []byte) error { return nil } +func (refusingRebaser) Sync(context.Context, uint64) error { return nil } +func (refusingRebaser) RebaseShipLSN(uint64) error { + return errors.New("injected: ship LSN cannot follow the store") +} + +// TestPrecopyPauseRefusedOnUnusableBackend pins that a pre-copy pause never +// begins on a backend that is closed, not operational, has a failed observer +// install, or already has a pause installed. +func TestPrecopyPauseRefusedOnUnusableBackend(t *testing.T) { + for _, tc := range []struct { + name string + spoil func(t *testing.T, b *StorageBackend) + }{ + {"observer install failed", func(t *testing.T, b *StorageBackend) { + if err := b.SetWriteObserver(refusingRebaser{}); err == nil { + t.Fatal("refused observer install reported success") + } + }}, + {"closed", func(t *testing.T, b *StorageBackend) { _ = b.Close() }}, + {"not operational", func(t *testing.T, b *StorageBackend) { b.SetOperational(false, "host drain") }}, + } { + t.Run(tc.name, func(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + tc.spoil(t, b) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + resume, err := b.BeginPrecopyPause(ctx) + if err == nil { + resume() + t.Fatal("pre-copy pause began on an unusable backend") + } + b.mu.Lock() + left := b.precopy + b.mu.Unlock() + if left != nil { + t.Fatal("refused pause left a pause installed") + } + }) + } + + t.Run("already paused", func(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + defer resume() + b.mu.Lock() + first := b.precopy + b.mu.Unlock() + second, err := b.BeginPrecopyPause(ctx) + if err == nil { + second() + t.Fatal("second pre-copy pause began while one is installed") + } + b.mu.Lock() + current := b.precopy + b.mu.Unlock() + if current != first { + t.Fatal("refused second pause replaced the installed pause") + } + resume() + if _, err := b.Read(context.Background(), 0, nil); err != nil { + t.Fatalf("resume of the first pause did not reopen admission: %v", err) + } + }) +} diff --git a/seaweed-block/core/frontend/durable/precopy_resume_test.go b/seaweed-block/core/frontend/durable/precopy_resume_test.go new file mode 100644 index 0000000000..1f4c528663 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_resume_test.go @@ -0,0 +1,192 @@ +package durable + +import ( + "bytes" + "context" + "sync" + "testing" + "time" +) + +// INV-CUT-PRECOPY-001: a completed pause releases admission, not one +// whole storage operation at a time. Independent LBAs must run concurrently. +func TestPrecopyResumeReleasesAllWaiters(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + queued := make(chan struct{}, 3) + var want, granted []*precopyWaiter + grantUnlocked := false + b.testPrecopyGranted = func(w *precopyWaiter) { + granted = append(granted, w) + if b.mu.TryLock() { + b.mu.Unlock() + grantUnlocked = true + } + } + b.testPrecopyQueued = func() { queued <- struct{}{} } + entered := make(chan byte, 3) + release := make(chan struct{}) + var once sync.Once + unpark := func() { once.Do(func() { close(release) }) } + if err := b.SetWriteObserver(precopyQueueObserver{observe: func(v byte) { + entered <- v + select { + case <-release: + case <-ctx.Done(): + } + }}); err != nil { + t.Fatal(err) + } + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + results := make(chan error, 3) + t.Cleanup(func() { + unpark() + cancel() + resume() + joined := make(chan struct{}) + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(time.Second): + t.Error("resumed writers did not join") + } + }) + for v := byte(1); v <= 3; v++ { + wg.Add(1) + go func(v byte) { + defer wg.Done() + _, err := b.Write(ctx, int64(v-1)*4096, bytes.Repeat([]byte{v}, 4096)) + results <- err + }(v) + select { + case <-queued: + b.mu.Lock() + want = append(want, b.precopy.waiters[len(b.precopy.waiters)-1]) + b.mu.Unlock() + case <-ctx.Done(): + t.Fatal("write did not queue") + } + } + select { + case v := <-entered: + t.Fatalf("paused write %d reached observer", v) + default: + } + resume() + if grantUnlocked || len(granted) != 3 { + t.Fatalf("FIFO grants not made together under mu: count=%d unlocked=%v", len(granted), grantUnlocked) + } + for i, w := range want { + if granted[i] != w { + t.Fatalf("grant %d bypassed arrival order", i) + } + } + seen := map[byte]bool{} + for i := 0; i < 3; i++ { + select { + case v := <-entered: + seen[v] = true + case <-ctx.Done(): + t.Fatalf("resume serialized independent I/O: %d/3 entered before any completion", len(seen)) + } + } + unpark() + for i := 0; i < 3; i++ { + select { + case err := <-results: + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("resumed write did not finish") + } + } + for v := byte(1); v <= 3; v++ { + got := make([]byte, 4096) + if _, err := b.Read(ctx, int64(v-1)*4096, got); err != nil || !bytes.Equal(got, bytes.Repeat([]byte{v}, 4096)) { + t.Fatalf("resumed LBA %d bytes incorrect: %v", v-1, err) + } + } +} + +// Real elapsed time, not a changed production budget: an admitted Sync remains +// held past the old pause's five-second clock while a fresh write must succeed. +func TestPrecopyResumedArrivalDoesNotInheritExpiredPause(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 9*time.Second) + queued := make(chan struct{}, 2) + b.testPrecopyQueued = func() { queued <- struct{}{} } + entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once sync.Once + unpark := func() { once.Do(func() { close(release) }) } + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(ctx context.Context) error { + close(entered) + select { + case <-release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }}); err != nil { + t.Fatal(err) + } + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + // Capture the existing pause's origin only to wait beyond its public bound. + b.mu.Lock() + started := b.precopy.started + b.mu.Unlock() + var syncErr error + t.Cleanup(func() { + unpark() + cancel() + resume() + select { + case <-done: + case <-time.After(time.Second): + t.Error("held Sync did not join") + } + }) + go func() { defer close(done); syncErr = b.Sync(ctx) }() + select { + case <-queued: + case <-ctx.Done(): + t.Fatal("Sync did not queue") + } + resume() + select { + case <-entered: + case <-ctx.Done(): + t.Fatal("Sync did not resume") + } + timer := time.NewTimer(time.Until(started.Add(5*time.Second + 50*time.Millisecond))) + defer timer.Stop() + select { + case <-timer.C: + case <-ctx.Done(): + t.Fatal("caller expired before pause-age witness") + } + want := bytes.Repeat([]byte{7}, 4096) + if n, err := b.Write(ctx, 4096, want); err != nil || n != len(want) { + t.Fatalf("serving volume rejected a fresh arrival after ended pause aged past five seconds: n=%d err=%v", n, err) + } + got := make([]byte, 4096) + if _, err := b.Read(ctx, 4096, got); err != nil || !bytes.Equal(got, want) { + t.Fatalf("fresh write bytes: %v", err) + } + unpark() + select { + case <-done: + if syncErr != nil { + t.Fatal(syncErr) + } + case <-ctx.Done(): + t.Fatal("Sync did not finish") + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_stale_retry_test.go b/seaweed-block/core/frontend/durable/precopy_stale_retry_test.go new file mode 100644 index 0000000000..279f50d7a8 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_stale_retry_test.go @@ -0,0 +1,52 @@ +package durable + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend" + "testing" + "time" +) + +type precopyProjectionFunc func() frontend.Projection + +func (f precopyProjectionFunc) Projection() frontend.Projection { return f() } + +// Projection is the real gate seam: pause B begins before admittedIO increments, +// and that same observation returns stale ownership. B cannot erase this error. +func TestPrecopyNewPauseCannotEraseObservedStalePrimary(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + resumeB := func() {} + defer func() { resumeB() }() + calls := 0 + var startErr error + b.view = precopyProjectionFunc(func() frontend.Projection { + calls++ + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + startErr = err + return frontend.Projection{} + } + resumeB = resume + return frontend.Projection{VolumeID: b.id.VolumeID, ReplicaID: b.id.ReplicaID, Epoch: b.id.Epoch + 1, EndpointVersion: b.id.EndpointVersion, Healthy: true} + }) + observed := false + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(context.Context) error { observed = true; return nil }}); err != nil { + t.Fatal(err) + } + err := b.Sync(ctx) + if startErr != nil { + t.Fatal("start B from projection:", startErr) + } + if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("observed stale ownership replaced by pause retry: %v", err) + } + b.mu.Lock() + admitted := b.admittedIO + b.mu.Unlock() + if calls != 1 || observed || admitted != 0 { + t.Fatalf("stale observation retried or admitted I/O: calls=%d observed=%v admitted=%d", calls, observed, admitted) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index c394aed3d5..39f54d80c2 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -172,6 +172,13 @@ type ProviderConfig struct { // passed since the volume's last successful cut (of any kind). Zero // disables the timer. ChunkCaptureInterval time.Duration + // ChunkCutTimeout bounds a cut as a whole; zero uses five minutes. + ChunkCutTimeout time.Duration + // Maintenance runs serially for an attached healthy volume. Zero interval disables + // it. Callback ownership ends only after cancellation and worker settlement. + ChunkMaintenanceInterval time.Duration + ChunkMaintenanceTimeout time.Duration + ChunkMaintenance func(context.Context, string) error // DetachFreezeTimeout bounds how long a failing DetachVolume keeps guest // I/O stopped before it resumes or settles: the drain and final cut get // three quarters of it, the settlement of a failed cut the rest (the @@ -192,13 +199,16 @@ type ProviderConfig struct { // call back into the provider. OnChunkDetach func(volumeID string) uint64 OnChunkDetachResumed func(volumeID string, attempt uint64) - // ChunkDirtyThreshold is the number of candidate chunks above which - // a cut pre-copies (stages) chunks before its barrier, in rounds of - // this size; copy-before-write copies the rest outside the barrier. - // It never triggers a cut: the remote holds snapshots, and cuts are - // published only by CaptureVolume, MakeVolumeRemoteDurable - // (snapshot, detach) and the timer. Zero: no pre-copy. - ChunkDirtyThreshold int + // ChunkOnPublishSettled, optional, is called once per confirmed + // publication of a chunk volume's HEAD, with the HEAD before and after it + // (storage.ChunkLayerConfig.OnPublishSettled): serialized, in publication + // order, outside the capture lock, by the volume's one registered drainer + // (whichever publishing caller is draining; a publisher may return before + // its own report is delivered). ctx ends when the volume's layer closes; + // after that no report is dequeued, though one already dequeued may still + // be delivered. It must return without blocking and without remote calls: + // enqueue work to your own worker (it is a guest-visible wait on detach). + ChunkOnPublishSettled func(ctx context.Context, volumeID string, prev, next storage.ChunkHead) // ChunkUploadConcurrency bounds remote uploads; zero defaults to 8. ChunkUploadConcurrency int // ChunkPayloadMemoryBudget bounds one volume's cut payloads; zero uses the storage default. @@ -266,9 +276,10 @@ type volHandle struct { // wait, 0 if none: a recovered volume whose layer waits for master // authority. A wait only acts while its generation is still the // latest recovery's. - recoverGen uint64 - waitGen uint64 - chunk storage.ChunkLayer // after RecoverVolume + recoverGen uint64 + waitGen uint64 + chunk storage.ChunkLayer // after RecoverVolume + chunkLineage chunkLineage // immutable authority captured by this attachment // Private until the owner commit succeeds; retained for attach retry. chunkPending storage.ChunkLayer // chunkDetach is set (under attachMu) when DetachVolume starts and @@ -283,23 +294,23 @@ type volHandle struct { // handle. It intentionally exposes lineage and readiness facts without giving // callers a control surface. type VolumeStatus struct { - VolumeID string - Path string - Impl string - ReplicaID string - Epoch uint64 - EndpointVersion uint64 - Latched bool - Operational bool - FrontierKnown bool - DurableLSN uint64 - RetainedLSN uint64 - HeadLSN uint64 - Evidence string - Closed bool - WriteProfile WriteProfileStatus - DataSync *storage.DataSyncStatus `json:",omitempty"` - CheckpointPersistence *storage.CheckpointPersistenceStatus `json:",omitempty"` + VolumeID string // the volume + Path string // its store path under --durable-root + Impl string // the durable implementation (walstore, smartwal, walstore-chunk, ...) + ReplicaID string // the replica this store holds + Epoch uint64 // the epoch the store is latched to; 0 before an assignment + EndpointVersion uint64 // the endpoint version it is latched to + Latched bool // an assignment latched the store (epoch and endpoint version set) + Operational bool // the backend admits I/O now + FrontierKnown bool // DurableLSN, RetainedLSN and HeadLSN are the store's current boundaries + DurableLSN uint64 // R: the newest LSN made durable + RetainedLSN uint64 // S: the oldest LSN the WAL still retains + HeadLSN uint64 // H: the newest LSN written + Evidence string // why the backend is or is not operational + Closed bool // the backend was closed + WriteProfile WriteProfileStatus // write-path counters since start + DataSync *storage.DataSyncStatus `json:",omitempty"` // data-file sync state, where the store has one + CheckpointPersistence *storage.CheckpointPersistenceStatus `json:",omitempty"` // checkpoint persistence state, where the store has one // Chunk is the chunk layer's state and cut counters; walstore-chunk // volumes only. Chunk *ChunkStatus @@ -314,12 +325,12 @@ type VolumeStatus struct { // AwaitingAuthority: recovered, the layer waits for master authority to // attach. Stats is zero until the layer is attached. type ChunkStatus struct { - Attached bool - AwaitingAuthority bool - Fenced bool - RemoteLSN uint64 - Stats storage.ChunkLayerStats - HostBudget any `json:",omitempty"` + Attached bool // the chunk layer is attached to the remote + AwaitingAuthority bool // recovered; the layer waits for master authority to attach + Fenced bool // a newer holder fenced this layer: it publishes nothing + RemoteLSN uint64 // the LSN of the remote HEAD (what the remote holds durably) + Stats storage.ChunkLayerStats // the layer's cut counters; zero until attached + HostBudget any `json:",omitempty"` // the host background-cut budget state, with --host-limit-dir } // NewDurableProvider constructs a provider. view is the ONLY @@ -336,6 +347,12 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura if cfg.Impl == ImplWALStoreChunk && cfg.ChunkRemoteFor == nil { return nil, fmt.Errorf("durable: impl %q requires ProviderConfig.ChunkRemoteFor", ImplWALStoreChunk) } + if cfg.ChunkCaptureInterval < 0 || cfg.ChunkCutTimeout < 0 || cfg.ChunkMaintenanceInterval < 0 || cfg.ChunkMaintenanceTimeout < 0 { + return nil, fmt.Errorf("durable: chunk schedule durations must not be negative") + } + if cfg.ChunkMaintenanceInterval > 0 && cfg.ChunkMaintenance == nil { + return nil, fmt.Errorf("durable: chunk maintenance interval requires its callback") + } if cfg.ChunkBlocks == 0 { cfg.ChunkBlocks = defaultChunkBlocks } diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 2c74773a1c..c418aa15d4 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -320,12 +320,14 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v // startChunkLoop starts the periodic cuts of an attached layer, if configured // and not already running. The caller holds h.attachMu and p.mu. func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer storage.ChunkLayer) { - if p.cfg.ChunkCaptureInterval <= 0 || h.chunkStop != nil { + if (p.cfg.ChunkCaptureInterval <= 0 && (p.cfg.ChunkMaintenanceInterval <= 0 || p.cfg.ChunkMaintenance == nil)) || h.chunkStop != nil { return } loopCtx, cancel := context.WithCancel(context.Background()) h.chunkStop, h.chunkDone = cancel, make(chan struct{}) - go p.chunkLoop(loopCtx, volumeID, layer, h.chunkDone) + lin := h.chunkLineage + current := func() bool { return p.maintenanceCurrent(volumeID, h, layer, lin) } + go p.chunkBackground(loopCtx, cancel, volumeID, layer, h.chunkDone, current) } func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) { @@ -374,6 +376,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h remote = &manifestBoundRemote{closeBoundRemote: bound, builder: builder} } cfg := storage.ChunkLayerConfig{ + OnPublishSettled: p.publishSettledHook(volumeID), ChunkBlocks: p.cfg.ChunkBlocks, RestoreChunkBytes: uint64(ws.BlockSize()) * uint64(p.cfg.ChunkBlocks), HeadCoolingWindow: p.cfg.ChunkHeadCoolingWindow, @@ -383,11 +386,11 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h ReadMissTimeout: p.cfg.ChunkReadMissTimeout, HydrationWorkers: p.cfg.ChunkHydrationWorkers, HydrationQueueDepth: p.cfg.ChunkHydrationQueueDepth, - BarrierBound: p.cfg.ChunkDirtyThreshold, UploadConcurrency: p.cfg.ChunkUploadConcurrency, PayloadMemoryBudget: p.cfg.ChunkPayloadMemoryBudget, Budget: p.cfg.ChunkBudget, COWSpillLimit: p.cfg.ChunkCOWSpillLimit, + COWSpillFree: spillFree(p.cfg.StorageRoot), CaptureAllowed: func() error { cur := p.view.Projection() if !cur.Healthy || cur.VolumeID != volumeID || lin.volumeID != volumeID { @@ -466,7 +469,11 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch} } - return storage.AttachChunkLayer(ws, remote, cfg) + layer, attachErr := storage.AttachChunkLayer(ws, remote, cfg) + if attachErr == nil { + h.chunkLineage = lin + } + return layer, attachErr } // closeBoundRemote ends every remote call when the provider closes, so a @@ -635,7 +642,7 @@ const ( // cutPolicy decides when an automatic cut is due. The remote holds // snapshots, not live data: cuts are published at Snapshot, Detach/stop -// and explicit Cut, and automatically only by the operator's timer: +// and explicit Cut, and automatically by the configured timer: // - the timer fires once interval has passed since the last successful // cut of any kind (explicit Cut, Snapshot and Detach included); zero // disables it, and with it every automatic cut; @@ -760,6 +767,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer if !ok { continue } + cutCtx, cancel := p.chunkCutContext(ctx) trace := p.testChunkLoopTrace if trace != nil { trace("due", ls.LastCutNs, false) @@ -769,19 +777,21 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer // A cut that completed after this decision (an explicit one // running meanwhile) restarted the timer: no cut now. var skipped bool - _, skipped, err = pc.CutUnlessCutSince(ctx, ls.LastCutNs) + _, skipped, err = pc.CutUnlessCutSince(cutCtx, ls.LastCutNs) if trace != nil { trace("cut", ls.LastCutNs, skipped) } if skipped { + cancel() continue } } else { - _, err = layer.Cut(ctx) + _, err = layer.Cut(cutCtx) if trace != nil { trace("cut", ls.LastCutNs, false) } } + cancel() s = pol.after(s, start, time.Now(), err) if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil { log.Printf("durable: %s chunk cut for volume=%s: %v (retry in %s)", reason, volumeID, err, s.backoff) @@ -789,15 +799,122 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer } } +// chunkBackground owns both workers and their cancellation. A fence is observed +// even while either worker is waiting on a cooperative remote call. INV-MAINT-JOIN: +// done closes only after every admitted worker has returned. +func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool) { + defer close(done) + defer cancel() + var workers sync.WaitGroup + if p.cfg.ChunkCaptureInterval > 0 { + workers.Add(1) + go func() { + defer workers.Done() + cutDone := make(chan struct{}) + p.chunkLoop(ctx, volumeID, layer, cutDone) + }() + } + if p.cfg.ChunkMaintenanceInterval > 0 && p.cfg.ChunkMaintenance != nil { + workers.Add(1) + go func() { defer workers.Done(); p.chunkMaintenanceLoop(ctx, volumeID, layer, current) }() + } + timer := time.NewTicker(chunkSchedulePoll) + defer timer.Stop() + for ctx.Err() == nil { + select { + case <-ctx.Done(): + case <-timer.C: + if layer.Fenced() { + cancel() + } + } + } + workers.Wait() +} + +// maintenanceCurrent binds the pass to the attached handle AND its lineage. +// The projection can remain healthy while a different owner replaces it. +func (p *DurableProvider) maintenanceCurrent(volumeID string, h *volHandle, layer storage.ChunkLayer, lin chunkLineage) bool { + p.mu.Lock() + active := !p.closed && p.volumes[volumeID] == h && h.chunk == layer + p.mu.Unlock() + cur := p.view.Projection() + return active && chunkAuthority(cur, volumeID) && cur.VolumeID == lin.volumeID && cur.ReplicaID == lin.replicaID && cur.Epoch == lin.epoch && cur.EndpointVersion == lin.endpoint +} + +func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool) { + interval := p.cfg.ChunkMaintenanceInterval + due := time.Now().Add(interval) + if p.cfg.ChunkStagger { + due = time.Now().Add(hostlimit.Phase(volumeID+":maintenance", interval)) + } + timer := time.NewTimer(time.Until(due)) + defer timer.Stop() + for { + select { + case <-ctx.Done(): + return + case <-timer.C: + } + if ctx.Err() != nil || layer.Fenced() { + return + } + if !current() { + return + } + timeout := p.cfg.ChunkMaintenanceTimeout + if timeout <= 0 { + timeout = time.Minute + } + passCtx, cancel := context.WithTimeout(ctx, timeout) + // The projection has no change channel. One bounded watcher belongs to + // this pass, never to an individual tick; cancellation is joined below. + watchDone := make(chan struct{}) + go func() { + defer close(watchDone) + tick := time.NewTicker(chunkSchedulePoll) + defer tick.Stop() + for { + select { + case <-passCtx.Done(): + return + case <-tick.C: + if layer.Fenced() || !current() { + cancel() + return + } + } + } + }() + err := p.cfg.ChunkMaintenance(passCtx, volumeID) + cancel() + <-watchDone + if err != nil && ctx.Err() == nil { + log.Printf("durable: maintenance volume=%s: %v", volumeID, err) + } + // Completion-relative reset coalesces all elapsed ticks; no catch-up queue. + timer.Reset(interval) + } +} + func (p *DurableProvider) stopChunkLoop(h *volHandle) { p.mu.Lock() stop, done := h.chunkStop, h.chunkDone - h.chunkStop = nil p.mu.Unlock() if stop != nil { stop() + } + // Every concurrent stopper joins the same lifetime; none can clear ownership + // while an earlier stopper is still waiting for an admitted remote call. + if done != nil { <-done } + p.mu.Lock() + if h.chunkDone == done { + h.chunkStop = nil + h.chunkDone = nil + } + p.mu.Unlock() } func (p *DurableProvider) chunkLayer(volumeID string) (storage.ChunkLayer, error) { @@ -831,6 +948,8 @@ func (p *DurableProvider) chunkHandle(volumeID string) (*volHandle, storage.Chun // CaptureVolume takes one quiesced cut of volumeID and publishes it to the // remote. It returns the cut's LSN. func (p *DurableProvider) CaptureVolume(ctx context.Context, volumeID string) (uint64, error) { + ctx, cancel := p.chunkCutContext(ctx) + defer cancel() layer, err := p.chunkLayer(volumeID) if err != nil { return 0, err @@ -841,6 +960,8 @@ func (p *DurableProvider) CaptureVolume(ctx context.Context, volumeID string) (u // MakeVolumeRemoteDurable returns nil only once volumeID's writes up to lsn // are published in the remote HEAD (snapshot, detach, migrate). func (p *DurableProvider) MakeVolumeRemoteDurable(ctx context.Context, volumeID string, lsn uint64) error { + ctx, cancel := p.chunkCutContext(ctx) + defer cancel() layer, err := p.chunkLayer(volumeID) if err != nil { return err @@ -863,7 +984,17 @@ func chunkFenced(volumeID string, h *volHandle) error { // and the cut's statistics (B9 W2 §2.4, §3.1). With minLSN > 0 it is // MakeRemoteDurable(minLSN) returning the cut: an LSN never written is // refused before anything is published, and the cut must reach minLSN. +func (p *DurableProvider) chunkCutContext(ctx context.Context) (context.Context, context.CancelFunc) { + timeout := p.cfg.ChunkCutTimeout + if timeout <= 0 { + timeout = 5 * time.Minute + } + return context.WithTimeout(ctx, timeout) +} + func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN uint64) (storage.ChunkCutResult, error) { + ctx, cancel := p.chunkCutContext(ctx) + defer cancel() h, layer, err := p.chunkHandle(volumeID) if err != nil { return storage.ChunkCutResult{}, err @@ -1174,3 +1305,12 @@ func (r *manifestBoundRemote) PrepareManifest(ctx context.Context, base, next st defer end() return r.builder.PrepareManifest(c, base, next, chunkBytes) } + +// publishSettledHook adapts ChunkOnPublishSettled to one volume's layer. +func (p *DurableProvider) publishSettledHook(volumeID string) func(context.Context, storage.ChunkHead, storage.ChunkHead) { + hook := p.cfg.ChunkOnPublishSettled + if hook == nil { + return nil + } + return func(ctx context.Context, prev, next storage.ChunkHead) { hook(ctx, volumeID, prev, next) } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go index 795a399f9b..74526bc5b6 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go @@ -4,6 +4,7 @@ package durable_test import ( "context" + "fmt" "sync" "sync/atomic" "testing" @@ -14,13 +15,12 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) -func schedProvider(t *testing.T, remote storage.ChunkRemote, interval time.Duration, threshold int) *durable.DurableProvider { +func schedProvider(t *testing.T, remote storage.ChunkRemote, interval time.Duration) *durable.DurableProvider { t.Helper() p, err := durable.NewDurableProvider(durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkCaptureInterval: interval, - ChunkDirtyThreshold: threshold, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, }, v1View()) if err != nil { @@ -40,12 +40,12 @@ func headGen(t *testing.T, remote storage.ChunkRemote) storage.ChunkHead { } // The remote holds snapshots: with the timer off, no number of dirty -// chunks publishes a cut on its own (the threshold only bounds a cut). -func TestWALStoreChunk_DirtyThresholdNeverTriggersCut(t *testing.T) { +// chunks publishes a cut on its own. +func TestWALStoreChunk_DirtyChunksNeverTriggerCut(t *testing.T) { remote := storage.NewMemChunkRemote() - p := schedProvider(t, remote, 0, 2) + p := schedProvider(t, remote, 0) s := openRecovered(t, p) - for c := uint32(0); c < 4; c++ { // four dirty chunks, twice the threshold + for c := uint32(0); c < 4; c++ { // four dirty chunks if _, err := s.Write(c*pcChunkBlocks+1, block(byte(c+1))); err != nil { t.Fatal(err) } @@ -71,7 +71,7 @@ func TestWALStoreChunk_DirtyThresholdNeverTriggersCut(t *testing.T) { func TestWALStoreChunk_ExplicitCutRestartsTheTimer(t *testing.T) { const interval = 3 * time.Second remote := storage.NewMemChunkRemote() - p := schedProvider(t, remote, interval, 0) + p := schedProvider(t, remote, interval) s := openRecovered(t, p) begin := time.Now() @@ -165,6 +165,44 @@ func TestWALStoreChunk_StatusHasNoChunkSectionForWALStore(t *testing.T) { } } +// ChunkOnPublishSettled sees every confirmed publication of a volume, with +// its volume id and the HEAD before and after it; a no-op capture is not one. +func TestWALStoreChunk_PublishSettledHook(t *testing.T) { + remote := storage.NewMemChunkRemote() + var mu sync.Mutex + var got []string + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + ChunkOnPublishSettled: func(_ context.Context, volumeID string, prev, next storage.ChunkHead) { + mu.Lock() + got = append(got, fmt.Sprintf("%s:%d->%d", volumeID, prev.Gen, next.Gen)) + mu.Unlock() + }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s := openRecovered(t, p) + for i, lba := range []uint32{1, 0, pcChunkBlocks + 1} { + if lba != 0 { + if _, err := s.Write(lba, block(byte(i+1))); err != nil { + t.Fatal(err) + } + } + if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + } + mu.Lock() + defer mu.Unlock() + if len(got) != 2 || got[0] != "v1:0->1" || got[1] != "v1:1->2" { + t.Fatalf("reports %v; want [v1:0->1 v1:1->2] (the middle capture changed nothing)", got) + } +} + // gatedCASRemote holds the next HEAD CAS, once armed, until it is released // (or its context ends), and reports when that CAS started. type gatedCASRemote struct { @@ -204,7 +242,7 @@ func TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt(t *testing.T) { var releaseOnce sync.Once release := func() { releaseOnce.Do(func() { close(remote.release) }) } t.Cleanup(release) - p := schedProvider(t, remote, interval, 0) + p := schedProvider(t, remote, interval) events := make(chan loopEvent, 64) durable.SetTestChunkLoopTrace(p, func(event string, lastCutNs int64, skipped bool) { select { diff --git a/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go b/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go index a4c3945460..5fd481e6d3 100644 --- a/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go +++ b/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go @@ -47,9 +47,6 @@ func TestWALStoreChunk_LedgerWriteAnonymousMemory(t *testing.T) { defer cancel() r := &memoryDiskRemote{MemChunkRemote: storage.NewMemChunkRemote(), dir: t.TempDir(), hashes: make(map[string][32]byte)} cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024, ChunkCaptureInterval: 0, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }} - if os.Getenv("SWBLOCK_MEMORY_STAGE") != "" { - cfg.ChunkDirtyThreshold = 64 - } p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) @@ -243,9 +240,6 @@ func TestWALStoreChunk_InitialWriteAnonymousMemory(t *testing.T) { defer cancel() r := &memoryDiskRemote{MemChunkRemote: storage.NewMemChunkRemote(), dir: t.TempDir(), hashes: make(map[string][32]byte)} cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024, ChunkCaptureInterval: 0, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }} - if os.Getenv("SWBLOCK_MEMORY_STAGE") != "" { - cfg.ChunkDirtyThreshold = 64 - } if raw := os.Getenv("SWBLOCK_MEMORY_CHUNKS"); raw != "" { chunks, e := strconv.Atoi(raw) if e != nil || chunks <= 0 { diff --git a/seaweed-block/core/frontend/durable/provider_maintenance_test.go b/seaweed-block/core/frontend/durable/provider_maintenance_test.go new file mode 100644 index 0000000000..1f38b998b2 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_maintenance_test.go @@ -0,0 +1,360 @@ +package durable_test + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock(t *testing.T) { + entered, cancelled, release := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once sync.Once + finish := func() { once.Do(func() { close(release) }) } + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + ChunkMaintenanceInterval: time.Millisecond, + ChunkMaintenance: func(ctx context.Context, vol string) error { + close(entered) + <-ctx.Done() + close(cancelled) + <-release + return ctx.Err() + }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { finish(); _ = p.Close() }) + s := openRecovered(t, p) + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("maintenance did not start with cut timer off") + } + writeDone := make(chan error, 1) + writerSettled := make(chan struct{}) + go func() { defer close(writerSettled); _, err := s.Write(1, block(0x51)); writeDone <- err }() + t.Cleanup(func() { + finish() + _ = p.Close() + select { + case <-writerSettled: + case <-time.After(5 * time.Second): + t.Error("writer cleanup did not settle") + } + }) + select { + case err := <-writeDone: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("maintenance held a guest lock") + } + closed := make(chan error, 1) + closeSettled := make(chan struct{}) + go func() { defer close(closeSettled); closed <- p.Close() }() + t.Cleanup(func() { + finish() + select { + case <-closeSettled: + case <-time.After(5 * time.Second): + t.Error("Close cleanup did not settle") + } + }) + select { + case <-cancelled: + case <-time.After(5 * time.Second): + t.Fatal("Close did not cancel maintenance") + } + select { + case err := <-closed: + t.Fatalf("Close released resources before worker join: %v", err) + default: + } + finish() + select { + case err := <-closed: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("Close did not join") + } +} + +func TestMaintenanceAuthorityLossCancelsHeldPass(t *testing.T) { + view := v1View() + entered, cancelled := make(chan struct{}), make(chan struct{}) + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, + ChunkMaintenanceInterval: time.Millisecond, + ChunkMaintenance: func(ctx context.Context, _ string) error { + close(entered) + <-ctx.Done() + close(cancelled) + return ctx.Err() + }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + openRecovered(t, p) + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("no pass") + } + view.set(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + select { + case <-cancelled: + case <-time.After(5 * time.Second): + t.Fatal("lost authority did not cancel held pass") + } +} + +func TestMaintenancePassHasOneDeadline(t *testing.T) { + entered := make(chan error, 1) + three := make(chan struct{}) + var completed atomic.Int32 + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, + ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenanceTimeout: 10 * time.Millisecond, + ChunkMaintenance: func(ctx context.Context, _ string) error { + <-ctx.Done() + select { + case entered <- ctx.Err(): + default: + } + if completed.Add(1) == 3 { + close(three) + } + return ctx.Err() + }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + done := make(chan struct{}) + go func() { _ = p.Close(); close(done) }() + timer := time.NewTimer(5 * time.Second) + defer timer.Stop() + for { + select { + case <-done: + return + case <-entered: + case <-timer.C: + t.Error("deadline callback cleanup failed to join") + return + } + } + }) + openRecovered(t, p) + // Deliberately leave the one-slot observation full across recurring passes. + select { + case <-three: + case <-time.After(5 * time.Second): + t.Fatal("recurring callback blocked with delayed receiver") + } + select { + case err := <-entered: + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatal(err) + } + default: + t.Fatal("no deadline observation") + } +} + +type pendingMaintenancePut struct{ *storage.MemChunkRemote } + +func (r pendingMaintenancePut) Put(ctx context.Context, _ string, _ []byte) error { + <-ctx.Done() + return ctx.Err() +} +func TestCutDeadlineIncludesUploadWithBackgroundCaller(t *testing.T) { + remote := pendingMaintenancePut{storage.NewMemChunkRemote()} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, ChunkCutTimeout: 10 * time.Millisecond, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s := openRecovered(t, p) + if _, err = s.Write(1, block(0x48)); err != nil { + t.Fatal(err) + } + _, err = p.CaptureVolume(context.Background(), "v1") + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("whole cut did not expire: %v", err) + } + h, err := remote.GetHead(context.Background()) + if err != nil || h.Gen != 0 { + t.Fatalf("expired upload published: %+v %v", h, err) + } +} + +func TestMaintenanceCoalescesWhileOnePassIsHeld(t *testing.T) { + entered, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + finish := func() { once.Do(func() { close(release) }) } + var calls atomic.Int32 + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, + ChunkMaintenanceInterval: time.Millisecond, + ChunkMaintenance: func(ctx context.Context, _ string) error { + if calls.Add(1) == 1 { + close(entered) + } + select { + case <-release: + case <-ctx.Done(): + } + return ctx.Err() + }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { finish(); _ = p.Close() }) + openRecovered(t, p) + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("no pass") + } + time.Sleep(30 * time.Millisecond) + if got := calls.Load(); got != 1 { + t.Fatalf("held pass started %d workers", got) + } + // Close cancels the held pass before release; there is no queued retry to drain. + if err := p.Close(); err != nil { + t.Fatal(err) + } + if got := calls.Load(); got != 1 { + t.Fatalf("Close dispatched %d elapsed ticks", got) + } + finish() +} + +func TestMaintenancePeriodicNoopDoesNotChurnHead(t *testing.T) { + remote := storage.NewMemChunkRemote() + p := schedProvider(t, remote, time.Millisecond) + s := openRecovered(t, p) + lsn, err := s.Write(1, block(0x91)) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var first storage.ChunkHead + for { + first, err = remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if first.RemoteLSN >= lsn { + break + } + select { + case <-ctx.Done(): + t.Fatal(ctx.Err()) + case <-time.After(time.Millisecond): + } + } + var before int64 + for before == 0 { + before = p.DurableStatuses()[0].Chunk.Stats.LastCutNs + select { + case <-ctx.Done(): + t.Fatal("first cut did not settle", ctx.Err()) + case <-time.After(time.Millisecond): + } + } + for { + status := p.DurableStatuses()[0] + if status.Chunk.Stats.LastCutNs > before { + break + } + select { + case <-ctx.Done(): + t.Fatal("no periodic noop", ctx.Err()) + case <-time.After(time.Millisecond): + } + } + after, err := remote.GetHead(ctx) + if err != nil || after.Gen != first.Gen { + t.Fatalf("noop churned HEAD: before=%d after=%d err=%v", first.Gen, after.Gen, err) + } +} + +func TestMaintenanceHealthyLineageChangeCancelsHeldPass(t *testing.T) { + for _, field := range []string{"epoch", "replica", "endpoint"} { + t.Run(field, func(t *testing.T) { + view := v1View() + entered, cancelled := make(chan struct{}), make(chan struct{}) + var enterOnce, cancelOnce sync.Once + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, + ChunkMaintenanceInterval: time.Millisecond, + ChunkMaintenance: func(ctx context.Context, _ string) error { + enterOnce.Do(func() { close(entered) }) + <-ctx.Done() + cancelOnce.Do(func() { close(cancelled) }) + return ctx.Err() + }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + done := make(chan struct{}) + go func() { _ = p.Close(); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("lineage cleanup did not join") + } + }) + openRecovered(t, p) + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("no held pass") + } + cur := view.Projection() + switch field { + case "epoch": + cur.Epoch++ + case "replica": + cur.ReplicaID = "r2" + case "endpoint": + cur.EndpointVersion++ + } + view.set(cur) + select { + case <-cancelled: + case <-time.After(5 * time.Second): + t.Fatal("healthy foreign lineage did not cancel pass") + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_restore.go b/seaweed-block/core/frontend/durable/provider_restore.go new file mode 100644 index 0000000000..6956c2d0f5 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_restore.go @@ -0,0 +1,74 @@ +package durable + +import ( + "context" + "errors" + "fmt" + + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// chunkRestorer is the chunk layer's independent-restore surface. +type chunkRestorer interface { + HydrateAllAt(ctx context.Context, bytesPerSecond int64) (storage.HydrateProgress, error) + OwnBatch(ctx context.Context, n int, foreign func(key string) bool) (storage.OwnProgress, error) +} + +func (p *DurableProvider) restorer(volumeID string) (chunkRestorer, error) { + _, layer, err := p.chunkHandle(volumeID) + if err != nil { + return nil, err + } + r, ok := layer.(chunkRestorer) + if !ok { + return nil, fmt.Errorf("durable: volume %s: chunk layer has no restore surface: %w", volumeID, ErrNotChunkVolume) + } + return r, nil +} + +// HydrateVolume makes every HEAD-named absent chunk of volumeID local +// (M6.Restore.Restoring>Hydrating), paced to bytesPerSecond, under the +// host limiter's BackgroundFill class. +func (p *DurableProvider) HydrateVolume(ctx context.Context, volumeID string, bytesPerSecond int64) (storage.HydrateProgress, error) { + r, err := p.restorer(volumeID) + if err != nil { + return storage.HydrateProgress{}, err + } + return r.HydrateAllAt(hostlimit.WithClass(ctx, hostlimit.BackgroundFill), bytesPerSecond) +} + +// OwnVolumeBatch runs one bounded cut of volumeID that re-uploads up to n +// local chunks with foreign HEAD keys under own keys +// (M6.Restore.Owning>Owning). +func (p *DurableProvider) OwnVolumeBatch(ctx context.Context, volumeID string, n int, foreign func(string) bool) (storage.OwnProgress, error) { + r, err := p.restorer(volumeID) + if err != nil { + return storage.OwnProgress{}, err + } + ctx, cancel := p.chunkCutContext(ctx) + defer cancel() + return r.OwnBatch(ctx, n, foreign) +} + +// ErrProviderClosed refuses work admitted after Close. +var ErrProviderClosed = errors.New("durable: provider closed") + +// GoOwned runs fn on its own goroutine inside the provider's lifetime: its +// ctx ends when Close starts, and Close waits for fn to return before it +// closes any store. A restore driver runs this way, so it never outlives the +// volume it drives. +func (p *DurableProvider) GoOwned(fn func(ctx context.Context)) error { + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return ErrProviderClosed + } + p.inflight.Add(1) + p.mu.Unlock() + go func() { + defer p.inflight.Done() + fn(p.closeCtx) + }() + return nil +} diff --git a/seaweed-block/core/frontend/durable/provider_restore_test.go b/seaweed-block/core/frontend/durable/provider_restore_test.go new file mode 100644 index 0000000000..5f57567ab5 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_restore_test.go @@ -0,0 +1,81 @@ +package durable_test + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" +) + +// A goroutine started with GoOwned sees its ctx end when Close starts, and +// Close returns only after it has returned (ordering witnessed by sequence +// numbers); after Close nothing is admitted. +func TestDurableProvider_GoOwnedIsCancelledAndJoinedByClose(t *testing.T) { + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 64}, v1View()) + if err != nil { + t.Fatal(err) + } + var seq, settledAt, closedAt atomic.Int64 + started, cancelled, release, closed := make(chan struct{}), make(chan struct{}), make(chan struct{}), make(chan struct{}) + releaseOnce := sync.OnceFunc(func() { close(release) }) + startClose := sync.OnceFunc(func() { // one Close, launched by the body or by cleanup + go func() { + _ = p.Close() + closedAt.Store(seq.Add(1)) + close(closed) + }() + }) + t.Cleanup(func() { // registered before launch: always cancels, releases and joins + startClose() + releaseOnce() + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Error("cleanup: Close did not return") + } + }) + if err := p.GoOwned(func(ctx context.Context) { + close(started) + <-ctx.Done() + close(cancelled) + <-release // held settlement: Close must wait for this + settledAt.Store(seq.Add(1)) + }); err != nil { + t.Fatal(err) + } + wait := func(ch <-chan struct{}, d time.Duration, what string) bool { + t.Helper() + select { + case <-ch: + return true + case <-time.After(d): + return false + } + } + if !wait(started, 5*time.Second, "start") { + t.Fatal("the owned goroutine never started") + } + startClose() + if !wait(cancelled, 5*time.Second, "cancel") { + t.Fatal("Close did not cancel the owned goroutine's ctx") + } + // Adverse schedule for a Close that does not join: give it time to + // return while the goroutine is still held. + if wait(closed, 200*time.Millisecond, "early close") { + t.Fatal("Close returned while the owned goroutine was still held") + } + releaseOnce() + if !wait(closed, 5*time.Second, "close") { + t.Fatal("Close did not return after the owned goroutine returned") + } + if s, c := settledAt.Load(), closedAt.Load(); s == 0 || c <= s { + t.Fatalf("Close returned (seq %d) before the owned goroutine settled (seq %d)", c, s) + } + if err := p.GoOwned(func(context.Context) {}); !errors.Is(err, durable.ErrProviderClosed) { + t.Fatalf("GoOwned after Close: %v, want ErrProviderClosed", err) + } +} diff --git a/seaweed-block/core/frontend/durable/spill_free_linux.go b/seaweed-block/core/frontend/durable/spill_free_linux.go new file mode 100644 index 0000000000..92843c70ff --- /dev/null +++ b/seaweed-block/core/frontend/durable/spill_free_linux.go @@ -0,0 +1,17 @@ +//go:build linux + +package durable + +import "syscall" + +// spillFree returns the free bytes available to an unprivileged writer on +// the filesystem holding dir (the COW side files). +func spillFree(dir string) func() (int64, error) { + return func() (int64, error) { + var st syscall.Statfs_t + if err := syscall.Statfs(dir, &st); err != nil { + return 0, err + } + return int64(st.Bavail) * int64(st.Bsize), nil + } +} diff --git a/seaweed-block/core/frontend/durable/spill_free_linux_test.go b/seaweed-block/core/frontend/durable/spill_free_linux_test.go new file mode 100644 index 0000000000..2bd3081dec --- /dev/null +++ b/seaweed-block/core/frontend/durable/spill_free_linux_test.go @@ -0,0 +1,29 @@ +//go:build linux + +package durable + +import ( + "syscall" + "testing" +) + +// The provider's spill free-space reader reports the bytes an unprivileged +// writer has on the storage root's filesystem. +func TestSpillFree_ReadsTheStorageRootFilesystem(t *testing.T) { + dir := t.TempDir() + free, err := spillFree(dir)() + if err != nil { + t.Fatal(err) + } + var st syscall.Statfs_t + if err := syscall.Statfs(dir, &st); err != nil { + t.Fatal(err) + } + want := int64(st.Bavail) * int64(st.Bsize) + if free <= 0 || free > 2*want+1<<30 || want > 2*free+1<<30 { + t.Fatalf("spill free %d bytes; statfs says %d", free, want) + } + if _, err := spillFree(dir + "/missing")(); err == nil { + t.Fatal("a missing storage root read as free space") + } +} diff --git a/seaweed-block/core/frontend/durable/spill_free_other.go b/seaweed-block/core/frontend/durable/spill_free_other.go new file mode 100644 index 0000000000..7ba44e278c --- /dev/null +++ b/seaweed-block/core/frontend/durable/spill_free_other.go @@ -0,0 +1,6 @@ +//go:build !linux + +package durable + +// spillFree is nil off Linux: the COW spill cap is the configured one. +func spillFree(string) func() (int64, error) { return nil } diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index f1c9e3779c..9ac6db58e4 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -149,8 +149,9 @@ type StorageBackend struct { // testBeforeIOLock, test-only, runs in admit after the readiness check, // right before the I/O lock (an arrival handshake for queued I/O). testBeforeIOLock func() - testPrecopyQueued func() // after FIFO registration, outside mu - testPrecopyStopFallback func() // before fallback lock attempts, outside mu + testPrecopyQueued func() // after FIFO registration, outside mu + testPrecopyGranted func(*precopyWaiter) // FIFO grant under mu; nonblocking test hook + testPrecopyStopFallback func() // before fallback lock attempts, outside mu // Runs outside locks after a read registers its readiness notification. testBeforeReadReadyWait func() testAfterAttachRefusal func() @@ -368,7 +369,7 @@ func (b *StorageBackend) Close() error { b.mu.Lock() defer b.mu.Unlock() b.closed = true - b.finishPrecopyLocked(false) + b.finishPrecopyLocked() b.notifyReadReadyLocked() return nil } @@ -488,7 +489,7 @@ func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) { // teardown. Keep a final pre-copy queue parked until Close or its budget; // publishing readiness loss must not complete commands on that path. if ok || b.precopy == nil || !b.precopy.active { - b.finishPrecopyLocked(ok) + b.finishPrecopyLocked() } b.notifyReadReadyLocked() } @@ -829,7 +830,7 @@ func (b *StorageBackend) admit() (func(), error) { if b.precopy != nil && b.precopy.active { b.mu.Unlock() b.ioMu.RUnlock() - return nil, fmt.Errorf("%w: %w: pre-copy admission paused", frontend.ErrNotReady, frontend.ErrBackendBusy) + return nil, errPrecopyPaused } b.admittedIO++ b.mu.Unlock() @@ -879,7 +880,7 @@ func (b *StorageBackend) readyCheck() error { return frontend.ErrStalePrimary } if precopyPending { - return fmt.Errorf("%w: %w: pre-copy admission paused", frontend.ErrNotReady, frontend.ErrBackendBusy) + return errPrecopyPaused } if !b.operational.Load() { ev, _ := b.opEvidence.Load().(string) diff --git a/seaweed-block/core/frontend/durable/write_profile.go b/seaweed-block/core/frontend/durable/write_profile.go index 6a2906f655..9192555c67 100644 --- a/seaweed-block/core/frontend/durable/write_profile.go +++ b/seaweed-block/core/frontend/durable/write_profile.go @@ -12,55 +12,55 @@ import ( // It is not a performance API; callers use it to prove which product-owned // path observed the write and roughly where time accumulated. type WriteProfileStatus struct { - DurabilityLatency DurabilityLatencyStatus - TargetWriteOps uint64 - TargetWriteBytes uint64 - TargetWriteRequestMaxBytes uint64 - TargetWriteDurationNanos uint64 - BackendWriteRequestOps uint64 - BackendWriteRequestBytes uint64 - BackendWriteRequestMaxBytes uint64 - BackendWriteOps uint64 - BackendWriteBytes uint64 - BackendWriteDurationNanos uint64 - BackendStorageWriteCalls uint64 - BackendStorageWriteBlocks uint64 - BackendStorageBatchCalls uint64 - BackendStorageBatchBlocks uint64 - BackendFullBlockBatchCalls uint64 - BackendFullBlockBatchBlocks uint64 - BackendFullBlockBatchMax uint64 - WALCopyOps uint64 - WALCopyBytes uint64 - WALCopyDurationNanos uint64 - WALEncodeOps uint64 - WALEncodeBytes uint64 - WALEncodeDurationNanos uint64 - WALChecksumOps uint64 - WALChecksumBytes uint64 - WALChecksumDurationNanos uint64 - WALAppendOps uint64 - WALAppendBytes uint64 - WALAppendDurationNanos uint64 - WALAppendLockWaitOps uint64 - WALAppendLockWaitNanos uint64 - WriteCommitLockWaitOps uint64 - WriteCommitLockWaitNanos uint64 - WALAppendWriteAtCalls uint64 - WALAppendWriteAtBytes uint64 - WALAppendWriteAtMaxBytes uint64 - WALAppendWrapCount uint64 - WALAppendPaddingBytes uint64 - DirtyMapUpdateOps uint64 - DirtyMapUpdateDurationNanos uint64 - BackendSyncOps uint64 - BackendSyncDurationNanos uint64 + DurabilityLatency DurabilityLatencyStatus // latency distributions of writes, flushes and syncs + TargetWriteOps uint64 // writes the protocol target handed to the volume + TargetWriteBytes uint64 // their bytes + TargetWriteRequestMaxBytes uint64 // the largest of them + TargetWriteDurationNanos uint64 // their total time at the target + BackendWriteRequestOps uint64 // write requests that entered the durable backend + BackendWriteRequestBytes uint64 // their bytes + BackendWriteRequestMaxBytes uint64 // the largest of them + BackendWriteOps uint64 // backend writes completed + BackendWriteBytes uint64 // their bytes + BackendWriteDurationNanos uint64 // their total time + BackendStorageWriteCalls uint64 // single-write calls into the store + BackendStorageWriteBlocks uint64 // blocks they wrote + BackendStorageBatchCalls uint64 // batch-write calls into the store + BackendStorageBatchBlocks uint64 // blocks they wrote + BackendFullBlockBatchCalls uint64 // batch calls made only of whole blocks + BackendFullBlockBatchBlocks uint64 // blocks they wrote + BackendFullBlockBatchMax uint64 // the largest such batch, in blocks + WALCopyOps uint64 // WAL record payload copies + WALCopyBytes uint64 // their bytes + WALCopyDurationNanos uint64 // their total time + WALEncodeOps uint64 // WAL record encodes + WALEncodeBytes uint64 // their bytes + WALEncodeDurationNanos uint64 // their total time + WALChecksumOps uint64 // WAL record checksums + WALChecksumBytes uint64 // their bytes + WALChecksumDurationNanos uint64 // their total time + WALAppendOps uint64 // WAL appends + WALAppendBytes uint64 // their bytes + WALAppendDurationNanos uint64 // their total time + WALAppendLockWaitOps uint64 // appends that waited for the WAL append lock + WALAppendLockWaitNanos uint64 // their total wait + WriteCommitLockWaitOps uint64 // writes that waited for the commit lock + WriteCommitLockWaitNanos uint64 // their total wait + WALAppendWriteAtCalls uint64 // file WriteAt calls made by WAL appends + WALAppendWriteAtBytes uint64 // their bytes + WALAppendWriteAtMaxBytes uint64 // the largest of them + WALAppendWrapCount uint64 // times the WAL append wrapped to the start of the log + WALAppendPaddingBytes uint64 // padding bytes written at those wraps + DirtyMapUpdateOps uint64 // dirty-map updates after writes + DirtyMapUpdateDurationNanos uint64 // their total time + BackendSyncOps uint64 // backend syncs (flush, FUA, explicit sync) + BackendSyncDurationNanos uint64 // their total time } type DurabilityLatencyStatus struct { - Frontend iolatency.RequestStatus - BackendSync iolatency.Distribution - WAL *storage.DurabilityLatencyStatus `json:",omitempty"` + Frontend iolatency.RequestStatus // per-request latency at the frontend, by stage + BackendSync iolatency.Distribution // latency of backend syncs + WAL *storage.DurabilityLatencyStatus `json:",omitempty"` // the WAL's own sync latency, where the store reports it } type writeProfile struct { diff --git a/seaweed-block/core/frontend/nvme/stats.go b/seaweed-block/core/frontend/nvme/stats.go index e167cccb4c..055c45278b 100644 --- a/seaweed-block/core/frontend/nvme/stats.go +++ b/seaweed-block/core/frontend/nvme/stats.go @@ -15,36 +15,38 @@ import ( // includes socket wait and decode. R2T collection includes target send, // initiator response, and H2CData receive. type Stats struct { - SessionsAccepted uint64 `json:"sessions_accepted"` - AdminConnects uint64 `json:"admin_connects"` - IOConnects uint64 `json:"io_connects"` + SessionsAccepted uint64 `json:"sessions_accepted"` // TCP sessions accepted + AdminConnects uint64 `json:"admin_connects"` // admin-queue Connect commands + IOConnects uint64 `json:"io_connects"` // I/O-queue Connect commands - ReadCommands uint64 `json:"read_commands"` - WriteCommands uint64 `json:"write_commands"` - FlushCommands uint64 `json:"flush_commands"` + ReadCommands uint64 `json:"read_commands"` // Read commands received + WriteCommands uint64 `json:"write_commands"` // Write commands received + FlushCommands uint64 `json:"flush_commands"` // Flush commands received - InlineWriteCommands uint64 `json:"inline_write_commands"` - InlineWriteBytes uint64 `json:"inline_write_bytes"` - R2TWriteCommands uint64 `json:"r2t_write_commands"` - R2TWriteBytes uint64 `json:"r2t_write_bytes"` + InlineWriteCommands uint64 `json:"inline_write_commands"` // writes whose data came inline in the command capsule + InlineWriteBytes uint64 `json:"inline_write_bytes"` // their data bytes + R2TWriteCommands uint64 `json:"r2t_write_commands"` // writes whose data the target requested with R2T + R2TWriteBytes uint64 `json:"r2t_write_bytes"` // their data bytes - H2CDataPDUs uint64 `json:"h2c_data_pdus"` - H2CDataBytes uint64 `json:"h2c_data_bytes"` - C2HDataPDUs uint64 `json:"c2h_data_pdus"` - C2HDataBytes uint64 `json:"c2h_data_bytes"` + H2CDataPDUs uint64 `json:"h2c_data_pdus"` // host-to-controller data PDUs received + H2CDataBytes uint64 `json:"h2c_data_bytes"` // their bytes + C2HDataPDUs uint64 `json:"c2h_data_pdus"` // controller-to-host data PDUs sent (read data) + C2HDataBytes uint64 `json:"c2h_data_bytes"` // their bytes - WriteCapsuleReceiveParseOps uint64 `json:"write_capsule_receive_parse_ops"` - WriteCapsuleReceiveParseNanos uint64 `json:"write_capsule_receive_parse_ns"` - R2TDataCollectionOps uint64 `json:"r2t_data_collection_ops"` - R2TDataCollectionNanos uint64 `json:"r2t_data_collection_ns"` - WriteDispatchWaitOps uint64 `json:"write_dispatch_wait_ops"` - WriteDispatchWaitNanos uint64 `json:"write_dispatch_wait_ns"` - WriteHandlerOps uint64 `json:"write_handler_ops"` - WriteHandlerNanos uint64 `json:"write_handler_ns"` - WriteCompletionQueueWaitOps uint64 `json:"write_completion_queue_wait_ops"` - WriteCompletionQueueWaitNanos uint64 `json:"write_completion_queue_wait_ns"` - WriteCompletionSendOps uint64 `json:"write_completion_send_ops"` - WriteCompletionSendNanos uint64 `json:"write_completion_send_ns"` + // Write phase attribution: for each phase, the operations timed and + // their total nanoseconds (overlapping phases can overlap in time). + WriteCapsuleReceiveParseOps uint64 `json:"write_capsule_receive_parse_ops"` // write capsules received and decoded (includes socket wait) + WriteCapsuleReceiveParseNanos uint64 `json:"write_capsule_receive_parse_ns"` // total nanoseconds of those operations + R2TDataCollectionOps uint64 `json:"r2t_data_collection_ops"` // R2T data collections (R2T send to the last H2CData) + R2TDataCollectionNanos uint64 `json:"r2t_data_collection_ns"` // total nanoseconds of those operations + WriteDispatchWaitOps uint64 `json:"write_dispatch_wait_ops"` // waits for a write handler to take the command + WriteDispatchWaitNanos uint64 `json:"write_dispatch_wait_ns"` // total nanoseconds of those operations + WriteHandlerOps uint64 `json:"write_handler_ops"` // write handler runs (the backend write) + WriteHandlerNanos uint64 `json:"write_handler_ns"` // total nanoseconds of those operations + WriteCompletionQueueWaitOps uint64 `json:"write_completion_queue_wait_ops"` // waits of a completion for the send queue + WriteCompletionQueueWaitNanos uint64 `json:"write_completion_queue_wait_ns"` // total nanoseconds of those operations + WriteCompletionSendOps uint64 `json:"write_completion_send_ops"` // completion sends to the host + WriteCompletionSendNanos uint64 `json:"write_completion_send_ns"` // total nanoseconds of those operations } type targetStats struct { diff --git a/seaweed-block/core/frontend/types.go b/seaweed-block/core/frontend/types.go index b61c2b42a1..920666050a 100644 --- a/seaweed-block/core/frontend/types.go +++ b/seaweed-block/core/frontend/types.go @@ -31,11 +31,11 @@ type Identity struct { // Mode into a single value that ProjectionView.Projection() // returns. type Projection struct { - VolumeID string - ReplicaID string - Epoch uint64 - EndpointVersion uint64 - Healthy bool + VolumeID string // the volume this host serves + ReplicaID string // this host's replica of it + Epoch uint64 // the authority epoch of the current assignment + EndpointVersion uint64 // the assignment's endpoint version within the epoch + Healthy bool // the replica may serve I/O at this epoch } // ProjectionView is the read-only seam between adapter/engine @@ -50,15 +50,16 @@ type ProjectionView interface { // Backend is a per-lineage handle for one open frontend session. // // Lifecycle ownership (BUG-005 2026-04-22): -// Backend.Close() is OWNED BY THE PROVIDER. Session-layer -// consumers (iSCSI session, NVMe controller, etc.) MUST NOT -// call Close on a Backend obtained from Provider.Open — -// treat the returned Backend as a BORROWED reference for the -// duration of the session. DurableProvider caches one Backend -// per volumeID; a session-level Close would mark the cached -// Backend closed and break every subsequent session. Session -// teardown should release conn + session-local state only. -// Provider.Close tears down all Backends in correct order. +// +// Backend.Close() is OWNED BY THE PROVIDER. Session-layer +// consumers (iSCSI session, NVMe controller, etc.) MUST NOT +// call Close on a Backend obtained from Provider.Open — +// treat the returned Backend as a BORROWED reference for the +// duration of the session. DurableProvider caches one Backend +// per volumeID; a session-level Close would mark the cached +// Backend closed and break every subsequent session. Session +// teardown should release conn + session-local state only. +// Provider.Close tears down all Backends in correct order. // // T3a extends the interface with two methods (all existing // implementations gain trivial impls in the same commit): diff --git a/seaweed-block/core/frontend/ublk/dispatch.go b/seaweed-block/core/frontend/ublk/dispatch.go index e2c9c7a8ed..429127b5bb 100644 --- a/seaweed-block/core/frontend/ublk/dispatch.go +++ b/seaweed-block/core/frontend/ublk/dispatch.go @@ -50,12 +50,12 @@ type handler struct { // counted when it is received, before the backend call; Errors counts the // requests that completed with a negative result. type Stats struct { - ReadRequests uint64 `json:"read_requests"` - WriteRequests uint64 `json:"write_requests"` - FlushRequests uint64 `json:"flush_requests"` - FUAWrites uint64 `json:"fua_writes"` - OtherRequests uint64 `json:"other_requests"` - Errors uint64 `json:"errors"` + ReadRequests uint64 `json:"read_requests"` // read requests received + WriteRequests uint64 `json:"write_requests"` // write requests received + FlushRequests uint64 `json:"flush_requests"` // flush requests received + FUAWrites uint64 `json:"fua_writes"` // writes with forced unit access + OtherRequests uint64 `json:"other_requests"` // requests of any other operation + Errors uint64 `json:"errors"` // requests completed with a negative result } type counters struct { diff --git a/seaweed-block/core/host/master/workspace_head.go b/seaweed-block/core/host/master/workspace_head.go index 0c5dd7f544..5c471123e2 100644 --- a/seaweed-block/core/host/master/workspace_head.go +++ b/seaweed-block/core/host/master/workspace_head.go @@ -14,9 +14,25 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" ) +// headFilerMtimeNS is the HEAD entry's mtime from the filer's Last-Modified +// header of the same response as the content (1 s resolution), or 0 +// (unknown) when the header is absent, unparseable or not after the epoch. +func headFilerMtimeNS(h http.Header) int64 { + v := h.Get("Last-Modified") + if v == "" { + return 0 + } + t, err := http.ParseTime(v) + if err != nil || t.UnixNano() <= 0 { + return 0 + } + return t.UnixNano() +} + // NewWorkspaceHEADReader reads inline HEAD content from the configured filer // HTTP directory. It never follows redirects or accepts operator-supplied HEAD -// evidence. W2's detached state is part of the committed HEAD document. +// evidence. W2's detached state is part of the committed HEAD document. The +// HEAD's filer mtime comes from the same response (headFilerMtimeNS). func NewWorkspaceHEADReader(base string) (func(context.Context, string) (authority.WorkspaceHead, error), error) { u, err := url.Parse(base) if err != nil || u == nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" { @@ -79,6 +95,6 @@ func NewWorkspaceHEADReader(base string) (func(context.Context, string) (authori } else if doc.DetachedBy != nil { return authority.WorkspaceHead{}, fmt.Errorf("active HEAD retains detachedBy proof") } - return authority.WorkspaceHead{Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, RemoteLSN: doc.RemoteLSN, Detached: doc.State == "detached"}, nil + return authority.WorkspaceHead{Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, RemoteLSN: doc.RemoteLSN, Detached: doc.State == "detached", FilerMtimeNS: headFilerMtimeNS(res.Header)}, nil }, nil } diff --git a/seaweed-block/core/host/master/workspace_lost_range_readout_test.go b/seaweed-block/core/host/master/workspace_lost_range_readout_test.go new file mode 100644 index 0000000000..c13969c27d --- /dev/null +++ b/seaweed-block/core/host/master/workspace_lost_range_readout_test.go @@ -0,0 +1,255 @@ +package master + +import ( + "context" + "io/fs" + "log" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// lostRangeFiles lists the lost range side files under dir. +func lostRangeFiles(t *testing.T, dir string) []string { + t.Helper() + var out []string + err := filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { + if err == nil && !d.IsDir() && strings.HasSuffix(p, ".lostrange.json") { + out = append(out, p) + } + return err + }) + if err != nil { + t.Fatal(err) + } + return out +} + +// startStoppableMaster starts a master and registers its close as cleanup +// immediately; the returned stop closes it at most once (an explicit stop +// before a restart, then the cleanup, never closes twice). +func startStoppableMaster(t *testing.T, cfg Config) (*Host, func()) { + t.Helper() + h, err := New(cfg) + if err != nil { + t.Fatal(err) + } + h.Start() + var once sync.Once + stop := func() { once.Do(func() { closeTestMaster(t, h) }) } + t.Cleanup(stop) + return h, stop +} + +// forcedMoveHost starts a master whose volume vol-f is held by r1 on node-a +// (epoch 1, lease renewed once) with a prepared target binding on node-b. +// The returned stop closes it once; it is also registered as cleanup as soon +// as the master starts, so a failing setup step never leaks it. +func forcedMoveHost(t *testing.T, cfg Config) (*Host, func(), control.WorkspaceServiceClient, *control.WorkspaceMove) { + t.Helper() + h, stop := startStoppableMaster(t, cfg) + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { conn.Close() }) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + client := control.NewWorkspaceServiceClient(conn) + for _, server := range []string{"node-a", "node-b"} { + if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + } + if _, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "vol-f", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + src := &control.WorkspaceBinding{VolumeId: "vol-f", ServerId: "node-a", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"} + target := &control.WorkspaceBinding{VolumeId: "vol-f", ServerId: "node-b", DataAddr: "127.0.0.1:29200", CtrlAddr: "127.0.0.1:29100"} + for _, b := range []*control.WorkspaceBinding{src, target} { + if _, err := client.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + } + if _, err := client.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "vol-f", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + if _, err := control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "vol-f", ReplicaId: "r1", DataAddr: src.DataAddr, CtrlAddr: src.CtrlAddr}}}); err != nil { + t.Fatal(err) + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + line := waitAuthorityLine(t, h.Publisher(), "vol-f") + if _, err := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-f", ReplicaId: "r1", Epoch: line.Epoch}); err != nil { + t.Fatal(err) + } + return h, stop, client, &control.WorkspaceMove{RequestId: "force-1", VolumeId: "vol-f", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch, TargetReplicaId: "r1", + TargetServerId: "node-b", TargetDataAddr: target.DataAddr, TargetCtrlAddr: target.CtrlAddr, Kind: "forced", Force: true} +} + +// INV-WS-LOST-RANGE-READOUT-001 over the real master: the preview writes +// nothing and says when the move becomes admissible; the issued forced +// grant carries the stored range (with the HEAD's filer time read with HEAD) +// and is logged; a replay returns the same grant; the lost range RPC returns +// the same stored range; after a restart with the range file damaged, a +// replay still returns the issued grant but without a range and with the +// reason, and the lost range RPC fails with DataLoss, never "no loss". +func TestWorkspaceForcedMoveLostRangeOverRPC(t *testing.T) { + logs := &syncBuffer{} + headTime := time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC) + authDir := t.TempDir() + cfg := Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: authDir, LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + Logger: log.New(logs, "", 0), + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, FilerMtimeNS: headTime.UnixNano()}, nil + }} + h, stop, client, move := forcedMoveHost(t, cfg) + ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) + defer cancel() + + pv, err := client.PreviewWorkspaceMove(ctx, move) + if err != nil { + t.Fatal(err) + } + if pv.Admitted || pv.LostUntilNs <= pv.MasterTimeNs || pv.HeadRead || !strings.Contains(pv.Reason, "has not elapsed") { + t.Fatalf("preview before the horizon: %+v", pv) + } + if _, err := client.MoveWorkspace(ctx, move); status.Code(err) != codes.FailedPrecondition { + t.Fatalf("move before the horizon: %v; want FailedPrecondition", err) + } + select { + case <-time.After(time.Until(time.Unix(0, pv.LostUntilNs)) + 50*time.Millisecond): + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + pv2, err := client.PreviewWorkspaceMove(ctx, move) + if err != nil { + t.Fatal(err) + } + if !pv2.Admitted || !pv2.HeadRead || pv2.HeadGen != 9 || pv2.HeadRemoteLsn != 42 || !pv2.HeadTimeKnown || pv2.HeadTimeNs != headTime.UnixNano() || pv2.LostUntilNs != pv.LostUntilNs { + t.Fatalf("preview after the horizon: %+v", pv2) + } + if st := h.Publisher().WorkspaceState("vol-f"); len(st.Moves) != 0 { + t.Fatalf("preview wrote a journal record: %+v", st.Moves) + } + if files := lostRangeFiles(t, authDir); len(files) != 0 { + t.Fatalf("preview wrote a lost range: %v", files) + } + + g, err := client.MoveWorkspace(ctx, move) + if err != nil { + t.Fatal(err) + } + want := &control.WorkspaceLostRange{RequestId: "force-1", VolumeId: "vol-f", NewEpoch: g.NewEpoch, OldReplicaId: "r1", OldEpoch: move.ExpectedEpoch, + LostAfterLsn: 42, LostUntilNs: pv.LostUntilNs, HeadGen: 9, HeadTimeNs: headTime.UnixNano(), HeadTimeKnown: true} + if !g.Issued || g.LostRangeError != "" || !proto.Equal(g.LostRange, want) { + t.Fatalf("forced grant %+v; want lost range %+v", g, want) + } + for _, s := range []string{`forced move issued volume="vol-f" request="force-1"`, "old=node-a/r1@1", "new=node-b/r1@2", "replay=false", "lost_after_lsn=42", "head_gen=9", "head_filer_time=2026-11-21T01:02:03Z"} { + if !strings.Contains(logs.String(), s) { + t.Fatalf("master log lacks %q:\n%s", s, logs.String()) + } + } + g2, err := client.MoveWorkspace(ctx, move) + if err != nil || !proto.Equal(g, g2) { + t.Fatalf("replay %+v %v; want the stored grant %+v", g2, err, g) + } + if !strings.Contains(logs.String(), "replay=true") { + t.Fatalf("replayed forced grant not logged:\n%s", logs.String()) + } + for _, id := range []string{"", "force-1"} { + lr, err := client.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: "vol-f", RequestId: id}) + if err != nil || len(lr.Ranges) != 1 || !proto.Equal(lr.Ranges[0], want) { + t.Fatalf("lost range query %q: %+v %v", id, lr, err) + } + } + if _, err := client.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: "vol-f", RequestId: "nope"}); status.Code(err) != codes.NotFound { + t.Fatalf("unknown request id: %v; want NotFound", err) + } + if st, err := client.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-f"}); err != nil || len(st.Moves) != 1 || !proto.Equal(st.Moves[0].LostRange, want) { + t.Fatalf("QueryWorkspace moves %+v %v", st.GetMoves(), err) + } + if pv3, err := client.PreviewWorkspaceMove(ctx, move); err != nil || !pv3.Admitted || pv3.HeadRead || pv3.LostUntilNs != pv.LostUntilNs { + t.Fatalf("preview of the issued request: %+v %v", pv3, err) + } + + stop() + files := lostRangeFiles(t, authDir) + if len(files) != 1 { + t.Fatalf("lost range files %v", files) + } + raw, err := os.ReadFile(files[0]) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(files[0], []byte(strings.Replace(string(raw), `"LostAfterLSN":42`, `"LostAfterLSN":41`, 1)), 0o644); err != nil { + t.Fatal(err) + } + h2, _ := startStoppableMaster(t, cfg) + conn, err := grpc.NewClient(h2.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + c2 := control.NewWorkspaceServiceClient(conn) + g3, err := c2.MoveWorkspace(ctx, move) + if err != nil || !g3.Issued || g3.NewEpoch != g.NewEpoch || g3.LostRange != nil || !strings.Contains(g3.LostRangeError, "missing or unreadable") { + t.Fatalf("replay with a damaged range: %+v %v; want the issued grant without a range, with the reason", g3, err) + } + if !strings.Contains(logs.String(), "lost_range=UNPROVEN") { + t.Fatalf("unproven range not logged:\n%s", logs.String()) + } + if _, err := c2.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: "vol-f"}); status.Code(err) != codes.DataLoss { + t.Fatalf("lost range query with a damaged record: %v; want DataLoss", err) + } +} + +// The HEAD reader takes the HEAD entry's mtime from the filer's +// Last-Modified header of the same response; without a usable header the +// time is unknown (0), never invented. +func TestWorkspaceHEADReadsFilerMtime(t *testing.T) { + mtime := time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC) + for _, tc := range []struct { + name, header string + want int64 + }{ + {"last-modified", mtime.Format(http.TimeFormat), mtime.UnixNano()}, + {"absent", "", 0}, + {"unparseable", "yesterday", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if tc.header != "" { + w.Header().Set("Last-Modified", tc.header) + } + _, _ = w.Write([]byte(`{"format":1,"gen":9,"epoch":3,"holder":"old","remote_lsn":42}`)) + })) + defer s.Close() + read, err := NewWorkspaceHEADReader(s.URL) + if err != nil { + t.Fatal(err) + } + h, err := read(context.Background(), "v") + if err != nil || h.FilerMtimeNS != tc.want || h.Gen != 9 || h.RemoteLSN != 42 { + t.Fatalf("HEAD %+v %v; want filer mtime %d", h, err, tc.want) + } + }) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 3e53da6ab8..60507669ef 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -2,6 +2,7 @@ package master import ( "context" + "errors" "fmt" "strings" "time" @@ -132,6 +133,53 @@ func grantFact(r authority.WorkspaceMoveRecord) *control.WorkspaceGrant { OldEpoch: r.OldEpoch, NewEpoch: r.NewEpoch, HeadGen: r.HeadGen, RemoteLsn: r.RemoteLSN, Issued: r.Issued, OldHost: r.OldHost, NewHost: r.NewHost} } +// lostRangeFact is the wire form of a stored lost range. +func lostRangeFact(r authority.WorkspaceLostRangeReadout) *control.WorkspaceLostRange { + return &control.WorkspaceLostRange{RequestId: r.RequestID, VolumeId: r.VolumeID, NewEpoch: r.NewEpoch, OldReplicaId: r.OldReplicaID, OldEpoch: r.OldEpoch, + LostAfterLsn: r.LostAfterLSN, LostUntilNs: r.LostUntilNS, HeadGen: r.HeadGen, HeadTimeNs: r.HeadTimeNS, HeadTimeKnown: r.HeadTimeNS != 0} +} + +// grantWithLostRange is grantFact plus, for an issued forced grant, its +// stored lost range; a range that cannot be read leaves lost_range unset and +// says why in lost_range_error (the readout is then unproven, not empty). +func (s *services) grantWithLostRange(r authority.WorkspaceMoveRecord) *control.WorkspaceGrant { + g := grantFact(r) + if !r.Issued || r.Kind != "forced" { + return g + } + ranges, err := s.host.Publisher().WorkspaceLostRangeReadouts(r.VolumeID, r.RequestID) + switch { + case err != nil: + g.LostRangeError = err.Error() + case len(ranges) != 1: + g.LostRangeError = fmt.Sprintf("%v: %d ranges for request %q", authority.ErrWorkspaceLostRangeMissing, len(ranges), r.RequestID) + default: + g.LostRange = lostRangeFact(ranges[0]) + } + return g +} + +// logForcedGrant records an issued forced move (also a replay of one). +func (s *services) logForcedGrant(g *control.WorkspaceGrant, replay bool, postIssue error) { + if g == nil || !g.GetIssued() || g.GetKind() != "forced" { + return + } + lost := "lost_range=UNPROVEN (" + g.GetLostRangeError() + ")" + if l := g.GetLostRange(); l != nil { + head := "unknown" + if l.GetHeadTimeKnown() { + head = time.Unix(0, l.GetHeadTimeNs()).UTC().Format(time.RFC3339Nano) + } + lost = fmt.Sprintf("lost_after_lsn=%d lost_until_ns=%d lost_until=%s head_gen=%d head_filer_time=%s", + l.GetLostAfterLsn(), l.GetLostUntilNs(), time.Unix(0, l.GetLostUntilNs()).UTC().Format(time.RFC3339Nano), l.GetHeadGen(), head) + } + if postIssue != nil { + lost += fmt.Sprintf(" answer_failed_after_issue=%q", postIssue.Error()) + } + s.host.log.Printf("blockmaster: MoveWorkspace forced move issued volume=%q request=%q old=%s/%s@%d new=%s/%s@%d replay=%t %s", + g.GetVolumeId(), g.GetRequestId(), g.GetOldHost(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewHost(), g.GetNewReplicaId(), g.GetNewEpoch(), replay, lost) +} + func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { if err := s.workspaceVolume(q.GetVolumeId()); err != nil { return nil, err @@ -157,11 +205,19 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) // local precondition below; Publisher checks the expected epoch atomically. // A refusal is logged after the lock is released (deferred first, so it // runs last): a slow log writer never holds workspaceMu. + // An issued forced grant is logged the same way, also after the unlock. var refusal string + var issued *control.WorkspaceGrant + var replay bool + var postIssue, unknown error defer func() { if refusal != "" { s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal) } + s.logForcedGrant(issued, replay, postIssue) + if unknown != nil { + s.host.log.Printf("blockmaster: MoveWorkspace outcome unknown volume=%q request=%q kind=%q: %v", q.GetVolumeId(), q.GetRequestId(), q.GetKind(), unknown) + } }() s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() @@ -171,11 +227,72 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) if err := s.workspaceVolume(q.GetVolumeId()); err != nil { return nil, err } + req, target, replay, why, err := s.workspaceMoveCheckLocked(q) + if err != nil { + return nil, workspaceError(err) + } + if refusal = why; refusal != "" { + return nil, status.Error(codes.FailedPrecondition, refusal) + } + if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { + return nil, workspaceError(err) + } + r, err := s.host.Publisher().MoveWorkspace(ctx, req, head) + if err != nil { + // A move that is issued in spite of the error (it failed after the + // issue) is never a refusal: the caller recovers its grant with the + // same request id. + if s.host.Publisher().IssuedWorkspaceMove(req) { + issued, postIssue = s.issuedRecord(req), err + return nil, postIssueError(q, err) + } + if errors.Is(err, authority.ErrWorkspaceOutcomeUncertain) { + unknown = err + return nil, status.Errorf(codes.Internal, "workspace move %q of volume %q has an UNKNOWN outcome: %v; the volume's workspace authority stays uncertain until the master restarts; after the restart, rerun with the same request id", + q.GetRequestId(), q.GetVolumeId(), err) + } + return nil, workspaceError(err) + } + // The move is issued from here on: record it for the audit log before + // anything else can fail. + issued = s.grantWithLostRange(r) + if err = s.host.reconcileWorkspaceBindings(); err != nil { + postIssue = err + return nil, postIssueError(q, err) + } + return issued, nil +} + +// postIssueError reports a failure after q's move was issued: never +// FailedPrecondition (a definite refusal); Internal, which clients treat as +// an unknown outcome, with the same-request-id recovery. +func postIssueError(q *control.WorkspaceMove, err error) error { + return status.Errorf(codes.Internal, "workspace move %q of volume %q is ISSUED, but a step after the issue failed: %v; rerun with the same request id to get its grant", + q.GetRequestId(), q.GetVolumeId(), err) +} + +// issuedRecord is the answer for req's issued journal record, if any. +func (s *services) issuedRecord(req authority.WorkspaceMoveRequest) *control.WorkspaceGrant { + if st := s.host.Publisher().WorkspaceState(req.VolumeID); st != nil { + for _, m := range st.Moves { + if m.RequestID == req.RequestID && m.Issued { + return s.grantWithLostRange(m) + } + } + } + return nil +} + +// workspaceMoveCheckLocked builds the authority request of q and the +// blockmaster's own refusal of it ("" when none): endpoints, source host, +// target node and binding. It reads and writes nothing else; MoveWorkspace +// and PreviewWorkspaceMove share it. Caller holds workspaceMu. +func (s *services) workspaceMoveCheckLocked(q *control.WorkspaceMove) (req authority.WorkspaceMoveRequest, target lifecycle.NodeRegistration, replay bool, refusal string, err error) { oldHost := s.host.workspaceSourceHost(q.GetVolumeId(), q.GetExpectedReplicaId(), q.GetExpectedEpoch()) target, ok := s.host.lifecycle.Nodes.GetNode(q.GetTargetServerId()) bindings, explicit, err := s.host.lifecycle.WorkspaceBindings.Get(q.GetVolumeId()) if err != nil { - return nil, workspaceError(err) + return authority.WorkspaceMoveRequest{}, lifecycle.NodeRegistration{}, false, "", err } // A volume without per-volume bindings may move to any port on the // target node's registered hosts (a host runs several slots): the host @@ -189,12 +306,12 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) matched = true } } - req := authority.WorkspaceMoveRequest{RequestID: q.GetRequestId(), VolumeID: q.GetVolumeId(), ExpectedReplicaID: q.GetExpectedReplicaId(), ExpectedHost: oldHost, TargetHost: target.ServerID, + req = authority.WorkspaceMoveRequest{RequestID: q.GetRequestId(), VolumeID: q.GetVolumeId(), ExpectedReplicaID: q.GetExpectedReplicaId(), ExpectedHost: oldHost, TargetHost: target.ServerID, ExpectedEpoch: q.GetExpectedEpoch(), TargetReplicaID: q.GetTargetReplicaId(), TargetDataAddr: q.GetTargetDataAddr(), TargetCtrlAddr: q.GetTargetCtrlAddr(), Kind: q.GetKind(), Force: q.GetForce()} // Strict journal isolation refuses new work only: an exact replay of an // issued move (its reply lost, the target found co-located since) gets // its durable grant back from MoveWorkspace, never a definite refusal. - replay := ok && s.host.Publisher().IssuedWorkspaceMove(req) + replay = ok && s.host.Publisher().IssuedWorkspaceMove(req) switch { case endpointErr != nil: refusal = fmt.Sprintf("move target endpoints invalid: %v", endpointErr) @@ -209,20 +326,7 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) case !matched: refusal = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit)) } - if refusal != "" { - return nil, status.Error(codes.FailedPrecondition, refusal) - } - if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { - return nil, workspaceError(err) - } - r, err := s.host.Publisher().MoveWorkspace(ctx, req, head) - if err != nil { - return nil, workspaceError(err) - } - if err = s.host.reconcileWorkspaceBindings(); err != nil { - return nil, workspaceError(err) - } - return grantFact(r), nil + return req, target, replay, refusal, nil } // sameHost reports whether two host:port addresses name the same host: @@ -276,7 +380,103 @@ func (s *services) QueryWorkspace(ctx context.Context, q *control.WorkspaceVolum out.RevocationAck = &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: q.GetVolumeId(), ReplicaId: state.Ack.ReplicaID, Epoch: state.Ack.Epoch}, HeadGen: state.Ack.HeadGen} } for _, r := range state.Moves { - out.Moves = append(out.Moves, grantFact(r)) + out.Moves = append(out.Moves, s.grantWithLostRange(r)) + } + return out, nil +} + +// QueryWorkspaceLostRange returns the stored lost ranges of the volume's +// issued forced moves in issue order, or the one of request_id. A forced +// move whose range is missing or failed its checks fails the call with +// DataLoss: the readout is unproven, never "no loss". +func (s *services) QueryWorkspaceLostRange(ctx context.Context, q *control.WorkspaceLostRangeQuery) (*control.WorkspaceLostRanges, error) { + if err := s.workspaceVolume(q.GetVolumeId()); err != nil { + return nil, err + } + ranges, err := s.host.Publisher().WorkspaceLostRangeReadouts(q.GetVolumeId(), q.GetRequestId()) + switch { + case errors.Is(err, authority.ErrWorkspaceLostRangeMissing): + return nil, status.Error(codes.DataLoss, err.Error()) + case errors.Is(err, authority.ErrWorkspaceNoForcedMove): + return nil, status.Error(codes.NotFound, err.Error()) + case err != nil: + return nil, workspaceError(err) + } + out := &control.WorkspaceLostRanges{} + for _, r := range ranges { + out.Ranges = append(out.Ranges, lostRangeFact(r)) + } + return out, nil +} + +// PreviewWorkspaceMove answers what MoveWorkspace would do with a forced +// move now, writing nothing: the blockmaster's own checks, the publisher's +// forced admission (with the barrier, i.e. when it becomes admissible) and, +// only once admitted, the HEAD read and HEAD rule, as the move does. A +// refusal is an answer (admitted false, reason), not an RPC error. +func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceMovePreview, error) { + out := &control.WorkspaceMovePreview{} + if !s.host.cfg.WorkspaceRPC { + return nil, status.Error(codes.FailedPrecondition, "workspace RPC disabled") + } + if q.GetKind() != "forced" || !q.GetForce() { + out.Reason = "workspace move preview: forced moves only (kind forced, force true)" + out.MasterTimeNs = time.Now().UnixNano() + return out, nil + } + var req authority.WorkspaceMoveRequest + var replay bool + if err := func() error { + s.host.workspaceMu.Lock() + defer s.host.workspaceMu.Unlock() + if err := s.workspaceVolume(q.GetVolumeId()); err != nil { + out.Reason = status.Convert(err).Message() + return nil + } + r, target, _, why, err := s.workspaceMoveCheckLocked(q) + if err != nil { + return err + } + req = r + pv := s.host.Publisher().PreviewWorkspaceForcedMove(req) + out.Admitted, out.LostUntilNs, out.MasterTimeNs = pv.Admitted, pv.LostUntilNS, pv.NowNS + switch { + case why != "": + out.Admitted, out.Reason = false, why + case !pv.Admitted: + out.Reason = pv.Reason + case pv.Replay: + replay, out.Reason = true, pv.Reason + default: + if err := s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { + out.Admitted, out.Reason = false, err.Error() + } + } + return nil + }(); err != nil { + return nil, workspaceError(err) + } + if out.MasterTimeNs == 0 { + out.MasterTimeNs = time.Now().UnixNano() + } + if !out.Admitted || replay { // a replay never reads a new HEAD + return out, nil + } + // As for the move: HEAD is read only after admission, outside the lock, + // bounded even when the caller set no deadline. + readCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + head, err := s.host.cfg.WorkspaceHeadReader(readCtx, q.GetVolumeId()) + if err != nil { + out.Admitted, out.HeadError = false, err.Error() + out.Reason = "workspace move: HEAD read failed: " + err.Error() + return out, nil + } + out.HeadRead = true + out.HeadGen, out.HeadEpoch, out.HeadHolder, out.HeadRemoteLsn = head.Gen, head.Epoch, head.Holder, head.RemoteLSN + out.HeadTimeNs, out.HeadTimeKnown = head.FilerMtimeNS, head.FilerMtimeNS != 0 + if !authority.WorkspaceMoveHeadAdmits(req, head) { + out.Admitted, out.Reason = false, "workspace move: HEAD not owned by expected holder" } return out, nil } diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index c3ad60dd8b..913f74efb0 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -93,7 +93,7 @@ type ChunkCutStatsBody struct { StagedChunks int `json:"stagedChunks"` StagedChunksUsed int `json:"stagedChunksUsed"` BarrierCopyChunks int `json:"barrierCopyChunks"` - BarrierOverBound bool `json:"barrierOverBound"` + BarrierOverBound bool `json:"barrierOverBound"` // always false in production: its bound is set only by legacy test fixtures } func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { @@ -174,7 +174,14 @@ type snapshotBody struct { Replayed bool `json:"replayed"` } +type chunkFrozenRefusalBody struct { + storage.FrozenBudget + RemainingFreeze time.Duration `json:"remainingFreezeNs"` + GuestFreezeElapsed time.Duration `json:"guestFreezeElapsedNs"` +} + type chunkErrorBody struct { + *chunkFrozenRefusalBody Code string `json:"code"` Message string `json:"message"` Retryable bool `json:"retryable"` @@ -198,9 +205,11 @@ const ( codeLSNBehind = "lsn_behind" codeInternal = "internal" codeBadRequest = "bad_request" - codeMethodNotAllowed = "method_not_allowed" - codeForbidden = "forbidden" - codeNotFound = "not_found" + // Only freeze-option validation before provider admission emits this code. + codeInvalidFreezeBudget = "invalid_freeze_budget" + codeMethodNotAllowed = "method_not_allowed" + codeForbidden = "forbidden" + codeNotFound = "not_found" ) const chunkBodyLimit = 64 << 10 @@ -229,6 +238,7 @@ func (s *StatusServer) chunkMux() http.Handler { mux.HandleFunc("/chunk/snapshots", s.handleChunkSnapshots) mux.HandleFunc("/chunk/snapshot/delete", s.handleChunkSnapshotDelete) mux.HandleFunc("/chunk/detach", s.handleChunkDetach) + mux.HandleFunc("/chunk/restore", s.handleChunkRestore) // Any other /chunk path: a typed JSON 404, like every other /chunk // error, not net/http's plain-text page. mux.HandleFunc("/chunk/", func(w http.ResponseWriter, r *http.Request) { @@ -255,7 +265,14 @@ func writeChunkFailure(w http.ResponseWriter, err error) { if errors.As(err, &ce) { msg = ce.Detail() // the code is in its own field } - writeChunkJSON(w, status, chunkErrorBody{Code: code, Message: msg, Retryable: retryable}) + body := chunkErrorBody{Code: code, Message: msg, Retryable: retryable} + var refusal *storage.FrozenRefusal + // INV-WS-FREEZE-ACCOUNTING-001: transport observation, never a second forecast. + if code == "frozen_tail_too_large" && errors.As(err, &refusal) { + r := refusal.Report + body.chunkFrozenRefusalBody = &chunkFrozenRefusalBody{FrozenBudget: r.FrozenBudget, RemainingFreeze: r.RemainingFreeze, GuestFreezeElapsed: r.GuestFreezeElapsed} + } + writeChunkJSON(w, status, body) } // chunkErrorCode maps an operation's error to (HTTP status, code, @@ -308,7 +325,7 @@ func chunkErrorCode(err error) (int, string, bool) { case errors.Is(err, errFrozenDetachUnsupported): return http.StatusConflict, "frozen_detach_unsupported", false case errors.Is(err, storage.ErrInvalidFreezeBudget): - return http.StatusBadRequest, "bad_request", false + return http.StatusBadRequest, codeInvalidFreezeBudget, false case errors.Is(err, storage.ErrFrozenTailTooLarge): return http.StatusConflict, "frozen_tail_too_large", true // A local window abort cancels its uploads; that cancellation is not @@ -532,7 +549,7 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) return } if (req.Frozen && (req.Plain || req.FreezeStartedAtNs <= 0 || time.Unix(0, req.FreezeStartedAtNs).After(time.Now()))) || (!req.Frozen && (req.FreezeStartedAtNs != 0 || req.AllowOverBudget)) { - writeChunkErr(w, http.StatusBadRequest, "bad_request", false, "frozen requires a non-future freezeStartedAtNs and cannot combine with plain; allowOverBudget requires frozen") + writeChunkErr(w, http.StatusBadRequest, codeInvalidFreezeBudget, false, "frozen requires a non-future freezeStartedAtNs and cannot combine with plain; allowOverBudget requires frozen") return } ctl := s.chunkTarget(w, req.VolumeID) @@ -587,8 +604,9 @@ type ChunkProvider interface { var errFrozenDetachUnsupported = errors.New("frozen detach unsupported by provider") type chunkControl struct { - p ChunkProvider - cat *chunkstore.Catalog + p ChunkProvider + cat *chunkstore.Catalog + restores restoreRuns } // NewChunkControl serves the routes from a durable provider (cut, detach) @@ -621,6 +639,14 @@ func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkS if info, replayed, err := c.cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed { return info, err } + // The share begins before the cut that produces the sealed HEAD. + if g := c.cat.ShareGuard(); g != nil { + token, err := g.Begin(ctx, volumeID) + if err != nil { + return chunkstore.SnapshotInfo{}, err + } + sreq.ShareToken = token + } // A named seal is urgent even without a minimum LSN. r, err := c.p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0) if err != nil { diff --git a/seaweed-block/core/host/volume/chunk_control_class_test.go b/seaweed-block/core/host/volume/chunk_control_class_test.go index 918ead3a02..89d333a9bc 100644 --- a/seaweed-block/core/host/volume/chunk_control_class_test.go +++ b/seaweed-block/core/host/volume/chunk_control_class_test.go @@ -29,9 +29,6 @@ func TestChunkControl_InvalidClassRefusedBeforeCut(t *testing.T) { t.Fatalf("%s maps to %d, want 400", code, s) } } - if s := catalogStatus(chunkstore.CodeSnapshotClaimed); s != http.StatusConflict { - t.Fatalf("snapshot_claimed maps to %d, want 409", s) - } info, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r1", Class: chunkstore.SnapshotClassPinned}) if err != nil || info.Class != chunkstore.SnapshotClassPinned || fp.cuts != 1 { diff --git a/seaweed-block/core/host/volume/chunk_control_order_test.go b/seaweed-block/core/host/volume/chunk_control_order_test.go index 87f19228ea..71a16b3e89 100644 --- a/seaweed-block/core/host/volume/chunk_control_order_test.go +++ b/seaweed-block/core/host/volume/chunk_control_order_test.go @@ -6,6 +6,7 @@ package volume import ( "context" + "errors" "testing" "github.com/seaweedfs/seaweed-block/core/frontend" @@ -96,3 +97,57 @@ func TestChunkControl_InvalidLabelRefusedBeforeCutting(t *testing.T) { t.Fatalf("snapshot with an invalid label: %v (cuts %d); want invalid_label without a cut", err, fp.cuts) } } + +// ownerGuard records, at Begin, how many cuts the provider had taken. +type ownerGuard struct { + cutsAtBegin []int + finishes []string + fp *fakeChunkProvider + beginErr error +} + +func (g *ownerGuard) Begin(context.Context, string) (string, error) { + g.cutsAtBegin = append(g.cutsAtBegin, g.fp.cuts) + if g.beginErr != nil { + return "", g.beginErr + } + return "owner", nil +} + +func (g *ownerGuard) Finish(_ context.Context, vol, token string, head storage.ChunkHead) error { + g.finishes = append(g.finishes, vol+":"+token) + return nil +} + +// The owner's seal begins the share BEFORE the cut that produces the sealed +// HEAD, and the catalog finishes it with that token (no second Begin). +func TestChunkControl_SnapshotBeginsShareBeforeTheCut(t *testing.T) { + ctx := context.Background() + fp, ctl := adapterFixture(t) + g := &ownerGuard{fp: fp} + ctl.(*chunkControl).cat.SetShareGuard(g) + if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"}); err != nil { + t.Fatal(err) + } + if len(g.cutsAtBegin) != 1 || g.cutsAtBegin[0] != 0 || fp.cuts != 1 { + t.Fatalf("Begin saw %v cuts (cuts now %d); want one Begin before the one cut", g.cutsAtBegin, fp.cuts) + } + if len(g.finishes) != 1 || g.finishes[0] != "v1:owner" { + t.Fatalf("finishes %v; want one Finish with the owner's token", g.finishes) + } +} + +// A refused Begin stops the owner's seal before its cut: no cut, no Finish, +// no snapshot. +func TestChunkControl_SnapshotBeginRefusedCutsNothing(t *testing.T) { + ctx := context.Background() + fp, ctl := adapterFixture(t) + g := &ownerGuard{fp: fp, beginErr: errors.New("share refused")} + ctl.(*chunkControl).cat.SetShareGuard(g) + if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"}); err == nil { + t.Fatal("snapshot after a refused Begin") + } + if fp.cuts != 0 || len(g.finishes) != 0 { + t.Fatalf("cuts %d finishes %v after a refused Begin; want none", fp.cuts, g.finishes) + } +} diff --git a/seaweed-block/core/host/volume/chunk_frozen_budget_test.go b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go index 58534c3fee..f905b2fe6f 100644 --- a/seaweed-block/core/host/volume/chunk_frozen_budget_test.go +++ b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go @@ -5,8 +5,10 @@ import ( "encoding/json" "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" "net/http" + "sync" "testing" "time" ) @@ -64,3 +66,173 @@ func TestChunkCheckpointCarriesCandidateTail(t *testing.T) { t.Fatalf("cut response lost tail: %d %s %v", w.Code, w.Body, err) } } + +func TestChunkFrozenValidationHasDistinctPreMutationCode(t *testing.T) { + p := &frozenDetachProvider{fakeChunkProvider: &fakeChunkProvider{}} + s := chunkServer(t, NewChunkControl(p, nil), true) + past := time.Now().Add(-time.Second).UnixNano() + for _, body := range []string{ + `{"volumeID":"v1","frozen":true}`, + fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d}`, time.Now().Add(time.Hour).UnixNano()), + fmt.Sprintf(`{"volumeID":"v1","frozen":true,"plain":true,"freezeStartedAtNs":%d}`, past), + `{"volumeID":"v1","allowOverBudget":true}`, + } { + w := serve(t, s, http.MethodPost, "/chunk/detach", body, "") + var got chunkErrorBody + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if w.Code != 400 || got.Code != "invalid_freeze_budget" || got.Retryable || p.calls != 0 { + t.Errorf("freeze validation lacked pre-mutation classification: status=%d body=%s calls=%d", w.Code, w.Body, p.calls) + } + } + // A malformed/generic400 is not evidence of a typed clean refusal. + w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":`, "") + var got chunkErrorBody + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if w.Code != 400 || got.Code != "bad_request" || p.calls != 0 { + t.Errorf("generic400 relabelled: %d %s calls=%d", w.Code, w.Body, p.calls) + } + status, code, retry := chunkErrorCode(storage.ErrInvalidFreezeBudget) + if status != 400 || code != "invalid_freeze_budget" || retry { + t.Errorf("storage validation lost classification: %d %s %t", status, code, retry) + } + for _, terminal := range []error{storage.ErrChunkCASOutcomeUnknown, storage.ErrChunkLayerClosed, storage.ErrChunkLayerFenced} { + wantStatus, wantCode, wantRetry := chunkErrorCode(terminal) + status, code, retry = chunkErrorCode(errors.Join(terminal, storage.ErrInvalidFreezeBudget)) + if status != wantStatus || code != wantCode || retry != wantRetry { + t.Errorf("validation hid terminal/unknown cause: %d %s %t", status, code, retry) + } + } +} + +func TestChunkFrozenRefusalCarriesServerBudget(t *testing.T) { + report := storage.PrecopyReport{FrozenBudget: storage.FrozenBudget{FrozenEstimate: 5570 * time.Millisecond, FrozenEstimateKnown: true, FreezeLimit: 5 * time.Second}, Estimate: 5570 * time.Millisecond, RemainingFreeze: 4 * time.Second, GuestFreezeElapsed: time.Second, Reason: "frozen_tail_too_large"} + refusal := &storage.FrozenRefusal{Report: report} + p := &frozenDetachProvider{fakeChunkProvider: &fakeChunkProvider{}, err: refusal} + srv := chunkServer(t, NewChunkControl(p, nil), true) + body := fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d}`, time.Now().Add(-time.Second).UnixNano()) + w := serve(t, srv, http.MethodPost, "/chunk/detach", body, "") + var got map[string]json.RawMessage + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || w.Code != 409 { + t.Fatalf("refusal %d %s", w.Code, w.Body) + } + for key, want := range map[string]int64{"frozenEstimateNs": 5570000000, "freezeLimitNs": 5000000000, "maxRefreezeQuiesceNs": 0, "remainingFreezeNs": 4000000000, "guestFreezeElapsedNs": 1000000000} { + var value int64 + if raw, ok := got[key]; !ok { + t.Errorf("missing %s: %s", key, w.Body) + } else if err := json.Unmarshal(raw, &value); err != nil || value != want { + t.Errorf("%s=%s want%d", key, raw, want) + } + } + var known bool + if err := json.Unmarshal(got["frozenEstimateKnown"], &known); err != nil || !known { + t.Errorf("known lost: %s", w.Body) + } + p.err = &storage.FrozenRefusal{Report: storage.PrecopyReport{FrozenBudget: storage.FrozenBudget{FrozenEstimate: 300 * time.Millisecond, FreezeLimit: 5 * time.Second}, Estimate: 300 * time.Millisecond, Reason: "frozen_tail_too_large", RemainingFreeze: 5 * time.Second}} + w = serve(t, srv, http.MethodPost, "/chunk/detach", body, "") + got = nil + _ = json.Unmarshal(w.Body.Bytes(), &got) + if string(got["frozenEstimateKnown"]) != "false" || string(got["maxRefreezeQuiesceNs"]) != "0" || string(got["frozenEstimateNs"]) != "300000000" { + t.Fatalf("unknown refusal became an actionable estimate: %s", w.Body) + } + p.err = errors.Join(storage.ErrChunkLayerClosed, refusal) + w = serve(t, srv, http.MethodPost, "/chunk/detach", body, "") + got = nil + if json.Unmarshal(w.Body.Bytes(), &got) != nil { + t.Fatal(w.Body) + } + status, code, _ := chunkErrorCode(storage.ErrChunkLayerClosed) + var gotCode string + _ = json.Unmarshal(got["code"], &gotCode) + if w.Code != status || gotCode != code { + t.Fatalf("terminal precedence lost: %d %s", w.Code, w.Body) + } + if _, ok := got["frozenEstimateNs"]; ok { + t.Fatalf("terminal response offered retry budget: %s", w.Body) + } +} + +// Hold a real admitted Sync through the replication observer, so the actual +// frontend drain expires before storage frozen admission. No report is injected. +type frozenDrainObserver struct{ entered, release chan struct{} } + +func (*frozenDrainObserver) Observe(context.Context, uint32, uint64, []byte) error { return nil } +func (o *frozenDrainObserver) Sync(ctx context.Context, _ uint64) error { + close(o.entered) + select { + case <-o.release: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} +func TestChunkFrozenDrainRefusalCarriesObservedBudget(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + dp, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16, + ChunkDetachPrecopy: true, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, healthyView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dp.Close() }) + if _, err = dp.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err = dp.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + backend, err := dp.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if _, err = backend.Write(ctx, 4096, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + observer := &frozenDrainObserver{make(chan struct{}), make(chan struct{})} + if err = backend.(*durable.StorageBackend).SetWriteObserver(observer); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + var once sync.Once + t.Cleanup(func() { + once.Do(func() { close(observer.release) }) + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("Sync did not join") + } + }) + go func() { done <- backend.Sync(ctx) }() + select { + case <-observer.entered: + case <-ctx.Done(): + t.Fatal("Sync never admitted") + } + before, _ := remote.GetHead(ctx) + puts := remote.Puts() + server := chunkServer(t, NewChunkControl(dp, nil), true) + body := fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d,"allowOverBudget":true}`, time.Now().Add(-time.Second).UnixNano()) + response := serve(t, server, http.MethodPost, "/chunk/detach", body, "") + var got struct { + Code string `json:"code"` + storage.FrozenBudget + Remaining time.Duration `json:"remainingFreezeNs"` + Elapsed time.Duration `json:"guestFreezeElapsedNs"` + } + if err = json.Unmarshal(response.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if response.Code != 409 || got.Code != "frozen_tail_too_large" || got.FreezeLimit != 5*time.Second || got.Elapsed < time.Second || got.Remaining <= 0 || got.Elapsed+got.Remaining != got.FreezeLimit || got.FrozenEstimateKnown || got.MaxRefreezeQuiesce != 0 { + t.Fatalf("real drain refusal lost observation: %d %s", response.Code, response.Body) + } + after, _ := remote.GetHead(ctx) + if after.Gen != before.Gen || remote.Puts() != puts { + t.Fatal("failed drain uploaded or published") + } +} diff --git a/seaweed-block/core/host/volume/chunk_restore.go b/seaweed-block/core/host/volume/chunk_restore.go new file mode 100644 index 0000000000..94521f0134 --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_restore.go @@ -0,0 +1,246 @@ +package volume + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "sync" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Independent restore driver (M6.Restore). A restored volume serves at once; +// the driver then makes every chunk local (Restoring>Hydrating), re-uploads +// the chunks whose HEAD keys name another volume under the volume's own keys +// in bounded batch cuts (Hydrating>Owning, Owning>Owning; the walker and the +// batches may overlap), and writes the independence marker once HEAD holds +// no foreign ref (Owning>Independent). Every decision is read from the +// target's own facts (its VOLUME, HEAD and marker), never from the source, so +// a rerun after a crash resumes where the remote state is, and a deleted +// source snapshot or volume is a normal state. + +// Restore quantities (invariants.md Part E). +const ( + DefaultRestoreBatchChunks = 64 + DefaultRestoreBytesPerSecond = 64 << 20 +) + +// RestoreProvider is the chunk layer's restore surface for an attached volume. +type RestoreProvider interface { + HydrateVolume(ctx context.Context, volumeID string, bytesPerSecond int64) (storage.HydrateProgress, error) + OwnVolumeBatch(ctx context.Context, volumeID string, n int, foreign func(string) bool) (storage.OwnProgress, error) +} + +// RestoreConfig bounds one restore run; zero fields take the defaults. +type RestoreConfig struct { + BatchChunks int + BytesPerSecond int64 +} + +// Restore phases. +const ( + RestoreHydrating = "hydrating" + RestoreOwning = "owning" + RestoreIndependent = "independent" + RestoreFailed = "failed" +) + +// RestoreStatus is the body of /chunk/restore. +type RestoreStatus struct { + VolumeID string `json:"volumeID"` + Phase string `json:"phase"` + Running bool `json:"running"` + Filled int `json:"filled"` // chunks the walker made local + Owned int `json:"owned"` // chunks re-uploaded under own keys + Foreign int `json:"foreign"` // HEAD chunks still naming another volume + NotLocal int `json:"notLocal"` // of those, not local yet + Batches int `json:"batches"` // batch cuts run + MarkedGen uint64 `json:"markedGen"` // HEAD gen the marker names (independent) + ErrorCode string `json:"errorCode,omitempty"` + ErrorText string `json:"error,omitempty"` +} + +// foreignKey reports whether key names another volume's object: an +// owner-qualified key whose owner is not vol. +func foreignKey(vol string) func(string) bool { + own := "@" + vol + "/" + return func(key string) bool { return strings.HasPrefix(key, "@") && !strings.HasPrefix(key, own) } +} + +var ( + errRestoreStuck = errors.New("restore: foreign chunks remain but none is local and the walker fills none") + errNotRestore = errors.New("restore: not a restore") +) + +// runRestore drives one restore of vol to independence, reporting progress. +func runRestore(ctx context.Context, cat *chunkstore.Catalog, p RestoreProvider, vol string, cfg RestoreConfig, report func(RestoreStatus)) (RestoreStatus, error) { + if cfg.BatchChunks <= 0 { + cfg.BatchChunks = DefaultRestoreBatchChunks + } + if cfg.BytesPerSecond <= 0 { + cfg.BytesPerSecond = DefaultRestoreBytesPerSecond + } + st := RestoreStatus{VolumeID: vol, Phase: RestoreHydrating, Running: true} + if m, ok, err := cat.ReadIndependence(ctx, vol); err != nil { + return st, err + } else if ok { + st.Phase, st.MarkedGen = RestoreIndependent, m.HeadGen + return st, nil + } + v, ok, err := cat.ReadVolume(ctx, vol) + if err != nil { + return st, err + } + if !ok || v.Origin != chunkstore.OriginRestore { + return st, fmt.Errorf("volume %s was not made by restore: %w", vol, errNotRestore) + } + foreign := foreignKey(vol) + for stalls := 0; ; { + h, err := p.HydrateVolume(ctx, vol, cfg.BytesPerSecond) + st.Filled += h.Filled + report(st) + if err != nil { + return st, err + } + st.Phase = RestoreOwning + progressed := h.Filled > 0 + for { + o, err := p.OwnVolumeBatch(ctx, vol, cfg.BatchChunks, foreign) + st.Owned, st.Foreign, st.NotLocal = st.Owned+o.Owned, o.Remaining, o.NotLocal + if o.Owned > 0 { + st.Batches++ + progressed = true + } + report(st) + if err != nil { + return st, err + } + if o.Remaining == 0 { + m, err := cat.MarkIndependent(ctx, vol) + if err != nil { + return st, err + } + st.Phase, st.MarkedGen, st.Running = RestoreIndependent, m.HeadGen, false + report(st) + return st, nil + } + if o.Owned == 0 { + break // what is left is not local: walk again + } + } + if !progressed { + if stalls++; stalls > 2 { + return st, errRestoreStuck + } + } else { + stalls = 0 + } + } +} + +// restoreRuns holds at most one running restore per volume and the last +// status of each. +type restoreRuns struct { + mu sync.Mutex + runs map[string]*RestoreStatus +} + +// Restore reports vol's restore status and, with start, starts a run unless +// one is running (POST /chunk/restore). A run outlives the request but not +// the serving provider (RestoreOwner); it ends independent, or failed with +// the error (a later start resumes from the target's remote facts). +func (c *chunkControl) Restore(ctx context.Context, vol string, start bool) (RestoreStatus, error) { + p, ok := c.p.(RestoreProvider) + owner, owned := c.p.(RestoreOwner) + if !ok || !owned { + return RestoreStatus{}, fmt.Errorf("restore: provider has no restore surface: %w", errNotRestore) + } + c.restores.mu.Lock() + defer c.restores.mu.Unlock() + if c.restores.runs == nil { + c.restores.runs = map[string]*RestoreStatus{} + } + cur := c.restores.runs[vol] + if cur != nil && (cur.Running || !start) { + return *cur, nil + } + if !start { + return RestoreStatus{VolumeID: vol}, nil + } + st := &RestoreStatus{VolumeID: vol, Phase: RestoreHydrating, Running: true} + c.restores.runs[vol] = st + report := func(s RestoreStatus) { + c.restores.mu.Lock() + *st = s + c.restores.mu.Unlock() + } + run := func(ctx context.Context) { + final, err := runRestore(ctx, c.cat, p, vol, RestoreConfig{}, report) + final.Running = false + if err != nil { + _, code, _ := chunkErrorCode(err) + final.Phase, final.ErrorCode, final.ErrorText = RestoreFailed, code, err.Error() + } + report(final) + } + if err := owner.GoOwned(run); err != nil { + delete(c.restores.runs, vol) + return RestoreStatus{}, err + } + return *st, nil +} + +// RestoreOwner runs the driver inside the serving volume's lifetime: the +// driver's ctx ends when the owner closes, and the owner waits for it +// (DurableProvider.GoOwned). +type RestoreOwner interface { + GoOwned(fn func(ctx context.Context)) error +} + +// handleChunkRestore serves GET /chunk/restore?volume=V (status) and +// POST /chunk/restore {"volumeID": V} (start or join a run; with +// "statusOnly": true, status only). Both answer 200 with the status. +func (s *StatusServer) handleChunkRestore(w http.ResponseWriter, r *http.Request) { + method := http.MethodGet + if r.Method == http.MethodPost { + method = http.MethodPost + } + if !s.chunkAdmit(w, r, method) { + return + } + vol := r.URL.Query().Get("volume") + if method == http.MethodPost { + var req struct { + VolumeID string `json:"volumeID"` + StatusOnly bool `json:"statusOnly"` + TimeoutMs int64 `json:"timeoutMs"` + } + if !decodeChunkBody(w, r, &req) { + return + } + vol = req.VolumeID + if req.StatusOnly { + method = http.MethodGet + } + } + ctl := s.chunkTarget(w, vol) + if ctl == nil { + return + } + rc, ok := ctl.(interface { + Restore(context.Context, string, bool) (RestoreStatus, error) + }) + if !ok { + writeChunkErr(w, http.StatusNotFound, codeNotFound, false, "restore is not served here") + return + } + st, err := rc.Restore(r.Context(), vol, method == http.MethodPost) + if err != nil { + writeChunkFailure(w, err) + return + } + writeChunkJSON(w, http.StatusOK, st) +} diff --git a/seaweed-block/core/host/volume/chunk_restore_test.go b/seaweed-block/core/host/volume/chunk_restore_test.go new file mode 100644 index 0000000000..d70420b8b4 --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_restore_test.go @@ -0,0 +1,394 @@ +package volume + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "path" + "sort" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const restoreBase = "/swblock/chunks" + +var restoreGeo = chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} + +// sourceReadGuard fails every catalog read of the source volume's own +// entries (VOLUME, HEAD, snapshots) once armed; chunk bindings stay readable +// (hydration reads the source's chunks through T's qualified refs). +type sourceReadGuard struct { + *adapterManifestFiler + armed bool + reads []string +} + +func (g *sourceReadGuard) denied(dir string) bool { + src := path.Join(restoreBase, "v1") + return g.armed && (dir == src || strings.HasPrefix(dir, src+"/snap")) +} + +func (g *sourceReadGuard) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if g.denied(dir) { + g.reads = append(g.reads, path.Join(dir, name)) + return nil, errors.New("test: the restore driver read the source") + } + return g.adapterManifestFiler.LookupEntry(ctx, dir, name) +} + +func (g *sourceReadGuard) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { + if g.denied(dir) { + g.reads = append(g.reads, dir) + return nil, errors.New("test: the restore driver listed the source") + } + return g.adapterManifestFiler.ListEntries(ctx, dir, prefix, after, limit) +} + +// fakeRestoreProvider stands in for the chunk layer: the walk makes every +// chunk local, and a batch is one HEAD CAS replacing up to n foreign keys. +type fakeRestoreProvider struct { + r *chunkstore.ChunkRemote + local bool + hydrations int + batches int + failAtBatch int // a batch with this 1-based number fails (0: never) + mu sync.Mutex + entered chan struct{} // if set, HydrateVolume signals entry and + gate chan struct{} // then waits for gate or its ctx +} + +func (p *fakeRestoreProvider) HydrateVolume(ctx context.Context, vol string, bps int64) (storage.HydrateProgress, error) { + p.mu.Lock() + p.hydrations++ + entered, gate := p.entered, p.gate + p.mu.Unlock() + if entered != nil { + entered <- struct{}{} + select { + case <-gate: + case <-ctx.Done(): + return storage.HydrateProgress{}, ctx.Err() + } + } + if bps != DefaultRestoreBytesPerSecond { + return storage.HydrateProgress{}, fmt.Errorf("walker pace %d, want the default %d", bps, DefaultRestoreBytesPerSecond) + } + if p.local { + return storage.HydrateProgress{}, nil + } + h, err := p.r.GetHead(ctx) + if err != nil { + return storage.HydrateProgress{}, err + } + p.local = true + return storage.HydrateProgress{Filled: len(h.Chunks)}, nil +} + +func (p *fakeRestoreProvider) OwnVolumeBatch(ctx context.Context, vol string, n int, foreign func(string) bool) (storage.OwnProgress, error) { + h, err := p.r.GetHead(ctx) + if err != nil { + return storage.OwnProgress{}, err + } + var todo []uint64 + for idx, ref := range h.Chunks { + if foreign(ref.Key) { + todo = append(todo, idx) + } + } + sort.Slice(todo, func(i, j int) bool { return todo[i] < todo[j] }) + if !p.local || len(todo) == 0 { + nl := 0 + if !p.local { + nl = len(todo) + } + return storage.OwnProgress{Remaining: len(todo), NotLocal: nl}, nil + } + p.batches++ + if p.batches == p.failAtBatch { + return storage.OwnProgress{Remaining: len(todo)}, errors.New("test: batch cut failed") + } + next := storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}} + for idx, ref := range h.Chunks { + next.Chunks[idx] = ref + } + owned := 0 + for _, idx := range todo { + if owned == n { + break + } + data, err := p.r.Get(ctx, h.Chunks[idx].Key) + if err != nil { + return storage.OwnProgress{}, err + } + key := fmt.Sprintf("chunks/e3/c%d/b%d", idx, p.batches) + if err := p.r.Put(ctx, key, data); err != nil { + return storage.OwnProgress{}, err + } + next.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + owned++ + } + next, intents, err := p.r.PrepareManifest(ctx, h, next, uint64(restoreGeo.BlockSize)*uint64(restoreGeo.ChunkBlocks)) + if err != nil { + return storage.OwnProgress{}, err + } + if _, err := p.r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next); err != nil { + return storage.OwnProgress{}, err + } + for _, id := range intents { + _ = p.r.DeleteIntent(ctx, id) + } + return storage.OwnProgress{Owned: owned, Remaining: len(todo) - owned}, nil +} + +// restoreFixtureHost publishes source v1 (chunks), snapshots it and restores +// it into v2; it returns the guard filer, the catalog and v2's provider. +func restoreFixtureHost(t *testing.T, chunks int) (*sourceReadGuard, *chunkstore.Catalog, *fakeRestoreProvider) { + t.Helper() + ctx := context.Background() + f := &sourceReadGuard{adapterManifestFiler: &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}}} + cat, err := chunkstore.NewCatalog(f, restoreBase) + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(ctx, "v1", restoreGeo); err != nil { + t.Fatal(err) + } + r1, err := chunkstore.NewChunkRemote(f, f, path.Join(restoreBase, "v1")) + if err != nil { + t.Fatal(err) + } + cur, err := r1.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}} + for idx := 0; idx < chunks; idx++ { + data := make([]byte, int(restoreGeo.BlockSize)*int(restoreGeo.ChunkBlocks)) + data[0] = byte(0x60 + idx) + key := fmt.Sprintf("chunks/e1/c%d/k", idx) + if err := r1.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + h.Chunks[uint64(idx)] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + h, intents, err := r1.PrepareManifest(ctx, cur, h, uint64(restoreGeo.BlockSize)*uint64(restoreGeo.ChunkBlocks)) + if err != nil { + t.Fatal(err) + } + if h.Gen, err = r1.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil { + t.Fatal(err) + } + for _, id := range intents { + _ = r1.DeleteIntent(ctx, id) + } + if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if _, err := cat.Restore(ctx, chunkstore.ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs"}); err != nil { + t.Fatal(err) + } + r2, err := chunkstore.NewChunkRemote(f, f, path.Join(restoreBase, "v2")) + if err != nil { + t.Fatal(err) + } + return f, cat, &fakeRestoreProvider{r: r2} +} + +func noReport(RestoreStatus) {} + +// The driver walks, cuts bounded batches until no foreign ref is left and +// writes the marker, reading only the target's facts (Restoring>Hydrating> +// Owning>Owning>Independent). +func TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly(t *testing.T) { + f, cat, p := restoreFixtureHost(t, 5) + f.armed = true // from here, any read of the source's catalog entries fails + ctx := context.Background() + st, err := runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err != nil { + t.Fatalf("restore: %+v %v (source reads %v)", st, err, f.reads) + } + if len(f.reads) != 0 { + t.Fatalf("the driver read the source: %v", f.reads) + } + if st.Phase != RestoreIndependent || st.Owned != 5 || st.Foreign != 0 || st.Batches != 3 || st.Filled != 5 { + t.Fatalf("status %+v, want independent after 3 batches of at most 2", st) + } + m, ok, err := cat.ReadIndependence(ctx, "v2") + if err != nil || !ok || m.HeadGen != st.MarkedGen { + t.Fatalf("marker: %+v ok=%v %v", m, ok, err) + } + again, err := runRestore(ctx, cat, p, "v2", RestoreConfig{}, noReport) + if err != nil || again.Phase != RestoreIndependent || p.batches != 3 { + t.Fatalf("a rerun of an independent restore must do nothing: %+v %v", again, err) + } +} + +// A failed batch leaves HEAD as it was; the next run resumes from the +// target's HEAD and finishes. +func TestRestoreDriver_ResumesAfterAFailedBatch(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 5) + ctx := context.Background() + p.failAtBatch = 2 + st, err := runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err == nil || st.Owned != 2 || st.Foreign != 3 { + t.Fatalf("first run: %+v %v, want the failure after 2 owned", st, err) + } + if _, ok, _ := cat.ReadIndependence(ctx, "v2"); ok { + t.Fatal("marker written with foreign refs left") + } + p.failAtBatch = 0 + st, err = runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err != nil || st.Phase != RestoreIndependent || st.Owned != 3 { + t.Fatalf("resumed run: %+v %v, want the 3 left owned and the marker", st, err) + } +} + +// Only a restore volume is driven. +func TestRestoreDriver_RefusesAVolumeNotMadeByRestore(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 1) + if _, err := runRestore(context.Background(), cat, p, "v1", RestoreConfig{}, noReport); !errors.Is(err, errNotRestore) { + t.Fatalf("driving the source volume: %v, want not a restore", err) + } +} + +// testOwner runs owned goroutines until close, which cancels and joins them +// (bounded), like DurableProvider.Close. +type testOwner struct { + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup +} + +func newTestOwner(t *testing.T) *testOwner { + o := &testOwner{} + o.ctx, o.cancel = context.WithCancel(context.Background()) + t.Cleanup(func() { o.close(t) }) + return o +} + +func (o *testOwner) GoOwned(fn func(context.Context)) error { + o.wg.Add(1) + go func() { defer o.wg.Done(); fn(o.ctx) }() + return nil +} + +func (o *testOwner) close(t *testing.T) { + o.cancel() + done := make(chan struct{}) + go func() { o.wg.Wait(); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("owned restore run did not return after close") + } +} + +// restoreOnlyProvider is a ChunkProvider (cut and detach unused) with the +// restore surface and an owner. +type restoreOnlyProvider struct { + *fakeRestoreProvider + *testOwner +} + +func (restoreOnlyProvider) CutVolume(context.Context, string, uint64) (storage.ChunkCutResult, error) { + return storage.ChunkCutResult{}, errors.New("unused") +} +func (restoreOnlyProvider) DetachVolume(context.Context, string) (storage.ChunkCutResult, uint64, error) { + return storage.ChunkCutResult{}, 0, errors.New("unused") +} + +func waitRestore(t *testing.T, ctl *chunkControl, vol string) RestoreStatus { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + st, err := ctl.Restore(context.Background(), vol, false) + if err != nil { + t.Fatal(err) + } + if !st.Running { + return st + } + if time.Now().After(deadline) { + t.Fatalf("restore still running: %+v", st) + } + time.Sleep(time.Millisecond) + } +} + +// POST /chunk/restore starts one background run: a second start while the +// first is held joins it (one walk), and the run is reported to the end. +func TestRestoreDriver_ChunkControlStartsOneRunAndReportsIt(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 3) + owner := newTestOwner(t) + p.entered, p.gate = make(chan struct{}, 2), make(chan struct{}) + release := func() { + select { + case <-p.gate: + default: + close(p.gate) + } + } + t.Cleanup(release) // registered before launch; the owner joins after it + ctl := &chunkControl{p: restoreOnlyProvider{p, owner}, cat: cat} + ctx := context.Background() + if st, err := ctl.Restore(ctx, "v2", false); err != nil || st.Phase != "" { + t.Fatalf("status before any run: %+v %v", st, err) + } + if _, err := ctl.Restore(ctx, "v2", true); err != nil { + t.Fatal(err) + } + select { + case <-p.entered: + case <-time.After(5 * time.Second): + t.Fatal("the run never reached the walker") + } + if st, err := ctl.Restore(ctx, "v2", true); err != nil || !st.Running { + t.Fatalf("second start while the first runs: %+v %v, want it joined", st, err) + } + release() + st := waitRestore(t, ctl, "v2") + p.mu.Lock() + walks := p.hydrations + p.mu.Unlock() + if walks != 1 || st.Phase != RestoreIndependent || st.Owned != 3 { + t.Fatalf("walks=%d status %+v, want one run to independence", walks, st) + } +} + +// Closing the serving owner cancels a run held in a provider call and joins +// it: the run ends failed and publishes no marker after the close. +func TestRestoreDriver_OwnerCloseCancelsAndJoinsTheRun(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 3) + owner := newTestOwner(t) + p.entered, p.gate = make(chan struct{}, 1), make(chan struct{}) // opened only at teardown + // Registered after the owner: it runs first, so a run that ignored the + // owner's cancel (the red case) is released before the owner's join. + t.Cleanup(func() { close(p.gate) }) + ctl := &chunkControl{p: restoreOnlyProvider{p, owner}, cat: cat} + if _, err := ctl.Restore(context.Background(), "v2", true); err != nil { + t.Fatal(err) + } + select { + case <-p.entered: + case <-time.After(5 * time.Second): + t.Fatal("the run never reached the walker") + } + owner.close(t) // cancel and bounded join, like DurableProvider.Close + st, err := ctl.Restore(context.Background(), "v2", false) + if err != nil || st.Running || st.Phase != RestoreFailed { + t.Fatalf("status after the owner closed: %+v %v, want a finished failed run", st, err) + } + if _, ok, _ := cat.ReadIndependence(context.Background(), "v2"); ok { + t.Fatal("a marker was published after the owner closed") + } +} + +var _ RestoreProvider = (*durable.DurableProvider)(nil) diff --git a/seaweed-block/core/host/volume/memory_status.go b/seaweed-block/core/host/volume/memory_status.go index 3a15daa127..b1ee1950bc 100644 --- a/seaweed-block/core/host/volume/memory_status.go +++ b/seaweed-block/core/host/volume/memory_status.go @@ -11,13 +11,13 @@ import ( // ProcessMemoryStatus separates live heap from resident pages awaiting return // to the OS. RSS fields are zero on systems without /proc/self/status. type ProcessMemoryStatus struct { - HeapAllocBytes uint64 - HeapInuseBytes uint64 - HeapSysBytes uint64 - HeapReleasedBytes uint64 - SoftLimitBytes int64 - RSSBytes uint64 - AnonymousRSSBytes uint64 + HeapAllocBytes uint64 // Go heap bytes in live objects (runtime.MemStats.HeapAlloc) + HeapInuseBytes uint64 // Go heap bytes in in-use spans (HeapInuse) + HeapSysBytes uint64 // Go heap bytes obtained from the OS (HeapSys) + HeapReleasedBytes uint64 // Go heap bytes returned to the OS (HeapReleased) + SoftLimitBytes int64 // the Go soft memory limit in force (--memory-limit-mib or GOMEMLIMIT) + RSSBytes uint64 // resident set size from /proc/self/status (VmRSS); 0 off Linux + AnonymousRSSBytes uint64 // anonymous resident memory (RssAnon); 0 off Linux } func processMemoryStatus() ProcessMemoryStatus { diff --git a/seaweed-block/core/host/volume/status_schema_test.go b/seaweed-block/core/host/volume/status_schema_test.go new file mode 100644 index 0000000000..348909f843 --- /dev/null +++ b/seaweed-block/core/host/volume/status_schema_test.go @@ -0,0 +1,308 @@ +package volume + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "reflect" + "sort" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/engine" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/replication" +) + +// statusRoutes are the status routes and the type each one encodes. The +// anonymous bodies of /status/peers and /status/durable are restated here +// field for field; TestStatusBodiesMatchTheRoutes checks they still match. +var statusRoutes = []struct { + route, note string + typ reflect.Type +}{ + {"/status", "the volume's authority and health projection", reflect.TypeOf(StatusProjection{})}, + {"/status/peers", "replication peers of the served volume", reflect.TypeOf(peersStatusBody{})}, + {"/status/durable", "durable store state of the served volume", reflect.TypeOf(durableStatusBody{})}, + {"/status/recovery", "the engine's replica projection (only with recovery enabled)", reflect.TypeOf(engine.ReplicaProjection{})}, + {"/status/chunk", "chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint)", reflect.TypeOf(chunkstore.VolumeUsage{})}, + {"/status/nvme", "NVMe/TCP frontend counters", reflect.TypeOf(NVMeStatus{})}, + {"/status/ublk", "ublk frontend counters", reflect.TypeOf(UblkStatus{})}, + {"/status/frontend-capabilities", "the frontends this host can serve", reflect.TypeOf(FrontendCapabilitiesStatus{})}, +} + +type peersStatusBody struct { + VolumeID string // the served volume + ReplicaID string // this host's replica + PeerCount int // number of entries in Peers + Peers []replication.ReplicaPeerStatus // this primary's replication peers +} + +type durableStatusBody struct { + VolumeID string // the served volume + ReplicaID string // this host's replica + VolumeCount int // number of entries in Volumes + Volumes []durable.VolumeStatus // the durable store state of the served volume +} + +const ( + statusSchemaDoc = "../../../docs/status-schema.md" + statusSchemaBegin = "" + statusSchemaEnd = "" + modulePath = "github.com/seaweedfs/seaweed-block/" +) + +// fieldDocs maps "pkgpath.Type.Field" to the field's doc or line comment. +type fieldDocs map[string]string + +func (d fieldDocs) load(t *testing.T, pkgPath string) { + t.Helper() + if !strings.HasPrefix(pkgPath, modulePath) { + return + } + if _, done := d["pkg:"+pkgPath]; done { + return + } + d["pkg:"+pkgPath] = "" + dir := filepath.Join("..", "..", "..", strings.TrimPrefix(pkgPath, modulePath)) + fset := token.NewFileSet() + pkgs, err := parser.ParseDir(fset, dir, func(fi os.FileInfo) bool { + return !strings.HasSuffix(fi.Name(), "_test.go") || fi.Name() == "status_schema_test.go" // the restated bodies + }, parser.ParseComments) + if err != nil { + t.Fatalf("parse %s: %v", dir, err) + } + for _, p := range pkgs { + for _, f := range p.Files { + ast.Inspect(f, func(n ast.Node) bool { + ts, ok := n.(*ast.TypeSpec) + if !ok { + return true + } + st, ok := ts.Type.(*ast.StructType) + if !ok { + return true + } + // A doc comment above a run of fields with no blank line + // between them describes the whole run (a group comment). + group, groupFirst, prevEnd := "", "", -1 + for _, fl := range st.Fields.List { + text := "" + line := fset.Position(fl.Pos()).Line + switch { + case fl.Doc != nil: + text = fl.Doc.Text() + group, groupFirst = strings.Join(strings.Fields(text), " "), "" + if len(fl.Names) > 0 { + groupFirst = fl.Names[0].Name + } + case fl.Comment != nil: + text = fl.Comment.Text() + case group != "" && line == prevEnd+1: + text = "(group of `" + groupFirst + "`) " + group + default: + group = "" + } + prevEnd = fset.Position(fl.End()).Line + text = strings.Join(strings.Fields(text), " ") + for _, name := range fl.Names { + d[pkgPath+"."+ts.Name.Name+"."+name.Name] = text + } + } + return true + }) + } + } +} + +// schemaRows walks t's JSON fields; prefix is the dotted JSON path so far. +func schemaRows(t *testing.T, docs fieldDocs, typ reflect.Type, prefix string, seen map[reflect.Type]bool, rows *[]string) { + for typ.Kind() == reflect.Pointer { + typ = typ.Elem() + } + if typ.Kind() != reflect.Struct || seen[typ] { + return + } + seen[typ] = true + defer delete(seen, typ) + docs.load(t, typ.PkgPath()) + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + if !f.IsExported() { + continue + } + tag := f.Tag.Get("json") + if tag == "-" { + continue + } + name, opts, _ := strings.Cut(tag, ",") + if f.Anonymous && name == "" { + schemaRows(t, docs, f.Type, prefix, seen, rows) + continue + } + if name == "" { + name = f.Name + } + path := name + if prefix != "" { + path = prefix + "." + name + } + ft, suffix := f.Type, "" + for { + switch ft.Kind() { + case reflect.Pointer: + ft = ft.Elem() + continue + case reflect.Slice, reflect.Array: + if ft.Elem().Kind() != reflect.Uint8 { + ft, suffix = ft.Elem(), suffix+"[]" + continue + } + case reflect.Map: + ft, suffix = ft.Elem(), suffix+"{}" + continue + } + break + } + typeName := ft.Kind().String() + if ft.Kind() == reflect.Struct { + typeName = "object" + if ft.PkgPath() == "time" && ft.Name() == "Time" { + typeName = "time (RFC 3339)" + } + } else if ft.Name() != "" && ft.PkgPath() != "" { + typeName = ft.Name() + " (" + ft.Kind().String() + ")" + } + if f.Type.Kind() == reflect.Slice && f.Type.Elem().Kind() == reflect.Uint8 { + typeName = "bytes (base64)" + } + desc := docs[typ.PkgPath()+"."+typ.Name()+"."+f.Name] + if desc == "" { + desc = "—" + } + if strings.Contains(opts, "omitempty") { + desc += " (omitted when empty)" + } + desc = strings.ReplaceAll(desc, "|", "\\|") + *rows = append(*rows, fmt.Sprintf("| `%s%s` | %s | %s |", path, suffix, typeName, desc)) + if ft.Kind() == reflect.Struct && !(ft.PkgPath() == "time" && ft.Name() == "Time") { + schemaRows(t, docs, ft, path+suffix, seen, rows) + } + } +} + +func generateStatusSchema(t *testing.T) string { + t.Helper() + docs := fieldDocs{} + var b strings.Builder + b.WriteString(statusSchemaBegin + "\n") + for _, r := range statusRoutes { + var rows []string + schemaRows(t, docs, r.typ, "", map[reflect.Type]bool{}, &rows) + fmt.Fprintf(&b, "\n### `GET %s`\n\n%s. Go type `%s`.\n\n| Field | Type | Meaning |\n|---|---|---|\n", r.route, upperFirst(r.note), r.typ.String()) + b.WriteString(strings.Join(rows, "\n") + "\n") + } + b.WriteString("\n" + statusSchemaEnd) + return b.String() +} + +func upperFirst(s string) string { + if s == "" { + return s + } + return strings.ToUpper(s[:1]) + s[1:] +} + +// The status schema document lists every field the status routes return, +// generated from the Go types and their field comments. A field added, +// removed or renamed without regenerating the document fails here. +func TestStatusSchemaDoc(t *testing.T) { + want := generateStatusSchema(t) + raw, err := os.ReadFile(statusSchemaDoc) + if err != nil { + t.Fatal(err) + } + doc := strings.ReplaceAll(string(raw), "\r\n", "\n") + i, j := strings.Index(doc, statusSchemaBegin), strings.Index(doc, statusSchemaEnd) + if i < 0 || j < i { + t.Fatalf("%s has no generated block", statusSchemaDoc) + } + got := doc[i : j+len(statusSchemaEnd)] + if got == want { + return + } + if os.Getenv("STATUS_SCHEMA_UPDATE") == "1" { + if err := os.WriteFile(statusSchemaDoc, []byte(doc[:i]+want+doc[j+len(statusSchemaEnd):]), 0o644); err != nil { + t.Fatal(err) + } + return + } + gl, wl := strings.Split(got, "\n"), strings.Split(want, "\n") + for k := 0; k < len(gl) || k < len(wl); k++ { + var g, w string + if k < len(gl) { + g = gl[k] + } + if k < len(wl) { + w = wl[k] + } + if g != w { + t.Fatalf("%s is out of date at line %d of the generated block:\n doc: %s\n code: %s\nregenerate with STATUS_SCHEMA_UPDATE=1", statusSchemaDoc, k+1, g, w) + } + } +} + +// The restated bodies of /status/peers and /status/durable keep the +// handlers' field names and types. +func TestStatusBodiesMatchTheRoutes(t *testing.T) { + fields := func(v any) []string { + var out []string + ty := reflect.TypeOf(v) + for i := 0; i < ty.NumField(); i++ { + out = append(out, ty.Field(i).Name+":"+ty.Field(i).Type.String()) + } + sort.Strings(out) + return out + } + src, err := os.ReadFile("status_server.go") + if err != nil { + t.Fatal(err) + } + s := string(src) + for _, f := range append(fields(peersStatusBody{}), fields(durableStatusBody{})...) { + name, typ, _ := strings.Cut(f, ":") + typ = strings.TrimPrefix(typ, "volume.") + if !strings.Contains(s, "\t\t"+name+" ") || !strings.Contains(s, typ) { + t.Errorf("status_server.go no longer declares body field %s %s", name, typ) + } + } +} + +// Every /status route the server registers is in the schema. +func TestStatusSchemaCoversEveryRoute(t *testing.T) { + listed := map[string]bool{} + for _, r := range statusRoutes { + listed[r.route] = true + } + for _, file := range []string{"status_server.go", "chunk_control.go"} { + src, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + for _, line := range strings.Split(string(src), "\n") { + i := strings.Index(line, `HandleFunc("/status`) + if i < 0 { + continue + } + route := line[i+len(`HandleFunc("`):] + route = route[:strings.Index(route, `"`)] + if !listed[route] { + t.Errorf("%s registers %s, which docs/status-schema.md does not cover", file, route) + } + } + } +} diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index e8fa35391e..eda1faaa63 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -131,39 +131,39 @@ type RuntimeRebuildResult struct { } type FrontendTransportCapability struct { - Protocol string `json:"protocol"` - Transport string `json:"transport"` - Supported bool `json:"supported"` - ListenerImplemented bool `json:"listenerImplemented"` - ListenerStarted bool `json:"listenerStarted"` - StartAllowed bool `json:"startAllowed"` - StartReason string `json:"startReason,omitempty"` - Reason string `json:"reason"` - Preflight []FrontendTransportPreflightFact `json:"preflight,omitempty"` + Protocol string `json:"protocol"` // the block protocol (iscsi, nvme, ublk) + Transport string `json:"transport"` // its transport (tcp, rdma, local) + Supported bool `json:"supported"` // this build and host can serve it + ListenerImplemented bool `json:"listenerImplemented"` // a listener exists for it in this binary + ListenerStarted bool `json:"listenerStarted"` // the listener is running now + StartAllowed bool `json:"startAllowed"` // the preflight checks allow starting it + StartReason string `json:"startReason,omitempty"` // why it may or may not start + Reason string `json:"reason"` // why it is or is not supported + Preflight []FrontendTransportPreflightFact `json:"preflight,omitempty"` // the host facts checked for it } type FrontendTransportPreflightFact struct { - Name string `json:"name"` - Available bool `json:"available"` - Reason string `json:"reason"` - Detail string `json:"detail,omitempty"` + Name string `json:"name"` // the host fact checked (a module, device or privilege) + Available bool `json:"available"` // the fact holds on this host + Reason string `json:"reason"` // why it holds or not + Detail string `json:"detail,omitempty"` // extra detail, such as the path probed } type FrontendCapabilitiesStatus struct { - VolumeID string `json:"volumeID"` - HostCapabilityIsProductClaim bool `json:"hostCapabilityIsProductClaim"` - FrontendTransports []FrontendTransportCapability `json:"frontendTransports"` + VolumeID string `json:"volumeID"` // the served volume + HostCapabilityIsProductClaim bool `json:"hostCapabilityIsProductClaim"` // always false: host facts, not a supported-product claim + FrontendTransports []FrontendTransportCapability `json:"frontendTransports"` // one entry per protocol and transport } type NVMeStatus struct { - VolumeID string `json:"volumeID"` - Stats nvme.Stats `json:"stats"` + VolumeID string `json:"volumeID"` // the served volume + Stats nvme.Stats `json:"stats"` // the NVMe/TCP target's counters since start } // UblkStatus is the /status/ublk body: the ublk device's request counters. type UblkStatus struct { - VolumeID string `json:"volumeID"` - Stats ublk.Stats `json:"stats"` + VolumeID string `json:"volumeID"` // the served volume + Stats ublk.Stats `json:"stats"` // the ublk device's request counters since start } const ( @@ -184,10 +184,16 @@ const ( // replica readiness from authority movement. type StatusProjection struct { frontend.Projection - Memory ProcessMemoryStatus + // Memory is the process's memory use at the time of the request. + Memory ProcessMemoryStatus + // FrontendPrimaryReady: this replica is the healthy, non-superseded + // primary and may serve guest I/O. FrontendPrimaryReady bool - AuthorityRole string - ReplicationRole string + // AuthorityRole is primary, superseded or unknown. + AuthorityRole string + // ReplicationRole is none (a primary), recovering, not_ready, + // replica_ready or unknown. + ReplicationRole string // RoleAdmissionFailure (G1) explains a not-Healthy projection caused // by a failed role call on the replica listener; empty otherwise. RoleAdmissionFailure string `json:",omitempty"` diff --git a/seaweed-block/core/iolatency/latency.go b/seaweed-block/core/iolatency/latency.go index 21a2a82688..c722f6000b 100644 --- a/seaweed-block/core/iolatency/latency.go +++ b/seaweed-block/core/iolatency/latency.go @@ -16,11 +16,11 @@ type Histogram struct { sum atomic.Uint64 } type Distribution struct { - Count uint64 - SumNanos uint64 - P50UpperNanos uint64 - P99UpperNanos uint64 - Buckets [64]uint64 + Count uint64 // samples observed + SumNanos uint64 // their total nanoseconds + P50UpperNanos uint64 // upper bound of the bucket holding the median + P99UpperNanos uint64 // upper bound of the bucket holding the 99th percentile + Buckets [64]uint64 // bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns } func (h *Histogram) Observe(d time.Duration) { @@ -69,16 +69,16 @@ type Requests struct { writes, flushes, fua, failed atomic.Uint64 } type RequestStatus struct { - WriteTotal Distribution - FlushTotal Distribution - FUATotal Distribution - ReceiveToBackend Distribution - AckDispatch Distribution - RequestTotal Distribution - Writes uint64 - Flushes uint64 - FUAWrites uint64 - Failed uint64 + WriteTotal Distribution // end-to-end latency of writes + FlushTotal Distribution // end-to-end latency of flushes + FUATotal Distribution // end-to-end latency of forced-unit-access writes + ReceiveToBackend Distribution // from request receipt to the backend call + AckDispatch Distribution // from backend completion to the acknowledgement sent + RequestTotal Distribution // end-to-end latency of every request + Writes uint64 // writes observed + Flushes uint64 // flushes observed + FUAWrites uint64 // forced-unit-access writes observed + Failed uint64 // requests that completed with an error } func (c *Requests) Snapshot() RequestStatus { diff --git a/seaweed-block/core/recovery/receiver_install_format_v3_test.go b/seaweed-block/core/recovery/receiver_install_format_v3_test.go index 907aaf6fbd..2a838cfd6a 100644 --- a/seaweed-block/core/recovery/receiver_install_format_v3_test.go +++ b/seaweed-block/core/recovery/receiver_install_format_v3_test.go @@ -15,13 +15,12 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) -// Plan row 9b controls (DESIGN r17.3.1 section 8.7): the dual-lane Receiver -// on a dark v3 store. Every BASE block and WAL entry goes through the -// session's install handle; both admission schedules run through the real -// receiver (WriteBase through frameBaseBlock, ApplyInstallEntry through -// RebuildSession.ApplyWALEntry from frameWALEntry). Owner: claude03. -// Mutants are the row 9a store mutants (shared-begin, no-id-check, -// premature-check) plus the row 9b caller mutants named per control. +// Controls for the dual-lane Receiver on a dark v3 store. Every BASE block +// and WAL entry goes through the session's install handle; both admission +// schedules run through the real receiver (WriteBase through frameBaseBlock, +// ApplyInstallEntry through RebuildSession.ApplyWALEntry from frameWALEntry). +// Mutants are the store mutants (shared-begin, no-id-check, premature-check) +// plus the caller mutants named per control. const v3RecvBlock = 4096 @@ -182,7 +181,7 @@ func TestReceiverV3InstallThroughTheHandle(t *testing.T) { } } -// Drain setup through the receiver (codex01 r12 P2): A's admitted BASE +// Drain setup through the receiver: A's admitted BASE // write is held; B's SessionStart begin waits for it; B writes the target // block and stays installing; a further A frame fails A's session with // ErrInstallSuperseded and B's block is byte-identical. @@ -248,7 +247,7 @@ func TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession(t *testing.T) { } } -// Premature-check setup through the receiver (codex03 r11): A's frame parks +// Premature-check setup through the receiver: A's frame parks // before acquiring installMu; B supersedes, writes the target block and // stays installing; A resumes and its session fails with // ErrInstallSuperseded, B's block byte-identical. WriteBase runs through @@ -311,7 +310,7 @@ func TestReceiverV3SupersededBaseDoneFailsWithoutAnAck(t *testing.T) { } } -// codex01 row 9b P1: the real Sender sends BaseDone from its base lane while +// The real Sender sends BaseDone from its base lane while // its WAL lane is still sending (sender.go base goroutine). A WAL entry of // the same session after BaseDone must still apply, and the barrier then // completes with both lanes' bytes. Mutant: admitting install-lane WAL diff --git a/seaweed-block/core/replication/peer.go b/seaweed-block/core/replication/peer.go index 6280721502..42dfadcedc 100644 --- a/seaweed-block/core/replication/peer.go +++ b/seaweed-block/core/replication/peer.go @@ -178,15 +178,15 @@ type ReplicaPeer struct { // append-only: status endpoints and TestOps gates use it to assert // peer recovery state without scraping logs. type ReplicaPeerStatus struct { - ReplicaID string - State string - Epoch uint64 - EndpointVersion uint64 - DataAddr string - CtrlAddr string - SessionID uint64 - ProbeInFlight bool - Closed bool + ReplicaID string // the peer replica + State string // the peer state (the replica peer table, M3) + Epoch uint64 // the epoch the peer was assigned at + EndpointVersion uint64 // the peer's endpoint version within the epoch + DataAddr string // the peer's data-path address + CtrlAddr string // the peer's control-path address + SessionID uint64 // the current recovery or shipping session; 0 when none + ProbeInFlight bool // a reachability probe of the peer is running + Closed bool // the peer handle was closed (it no longer ships) } // NewReplicaPeer constructs a per-replica runtime handle and registers diff --git a/seaweed-block/core/rpc/control/workspace.pb.go b/seaweed-block/core/rpc/control/workspace.pb.go index af8db26e4b..29fd611ef7 100644 --- a/seaweed-block/core/rpc/control/workspace.pb.go +++ b/seaweed-block/core/rpc/control/workspace.pb.go @@ -414,21 +414,26 @@ func (x *WorkspaceMove) GetTargetServerId() string { } type WorkspaceGrant struct { - state protoimpl.MessageState `protogen:"open.v1"` - RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` - VolumeId string `protobuf:"bytes,2,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` - OldReplicaId string `protobuf:"bytes,3,opt,name=old_replica_id,json=oldReplicaId,proto3" json:"old_replica_id,omitempty"` - NewReplicaId string `protobuf:"bytes,4,opt,name=new_replica_id,json=newReplicaId,proto3" json:"new_replica_id,omitempty"` - Kind string `protobuf:"bytes,5,opt,name=kind,proto3" json:"kind,omitempty"` - OldEpoch uint64 `protobuf:"varint,6,opt,name=old_epoch,json=oldEpoch,proto3" json:"old_epoch,omitempty"` - NewEpoch uint64 `protobuf:"varint,7,opt,name=new_epoch,json=newEpoch,proto3" json:"new_epoch,omitempty"` - HeadGen uint64 `protobuf:"varint,8,opt,name=head_gen,json=headGen,proto3" json:"head_gen,omitempty"` - RemoteLsn uint64 `protobuf:"varint,9,opt,name=remote_lsn,json=remoteLsn,proto3" json:"remote_lsn,omitempty"` - Issued bool `protobuf:"varint,10,opt,name=issued,proto3" json:"issued,omitempty"` - OldHost string `protobuf:"bytes,11,opt,name=old_host,json=oldHost,proto3" json:"old_host,omitempty"` - NewHost string `protobuf:"bytes,12,opt,name=new_host,json=newHost,proto3" json:"new_host,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + VolumeId string `protobuf:"bytes,2,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` + OldReplicaId string `protobuf:"bytes,3,opt,name=old_replica_id,json=oldReplicaId,proto3" json:"old_replica_id,omitempty"` + NewReplicaId string `protobuf:"bytes,4,opt,name=new_replica_id,json=newReplicaId,proto3" json:"new_replica_id,omitempty"` + Kind string `protobuf:"bytes,5,opt,name=kind,proto3" json:"kind,omitempty"` + OldEpoch uint64 `protobuf:"varint,6,opt,name=old_epoch,json=oldEpoch,proto3" json:"old_epoch,omitempty"` + NewEpoch uint64 `protobuf:"varint,7,opt,name=new_epoch,json=newEpoch,proto3" json:"new_epoch,omitempty"` + HeadGen uint64 `protobuf:"varint,8,opt,name=head_gen,json=headGen,proto3" json:"head_gen,omitempty"` + RemoteLsn uint64 `protobuf:"varint,9,opt,name=remote_lsn,json=remoteLsn,proto3" json:"remote_lsn,omitempty"` + Issued bool `protobuf:"varint,10,opt,name=issued,proto3" json:"issued,omitempty"` + OldHost string `protobuf:"bytes,11,opt,name=old_host,json=oldHost,proto3" json:"old_host,omitempty"` + NewHost string `protobuf:"bytes,12,opt,name=new_host,json=newHost,proto3" json:"new_host,omitempty"` + // Forced grants only: the lost range stored before the issue (also on a + // replay). Absent on a forced grant means the readout is not proven, and + // lost_range_error says why; it never means "no loss". + LostRange *WorkspaceLostRange `protobuf:"bytes,13,opt,name=lost_range,json=lostRange,proto3" json:"lost_range,omitempty"` + LostRangeError string `protobuf:"bytes,14,opt,name=lost_range_error,json=lostRangeError,proto3" json:"lost_range_error,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *WorkspaceGrant) Reset() { @@ -545,6 +550,370 @@ func (x *WorkspaceGrant) GetNewHost() string { return "" } +func (x *WorkspaceGrant) GetLostRange() *WorkspaceLostRange { + if x != nil { + return x.LostRange + } + return nil +} + +func (x *WorkspaceGrant) GetLostRangeError() string { + if x != nil { + return x.LostRangeError + } + return "" +} + +// What a forced move abandoned. head_gen 0: no published HEAD (everything the +// old holder wrote is lost). head_time_ns is the HEAD entry's filer mtime read +// with HEAD at the move (1 s resolution), valid only when head_time_known. +// lost_until_ns is master time; the upper bound is a time, not an LSN. +type WorkspaceLostRange struct { + state protoimpl.MessageState `protogen:"open.v1"` + RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + VolumeId string `protobuf:"bytes,2,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` + NewEpoch uint64 `protobuf:"varint,3,opt,name=new_epoch,json=newEpoch,proto3" json:"new_epoch,omitempty"` + OldReplicaId string `protobuf:"bytes,4,opt,name=old_replica_id,json=oldReplicaId,proto3" json:"old_replica_id,omitempty"` + OldEpoch uint64 `protobuf:"varint,5,opt,name=old_epoch,json=oldEpoch,proto3" json:"old_epoch,omitempty"` + LostAfterLsn uint64 `protobuf:"varint,6,opt,name=lost_after_lsn,json=lostAfterLsn,proto3" json:"lost_after_lsn,omitempty"` + LostUntilNs int64 `protobuf:"varint,7,opt,name=lost_until_ns,json=lostUntilNs,proto3" json:"lost_until_ns,omitempty"` + HeadGen uint64 `protobuf:"varint,8,opt,name=head_gen,json=headGen,proto3" json:"head_gen,omitempty"` + HeadTimeNs int64 `protobuf:"varint,9,opt,name=head_time_ns,json=headTimeNs,proto3" json:"head_time_ns,omitempty"` + HeadTimeKnown bool `protobuf:"varint,10,opt,name=head_time_known,json=headTimeKnown,proto3" json:"head_time_known,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkspaceLostRange) Reset() { + *x = WorkspaceLostRange{} + mi := &file_workspace_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkspaceLostRange) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkspaceLostRange) ProtoMessage() {} + +func (x *WorkspaceLostRange) ProtoReflect() protoreflect.Message { + mi := &file_workspace_proto_msgTypes[7] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkspaceLostRange.ProtoReflect.Descriptor instead. +func (*WorkspaceLostRange) Descriptor() ([]byte, []int) { + return file_workspace_proto_rawDescGZIP(), []int{7} +} + +func (x *WorkspaceLostRange) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + +func (x *WorkspaceLostRange) GetVolumeId() string { + if x != nil { + return x.VolumeId + } + return "" +} + +func (x *WorkspaceLostRange) GetNewEpoch() uint64 { + if x != nil { + return x.NewEpoch + } + return 0 +} + +func (x *WorkspaceLostRange) GetOldReplicaId() string { + if x != nil { + return x.OldReplicaId + } + return "" +} + +func (x *WorkspaceLostRange) GetOldEpoch() uint64 { + if x != nil { + return x.OldEpoch + } + return 0 +} + +func (x *WorkspaceLostRange) GetLostAfterLsn() uint64 { + if x != nil { + return x.LostAfterLsn + } + return 0 +} + +func (x *WorkspaceLostRange) GetLostUntilNs() int64 { + if x != nil { + return x.LostUntilNs + } + return 0 +} + +func (x *WorkspaceLostRange) GetHeadGen() uint64 { + if x != nil { + return x.HeadGen + } + return 0 +} + +func (x *WorkspaceLostRange) GetHeadTimeNs() int64 { + if x != nil { + return x.HeadTimeNs + } + return 0 +} + +func (x *WorkspaceLostRange) GetHeadTimeKnown() bool { + if x != nil { + return x.HeadTimeKnown + } + return false +} + +type WorkspaceLostRangeQuery struct { + state protoimpl.MessageState `protogen:"open.v1"` + VolumeId string `protobuf:"bytes,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` + RequestId string `protobuf:"bytes,2,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkspaceLostRangeQuery) Reset() { + *x = WorkspaceLostRangeQuery{} + mi := &file_workspace_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkspaceLostRangeQuery) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkspaceLostRangeQuery) ProtoMessage() {} + +func (x *WorkspaceLostRangeQuery) ProtoReflect() protoreflect.Message { + mi := &file_workspace_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkspaceLostRangeQuery.ProtoReflect.Descriptor instead. +func (*WorkspaceLostRangeQuery) Descriptor() ([]byte, []int) { + return file_workspace_proto_rawDescGZIP(), []int{8} +} + +func (x *WorkspaceLostRangeQuery) GetVolumeId() string { + if x != nil { + return x.VolumeId + } + return "" +} + +func (x *WorkspaceLostRangeQuery) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + +type WorkspaceLostRanges struct { + state protoimpl.MessageState `protogen:"open.v1"` + Ranges []*WorkspaceLostRange `protobuf:"bytes,1,rep,name=ranges,proto3" json:"ranges,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkspaceLostRanges) Reset() { + *x = WorkspaceLostRanges{} + mi := &file_workspace_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkspaceLostRanges) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkspaceLostRanges) ProtoMessage() {} + +func (x *WorkspaceLostRanges) ProtoReflect() protoreflect.Message { + mi := &file_workspace_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkspaceLostRanges.ProtoReflect.Descriptor instead. +func (*WorkspaceLostRanges) Descriptor() ([]byte, []int) { + return file_workspace_proto_rawDescGZIP(), []int{9} +} + +func (x *WorkspaceLostRanges) GetRanges() []*WorkspaceLostRange { + if x != nil { + return x.Ranges + } + return nil +} + +// lost_until_ns is when a forced move becomes admissible (0 if the master has +// no lease to judge). HEAD is read only when admitted, as for the move. +type WorkspaceMovePreview struct { + state protoimpl.MessageState `protogen:"open.v1"` + Admitted bool `protobuf:"varint,1,opt,name=admitted,proto3" json:"admitted,omitempty"` + Reason string `protobuf:"bytes,2,opt,name=reason,proto3" json:"reason,omitempty"` + LostUntilNs int64 `protobuf:"varint,3,opt,name=lost_until_ns,json=lostUntilNs,proto3" json:"lost_until_ns,omitempty"` + MasterTimeNs int64 `protobuf:"varint,4,opt,name=master_time_ns,json=masterTimeNs,proto3" json:"master_time_ns,omitempty"` + HeadRead bool `protobuf:"varint,5,opt,name=head_read,json=headRead,proto3" json:"head_read,omitempty"` + HeadError string `protobuf:"bytes,6,opt,name=head_error,json=headError,proto3" json:"head_error,omitempty"` + HeadGen uint64 `protobuf:"varint,7,opt,name=head_gen,json=headGen,proto3" json:"head_gen,omitempty"` + HeadEpoch uint64 `protobuf:"varint,8,opt,name=head_epoch,json=headEpoch,proto3" json:"head_epoch,omitempty"` + HeadHolder string `protobuf:"bytes,9,opt,name=head_holder,json=headHolder,proto3" json:"head_holder,omitempty"` + HeadRemoteLsn uint64 `protobuf:"varint,10,opt,name=head_remote_lsn,json=headRemoteLsn,proto3" json:"head_remote_lsn,omitempty"` + HeadTimeNs int64 `protobuf:"varint,11,opt,name=head_time_ns,json=headTimeNs,proto3" json:"head_time_ns,omitempty"` + HeadTimeKnown bool `protobuf:"varint,12,opt,name=head_time_known,json=headTimeKnown,proto3" json:"head_time_known,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkspaceMovePreview) Reset() { + *x = WorkspaceMovePreview{} + mi := &file_workspace_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkspaceMovePreview) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkspaceMovePreview) ProtoMessage() {} + +func (x *WorkspaceMovePreview) ProtoReflect() protoreflect.Message { + mi := &file_workspace_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkspaceMovePreview.ProtoReflect.Descriptor instead. +func (*WorkspaceMovePreview) Descriptor() ([]byte, []int) { + return file_workspace_proto_rawDescGZIP(), []int{10} +} + +func (x *WorkspaceMovePreview) GetAdmitted() bool { + if x != nil { + return x.Admitted + } + return false +} + +func (x *WorkspaceMovePreview) GetReason() string { + if x != nil { + return x.Reason + } + return "" +} + +func (x *WorkspaceMovePreview) GetLostUntilNs() int64 { + if x != nil { + return x.LostUntilNs + } + return 0 +} + +func (x *WorkspaceMovePreview) GetMasterTimeNs() int64 { + if x != nil { + return x.MasterTimeNs + } + return 0 +} + +func (x *WorkspaceMovePreview) GetHeadRead() bool { + if x != nil { + return x.HeadRead + } + return false +} + +func (x *WorkspaceMovePreview) GetHeadError() string { + if x != nil { + return x.HeadError + } + return "" +} + +func (x *WorkspaceMovePreview) GetHeadGen() uint64 { + if x != nil { + return x.HeadGen + } + return 0 +} + +func (x *WorkspaceMovePreview) GetHeadEpoch() uint64 { + if x != nil { + return x.HeadEpoch + } + return 0 +} + +func (x *WorkspaceMovePreview) GetHeadHolder() string { + if x != nil { + return x.HeadHolder + } + return "" +} + +func (x *WorkspaceMovePreview) GetHeadRemoteLsn() uint64 { + if x != nil { + return x.HeadRemoteLsn + } + return 0 +} + +func (x *WorkspaceMovePreview) GetHeadTimeNs() int64 { + if x != nil { + return x.HeadTimeNs + } + return 0 +} + +func (x *WorkspaceMovePreview) GetHeadTimeKnown() bool { + if x != nil { + return x.HeadTimeKnown + } + return false +} + type WorkspaceStatus struct { state protoimpl.MessageState `protogen:"open.v1"` Lease *WorkspaceLeaseFact `protobuf:"bytes,1,opt,name=lease,proto3" json:"lease,omitempty"` @@ -557,7 +926,7 @@ type WorkspaceStatus struct { func (x *WorkspaceStatus) Reset() { *x = WorkspaceStatus{} - mi := &file_workspace_proto_msgTypes[7] + mi := &file_workspace_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -569,7 +938,7 @@ func (x *WorkspaceStatus) String() string { func (*WorkspaceStatus) ProtoMessage() {} func (x *WorkspaceStatus) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[7] + mi := &file_workspace_proto_msgTypes[11] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -582,7 +951,7 @@ func (x *WorkspaceStatus) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceStatus.ProtoReflect.Descriptor instead. func (*WorkspaceStatus) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{7} + return file_workspace_proto_rawDescGZIP(), []int{11} } func (x *WorkspaceStatus) GetLease() *WorkspaceLeaseFact { @@ -626,7 +995,7 @@ type WorkspaceBinding struct { func (x *WorkspaceBinding) Reset() { *x = WorkspaceBinding{} - mi := &file_workspace_proto_msgTypes[8] + mi := &file_workspace_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -638,7 +1007,7 @@ func (x *WorkspaceBinding) String() string { func (*WorkspaceBinding) ProtoMessage() {} func (x *WorkspaceBinding) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[8] + mi := &file_workspace_proto_msgTypes[12] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -651,7 +1020,7 @@ func (x *WorkspaceBinding) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceBinding.ProtoReflect.Descriptor instead. func (*WorkspaceBinding) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{8} + return file_workspace_proto_rawDescGZIP(), []int{12} } func (x *WorkspaceBinding) GetVolumeId() string { @@ -700,7 +1069,7 @@ type WorkspacePlacement struct { func (x *WorkspacePlacement) Reset() { *x = WorkspacePlacement{} - mi := &file_workspace_proto_msgTypes[9] + mi := &file_workspace_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -712,7 +1081,7 @@ func (x *WorkspacePlacement) String() string { func (*WorkspacePlacement) ProtoMessage() {} func (x *WorkspacePlacement) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[9] + mi := &file_workspace_proto_msgTypes[13] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -725,7 +1094,7 @@ func (x *WorkspacePlacement) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspacePlacement.ProtoReflect.Descriptor instead. func (*WorkspacePlacement) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{9} + return file_workspace_proto_rawDescGZIP(), []int{13} } func (x *WorkspacePlacement) GetVolumeId() string { @@ -786,7 +1155,7 @@ const file_workspace_proto_rawDesc = "" + "\x04kind\x18\b \x01(\tR\x04kind\x12\x14\n" + "\x05force\x18\t \x01(\bR\x05force\x12(\n" + "\x10target_server_id\x18\n" + - " \x01(\tR\x0etargetServerId\"\xee\x02\n" + + " \x01(\tR\x0etargetServerId\"\xe4\x03\n" + "\x0eWorkspaceGrant\x12\x1d\n" + "\n" + "request_id\x18\x01 \x01(\tR\trequestId\x12\x1b\n" + @@ -802,7 +1171,48 @@ const file_workspace_proto_rawDesc = "" + "\x06issued\x18\n" + " \x01(\bR\x06issued\x12\x19\n" + "\bold_host\x18\v \x01(\tR\aoldHost\x12\x19\n" + - "\bnew_host\x18\f \x01(\tR\anewHost\"\xb2\x02\n" + + "\bnew_host\x18\f \x01(\tR\anewHost\x12J\n" + + "\n" + + "lost_range\x18\r \x01(\v2+.seaweedfs.block.control.WorkspaceLostRangeR\tlostRange\x12(\n" + + "\x10lost_range_error\x18\x0e \x01(\tR\x0elostRangeError\"\xdf\x02\n" + + "\x12WorkspaceLostRange\x12\x1d\n" + + "\n" + + "request_id\x18\x01 \x01(\tR\trequestId\x12\x1b\n" + + "\tvolume_id\x18\x02 \x01(\tR\bvolumeId\x12\x1b\n" + + "\tnew_epoch\x18\x03 \x01(\x04R\bnewEpoch\x12$\n" + + "\x0eold_replica_id\x18\x04 \x01(\tR\foldReplicaId\x12\x1b\n" + + "\told_epoch\x18\x05 \x01(\x04R\boldEpoch\x12$\n" + + "\x0elost_after_lsn\x18\x06 \x01(\x04R\flostAfterLsn\x12\"\n" + + "\rlost_until_ns\x18\a \x01(\x03R\vlostUntilNs\x12\x19\n" + + "\bhead_gen\x18\b \x01(\x04R\aheadGen\x12 \n" + + "\fhead_time_ns\x18\t \x01(\x03R\n" + + "headTimeNs\x12&\n" + + "\x0fhead_time_known\x18\n" + + " \x01(\bR\rheadTimeKnown\"U\n" + + "\x17WorkspaceLostRangeQuery\x12\x1b\n" + + "\tvolume_id\x18\x01 \x01(\tR\bvolumeId\x12\x1d\n" + + "\n" + + "request_id\x18\x02 \x01(\tR\trequestId\"Z\n" + + "\x13WorkspaceLostRanges\x12C\n" + + "\x06ranges\x18\x01 \x03(\v2+.seaweedfs.block.control.WorkspaceLostRangeR\x06ranges\"\x9d\x03\n" + + "\x14WorkspaceMovePreview\x12\x1a\n" + + "\badmitted\x18\x01 \x01(\bR\badmitted\x12\x16\n" + + "\x06reason\x18\x02 \x01(\tR\x06reason\x12\"\n" + + "\rlost_until_ns\x18\x03 \x01(\x03R\vlostUntilNs\x12$\n" + + "\x0emaster_time_ns\x18\x04 \x01(\x03R\fmasterTimeNs\x12\x1b\n" + + "\thead_read\x18\x05 \x01(\bR\bheadRead\x12\x1d\n" + + "\n" + + "head_error\x18\x06 \x01(\tR\theadError\x12\x19\n" + + "\bhead_gen\x18\a \x01(\x04R\aheadGen\x12\x1d\n" + + "\n" + + "head_epoch\x18\b \x01(\x04R\theadEpoch\x12\x1f\n" + + "\vhead_holder\x18\t \x01(\tR\n" + + "headHolder\x12&\n" + + "\x0fhead_remote_lsn\x18\n" + + " \x01(\x04R\rheadRemoteLsn\x12 \n" + + "\fhead_time_ns\x18\v \x01(\x03R\n" + + "headTimeNs\x12&\n" + + "\x0fhead_time_known\x18\f \x01(\bR\rheadTimeKnown\"\xb2\x02\n" + "\x0fWorkspaceStatus\x12A\n" + "\x05lease\x18\x01 \x01(\v2+.seaweedfs.block.control.WorkspaceLeaseFactR\x05lease\x12V\n" + "\x0erevocation_ack\x18\x02 \x01(\v2/.seaweedfs.block.control.WorkspaceRevocationAckR\rrevocationAck\x12=\n" + @@ -818,7 +1228,7 @@ const file_workspace_proto_rawDesc = "" + "\tvolume_id\x18\x01 \x01(\tR\bvolumeId\x12\x1b\n" + "\tserver_id\x18\x02 \x01(\tR\bserverId\x12\x1d\n" + "\n" + - "replica_id\x18\x03 \x01(\tR\treplicaId2\x81\x06\n" + + "replica_id\x18\x03 \x01(\tR\treplicaId2\xeb\a\n" + "\x10WorkspaceService\x12p\n" + "\x18RegisterWorkspaceBinding\x12).seaweedfs.block.control.WorkspaceBinding\x1a).seaweedfs.block.control.WorkspaceBinding\x12f\n" + "\x0ePlaceWorkspace\x12+.seaweedfs.block.control.WorkspacePlacement\x1a'.seaweedfs.block.control.WorkspaceEmpty\x12n\n" + @@ -826,7 +1236,9 @@ const file_workspace_proto_rawDesc = "" + "\x0fRevokeWorkspace\x12*.seaweedfs.block.control.WorkspaceIdentity\x1a+.seaweedfs.block.control.WorkspaceLeaseFact\x12o\n" + "\x13AckWorkspaceRevoked\x12/.seaweedfs.block.control.WorkspaceRevocationAck\x1a'.seaweedfs.block.control.WorkspaceEmpty\x12`\n" + "\rMoveWorkspace\x12&.seaweedfs.block.control.WorkspaceMove\x1a'.seaweedfs.block.control.WorkspaceGrant\x12d\n" + - "\x0eQueryWorkspace\x12(.seaweedfs.block.control.WorkspaceVolume\x1a(.seaweedfs.block.control.WorkspaceStatusB=Z;github.com/seaweedfs/seaweed-block/core/rpc/control;controlb\x06proto3" + "\x0eQueryWorkspace\x12(.seaweedfs.block.control.WorkspaceVolume\x1a(.seaweedfs.block.control.WorkspaceStatus\x12y\n" + + "\x17QueryWorkspaceLostRange\x120.seaweedfs.block.control.WorkspaceLostRangeQuery\x1a,.seaweedfs.block.control.WorkspaceLostRanges\x12m\n" + + "\x14PreviewWorkspaceMove\x12&.seaweedfs.block.control.WorkspaceMove\x1a-.seaweedfs.block.control.WorkspaceMovePreviewB=Z;github.com/seaweedfs/seaweed-block/core/rpc/control;controlb\x06proto3" var ( file_workspace_proto_rawDescOnce sync.Once @@ -840,44 +1252,54 @@ func file_workspace_proto_rawDescGZIP() []byte { return file_workspace_proto_rawDescData } -var file_workspace_proto_msgTypes = make([]protoimpl.MessageInfo, 10) +var file_workspace_proto_msgTypes = make([]protoimpl.MessageInfo, 14) var file_workspace_proto_goTypes = []any{ - (*WorkspaceIdentity)(nil), // 0: seaweedfs.block.control.WorkspaceIdentity - (*WorkspaceVolume)(nil), // 1: seaweedfs.block.control.WorkspaceVolume - (*WorkspaceEmpty)(nil), // 2: seaweedfs.block.control.WorkspaceEmpty - (*WorkspaceLeaseFact)(nil), // 3: seaweedfs.block.control.WorkspaceLeaseFact - (*WorkspaceRevocationAck)(nil), // 4: seaweedfs.block.control.WorkspaceRevocationAck - (*WorkspaceMove)(nil), // 5: seaweedfs.block.control.WorkspaceMove - (*WorkspaceGrant)(nil), // 6: seaweedfs.block.control.WorkspaceGrant - (*WorkspaceStatus)(nil), // 7: seaweedfs.block.control.WorkspaceStatus - (*WorkspaceBinding)(nil), // 8: seaweedfs.block.control.WorkspaceBinding - (*WorkspacePlacement)(nil), // 9: seaweedfs.block.control.WorkspacePlacement + (*WorkspaceIdentity)(nil), // 0: seaweedfs.block.control.WorkspaceIdentity + (*WorkspaceVolume)(nil), // 1: seaweedfs.block.control.WorkspaceVolume + (*WorkspaceEmpty)(nil), // 2: seaweedfs.block.control.WorkspaceEmpty + (*WorkspaceLeaseFact)(nil), // 3: seaweedfs.block.control.WorkspaceLeaseFact + (*WorkspaceRevocationAck)(nil), // 4: seaweedfs.block.control.WorkspaceRevocationAck + (*WorkspaceMove)(nil), // 5: seaweedfs.block.control.WorkspaceMove + (*WorkspaceGrant)(nil), // 6: seaweedfs.block.control.WorkspaceGrant + (*WorkspaceLostRange)(nil), // 7: seaweedfs.block.control.WorkspaceLostRange + (*WorkspaceLostRangeQuery)(nil), // 8: seaweedfs.block.control.WorkspaceLostRangeQuery + (*WorkspaceLostRanges)(nil), // 9: seaweedfs.block.control.WorkspaceLostRanges + (*WorkspaceMovePreview)(nil), // 10: seaweedfs.block.control.WorkspaceMovePreview + (*WorkspaceStatus)(nil), // 11: seaweedfs.block.control.WorkspaceStatus + (*WorkspaceBinding)(nil), // 12: seaweedfs.block.control.WorkspaceBinding + (*WorkspacePlacement)(nil), // 13: seaweedfs.block.control.WorkspacePlacement } var file_workspace_proto_depIdxs = []int32{ 0, // 0: seaweedfs.block.control.WorkspaceRevocationAck.identity:type_name -> seaweedfs.block.control.WorkspaceIdentity - 3, // 1: seaweedfs.block.control.WorkspaceStatus.lease:type_name -> seaweedfs.block.control.WorkspaceLeaseFact - 4, // 2: seaweedfs.block.control.WorkspaceStatus.revocation_ack:type_name -> seaweedfs.block.control.WorkspaceRevocationAck - 6, // 3: seaweedfs.block.control.WorkspaceStatus.moves:type_name -> seaweedfs.block.control.WorkspaceGrant - 8, // 4: seaweedfs.block.control.WorkspaceStatus.bindings:type_name -> seaweedfs.block.control.WorkspaceBinding - 8, // 5: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:input_type -> seaweedfs.block.control.WorkspaceBinding - 9, // 6: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:input_type -> seaweedfs.block.control.WorkspacePlacement - 0, // 7: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:input_type -> seaweedfs.block.control.WorkspaceIdentity - 0, // 8: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:input_type -> seaweedfs.block.control.WorkspaceIdentity - 4, // 9: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:input_type -> seaweedfs.block.control.WorkspaceRevocationAck - 5, // 10: seaweedfs.block.control.WorkspaceService.MoveWorkspace:input_type -> seaweedfs.block.control.WorkspaceMove - 1, // 11: seaweedfs.block.control.WorkspaceService.QueryWorkspace:input_type -> seaweedfs.block.control.WorkspaceVolume - 8, // 12: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:output_type -> seaweedfs.block.control.WorkspaceBinding - 2, // 13: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:output_type -> seaweedfs.block.control.WorkspaceEmpty - 3, // 14: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:output_type -> seaweedfs.block.control.WorkspaceLeaseFact - 3, // 15: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:output_type -> seaweedfs.block.control.WorkspaceLeaseFact - 2, // 16: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:output_type -> seaweedfs.block.control.WorkspaceEmpty - 6, // 17: seaweedfs.block.control.WorkspaceService.MoveWorkspace:output_type -> seaweedfs.block.control.WorkspaceGrant - 7, // 18: seaweedfs.block.control.WorkspaceService.QueryWorkspace:output_type -> seaweedfs.block.control.WorkspaceStatus - 12, // [12:19] is the sub-list for method output_type - 5, // [5:12] is the sub-list for method input_type - 5, // [5:5] is the sub-list for extension type_name - 5, // [5:5] is the sub-list for extension extendee - 0, // [0:5] is the sub-list for field type_name + 7, // 1: seaweedfs.block.control.WorkspaceGrant.lost_range:type_name -> seaweedfs.block.control.WorkspaceLostRange + 7, // 2: seaweedfs.block.control.WorkspaceLostRanges.ranges:type_name -> seaweedfs.block.control.WorkspaceLostRange + 3, // 3: seaweedfs.block.control.WorkspaceStatus.lease:type_name -> seaweedfs.block.control.WorkspaceLeaseFact + 4, // 4: seaweedfs.block.control.WorkspaceStatus.revocation_ack:type_name -> seaweedfs.block.control.WorkspaceRevocationAck + 6, // 5: seaweedfs.block.control.WorkspaceStatus.moves:type_name -> seaweedfs.block.control.WorkspaceGrant + 12, // 6: seaweedfs.block.control.WorkspaceStatus.bindings:type_name -> seaweedfs.block.control.WorkspaceBinding + 12, // 7: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:input_type -> seaweedfs.block.control.WorkspaceBinding + 13, // 8: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:input_type -> seaweedfs.block.control.WorkspacePlacement + 0, // 9: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:input_type -> seaweedfs.block.control.WorkspaceIdentity + 0, // 10: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:input_type -> seaweedfs.block.control.WorkspaceIdentity + 4, // 11: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:input_type -> seaweedfs.block.control.WorkspaceRevocationAck + 5, // 12: seaweedfs.block.control.WorkspaceService.MoveWorkspace:input_type -> seaweedfs.block.control.WorkspaceMove + 1, // 13: seaweedfs.block.control.WorkspaceService.QueryWorkspace:input_type -> seaweedfs.block.control.WorkspaceVolume + 8, // 14: seaweedfs.block.control.WorkspaceService.QueryWorkspaceLostRange:input_type -> seaweedfs.block.control.WorkspaceLostRangeQuery + 5, // 15: seaweedfs.block.control.WorkspaceService.PreviewWorkspaceMove:input_type -> seaweedfs.block.control.WorkspaceMove + 12, // 16: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:output_type -> seaweedfs.block.control.WorkspaceBinding + 2, // 17: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:output_type -> seaweedfs.block.control.WorkspaceEmpty + 3, // 18: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:output_type -> seaweedfs.block.control.WorkspaceLeaseFact + 3, // 19: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:output_type -> seaweedfs.block.control.WorkspaceLeaseFact + 2, // 20: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:output_type -> seaweedfs.block.control.WorkspaceEmpty + 6, // 21: seaweedfs.block.control.WorkspaceService.MoveWorkspace:output_type -> seaweedfs.block.control.WorkspaceGrant + 11, // 22: seaweedfs.block.control.WorkspaceService.QueryWorkspace:output_type -> seaweedfs.block.control.WorkspaceStatus + 9, // 23: seaweedfs.block.control.WorkspaceService.QueryWorkspaceLostRange:output_type -> seaweedfs.block.control.WorkspaceLostRanges + 10, // 24: seaweedfs.block.control.WorkspaceService.PreviewWorkspaceMove:output_type -> seaweedfs.block.control.WorkspaceMovePreview + 16, // [16:25] is the sub-list for method output_type + 7, // [7:16] is the sub-list for method input_type + 7, // [7:7] is the sub-list for extension type_name + 7, // [7:7] is the sub-list for extension extendee + 0, // [0:7] is the sub-list for field type_name } func init() { file_workspace_proto_init() } @@ -891,7 +1313,7 @@ func file_workspace_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_workspace_proto_rawDesc), len(file_workspace_proto_rawDesc)), NumEnums: 0, - NumMessages: 10, + NumMessages: 14, NumExtensions: 0, NumServices: 1, }, diff --git a/seaweed-block/core/rpc/control/workspace_grpc.pb.go b/seaweed-block/core/rpc/control/workspace_grpc.pb.go index 25e43e9512..dd8830b5b7 100644 --- a/seaweed-block/core/rpc/control/workspace_grpc.pb.go +++ b/seaweed-block/core/rpc/control/workspace_grpc.pb.go @@ -26,6 +26,8 @@ const ( WorkspaceService_AckWorkspaceRevoked_FullMethodName = "/seaweedfs.block.control.WorkspaceService/AckWorkspaceRevoked" WorkspaceService_MoveWorkspace_FullMethodName = "/seaweedfs.block.control.WorkspaceService/MoveWorkspace" WorkspaceService_QueryWorkspace_FullMethodName = "/seaweedfs.block.control.WorkspaceService/QueryWorkspace" + WorkspaceService_QueryWorkspaceLostRange_FullMethodName = "/seaweedfs.block.control.WorkspaceService/QueryWorkspaceLostRange" + WorkspaceService_PreviewWorkspaceMove_FullMethodName = "/seaweedfs.block.control.WorkspaceService/PreviewWorkspaceMove" ) // WorkspaceServiceClient is the client API for WorkspaceService service. @@ -43,6 +45,13 @@ type WorkspaceServiceClient interface { AckWorkspaceRevoked(ctx context.Context, in *WorkspaceRevocationAck, opts ...grpc.CallOption) (*WorkspaceEmpty, error) MoveWorkspace(ctx context.Context, in *WorkspaceMove, opts ...grpc.CallOption) (*WorkspaceGrant, error) QueryWorkspace(ctx context.Context, in *WorkspaceVolume, opts ...grpc.CallOption) (*WorkspaceStatus, error) + // The stored lost ranges of the volume's issued forced moves, in issue + // order (or the one of request_id); never recomputed. A forced move whose + // range is missing or unreadable fails with DATA_LOSS, never "no loss". + QueryWorkspaceLostRange(ctx context.Context, in *WorkspaceLostRangeQuery, opts ...grpc.CallOption) (*WorkspaceLostRanges, error) + // Read-only forced-move admission check (no reservation, no journal + // write): advisory, re-checked by MoveWorkspace. + PreviewWorkspaceMove(ctx context.Context, in *WorkspaceMove, opts ...grpc.CallOption) (*WorkspaceMovePreview, error) } type workspaceServiceClient struct { @@ -123,6 +132,26 @@ func (c *workspaceServiceClient) QueryWorkspace(ctx context.Context, in *Workspa return out, nil } +func (c *workspaceServiceClient) QueryWorkspaceLostRange(ctx context.Context, in *WorkspaceLostRangeQuery, opts ...grpc.CallOption) (*WorkspaceLostRanges, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(WorkspaceLostRanges) + err := c.cc.Invoke(ctx, WorkspaceService_QueryWorkspaceLostRange_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *workspaceServiceClient) PreviewWorkspaceMove(ctx context.Context, in *WorkspaceMove, opts ...grpc.CallOption) (*WorkspaceMovePreview, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(WorkspaceMovePreview) + err := c.cc.Invoke(ctx, WorkspaceService_PreviewWorkspaceMove_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + // WorkspaceServiceServer is the server API for WorkspaceService service. // All implementations must embed UnimplementedWorkspaceServiceServer // for forward compatibility. @@ -138,6 +167,13 @@ type WorkspaceServiceServer interface { AckWorkspaceRevoked(context.Context, *WorkspaceRevocationAck) (*WorkspaceEmpty, error) MoveWorkspace(context.Context, *WorkspaceMove) (*WorkspaceGrant, error) QueryWorkspace(context.Context, *WorkspaceVolume) (*WorkspaceStatus, error) + // The stored lost ranges of the volume's issued forced moves, in issue + // order (or the one of request_id); never recomputed. A forced move whose + // range is missing or unreadable fails with DATA_LOSS, never "no loss". + QueryWorkspaceLostRange(context.Context, *WorkspaceLostRangeQuery) (*WorkspaceLostRanges, error) + // Read-only forced-move admission check (no reservation, no journal + // write): advisory, re-checked by MoveWorkspace. + PreviewWorkspaceMove(context.Context, *WorkspaceMove) (*WorkspaceMovePreview, error) mustEmbedUnimplementedWorkspaceServiceServer() } @@ -169,6 +205,12 @@ func (UnimplementedWorkspaceServiceServer) MoveWorkspace(context.Context, *Works func (UnimplementedWorkspaceServiceServer) QueryWorkspace(context.Context, *WorkspaceVolume) (*WorkspaceStatus, error) { return nil, status.Error(codes.Unimplemented, "method QueryWorkspace not implemented") } +func (UnimplementedWorkspaceServiceServer) QueryWorkspaceLostRange(context.Context, *WorkspaceLostRangeQuery) (*WorkspaceLostRanges, error) { + return nil, status.Error(codes.Unimplemented, "method QueryWorkspaceLostRange not implemented") +} +func (UnimplementedWorkspaceServiceServer) PreviewWorkspaceMove(context.Context, *WorkspaceMove) (*WorkspaceMovePreview, error) { + return nil, status.Error(codes.Unimplemented, "method PreviewWorkspaceMove not implemented") +} func (UnimplementedWorkspaceServiceServer) mustEmbedUnimplementedWorkspaceServiceServer() {} func (UnimplementedWorkspaceServiceServer) testEmbeddedByValue() {} @@ -316,6 +358,42 @@ func _WorkspaceService_QueryWorkspace_Handler(srv interface{}, ctx context.Conte return interceptor(ctx, in, info, handler) } +func _WorkspaceService_QueryWorkspaceLostRange_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(WorkspaceLostRangeQuery) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WorkspaceServiceServer).QueryWorkspaceLostRange(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WorkspaceService_QueryWorkspaceLostRange_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WorkspaceServiceServer).QueryWorkspaceLostRange(ctx, req.(*WorkspaceLostRangeQuery)) + } + return interceptor(ctx, in, info, handler) +} + +func _WorkspaceService_PreviewWorkspaceMove_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(WorkspaceMove) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WorkspaceServiceServer).PreviewWorkspaceMove(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WorkspaceService_PreviewWorkspaceMove_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WorkspaceServiceServer).PreviewWorkspaceMove(ctx, req.(*WorkspaceMove)) + } + return interceptor(ctx, in, info, handler) +} + // WorkspaceService_ServiceDesc is the grpc.ServiceDesc for WorkspaceService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -351,6 +429,14 @@ var WorkspaceService_ServiceDesc = grpc.ServiceDesc{ MethodName: "QueryWorkspace", Handler: _WorkspaceService_QueryWorkspace_Handler, }, + { + MethodName: "QueryWorkspaceLostRange", + Handler: _WorkspaceService_QueryWorkspaceLostRange_Handler, + }, + { + MethodName: "PreviewWorkspaceMove", + Handler: _WorkspaceService_PreviewWorkspaceMove_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "workspace.proto", diff --git a/seaweed-block/core/rpc/proto/workspace.proto b/seaweed-block/core/rpc/proto/workspace.proto index 0414ea99a2..5a227f6c79 100644 --- a/seaweed-block/core/rpc/proto/workspace.proto +++ b/seaweed-block/core/rpc/proto/workspace.proto @@ -13,6 +13,13 @@ service WorkspaceService { rpc AckWorkspaceRevoked(WorkspaceRevocationAck) returns (WorkspaceEmpty); rpc MoveWorkspace(WorkspaceMove) returns (WorkspaceGrant); rpc QueryWorkspace(WorkspaceVolume) returns (WorkspaceStatus); + // The stored lost ranges of the volume's issued forced moves, in issue + // order (or the one of request_id); never recomputed. A forced move whose + // range is missing or unreadable fails with DATA_LOSS, never "no loss". + rpc QueryWorkspaceLostRange(WorkspaceLostRangeQuery) returns (WorkspaceLostRanges); + // Read-only forced-move admission check (no reservation, no journal + // write): advisory, re-checked by MoveWorkspace. + rpc PreviewWorkspaceMove(WorkspaceMove) returns (WorkspaceMovePreview); } message WorkspaceIdentity { string volume_id = 1; string replica_id = 2; uint64 epoch = 3; } message WorkspaceVolume { string volume_id = 1; } @@ -34,6 +41,32 @@ message WorkspaceGrant { string kind = 5; uint64 old_epoch = 6; uint64 new_epoch = 7; uint64 head_gen = 8; uint64 remote_lsn = 9; bool issued = 10; string old_host = 11; string new_host = 12; + // Forced grants only: the lost range stored before the issue (also on a + // replay). Absent on a forced grant means the readout is not proven, and + // lost_range_error says why; it never means "no loss". + WorkspaceLostRange lost_range = 13; + string lost_range_error = 14; +} +// What a forced move abandoned. head_gen 0: no published HEAD (everything the +// old holder wrote is lost). head_time_ns is the HEAD entry's filer mtime read +// with HEAD at the move (1 s resolution), valid only when head_time_known. +// lost_until_ns is master time; the upper bound is a time, not an LSN. +message WorkspaceLostRange { + string request_id = 1; string volume_id = 2; uint64 new_epoch = 3; + string old_replica_id = 4; uint64 old_epoch = 5; + uint64 lost_after_lsn = 6; int64 lost_until_ns = 7; + uint64 head_gen = 8; int64 head_time_ns = 9; bool head_time_known = 10; +} +message WorkspaceLostRangeQuery { string volume_id = 1; string request_id = 2; } +message WorkspaceLostRanges { repeated WorkspaceLostRange ranges = 1; } +// lost_until_ns is when a forced move becomes admissible (0 if the master has +// no lease to judge). HEAD is read only when admitted, as for the move. +message WorkspaceMovePreview { + bool admitted = 1; string reason = 2; + int64 lost_until_ns = 3; int64 master_time_ns = 4; + bool head_read = 5; string head_error = 6; + uint64 head_gen = 7; uint64 head_epoch = 8; string head_holder = 9; uint64 head_remote_lsn = 10; + int64 head_time_ns = 11; bool head_time_known = 12; } message WorkspaceStatus { WorkspaceLeaseFact lease = 1; WorkspaceRevocationAck revocation_ack = 2; diff --git a/seaweed-block/core/rpc/wsclient/wsclient.go b/seaweed-block/core/rpc/wsclient/wsclient.go new file mode 100644 index 0000000000..14370cfc09 --- /dev/null +++ b/seaweed-block/core/rpc/wsclient/wsclient.go @@ -0,0 +1,318 @@ +// Package wsclient is the operator client of the blockmaster workspace +// service for FORCED moves: the move itself, its read-only preview, and the +// lost-range readout. The sw-block CLI and other operator tools share it so +// the confirmation rule and the readout wording are the same everywhere. +// +// A forced move transfers AUTHORITY only. Starting the volume on the target +// is the next step, and nothing here bypasses the master's admission (lease +// horizon plus clock skew): there is no bypass. +package wsclient + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +// Outcome classifies a call's failure for the operator. +type Outcome int + +const ( + // OutcomeOK: the call succeeded. + OutcomeOK Outcome = iota + // OutcomeRefusedLocally: refused before any RPC (bad confirmation). + OutcomeRefusedLocally + // OutcomeRefused: the master answered with a definite refusal; nothing + // was moved by this call. + OutcomeRefused + // OutcomeUnknown: transport error or deadline; the move may or may not + // have been issued. Rerun with the SAME request id: the master replays + // an issued move's stored grant and never mints a second one. + OutcomeUnknown + // OutcomeReadoutUnproven: the lost range cannot be read (missing record + // or failed checks); it must never be reported as "no loss". + OutcomeReadoutUnproven +) + +// ErrConfirmation refuses a forced move locally: the confirmation must be +// exactly "@". +var ErrConfirmation = errors.New("forced move confirmation") + +// Error carries a classified failure. +type Error struct { + Outcome Outcome + Op string + Err error +} + +func (e *Error) Error() string { return e.Op + ": " + e.Err.Error() } +func (e *Error) Unwrap() error { return e.Err } + +// OutcomeOf returns err's outcome (OutcomeOK for nil). +func OutcomeOf(err error) Outcome { + if err == nil { + return OutcomeOK + } + var e *Error + if errors.As(err, &e) { + return e.Outcome + } + return OutcomeUnknown +} + +// classify maps a gRPC error: the master's definite answers are refusals, +// DataLoss is an unproven readout, anything else leaves the outcome unknown. +func classify(op string, err error) error { + if err == nil { + return nil + } + switch status.Code(err) { + case codes.FailedPrecondition, codes.InvalidArgument, codes.NotFound, codes.PermissionDenied, codes.Unimplemented: + return &Error{Outcome: OutcomeRefused, Op: op, Err: errors.New(status.Convert(err).Message())} + case codes.DataLoss: + return &Error{Outcome: OutcomeReadoutUnproven, Op: op, Err: errors.New(status.Convert(err).Message())} + } + return &Error{Outcome: OutcomeUnknown, Op: op, Err: err} +} + +// ParseConfirmation checks that confirm is exactly "@" for +// volume, with a positive decimal epoch, and returns that epoch: it is the +// expected epoch the move is sent with (the master refuses it unless it is +// the current one). +func ParseConfirmation(confirm, volume string) (uint64, error) { + if confirm == "" { + return 0, fmt.Errorf("%w: --confirm-forced %s@ is required", ErrConfirmation, volume) + } + at := strings.LastIndexByte(confirm, '@') + if at < 0 || confirm[:at] != volume { + return 0, fmt.Errorf("%w: %q does not name volume %q as %s@", ErrConfirmation, confirm, volume, volume) + } + digits := confirm[at+1:] + epoch, err := strconv.ParseUint(digits, 10, 64) + if err != nil || epoch == 0 || strconv.FormatUint(epoch, 10) != digits { + return 0, fmt.Errorf("%w: %q: the epoch must be a positive decimal number", ErrConfirmation, confirm) + } + return epoch, nil +} + +// ForcedMove names a forced move. TargetHost is the target node's server id. +type ForcedMove struct { + RequestID, VolumeID string + TargetHost, TargetDataAddr, TargetCtrlAddr string + // Confirm must be exactly "@". + Confirm string +} + +// Client calls the workspace service. +type Client struct { + rpc control.WorkspaceServiceClient + conn *grpc.ClientConn +} + +// New wraps an existing service client. +func New(rpc control.WorkspaceServiceClient) *Client { return &Client{rpc: rpc} } + +// Dial connects to the blockmaster gRPC address (plaintext, as the other +// operator commands). +func Dial(addr string) (*Client, error) { + conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return nil, err + } + return &Client{rpc: control.NewWorkspaceServiceClient(conn), conn: conn}, nil +} + +// Close closes a Dial connection. +func (c *Client) Close() error { + if c.conn == nil { + return nil + } + return c.conn.Close() +} + +// request checks the confirmation (no RPC on failure), resolves the +// holder's logical replica id at the confirmed epoch from QueryWorkspace +// (v1 keeps the replica id across moves) and builds the forced request. +func (c *Client) request(ctx context.Context, op string, m ForcedMove) (*control.WorkspaceMove, error) { + epoch, err := ParseConfirmation(m.Confirm, m.VolumeID) + if err != nil { + return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: err} + } + if m.RequestID == "" || m.TargetHost == "" || m.TargetDataAddr == "" || m.TargetCtrlAddr == "" { + return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: errors.New("a request id, target host and target data/ctrl addresses are required")} + } + st, err := c.rpc.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: m.VolumeID}) + if err != nil { + e := classify(op+": read the volume's holder", err) + var ce *Error + if errors.As(e, &ce) && ce.Outcome == OutcomeUnknown { + ce.Err = fmt.Errorf("no move was sent: %w", ce.Err) + } + return nil, e + } + replica := holderAt(st, epoch) + if replica == "" { + cur := "none" + if l := st.GetLease(); l != nil { + cur = fmt.Sprintf("%s@%d", l.GetReplicaId(), l.GetEpoch()) + } + return nil, &Error{Outcome: OutcomeRefused, Op: op, Err: fmt.Errorf("the master knows no holder of volume %q at epoch %d (current lease: %s); nothing was sent", m.VolumeID, epoch, cur)} + } + return &control.WorkspaceMove{RequestId: m.RequestID, VolumeId: m.VolumeID, ExpectedReplicaId: replica, ExpectedEpoch: epoch, TargetReplicaId: replica, + TargetServerId: m.TargetHost, TargetDataAddr: m.TargetDataAddr, TargetCtrlAddr: m.TargetCtrlAddr, Kind: "forced", Force: true}, nil +} + +// holderAt returns the logical replica id that held the volume at epoch: +// the current lease, or the journal (an issued move from or to that epoch, +// e.g. on a rerun after the move issued). +func holderAt(st *control.WorkspaceStatus, epoch uint64) string { + if l := st.GetLease(); l != nil && l.GetEpoch() == epoch && l.GetReplicaId() != "" { + return l.GetReplicaId() + } + for _, g := range st.GetMoves() { + if g.GetOldEpoch() == epoch && g.GetOldReplicaId() != "" { + return g.GetOldReplicaId() + } + if g.GetIssued() && g.GetNewEpoch() == epoch && g.GetNewReplicaId() != "" { + return g.GetNewReplicaId() + } + } + return "" +} + +// ForceMove sends the forced move (kind forced, force true) only when the +// confirmation matches. On success the grant is issued; its stored lost +// range is grant.LostRange, and when that is absent the error is +// OutcomeReadoutUnproven with the grant still returned. +func (c *Client) ForceMove(ctx context.Context, m ForcedMove) (*control.WorkspaceGrant, error) { + const op = "forced move" + q, err := c.request(ctx, op, m) + if err != nil { + return nil, err + } + g, err := c.rpc.MoveWorkspace(ctx, q) + if err != nil { + return nil, classify(op, err) + } + if err := checkGrant(g, q); err != nil { + return g, &Error{Outcome: OutcomeUnknown, Op: op, Err: fmt.Errorf("%v; rerun with the same request id", err)} + } + if err := checkRange(g.GetLostRange(), g); err != nil { + return g, &Error{Outcome: OutcomeReadoutUnproven, Op: op, Err: err} + } + return g, nil +} + +// checkGrant binds a successful answer to the request that was sent: an +// issued forced grant for this request id and volume, from the expected +// holder at the expected epoch to the requested target, at a higher epoch. +// Anything else leaves the outcome unknown. +func checkGrant(g *control.WorkspaceGrant, q *control.WorkspaceMove) error { + if !g.GetIssued() || g.GetKind() != "forced" || g.GetRequestId() != q.GetRequestId() || g.GetVolumeId() != q.GetVolumeId() || + g.GetOldReplicaId() != q.GetExpectedReplicaId() || g.GetOldEpoch() != q.GetExpectedEpoch() || + g.GetNewReplicaId() != q.GetTargetReplicaId() || g.GetNewHost() != q.GetTargetServerId() || g.GetNewEpoch() <= g.GetOldEpoch() { + return fmt.Errorf("the answer does not match the request (issued=%t kind=%q request=%q volume=%q old=%s@%d new=%s@%d on %q)", + g.GetIssued(), g.GetKind(), g.GetRequestId(), g.GetVolumeId(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewReplicaId(), g.GetNewEpoch(), g.GetNewHost()) + } + return nil +} + +// checkRange: a forced grant must carry its own stored range, naming the +// same move and the same kept HEAD (generation and frontier). +func checkRange(r *control.WorkspaceLostRange, g *control.WorkspaceGrant) error { + if r == nil { + why := g.GetLostRangeError() + if why == "" { + why = "the master returned no lost range" + } + return fmt.Errorf("move issued (volume %s epoch %d -> %d) but the lost range is not proven: %s", g.GetVolumeId(), g.GetOldEpoch(), g.GetNewEpoch(), why) + } + if r.GetRequestId() != g.GetRequestId() || r.GetVolumeId() != g.GetVolumeId() || r.GetNewEpoch() != g.GetNewEpoch() || r.GetOldEpoch() != g.GetOldEpoch() || r.GetOldReplicaId() != g.GetOldReplicaId() { + return fmt.Errorf("move issued (volume %s epoch %d -> %d) but its lost range names another move (volume %q request %q epoch %d)", g.GetVolumeId(), g.GetOldEpoch(), g.GetNewEpoch(), r.GetVolumeId(), r.GetRequestId(), r.GetNewEpoch()) + } + if r.GetHeadGen() != g.GetHeadGen() || r.GetLostAfterLsn() != g.GetRemoteLsn() { + return fmt.Errorf("move issued (volume %s epoch %d -> %d) but its lost range disagrees with the kept HEAD (range gen %d LSN %d, grant gen %d LSN %d)", g.GetVolumeId(), g.GetOldEpoch(), g.GetNewEpoch(), r.GetHeadGen(), r.GetLostAfterLsn(), g.GetHeadGen(), g.GetRemoteLsn()) + } + return nil +} + +// PreviewForcedMove asks the master whether the forced move is admitted +// now, writing nothing. The confirmation is checked as for the move (the +// preview is evaluated at its epoch), but a preview never stands in for it. +func (c *Client) PreviewForcedMove(ctx context.Context, m ForcedMove) (*control.WorkspaceMovePreview, error) { + const op = "forced move preview" + q, err := c.request(ctx, op, m) + if err != nil { + return nil, err + } + p, err := c.rpc.PreviewWorkspaceMove(ctx, q) + return p, classify(op, err) +} + +// previewMove is PreviewForcedMove for an already built request. +func (c *Client) previewMove(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceMovePreview, error) { + p, err := c.rpc.PreviewWorkspaceMove(ctx, q) + return p, classify("forced move preview", err) +} + +// AdmissibleAt asks the preview for when a refused forced move becomes +// admissible; ok is false when the preview cannot tell (admitted already, +// no lease, or the preview failed). +func (c *Client) AdmissibleAt(ctx context.Context, m ForcedMove) (at time.Time, ok bool) { + q, err := c.request(ctx, "forced move preview", m) + if err != nil { + return time.Time{}, false + } + p, err := c.previewMove(ctx, q) + if err != nil || p.GetLostUntilNs() == 0 || p.GetLostUntilNs() <= p.GetMasterTimeNs() { + return time.Time{}, false + } + return time.Unix(0, p.GetLostUntilNs()), true +} + +// LostRanges returns the stored lost ranges of the volume's issued forced +// moves in issue order, or requestID's only. A missing or unreadable record +// is OutcomeReadoutUnproven. +func (c *Client) LostRanges(ctx context.Context, volume, requestID string) ([]*control.WorkspaceLostRange, error) { + r, err := c.rpc.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: volume, RequestId: requestID}) + if err != nil { + return nil, classify("lost range", err) + } + for _, x := range r.GetRanges() { + if x.GetVolumeId() != volume || (requestID != "" && x.GetRequestId() != requestID) { + return nil, &Error{Outcome: OutcomeReadoutUnproven, Op: "lost range", Err: fmt.Errorf("the answer names another range (volume %q request %q)", x.GetVolumeId(), x.GetRequestId())} + } + } + return r.GetRanges(), nil +} + +// HeadTimeClock labels a HEAD time: the filer entry's mtime, which the +// host that published the HEAD sets from its own clock. +const HeadTimeClock = "(publishing host clock as recorded in the filer, 1 s resolution)" + +// FormatTime prints a master or filer time. +func FormatTime(ns int64) string { return time.Unix(0, ns).UTC().Format(time.RFC3339Nano) } + +// Readout is the operator sentence for a stored lost range of volume. +func Readout(volume string, r *control.WorkspaceLostRange) string { + old := fmt.Sprintf("%s@%d", r.GetOldReplicaId(), r.GetOldEpoch()) + if r.GetHeadGen() == 0 { + return fmt.Sprintf("no remote image exists: everything written by %s is lost.", old) + } + at := "an unknown time (no filer time was recorded)" + if r.GetHeadTimeKnown() { + at = FormatTime(r.GetHeadTimeNs()) + " " + HeadTimeClock + } + return fmt.Sprintf("volume %s restored to the last published image at %s (gen %d, LSN %d): writes with LSN <= %d are preserved; "+ + "writes acknowledged by %s after that and before %s, master clock, may be lost; the upper bound is a time, not an LSN.", + volume, at, r.GetHeadGen(), r.GetLostAfterLsn(), r.GetLostAfterLsn(), old, FormatTime(r.GetLostUntilNs())) +} diff --git a/seaweed-block/core/rpc/wsclient/wsclient_test.go b/seaweed-block/core/rpc/wsclient/wsclient_test.go new file mode 100644 index 0000000000..2d1c9fdbf9 --- /dev/null +++ b/seaweed-block/core/rpc/wsclient/wsclient_test.go @@ -0,0 +1,224 @@ +package wsclient + +import ( + "context" + "errors" + "testing" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// fakeRPC answers QueryWorkspace and MoveWorkspace and counts every call. +type fakeRPC struct { + control.WorkspaceServiceClient // nil: other methods panic + calls int + status *control.WorkspaceStatus + moves []*control.WorkspaceMove + grant *control.WorkspaceGrant + moveErr error +} + +func (f *fakeRPC) QueryWorkspace(context.Context, *control.WorkspaceVolume, ...grpc.CallOption) (*control.WorkspaceStatus, error) { + f.calls++ + return f.status, nil +} + +func (f *fakeRPC) MoveWorkspace(_ context.Context, q *control.WorkspaceMove, _ ...grpc.CallOption) (*control.WorkspaceGrant, error) { + f.calls++ + f.moves = append(f.moves, q) + return f.grant, f.moveErr +} + +// INV-WS-FORCED-CONFIRM-001: the confirmation is exactly @. +func TestParseConfirmation(t *testing.T) { + for _, tc := range []struct { + confirm, volume string + epoch uint64 + }{ + {"vol@3", "vol", 3}, + {"a@b@7", "a@b", 7}, + {"", "vol", 0}, + {"vol", "vol", 0}, + {"vol@", "vol", 0}, + {"other@3", "vol", 0}, + {"vol@0", "vol", 0}, + {"vol@03", "vol", 0}, + {"vol@+3", "vol", 0}, + {"vol@-3", "vol", 0}, + {"vol@3 ", "vol", 0}, + {" vol@3", "vol", 0}, + {"VOL@3", "vol", 0}, + } { + got, err := ParseConfirmation(tc.confirm, tc.volume) + if got != tc.epoch || (err == nil) != (tc.epoch != 0) || (err != nil && !errors.Is(err, ErrConfirmation)) { + t.Errorf("ParseConfirmation(%q, %q) = %d, %v; want %d", tc.confirm, tc.volume, got, err, tc.epoch) + } + } +} + +var testMove = ForcedMove{RequestID: "req-1", VolumeID: "vol", TargetHost: "node-b", TargetDataAddr: "10.0.0.2:1", TargetCtrlAddr: "10.0.0.2:2", Confirm: "vol@3"} + +// INV-WS-FORCED-CONFIRM-001: force:true is sent only with a matching +// confirmation, and then always with kind forced and the confirmed epoch. +func TestForceMoveSendsForceOnlyWithTheConfirmation(t *testing.T) { + for _, bad := range []string{"", "vol@x", "other@3", "vol@0"} { + f := &fakeRPC{} + m := testMove + m.Confirm = bad + if _, err := New(f).ForceMove(context.Background(), m); OutcomeOf(err) != OutcomeRefusedLocally || f.calls != 0 { + t.Fatalf("confirmation %q: %v after %d RPCs; want a local refusal and none", bad, err, f.calls) + } + } + f := &fakeRPC{status: &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3}}, moveErr: status.Error(codes.FailedPrecondition, "not yet")} + if _, err := New(f).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeRefused { + t.Fatalf("master refusal: %v", err) + } + q := f.moves[0] + if len(f.moves) != 1 || q.Kind != "forced" || !q.Force || q.ExpectedEpoch != 3 || q.ExpectedReplicaId != "r1" || q.TargetReplicaId != "r1" || q.RequestId != "req-1" || q.TargetServerId != "node-b" { + t.Fatalf("sent %+v", f.moves) + } +} + +// The holder's replica id at the confirmed epoch comes from the lease, or +// on a rerun after the issue from the journal; an epoch the master never +// had is refused without sending a move. +func TestForceMoveResolvesTheHolder(t *testing.T) { + rerun := &fakeRPC{status: &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{ReplicaId: "r1", Epoch: 4}, + Moves: []*control.WorkspaceGrant{{RequestId: "req-1", OldReplicaId: "r1", OldEpoch: 3, NewReplicaId: "r1", NewEpoch: 4, Issued: true, Kind: "forced"}}}, moveErr: status.Error(codes.Unavailable, "down")} + if _, err := New(rerun).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeUnknown || len(rerun.moves) != 1 || rerun.moves[0].ExpectedReplicaId != "r1" { + t.Fatalf("rerun: %v %+v", err, rerun.moves) + } + stale := &fakeRPC{status: &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{ReplicaId: "r1", Epoch: 9}}} + if _, err := New(stale).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeRefused || len(stale.moves) != 0 { + t.Fatalf("stale epoch: %v, %d moves sent", err, len(stale.moves)) + } +} + +// goodGrant is the issued forced grant for testMove with its own range. +func goodGrant() *control.WorkspaceGrant { + return &control.WorkspaceGrant{RequestId: "req-1", VolumeId: "vol", Kind: "forced", Issued: true, OldReplicaId: "r1", OldEpoch: 3, NewReplicaId: "r1", NewEpoch: 4, + OldHost: "node-a", NewHost: "node-b", HeadGen: 9, RemoteLsn: 42, + LostRange: &control.WorkspaceLostRange{RequestId: "req-1", VolumeId: "vol", NewEpoch: 4, OldReplicaId: "r1", OldEpoch: 3, LostAfterLsn: 42, LostUntilNs: 1, HeadGen: 9}} +} + +func holderAt3() *control.WorkspaceStatus { + return &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{ReplicaId: "r1", Epoch: 3}} +} + +// A forced grant without its own stored range is issued but unproven. +func TestForceMoveGrantWithoutRangeIsUnproven(t *testing.T) { + g := goodGrant() + if _, err := New(&fakeRPC{status: holderAt3(), grant: g}).ForceMove(context.Background(), testMove); err != nil { + t.Fatalf("own range: %v", err) + } + g.LostRange = nil + got, err := New(&fakeRPC{status: holderAt3(), grant: g}).ForceMove(context.Background(), testMove) + if OutcomeOf(err) != OutcomeReadoutUnproven || got != g { + t.Fatalf("no range: %v", err) + } +} + +// The answer is bound to the request: each identity field of the grant +// corrupted on its own leaves the outcome unknown; each identity or +// frontier field of the range corrupted on its own leaves the readout +// unproven. Neither ever yields a successful readout. +func TestForceMoveBindsGrantAndRange(t *testing.T) { + grantFaults := map[string]func(*control.WorkspaceGrant){ + "not issued": func(g *control.WorkspaceGrant) { g.Issued = false }, + "kind": func(g *control.WorkspaceGrant) { g.Kind = "clean" }, + "request": func(g *control.WorkspaceGrant) { g.RequestId = "req-2" }, + "volume": func(g *control.WorkspaceGrant) { g.VolumeId = "vol2" }, + "old replica": func(g *control.WorkspaceGrant) { g.OldReplicaId = "r2" }, + "old epoch": func(g *control.WorkspaceGrant) { g.OldEpoch = 2 }, + "new replica": func(g *control.WorkspaceGrant) { g.NewReplicaId = "r2" }, + "target host": func(g *control.WorkspaceGrant) { g.NewHost = "node-c" }, + "epoch not up": func(g *control.WorkspaceGrant) { g.NewEpoch = 3 }, + } + for name, fault := range grantFaults { + g := goodGrant() + fault(g) + if _, err := New(&fakeRPC{status: holderAt3(), grant: g}).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeUnknown { + t.Errorf("grant %s corrupted: %v; want unknown", name, err) + } + } + rangeFaults := map[string]func(*control.WorkspaceLostRange){ + "request": func(r *control.WorkspaceLostRange) { r.RequestId = "req-2" }, + "volume": func(r *control.WorkspaceLostRange) { r.VolumeId = "vol2" }, + "new epoch": func(r *control.WorkspaceLostRange) { r.NewEpoch = 5 }, + "old epoch": func(r *control.WorkspaceLostRange) { r.OldEpoch = 2 }, + "old replica": func(r *control.WorkspaceLostRange) { r.OldReplicaId = "r2" }, + "head gen": func(r *control.WorkspaceLostRange) { r.HeadGen = 8 }, + "lost after": func(r *control.WorkspaceLostRange) { r.LostAfterLsn = 41 }, + } + for name, fault := range rangeFaults { + g := goodGrant() + fault(g.LostRange) + if _, err := New(&fakeRPC{status: holderAt3(), grant: g}).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeReadoutUnproven { + t.Errorf("range %s corrupted: %v; want unproven", name, err) + } + } +} + +// lostRangeRPC answers QueryWorkspaceLostRange with fixed ranges. +type lostRangeRPC struct { + control.WorkspaceServiceClient + ranges []*control.WorkspaceLostRange +} + +func (f *lostRangeRPC) QueryWorkspaceLostRange(context.Context, *control.WorkspaceLostRangeQuery, ...grpc.CallOption) (*control.WorkspaceLostRanges, error) { + return &control.WorkspaceLostRanges{Ranges: f.ranges}, nil +} + +// A lost-range answer that names another volume or request is unproven. +func TestLostRangesBindsTheAnswer(t *testing.T) { + r := goodGrant().LostRange + if got, err := New(&lostRangeRPC{ranges: []*control.WorkspaceLostRange{r}}).LostRanges(context.Background(), "vol", "req-1"); err != nil || len(got) != 1 { + t.Fatalf("matching answer: %v", err) + } + if _, err := New(&lostRangeRPC{ranges: []*control.WorkspaceLostRange{r}}).LostRanges(context.Background(), "other", ""); OutcomeOf(err) != OutcomeReadoutUnproven { + t.Fatalf("another volume: %v", err) + } + if _, err := New(&lostRangeRPC{ranges: []*control.WorkspaceLostRange{r}}).LostRanges(context.Background(), "vol", "req-9"); OutcomeOf(err) != OutcomeReadoutUnproven { + t.Fatalf("another request: %v", err) + } +} + +func TestClassify(t *testing.T) { + for code, want := range map[codes.Code]Outcome{ + codes.FailedPrecondition: OutcomeRefused, codes.NotFound: OutcomeRefused, codes.DataLoss: OutcomeReadoutUnproven, + codes.Unavailable: OutcomeUnknown, codes.DeadlineExceeded: OutcomeUnknown, codes.Canceled: OutcomeUnknown, codes.Internal: OutcomeUnknown, + } { + if got := OutcomeOf(classify("op", status.Error(code, "x"))); got != want { + t.Errorf("%v: %v; want %v", code, got, want) + } + } + if OutcomeOf(classify("op", context.DeadlineExceeded)) != OutcomeUnknown { + t.Error("a bare deadline is not unknown") + } +} + +// INV-WS-LOST-RANGE-READOUT-001: the readout wording (ruling A: HEAD time is +// the filer time; the upper bound is master time). +func TestReadoutWording(t *testing.T) { + r := &control.WorkspaceLostRange{OldReplicaId: "r1", OldEpoch: 3, LostAfterLsn: 42, LostUntilNs: time.Date(2026, 11, 21, 1, 5, 0, 5, time.UTC).UnixNano(), + HeadGen: 9, HeadTimeNs: time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC).UnixNano(), HeadTimeKnown: true} + want := "volume vol restored to the last published image at 2026-11-21T01:02:03Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 9, LSN 42): writes with LSN <= 42 are preserved; " + + "writes acknowledged by r1@3 after that and before 2026-11-21T01:05:00.000000005Z, master clock, may be lost; the upper bound is a time, not an LSN." + if got := Readout("vol", r); got != want { + t.Fatalf("readout\n got %s\nwant %s", got, want) + } + r.HeadTimeKnown = false + want = "volume vol restored to the last published image at an unknown time (no filer time was recorded) (gen 9, LSN 42): writes with LSN <= 42 are preserved; " + + "writes acknowledged by r1@3 after that and before 2026-11-21T01:05:00.000000005Z, master clock, may be lost; the upper bound is a time, not an LSN." + if got := Readout("vol", r); got != want { + t.Fatalf("readout, time unknown\n got %s\nwant %s", got, want) + } + r.HeadGen = 0 + if got := Readout("vol", r); got != "no remote image exists: everything written by r1@3 is lost." { + t.Fatalf("no-HEAD readout: %s", got) + } +} diff --git a/seaweed-block/core/storage/base_install_reopen_v3_test.go b/seaweed-block/core/storage/base_install_reopen_v3_test.go index d2db295dc8..132b3b6f71 100644 --- a/seaweed-block/core/storage/base_install_reopen_v3_test.go +++ b/seaweed-block/core/storage/base_install_reopen_v3_test.go @@ -6,7 +6,7 @@ import ( "testing" ) -// Plan row 11a controls (DESIGN r17.4 sections 6.6 and 8.3; owner claude03): +// Install-reopen controls: // a covering superseding begin after an installing reopen. // installThenCrashV3 begins install A at BaseLSN 10 over two acknowledged diff --git a/seaweed-block/core/storage/base_install_resume_v3_test.go b/seaweed-block/core/storage/base_install_resume_v3_test.go index 8c21abac9d..0637dd5449 100644 --- a/seaweed-block/core/storage/base_install_resume_v3_test.go +++ b/seaweed-block/core/storage/base_install_resume_v3_test.go @@ -7,7 +7,7 @@ import ( "testing" ) -// Plan row 11b controls (DESIGN r17.4 sections 6.6 and 8.3; owner claude03): +// Install-resume controls: // the same-ID resume after an installing reopen. // An intact reopen (W 2 <= R 11; record 12 damaged, 13 beyond the gap) @@ -65,7 +65,7 @@ func TestBaseInstallV3ResumeRefusesADamagedSuffix(t *testing.T) { } } -// E below the persisted retainedHead (codex03 r17 check): the head was +// E below the persisted retainedHead: the head was // published past LSN 13 (white-box, as an earlier same-open recovery // would), then 13 is damaged, so the reopen's E ends after 12, below the // head. The resume is refused (E >= head is part of trusted-through-W). A @@ -121,9 +121,9 @@ func TestBaseInstallV3EBelowThePersistedHead(t *testing.T) { } } -// codex01 row 11b P1: a same-open Recover while this open's install is live +// A same-open Recover while this open's install is live // must not leave a resumable cut behind. The old handle stays valid -// (r17.4) and applies and acknowledges LSN 12 after the Recover; a resume +// and applies and acknowledges LSN 12 after the Recover; a resume // then refuses before any I/O, so the acknowledged record's bytes are // unchanged, and a crash and a physical reopen still resume the same ID and // serve LSN 12. Mutant: recording the recovered bounds on a same-open @@ -191,7 +191,7 @@ func readRawV3(t *testing.T, path string, off int64, n int) []byte { return b } -// codex01 04180c33 P1 (live continuation): BASE writes LBA 1 = B0, then the +// Live continuation: BASE writes LBA 1 = B0, then the // install lane applies and acknowledges LSN 11 at LBA 1; a same-open // Recover clears the dirty map; the ORIGINAL handle then applies and // acknowledges LSN 12 at LBA 2 and completes; reads in the same open must diff --git a/seaweed-block/core/storage/base_install_v3.go b/seaweed-block/core/storage/base_install_v3.go index dba6fb0aaa..c251b58cde 100644 --- a/seaweed-block/core/storage/base_install_v3.go +++ b/seaweed-block/core/storage/base_install_v3.go @@ -134,7 +134,7 @@ type installHandleV3 struct { // completed is set once this handle's own MarkBaseComplete succeeded: // the session's WAL lane may still be sending (the Sender sends BaseDone // from its base lane), so install-lane applies stay admitted until the - // next begin (codex01 row 9b P1). + // next begin. completed atomic.Bool } @@ -203,7 +203,7 @@ func (s *WALStore) beginBaseInstallV3(baseLSN uint64, id [16]byte) (*installHand // BaseLSN must also cover every appended LSN: an unacknowledged record // above BaseLSN would lie behind BaseCursor, so recovery from // max(CheckpointLSN, BaseLSN) would meet a hole where the allocator - // continued (codex01 row 9a P1-1). Such a begin is refused, writing + // continued. Such a begin is refused, writing // nothing; the records are never rewound or dropped to make room. w := max(d.W, v.wack.Load()) appended := v.appended.Load() @@ -448,7 +448,7 @@ func (s *WALStore) applyEntryV3(lba uint32, data []byte, lsn uint64, installLane // a checkpoint does: one fsync for the BASE extent bytes and the // install-lane suffix (they share the file), the optional metadata and // chunk barriers, and a fresh owned-map candidate that carries the UNKNOWN -// coverage the BASE writes set (codex01 row 9a P1-2). It then publishes +// coverage the BASE writes set. It then publishes // installed with the same ID and that candidate in one publication // (retainedTail = max(retainedTail, P), 8.4), stops serving the superseded // pre-BASE records and moves the frontier to BaseLSN. A guest write that diff --git a/seaweed-block/core/storage/base_install_v3_test.go b/seaweed-block/core/storage/base_install_v3_test.go index 5e1c9311a5..8479271a72 100644 --- a/seaweed-block/core/storage/base_install_v3_test.go +++ b/seaweed-block/core/storage/base_install_v3_test.go @@ -10,9 +10,9 @@ import ( "time" ) -// Plan row 9a controls (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7): +// BASE install controls: // the v3 BASE begin, the install handle, complete, no abort and retirement. -// Owner: claude03. Each control names the mutant it qualifies. +// Each control names the mutant it qualifies. var ( idA = [16]byte{0xA} @@ -244,8 +244,7 @@ func TestBaseInstallV3ApplyInstallEntryOrderAndGap(t *testing.T) { // holdOnce returns a hook that parks the first call until release runs, // and reports through parked when it has parked. The test's cleanup always -// releases, so a failing test never leaves a parked goroutine behind -// (codex01 row 9a P2). +// releases, so a failing test never leaves a parked goroutine behind. func holdOnce(t *testing.T) (hook func(), parked chan struct{}, release func()) { parked = make(chan struct{}) gate := make(chan struct{}) @@ -262,7 +261,7 @@ func holdOnce(t *testing.T) (hook func(), parked chan struct{}, release func()) }, parked, release } -// Drain setup, held inside the mutation (plan row 9, codex01 r12 P2): +// Drain setup, held inside the mutation: // A's admitted write is held; B's begin waits for it; B then writes the // target block and stays installing; a further A attempt is refused with // B's block byte-identical. Mutants: begin taking installMu shared (A's @@ -316,8 +315,8 @@ func TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin(t *testing.T) { } } -// Premature-check setup, parked before admission (codex03 r11, plan row -// 9): A parks before acquiring installMu; B supersedes, writes the target +// Premature-check setup, parked before admission: +// A parks before acquiring installMu; B supersedes, writes the target // block and stays installing; A resumes and is refused under the lock. // Mutants: checking the ID before acquiring installMu, and no ID check. func TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession(t *testing.T) { @@ -355,7 +354,7 @@ func TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession(t *testing.T) { } } -// codex01 row 9a P1-1: W 1 with unacknowledged LSNs 2 and 3 appended. A +// W 1 with unacknowledged LSNs 2 and 3 appended. A // begin at BaseLSN 1 would put 2 and 3 behind BaseCursor while the // allocator continues at 4: after complete, an acknowledged write 4 and a // reopen from F = 1 meet the hole (strict: R 1 < W 4; lagged: 4 dropped). @@ -407,7 +406,7 @@ func TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN(t *testing.T) { } } -// codex01 row 9a P1-2: a BASE write makes its chunk's coverage UNKNOWN only +// A BASE write makes its chunk's coverage UNKNOWN only // in memory. Complete settles the map like a checkpoint: the installed // publication carries a fresh root with that UNKNOWN, so a crash and a // mapped reopen keep it. Setup: chunk 2 is clean in the durable root (as a @@ -473,7 +472,7 @@ func TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer(t *testing } } -// codex01 row 9b P1, store part: a completed handle keeps admitting +// Store side: a completed handle keeps admitting // install-lane applies (the session's WAL lane outlives its BaseDone) while // installed and after its retirement, until the next begin; a BASE write // after complete is refused; once a later begin has run (here after the diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go index 68303be17a..4a2ae329e2 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -14,12 +14,12 @@ import ( // LastAdvance stays frozen. Fields are cumulative atomic observations, not a // coherent frontier. type CheckpointPersistenceStatus struct { - Successes uint64 - Refusals uint64 - Failures uint64 - CheckpointLSN uint64 - Advances uint64 - LastAdvance time.Time + Successes uint64 // checkpoint calls that succeeded (including unchanged ones) + Refusals uint64 // checkpoint calls refused because the map coverage was stale + Failures uint64 // checkpoint calls that failed with an error + CheckpointLSN uint64 // the persisted checkpoint LSN + Advances uint64 // successes that moved CheckpointLSN forward + LastAdvance time.Time // when the latest advance happened; zero if none in this open } func (s *WALStore) CheckpointPersistence() CheckpointPersistenceStatus { diff --git a/seaweed-block/core/storage/chunk_base_v3.go b/seaweed-block/core/storage/chunk_base_v3.go index b908fe6eff..07b9190d55 100644 --- a/seaweed-block/core/storage/chunk_base_v3.go +++ b/seaweed-block/core/storage/chunk_base_v3.go @@ -29,7 +29,7 @@ func (l *chunkLayerImpl) holdBaseTransitionV3() (func(), error) { } l.stMu.Unlock() if refusal != nil { - l.capMu.Unlock() + l.unlockCap() done() return nil, fmt.Errorf("storage: BASE transition refused: %w", refusal) } @@ -56,7 +56,7 @@ func (l *chunkLayerImpl) holdBaseTransitionV3() (func(), error) { if d.BaseState == BaseInstalled && presenceDurable && l.s.OwnerChunkAttachDurableV3() { l.s.AllowBaseRetirementV3() } - l.capMu.Unlock() + l.unlockCap() done() }, nil } diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index c9fc09dc5c..35144e34ff 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -21,6 +21,62 @@ const cutCOWMemoryLimit = DefaultCutPayloadMemoryBudget // defaultCOWSpillLimit caps a copy window's side-file bytes by default. const defaultCOWSpillLimit = 1 << 30 + +// cowSpillFreeReserve is the free space a cut's side file never takes, +// on top of leaving half of the rest. +const cowSpillFreeReserve = 1 << 30 + +var ( + // errCutNoRoom: the free space leaves this cut no side-file room. + errCutNoRoom = errors.New("storage: no room to cut") + // errCutFreeUnreadable: the free space could not be read, so this cut + // has no side-file room. + errCutFreeUnreadable = errors.New("storage: free space unreadable") +) + +// cowSpillCap is one cut's side-file cap. cause is set when the free space +// made it zero: errCutNoRoom or errCutFreeUnreadable. +type cowSpillCap struct { + bytes int64 + cause error +} + +// cowSpillLimit is this cut's side-file cap: COWSpillLimit, lowered to +// half the free space minus cowSpillFreeReserve when COWSpillFree is set. +// A read error gives a cap of 0 with its own cause. +func (l *chunkLayerImpl) cowSpillLimit() cowSpillCap { + limit := l.cfg.COWSpillLimit + if l.cfg.COWSpillFree == nil { + return cowSpillCap{bytes: limit} + } + free, err := l.cfg.COWSpillFree() + if err != nil { + return cowSpillCap{cause: fmt.Errorf("%w: %w", errCutFreeUnreadable, err)} + } + c := cowSpillCap{bytes: max(0, min(limit, free/2-cowSpillFreeReserve))} + if c.bytes == 0 { + c.cause = errCutNoRoom + } + return c +} + +// readCutSpill reads this cut's side-file cap once, for both the staging +// bound and the copy window, and records it in the stats. +func (l *chunkLayerImpl) readCutSpill() cowSpillCap { + c := l.cowSpillLimit() + reason := "" + switch { + case errors.Is(c.cause, errCutFreeUnreadable): + reason = "free_space_unreadable" + case errors.Is(c.cause, errCutNoRoom): + reason = "no_room_to_cut" + } + l.stMu.Lock() + l.stats.COWSpillCap, l.stats.COWSpillCapReason = c.bytes, reason + l.stMu.Unlock() + return c +} + const ( cowPending uint8 = iota cowCopying @@ -68,6 +124,7 @@ type cutCOWWindow struct { memory int64 spillBytes int64 // bytes written to the side file; at most spillLimit spillLimit int64 + spillCause error // why spillLimit is 0, when the free space made it so chunkBytes int64 memoryLimit int64 saverSlots chan struct{} @@ -143,12 +200,12 @@ func (l *chunkLayerImpl) holdCOWDestructive() func() { } // The caller owns captureMu exclusive, so no writer can miss this publication. -func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, head map[uint64]chunkRef) (*cutCOWWindow, error) { +func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, head map[uint64]chunkRef, spill cowSpillCap) (*cutCOWWindow, error) { size := uint64(l.blockSize) * l.chunkBlocks if size == 0 || size > math.MaxInt64 || uint64(len(candidates)) > math.MaxInt64/size { return nil, fmt.Errorf("%w: side-store geometry", errCutCOWAborted) } - w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: l.cfg.COWSpillLimit, chunkBytes: int64(size)} + w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: spill.bytes, spillCause: spill.cause, chunkBytes: int64(size)} w.ctx, w.cancel = context.WithCancel(context.Background()) _, reserved, limit := l.cutPayloadWorkers() savers := min(max(1, int((16<<20)/int64(size))), int((limit-reserved)/(2*int64(size)))) @@ -373,6 +430,9 @@ func (w *cutCOWWindow) save(e *cutCOWEntry, data []byte, missing []uint64) error // The side file is sparse but its saved chunks are real bytes on the // volume's filesystem: abort the cut (retried) instead of filling it. w.mu.Unlock() + if w.spillCause != nil { + return fmt.Errorf("%w: %w: %w: COW spill cap is 0", errCutCOWAborted, errCutCOWCapacity, w.spillCause) + } return fmt.Errorf("%w: %w: COW spill would exceed its cap of %d bytes", errCutCOWAborted, errCutCOWCapacity, w.spillLimit) } else { w.spillBytes += w.chunkBytes diff --git a/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go b/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go new file mode 100644 index 0000000000..eefd41798b --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go @@ -0,0 +1,225 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "sync/atomic" + "testing" +) + +// The spill cap is min(COWSpillLimit, free/2 - reserve), at least 0, read +// from COWSpillFree on every call. A cap of 0 carries its cause: no room +// (the free space is within the reserve) or a read error, which is not +// reported as a full disk. Without COWSpillFree the configured cap applies. +func TestCOWSpillLimit_FromFreeSpace(t *testing.T) { + l := &chunkLayerImpl{cfg: ChunkLayerConfig{COWSpillLimit: 4 << 30}} + if got := l.cowSpillLimit(); got.bytes != 4<<30 || got.cause != nil { + t.Fatalf("no free-space reader: cap %+v, want the configured 4 GiB", got) + } + var free atomic.Int64 + var reads atomic.Int64 + var fail atomic.Bool + l.cfg.COWSpillFree = func() (int64, error) { + reads.Add(1) + if fail.Load() { + return 1 << 40, errors.New("statfs failed") + } + return free.Load(), nil + } + for _, c := range []struct { + free, want int64 + cause error + }{ + {100 << 30, 4 << 30, nil}, // plenty: the configured cap + {6 << 30, 2 << 30, nil}, // 6 GiB free: half is 3, minus the 1 GiB reserve + {2 << 30, 0, errCutNoRoom}, // half the free space is all reserve + {1 << 30, 0, errCutNoRoom}, // below the reserve: never negative + {10<<30 + 2, 4 << 30, nil}, // the configured cap still bounds it + {3 << 30, (3<<30)/2 - (1 << 30), nil}, // 1.5 GiB - 1 GiB + } { + free.Store(c.free) + if got := l.cowSpillLimit(); got.bytes != c.want || !errors.Is(got.cause, c.cause) || (c.cause == nil) != (got.cause == nil) { + t.Fatalf("free %d: cap %+v, want %d (cause %v)", c.free, got, c.want, c.cause) + } + } + if reads.Load() != 6 { + t.Fatalf("free space read %d times for 6 calls; want once per call", reads.Load()) + } + fail.Store(true) + if got := l.cowSpillLimit(); got.bytes != 0 || !errors.Is(got.cause, errCutFreeUnreadable) || errors.Is(got.cause, errCutNoRoom) { + t.Fatalf("free-space read error: cap %+v, want 0 with cause free_space_unreadable (not no room)", got) + } +} + +// Each cut reads the free space once, for both the staging bound and the +// window, and shows the cap in the stats: the configured cap with ample +// free space; 0 with reason no_room_to_cut when the free space is within +// the reserve (the cut still completes by staging before the barrier); +// 0 with reason free_space_unreadable when the read fails. +func TestCutCOWV3_SpillCapIsReadOncePerCutAndShown(t *testing.T) { + s, l, _, gate := cowFixture(t) + gate.unblock() + var free, reads atomic.Int64 + var fail atomic.Bool + l.cfg.COWSpillFree = func() (int64, error) { + reads.Add(1) + if fail.Load() { + return 0, errors.New("statfs failed") + } + return free.Load(), nil + } + for i, c := range []struct { + free int64 + fail bool + cap int64 + reason string + }{ + {100 << 30, false, l.cfg.COWSpillLimit, ""}, + {1 << 30, false, 0, "no_room_to_cut"}, + {100 << 30, true, 0, "free_space_unreadable"}, + } { + free.Store(c.free) + fail.Store(c.fail) + if _, err := s.Write(uint32(i*ctChunkBlocks+1), makeBlock(ctBlockSize, byte(0x60+i))); err != nil { + t.Fatal(err) + } + before := reads.Load() + if _, err := l.Cut(context.Background()); err != nil { + t.Fatalf("cut %d (free %d, read error %v): %v; want it to complete by staging, not refuse", i, c.free, c.fail, err) + } + if st := l.Stats(); len(st.CutsAborted) != 0 { + t.Fatalf("cut %d: aborts %v; want none", i, st.CutsAborted) + } + if n := reads.Load() - before; n != 1 { + t.Fatalf("cut %d read the free space %d times; want once", i, n) + } + if st := l.Stats(); st.COWSpillCap != c.cap || st.COWSpillCapReason != c.reason { + t.Fatalf("cut %d: stats cap %d reason %q; want %d %q", i, st.COWSpillCap, st.COWSpillCapReason, c.cap, c.reason) + } + } +} + +// The cap the window holds is the one this cut read: with the free space +// within the reserve (or unreadable) the copy window opens with a cap of 0 +// and that cause, straight from the reader. The window is caught open by +// holding its copy of chunk 0: staging runs with the read gate disarmed, +// and the stage hook re-dirties chunk 0 each round and arms the gate after +// the second, so the barrier leaves chunk 0 to the window. +func TestCutCOWV3_WindowGetsTheCutsReadCap(t *testing.T) { + for _, c := range []struct { + name string + read func() (int64, error) + cause error + }{ + {"no room", func() (int64, error) { return 1 << 30, nil }, errCutNoRoom}, + {"unreadable", func() (int64, error) { return 0, errors.New("statfs failed") }, errCutFreeUnreadable}, + } { + t.Run(c.name, func(t *testing.T) { + s, l, _, gate := cowFixture(t) + gate.mu.Lock() + gate.armed = false + gate.mu.Unlock() + l.cfg.COWSpillFree = c.read + l.testAfterStageHook = func(round int) { + if _, err := s.Write(1, makeBlock(ctBlockSize, byte(0x70+round))); err != nil { + t.Error(err) + } + if round == 1 { + gate.mu.Lock() + gate.armed = true + gate.mu.Unlock() + } + } + cutDone, cutErr := cowStartCut(t, l, gate) + w := l.cowActive.Load() + if w == nil { + t.Fatal("no copy window open while its copy is held") + } + w.mu.Lock() + limit, cause := w.spillLimit, w.spillCause + w.mu.Unlock() + if limit != 0 || !errors.Is(cause, c.cause) { + t.Fatalf("window cap %d cause %v; want 0 and %v from the cut's read", limit, cause, c.cause) + } + gate.unblock() + cowWaitSignal(t, cutDone, "cut with the window held") + if err := <-cutErr; err != nil { + t.Fatalf("cut: %v; want it to complete (the held copy needs no spill)", err) + } + }) + } +} + +// A save that meets a zero cap aborts the cut under the cap's own cause: +// no_room_to_cut or free_space_unreadable, not cow_capacity; the guest +// write completes and the next cut is not blocked. +func TestCutCOWV3_ZeroCapAbortIsCountedByItsCause(t *testing.T) { + for _, c := range []struct { + cause error + reason string + }{ + {errCutNoRoom, "no_room_to_cut"}, + {fmt.Errorf("%w: %w", errCutFreeUnreadable, errors.New("statfs failed")), "free_space_unreadable"}, + } { + t.Run(c.reason, func(t *testing.T) { + s, l, _, gate := cowFixture(t) + cutDone, cutErr := cowStartCut(t, l, gate) + w := l.cowActive.Load() + w.mu.Lock() + w.memory = cutCOWMemoryLimit // the in-memory budget is used + w.spillLimit, w.spillCause = 0, c.cause + w.mu.Unlock() + writeDone := make(chan struct{}) + writeErr := make(chan error, 1) + // Registered before the writer starts: release the copier and + // join the writer (bounded) whatever the test's outcome. + t.Cleanup(func() { gate.unblock(); cowWaitSignal(t, writeDone, "zero-cap writer cleanup") }) + go func() { + defer close(writeDone) + _, err := s.Write(5, makeBlock(ctBlockSize, 0xd7)) + writeErr <- err + }() + cowWaitSignal(t, writeDone, "guest write at a zero cap") + if err := <-writeErr; err != nil { + t.Fatal("guest write refused at a zero cap:", err) + } + gate.unblock() + cowWaitSignal(t, cutDone, "cut at a zero cap") + if err := <-cutErr; !errors.Is(err, errCutCOWAborted) || !errors.Is(err, c.cause) { + t.Fatalf("cut at a zero cap: %v, want an abort carrying %v", err, c.cause) + } + if st := l.Stats(); st.CutsAborted[c.reason] != 1 || st.CutsAborted["cow_capacity"] != 0 { + t.Fatalf("aborts %v; want one %s and no cow_capacity", st.CutsAborted, c.reason) + } + }) + } +} + +// The staging bound follows the free space read at the cut: with ample +// free space the fixture's two dirty chunks are within the bound and go to +// the barrier unstaged; with free space below the reserve the cap is 0, so +// the cut pre-uploads them in a staging round before the barrier. +func TestCutCOWV3_LowFreeSpaceStagesBeforeTheBarrier(t *testing.T) { + for _, c := range []struct { + name string + free int64 + wantStaged bool + }{ + {"ample free space", 100 << 30, false}, + {"free space below the reserve", 1 << 30, true}, + } { + t.Run(c.name, func(t *testing.T) { + _, l, _, gate := cowFixture(t) + gate.unblock() + l.cfg.COWSpillFree = func() (int64, error) { return c.free, nil } + r, err := l.Cut(context.Background()) + if err != nil { + t.Fatal(err) + } + if staged := r.Stats.StageRounds > 0 && r.Stats.StagedChunks >= 2; staged != c.wantStaged { + t.Fatalf("free %d: %d staging rounds, %d staged chunks; want staged=%v", c.free, r.Stats.StageRounds, r.Stats.StagedChunks, c.wantStaged) + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_cut_payload.go b/seaweed-block/core/storage/chunk_cut_payload.go index 3cac8535be..6e66f07433 100644 --- a/seaweed-block/core/storage/chunk_cut_payload.go +++ b/seaweed-block/core/storage/chunk_cut_payload.go @@ -58,7 +58,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, return err } ref, had := head.Chunks[c.idx] - if !c.zero && !(had && ref.SHA256 == c.sum) { + if !c.zero && !(had && ref.SHA256 == c.sum && !l.owning(c.idx)) { c.key, c.size = keys[i], len(c.data) once.Do(func() { intent, intentErr = l.remote.PutIntent(ctx, chunkIntent{Gen: head.Gen, Epoch: l.cfg.Epoch, Holder: l.cfg.Holder, Keys: keys}) diff --git a/seaweed-block/core/storage/chunk_cut_payload_budget_test.go b/seaweed-block/core/storage/chunk_cut_payload_budget_test.go index bf141d776b..7fae795b32 100644 --- a/seaweed-block/core/storage/chunk_cut_payload_budget_test.go +++ b/seaweed-block/core/storage/chunk_cut_payload_budget_test.go @@ -13,7 +13,7 @@ func TestCutPayloadBudgetBoundsSlots(t *testing.T) { for i := 0; i < candidates; i++ { pending[uint64(i)] = true } - w, err := l.installCOWWindow(pending, nil, nil) + w, err := l.installCOWWindow(pending, nil, nil, l.cowSpillLimit()) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/chunk_cut_progress_test.go b/seaweed-block/core/storage/chunk_cut_progress_test.go index a5d79f6fbf..97a0b0784b 100644 --- a/seaweed-block/core/storage/chunk_cut_progress_test.go +++ b/seaweed-block/core/storage/chunk_cut_progress_test.go @@ -121,3 +121,98 @@ func TestChunkStageV3_FourTimesCapConvergesUnderSteadyWrites(t *testing.T) { assertEveryHeadIsPrefixImage(t, f, w) assertNoIntentsLeft(t, f) } + +// Each of two deadlines interrupts the third upload, after two immutable chunks +// completed. The next pass must reuse those chunks rather than restart the set. +type deadlineProgressRemote struct { + successful map[string][]byte + *fakeChunkRemote + completed int + calls int + interrupt context.CancelCauseFunc +} + +func (r *deadlineProgressRemote) Put(ctx context.Context, key string, b []byte) error { + r.calls++ + if r.completed == 2 && r.interrupt != nil { + r.interrupt(context.DeadlineExceeded) + <-ctx.Done() + return context.Cause(ctx) + } + err := r.fakeChunkRemote.Put(ctx, key, b) + if err == nil { + r.completed++ + if _, exists := r.successful[key]; exists { + return errors.New("test: retransmitted unchanged successful key") + } + if r.successful == nil { + r.successful = map[string][]byte{} + } + r.successful[key] = append([]byte(nil), b...) + } + return err +} +func TestChunkStageV3_MultipleDeadlinesKeepProgress(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 5) + l.cfg.COWSpillLimit = ctChunkBytes + l.cfg.UploadConcurrency = 1 + r := &deadlineProgressRemote{fakeChunkRemote: f} + l.remote = r + base := f.stats().head.Gen + previous := 0 + lastSubmitted := s.NextLSN() - 1 + expectedImage := w.imageAt(lastSubmitted) + var finalHead chunkHead + for pass := 0; pass < 3; pass++ { + r.completed = 0 + r.calls = 0 + // Expire at the third PUT event, not one second after setup. This + // witnesses two completed immutable uploads even on a loaded host. + ctx, cancel := context.WithCancelCause(context.Background()) + r.interrupt = nil + if pass < 2 { + r.interrupt = cancel + } + result, err := l.Cut(ctx) + cancel(nil) + if pass < 2 { + if !errors.Is(err, context.DeadlineExceeded) || r.calls != 3 || r.completed != 2 { + t.Fatalf("pass %d did not reach injected deadline: %v", pass, err) + } + if f.stats().head.Gen != base { + t.Fatal("deadline moved HEAD") + } + l.stMu.Lock() + cached := len(l.reusable) + l.stMu.Unlock() + if cached <= previous { + t.Fatalf("pass %d restarted dirty set: cached=%d previous=%d", pass, cached, previous) + } + previous = cached + } else if err != nil || result.Head.Gen != base+1 { + t.Fatalf("third pass failed to publish: %+v %v", result, err) + } else { + finalHead = result.Head + } + } + // Five changed chunks, five successful puts, no retransmission after expiry. + if len(r.successful) != 5 { + t.Fatalf("successful upload keys=%d want5", len(r.successful)) + } + totalBytes := 0 + for _, payload := range r.successful { + totalBytes += len(payload) + } + if totalBytes != 5*ctChunkBytes { + t.Fatalf("uploaded bytes=%d want%d", totalBytes, 5*ctChunkBytes) + } + assertEveryHeadIsPrefixImage(t, f, w) + if finalHead.RemoteLSN != lastSubmitted { + t.Fatalf("final frontier=%d want last submitted=%d", finalHead.RemoteLSN, lastSubmitted) + } + assertImage(t, "final complete submitted image", f.imageOf(t, finalHead), expectedImage) + if previous != 4 { + t.Fatalf("reusable chunks=%d", previous) + } + assertNoIntentsLeft(t, f) +} diff --git a/seaweed-block/core/storage/chunk_frontier_v3_test.go b/seaweed-block/core/storage/chunk_frontier_v3_test.go index c965d17fc0..d4f5c4859c 100644 --- a/seaweed-block/core/storage/chunk_frontier_v3_test.go +++ b/seaweed-block/core/storage/chunk_frontier_v3_test.go @@ -5,7 +5,7 @@ import ( "testing" ) -// Plan row 9c controls (owner claude03): SeedChunkFrontier on a dark v3 +// Chunk-frontier controls: SeedChunkFrontier on a dark v3 // store uses the checkpoint's map/metadata barrier and the sole descriptor // publication (publishCheckpointV3), never the legacy superblock writer. diff --git a/seaweed-block/core/storage/chunk_frozen_budget.go b/seaweed-block/core/storage/chunk_frozen_budget.go index 4f6ce4090e..1e87bba27b 100644 --- a/seaweed-block/core/storage/chunk_frozen_budget.go +++ b/seaweed-block/core/storage/chunk_frozen_budget.go @@ -17,6 +17,35 @@ type FrozenDetachOptions struct { StartedAt time.Time AllowOverBudget bool } + +// FrozenBudget reports the storage-owned admission forecast and quiesce slack. +// A tail above the existing 60s ceiling is a saturated rejection sentinel, +// not a complete duration: it stays known but offers zero quiesce slack. +// INV-WS-FREEZE-ACCOUNTING-001: same-host durations; admission still rechecks. +type FrozenBudget struct { + FrozenEstimate time.Duration `json:"frozenEstimateNs"` + FrozenEstimateKnown bool `json:"frozenEstimateKnown"` + FreezeLimit time.Duration `json:"freezeLimitNs"` + MaxRefreezeQuiesce time.Duration `json:"maxRefreezeQuiesceNs"` +} + +func (r PrecopyReport) frozenBudgetEstimate() FrozenBudget { + b := FrozenBudget{FrozenEstimate: r.Estimate, FrozenEstimateKnown: r.Reason != "samples_unknown" && r.Estimate > 0, FreezeLimit: precopyFreezeLimit} + if b.FrozenEstimateKnown { + b.MaxRefreezeQuiesce = max(time.Duration(0), b.FreezeLimit-b.FrozenEstimate) + } + return b +} + +// FrozenRefusal keeps the admission observation attached to the typed error. +type FrozenRefusal struct{ Report PrecopyReport } + +func (e *FrozenRefusal) Error() string { + r := e.Report + return fmt.Sprintf("%s: reason=%s estimate=%s remaining=%s elapsed=%s", ErrFrozenTailTooLarge, r.Reason, r.Estimate, r.RemainingFreeze, r.GuestFreezeElapsed) +} +func (e *FrozenRefusal) Unwrap() error { return ErrFrozenTailTooLarge } + type frozenDetachKey struct{} func WithFrozenDetach(ctx context.Context, opts FrozenDetachOptions) (context.Context, error) { @@ -35,11 +64,17 @@ func FrozenDetachFromContext(ctx context.Context) (FrozenDetachOptions, bool) { func (r *PrecopyReport) admitFrozen(opts FrozenDetachOptions) bool { return r.admitFrozenAt(opts, time.Now()) } -func (r *PrecopyReport) admitFrozenAt(opts FrozenDetachOptions, now time.Time) bool { +func (r *PrecopyReport) observeFrozenAt(opts FrozenDetachOptions, now time.Time) { + r.FrozenBudget = r.frozenBudgetEstimate() r.GuestFrozen = true r.GuestFreezeElapsed = max(time.Duration(0), now.Sub(opts.StartedAt)) - r.RemainingFreeze = max(time.Duration(0), precopyFreezeLimit-r.GuestFreezeElapsed) - known := r.Reason != "samples_unknown" && r.Estimate > 0 + budget := r.FrozenBudget + r.RemainingFreeze = max(time.Duration(0), budget.FreezeLimit-r.GuestFreezeElapsed) +} + +func (r *PrecopyReport) admitFrozenAt(opts FrozenDetachOptions, now time.Time) bool { + r.observeFrozenAt(opts, now) + known := r.FrozenBudget.FrozenEstimateKnown if opts.AllowOverBudget { r.Reason = "over_budget" r.OverBudget = true @@ -56,19 +91,31 @@ func (r *PrecopyReport) admitFrozenAt(opts FrozenDetachOptions, now time.Time) b return true } func frozenRefusal(r PrecopyReport) error { - return fmt.Errorf("%w: reason=%s estimate=%s remaining=%s elapsed=%s", ErrFrozenTailTooLarge, r.Reason, r.Estimate, r.RemainingFreeze, r.GuestFreezeElapsed) + return &FrozenRefusal{Report: r} } // IsReplay distinguishes a replayed applied point from a newly completed freeze. // The original report remains unchanged on the wire. func (r PrecopyReport) IsReplay() bool { return r.replayed } -func (l *chunkLayerImpl) admitFrozen(r *PrecopyReport, opts FrozenDetachOptions) bool { +func (l *chunkLayerImpl) frozenNow() time.Time { now := time.Now() if hook := l.testFrozenNow; hook != nil { now = hook() } - return r.admitFrozenAt(opts, now) + return now +} + +// M5 frozen-detach report: observe before drain/reason handling, without +// deciding admission or overriding an existing refusal. +func (l *chunkLayerImpl) observeFrozen(r *PrecopyReport, opts FrozenDetachOptions, enabled bool) { + if enabled { + r.observeFrozenAt(opts, l.frozenNow()) + } +} + +func (l *chunkLayerImpl) admitFrozen(r *PrecopyReport, opts FrozenDetachOptions) bool { + return r.admitFrozenAt(opts, l.frozenNow()) } // RememberDetachReport completes the telemetry kept with an applied or still diff --git a/seaweed-block/core/storage/chunk_frozen_report_test.go b/seaweed-block/core/storage/chunk_frozen_report_test.go new file mode 100644 index 0000000000..22430ec208 --- /dev/null +++ b/seaweed-block/core/storage/chunk_frozen_report_test.go @@ -0,0 +1,102 @@ +package storage + +import ( + "context" + "encoding/json" + "errors" + "testing" + "time" +) + +func TestCandidateTailReportsCompleteFrozenBudget(t *testing.T) { + for _, tc := range []struct { + name string + fixed time.Duration + samples int + tail uint64 + estimate, slack int64 + known bool + }{ + {"d05_fixed_does_not_fit", 5370 * time.Millisecond, 3, 1000, 5570000000, 0, true}, + {"small_complete_estimate", 200 * time.Millisecond, 3, 1000, 400000000, 4600000000, true}, + {"known_zero_tail", 200 * time.Millisecond, 1, 0, 300000000, 4700000000, true}, + {"zero_tail_without_fixed_sample", 0, 0, 0, 0, 0, false}, + {"ceiling_boundary_is_complete", 200 * time.Millisecond, 3, 600000, 60300000000, 0, true}, + {"saturated_tail_is_non_actionable", 200 * time.Millisecond, 3, 610000, 60000000000, 0, true}, + {"partial_unknown_rate", 200 * time.Millisecond, 1, 1000, 300000000, 0, false}, + } { + t.Run(tc.name, func(t *testing.T) { + l := &chunkLayerImpl{} + for i := 0; i < tc.samples; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: tc.fixed, rate: 20000}) + } + tail := l.estimateCandidateTail(tc.tail) + b, err := json.Marshal(tail) + if err != nil { + t.Fatal(err) + } + var got map[string]json.RawMessage + if err = json.Unmarshal(b, &got); err != nil { + t.Fatal(err) + } + for key, want := range map[string]int64{"frozenEstimateNs": tc.estimate, "freezeLimitNs": 5000000000, "maxRefreezeQuiesceNs": tc.slack} { + var value int64 + if raw, ok := got[key]; !ok { + t.Errorf("missing %s: %s", key, b) + } else if err = json.Unmarshal(raw, &value); err != nil || value != want { + t.Errorf("%s=%s want %d", key, raw, want) + } + } + var known bool + if raw, ok := got["frozenEstimateKnown"]; !ok { + t.Errorf("missing frozenEstimateKnown: %s", b) + } else if err = json.Unmarshal(raw, &known); err != nil || known != tc.known { + t.Errorf("known=%s want %v", raw, tc.known) + } + }) + } +} + +func TestFrozenRefusalRetainsUnknownCompleteEstimate(t *testing.T) { + l := &chunkLayerImpl{precopySamples: []precopySample{{at: time.Now(), fixed: 200 * time.Millisecond, rate: 20000}}} + r := l.precopyEstimate(1000, 0) + now := time.Now() + if r.admitFrozenAt(FrozenDetachOptions{StartedAt: now}, now) { + t.Fatal("unknown rate admitted") + } + refusal, ok := frozenRefusal(r).(*FrozenRefusal) + if !ok || refusal.Report.FrozenEstimateKnown || refusal.Report.MaxRefreezeQuiesce != 0 || refusal.Report.FrozenEstimate != 300*time.Millisecond { + t.Fatalf("partial estimate became known after reason changed: %+v", r) + } +} + +func TestFrozenDrainObservationPreservesKnownBeforeReasonMutation(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 3) + w.write(t, s, 1, 0x71) + seedFrozenSamples(l, 200*time.Millisecond) + before := f.stats() + result, err := l.PrecopyDetachWithAdmission(frozenContext(t, time.Second, false), func(context.Context) (func(), error) { return nil, context.Canceled }, func() bool { t.Fatal("drain refusal stopped I/O"); return true }) + var refusal *FrozenRefusal + if !errors.As(err, &refusal) || result.Precopy.Reason != "drain_refused" { + t.Fatalf("drain path not witnessed: %+v %v", result.Precopy, err) + } + r := refusal.Report + if !r.FrozenEstimateKnown || r.FrozenEstimate != r.Estimate || r.FreezeLimit != 5*time.Second || r.GuestFreezeElapsed < time.Second || r.RemainingFreeze <= 0 || r.RemainingFreeze+r.GuestFreezeElapsed != 5*time.Second { + t.Fatalf("drain reason destroyed known observation: %+v", r) + } + after := f.stats() + if after.puts != before.puts || after.cas != before.cas { + t.Fatal("drain refusal did remote work") + } +} +func TestFrozenSaturatedTailRemainsKnownButNonActionable(t *testing.T) { + l := &chunkLayerImpl{} + for i := 0; i < 3; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: 200 * time.Millisecond, rate: 20000}) + } + r := l.precopyEstimate(610000, 0) // safe rate 10000 B/s -> 61s tail, beyond the existing ceiling. + now := time.Now() + if r.admitFrozenAt(FrozenDetachOptions{StartedAt: now}, now) || r.Estimate != 60*time.Second || r.TailEstimate != 60*time.Second || !r.FrozenEstimateKnown || r.FrozenEstimate != 60*time.Second || r.FreezeLimit != 5*time.Second || r.MaxRefreezeQuiesce != 0 { + t.Fatalf("saturated sentinel became actionable or changed admission: %+v", r) + } +} diff --git a/seaweed-block/core/storage/chunk_hydrate_all.go b/seaweed-block/core/storage/chunk_hydrate_all.go new file mode 100644 index 0000000000..17fae0e4b3 --- /dev/null +++ b/seaweed-block/core/storage/chunk_hydrate_all.go @@ -0,0 +1,272 @@ +package storage + +import ( + "context" + "errors" + "sync" + "time" +) + +// HydrateProgress reports one HydrateAll call. +// - Filled: chunks this call made local. +// - Remaining: chunks still absent (HEAD-named, with a block not written +// locally) when the call returned; 0 means the volume is fully local. +// - Paused: times the walker yielded to guest read misses. +// - Deferred: times the host limiter refused a fill (retried later). +type HydrateProgress struct { + Filled int + Remaining int + Paused uint64 + Deferred uint64 +} + +// Walker pacing: a guest wait or a refused fill is retried after a short +// backoff that doubles up to the cap. +var ( + hydrateAllMinBackoff = 20 * time.Millisecond + hydrateAllMaxBackoff = 2 * time.Second +) + +// HydrateAll makes every chunk local that HEAD names and the volume does not +// hold yet (an independent restore's background hydrate). It walks +// the absent chunks lowest index first through the same shared fill flights +// as guest read misses (one fetch per chunk, the hydration queue bound and +// the read-miss timeout apply), so it never fetches a chunk twice or races a +// guest fill. It yields while any flight has guest waiters; its own flights +// have no waiters, so workers serve guest flights first. +// +// Each fill holds one host-limiter permit (cfg.Budget), admitted with ctx and +// no cut payload, the background fill/idle contract (hostlimit Acquire): the +// caller sets the class on ctx (hostlimit.WithClass(ctx, +// hostlimit.BackgroundFill)). The permit belongs to the flight, not the wait: +// it is released only when the flight's I/O is over, also when the walker +// returns early on cancellation, revocation or close. The limiter's abort +// callback (revocation) stops the walker, which then returns the cause. +// +// It returns when nothing is absent, when ctx ends or the permit is revoked, +// or on a fill error that is not a retryable pending state; the caller may +// call it again. +func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error) { + return l.HydrateAllAt(ctx, 0) +} + +// HydrateAllAt is HydrateAll paced to at most bytesPerSecond of fill payload +// (one chunk per fill), counted from its start; 0 means unpaced. The pace +// applies before admission, so a paced walker holds no permit while it waits. +func (l *chunkLayerImpl) HydrateAllAt(ctx context.Context, bytesPerSecond int64) (HydrateProgress, error) { + var p HydrateProgress + start := time.Now() + started := int64(0) // fills started, for the pace + walk, stop := context.WithCancelCause(ctx) + defer stop(nil) + backoff := hydrateAllMinBackoff + quit := func(err error) (HydrateProgress, error) { + p.Remaining = l.absentHydratable() + return p, err + } + wait := func() error { + t := time.NewTimer(backoff) + defer t.Stop() + if backoff *= 2; backoff > hydrateAllMaxBackoff { + backoff = hydrateAllMaxBackoff + } + select { + case <-t.C: + return nil + case <-walk.Done(): + return context.Cause(walk) + case <-l.ctx.Done(): + return errChunkLayerClosed + } + } + for { + if walk.Err() != nil { + return quit(context.Cause(walk)) + } + lba, ok, guests := l.nextHydrateTarget() + if !ok { + p.Remaining = 0 + return p, nil + } + if guests > 0 { + p.Paused++ + if hook := l.testHydrateAllPause; hook != nil { + hook() + } + if err := wait(); err != nil { + return quit(err) + } + continue + } + if bytesPerSecond > 0 && started > 0 { + due := start.Add(time.Duration(float64(started*int64(l.chunkBlocks)*int64(l.blockSize)) / float64(bytesPerSecond) * float64(time.Second))) + if d := time.Until(due); d > 0 { + t := time.NewTimer(d) + select { + case <-t.C: + case <-walk.Done(): + t.Stop() + return quit(context.Cause(walk)) + case <-l.ctx.Done(): + t.Stop() + return quit(errChunkLayerClosed) + } + } + } + release, err := l.admitFill(walk, stop) + if err != nil { + p.Deferred++ + if err := wait(); err != nil { + return quit(err) + } + continue + } + f, err := l.startWalkerFill(lba, release) + if err != nil { + if errors.Is(err, ErrChunkHydrationPending) { + if err := wait(); err != nil { // queue full: retry later + return quit(err) + } + continue + } + return quit(err) + } + if f == nil { + continue // resolved meanwhile + } + started++ + select { + case <-f.done: + case <-walk.Done(): + return quit(context.Cause(walk)) + case <-l.ctx.Done(): + return quit(errChunkLayerClosed) + } + l.stMu.Lock() + changed := l.absentGen[f.idx] != f.gen || l.head.Chunks[f.idx] != f.ref + ferr := f.err + l.stMu.Unlock() + switch { + case changed: + // a newer absence or HEAD: the next pass looks again + case ferr == nil: + p.Filled++ + backoff = hydrateAllMinBackoff + case errors.Is(ferr, ErrChunkHydrationPending): + if err := wait(); err != nil { // the read-miss timeout: retry later + return quit(err) + } + default: + return quit(ferr) + } + } +} + +// startWalkerFill queues (or joins) the fill flight of lba's chunk without +// becoming a waiter, and hands the permit's release to the flight's +// settlement: a layer-owned goroutine releases it once the flight's I/O is +// over, whatever the walker does meanwhile. A nil flight means nothing is to +// fetch any more (release already called). +func (l *chunkLayerImpl) startWalkerFill(lba uint64, release func()) (*chunkHydrationFlight, error) { + idx := l.chunkOf(lba) + l.stMu.Lock() + defer l.stMu.Unlock() + if l.closed { + release() + return nil, errChunkLayerClosed + } + ref, named := l.head.Chunks[idx] + if !l.absent[idx] || l.localBlocks[lba] || !named { + release() + return nil, nil + } + f, _, err := l.hydrationFlightLocked(idx, ref) + if err != nil { + release() + return nil, err + } + l.wakeHydrationLocked() + // Close joins wg only after taking stMu and marking closed; every queued + // flight is settled by closeHydrationLocked, every running one by its worker. + l.wg.Add(1) + go func() { + defer l.wg.Done() + <-f.settled + release() + }() + return f, nil +} + +// nextHydrateTarget returns a block of the lowest-index chunk that HEAD names, +// is absent and has a block without a local extent version (localBlocks: a +// chunk whose every block reached the extent needs no fetch; a write still only +// in the WAL does not count, and the fill never overwrites it), and the number +// of flights that have guest waiters. +func (l *chunkLayerImpl) nextHydrateTarget() (lba uint64, ok bool, guests int) { + l.stMu.Lock() + defer l.stMu.Unlock() + for _, f := range l.hydration { + if f.waiters > 0 { + guests++ + } + } + best := uint64(0) + for idx := range l.absent { + if !l.absent[idx] || (ok && idx >= best) { + continue + } + if b, has := l.hydratableBlockLocked(idx); has { + best, lba, ok = idx, b, true + } + } + return lba, ok, guests +} + +// absentHydratable counts the chunks nextHydrateTarget would still visit. +func (l *chunkLayerImpl) absentHydratable() int { + l.stMu.Lock() + defer l.stMu.Unlock() + n := 0 + for idx, absent := range l.absent { + if _, has := l.hydratableBlockLocked(idx); absent && has { + n++ + } + } + return n +} + +// hydratableBlockLocked returns a block of chunk idx that is not written +// locally, if HEAD names the chunk. Caller holds stMu. +func (l *chunkLayerImpl) hydratableBlockLocked(idx uint64) (uint64, bool) { + if _, named := l.head.Chunks[idx]; !named { + return 0, false + } + first := idx * l.chunkBlocks + for i := uint64(0); i < l.chunkBlocks; i++ { + b := first + i + if b >= uint64(l.s.NumBlocks()) { + break + } + if !l.localBlocks[b] { + return b, true + } + } + return 0, false +} + +// admitFill takes one background permit from the host limiter, if there is +// one: no cut payload (a fill/idle permit carries none and the limiter refuses +// one), the class from ctx. A revocation runs abort, which stops the walker. +// The returned release gives the permit back, once. +func (l *chunkLayerImpl) admitFill(ctx context.Context, abort func(error)) (func(), error) { + host := l.cfg.Budget + if host == nil { + return func() {}, nil + } + ticket, err := host.Admit(ctx, 0, abort) + if err != nil { + return nil, err + } + var once sync.Once + return func() { once.Do(func() { host.Release(ticket) }) }, nil +} diff --git a/seaweed-block/core/storage/chunk_hydrate_all_test.go b/seaweed-block/core/storage/chunk_hydrate_all_test.go new file mode 100644 index 0000000000..9efd0c2d57 --- /dev/null +++ b/seaweed-block/core/storage/chunk_hydrate_all_test.go @@ -0,0 +1,459 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/hostlimit" +) + +func countGets(r *fakeChunkRemote) map[string]int { + r.mu.Lock() + defer r.mu.Unlock() + out := map[string]int{} + for _, op := range r.ops { + if key, ok := strings.CutPrefix(op, "get:"); ok { + out[key]++ + } + } + return out +} + +func fastWalker(t *testing.T) { + t.Helper() + minB, maxB := hydrateAllMinBackoff, hydrateAllMaxBackoff + hydrateAllMinBackoff, hydrateAllMaxBackoff = time.Millisecond, 5*time.Millisecond + t.Cleanup(func() { hydrateAllMinBackoff, hydrateAllMaxBackoff = minB, maxB }) +} + +// walkRun is one HydrateAll call on its own goroutine. Its ctx is cancelled +// and its return joined (bounded) at cleanup, registered before launch. +type walkRun struct { + done chan struct{} + cancel context.CancelFunc + p HydrateProgress + err error +} + +func startWalker(t *testing.T, layer *chunkLayerImpl, parent context.Context) *walkRun { + t.Helper() + ctx, cancel := context.WithCancel(parent) + w := &walkRun{done: make(chan struct{}), cancel: cancel} + t.Cleanup(func() { + cancel() + select { + case <-w.done: + case <-time.After(ctLocalBound): + t.Error("cleanup: walker did not return") + } + }) + go func() { + w.p, w.err = layer.HydrateAll(ctx) + close(w.done) + }() + return w +} + +func (w *walkRun) wait(t *testing.T, what string) { + t.Helper() + select { + case <-w.done: + case <-time.After(ctLocalBound): + t.Fatalf("%s: walker did not return", what) + } +} + +func walkerSignal[T any](t *testing.T, ch <-chan T, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(ctLocalBound): + t.Fatalf("timed out waiting for %s", what) + } +} + +// waitUntil polls cond (bounded by ctLocalBound); permits are released +// asynchronously, when each flight settles. +func waitUntil(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(ctLocalBound) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting until %s", what) + } + time.Sleep(time.Millisecond) + } +} + +// fillLimiter is a real host limiter on pool dir with fillSlots fill permits. +func fillLimiter(t *testing.T, dir string, fillSlots int) *hostlimit.Limiter { + t.Helper() + c := hostlimit.DefaultConfig(dir) + c.FillSlots = fillSlots + l, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + t.Cleanup(l.Close) + return l +} + +// payloadRecorder passes admissions to a real Budget and records each payload. +type payloadRecorder struct { + Budget + mu sync.Mutex + payloads []int64 +} + +func (r *payloadRecorder) Admit(ctx context.Context, payload int64, abort func(error)) (uint64, error) { + r.mu.Lock() + r.payloads = append(r.payloads, payload) + r.mu.Unlock() + return r.Budget.Admit(ctx, payload, abort) +} + +// boundedCtx bounds a synchronous walk so that a walker that never finishes +// fails the test instead of hanging it. +func boundedCtx(t *testing.T, parent context.Context) context.Context { + t.Helper() + ctx, cancel := context.WithTimeout(parent, ctLocalBound) + t.Cleanup(cancel) + return ctx +} + +func bgFill() context.Context { + return hostlimit.WithClass(context.Background(), hostlimit.BackgroundFill) +} + +func TestHydrateAll_FillsEveryChunkOnceAndReadsTheHeadImage(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + ctx := boundedCtx(t, context.Background()) + p, err := layer.HydrateAll(ctx) + if err != nil || p.Remaining != 0 || p.Filled != ctNumBlocks/ctChunkBlocks { + t.Fatalf("hydrate all: %+v %v, want %d filled, 0 remaining", p, err, ctNumBlocks/ctChunkBlocks) + } + for key, n := range countGets(remote) { + if n != 1 { + t.Fatalf("chunk %s fetched %d times, want exactly once", key, n) + } + } + for b := uint32(0); b < ctNumBlocks; b++ { + got, err := s.Read(b) + if err != nil || !bytes.Equal(got, makeBlock(ctBlockSize, byte(0x40+b))) { + t.Fatalf("block %d after hydrate: %v", b, err) + } + } + before := len(countGets(remote)) + if p, err := layer.HydrateAll(ctx); err != nil || p.Filled != 0 || p.Remaining != 0 || len(countGets(remote)) != before { + t.Fatalf("a second walk of a full volume must do nothing: %+v %v", p, err) + } +} + +// A guest write that is still only in the WAL is not visible to the walker as +// local (localBlocks is set when the extent gets a local version), so the chunk +// may be fetched; the fill must never overwrite the local write (reads resolve +// the WAL first and the fill installs only blocks without a newer local version). +func TestHydrateAll_NeverOverwritesALocalWrite(t *testing.T) { + fastWalker(t) + s, layer, _, _ := hydrationFixture(t, 2, 64) + for i := uint32(0); i < ctChunkBlocks; i++ { // chunk 0 fully overwritten + if _, err := s.Write(i, makeBlock(ctBlockSize, 0xEE)); err != nil { + t.Fatal(err) + } + } + if _, err := s.Write(ctChunkBlocks+1, makeBlock(ctBlockSize, 0xEF)); err != nil { // one block of chunk 1 + t.Fatal(err) + } + p, err := layer.HydrateAll(boundedCtx(t, context.Background())) + if err != nil || p.Remaining != 0 { + t.Fatalf("hydrate all: %+v %v", p, err) + } + for i := uint32(0); i < ctChunkBlocks; i++ { + if got, _ := s.Read(i); !bytes.Equal(got, makeBlock(ctBlockSize, 0xEE)) { + t.Fatalf("block %d: the local write was overwritten by the walker", i) + } + } + if got, _ := s.Read(ctChunkBlocks + 1); !bytes.Equal(got, makeBlock(ctBlockSize, 0xEF)) { + t.Fatal("partial local write in chunk 1 overwritten") + } + if got, _ := s.Read(ctChunkBlocks); !bytes.Equal(got, makeBlock(ctBlockSize, byte(0x40+ctChunkBlocks))) { + t.Fatal("the unwritten blocks of chunk 1 must read HEAD's bytes after the walk") + } +} + +// The walker's deferral is witnessed (its pause hook fires) while the guest's +// fetch is held, before anything is allowed to progress. +func TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice(t *testing.T) { + fastWalker(t) + s, layer, remote, registered := hydrationFixture(t, 2, 64) + paused := make(chan struct{}, 1) + layer.testHydrateAllPause = func() { + select { + case paused <- struct{}{}: + default: + } + } + entered, release := holdNextGet(t, remote) + guest := startHydrationRead(t, s, context.Background(), 5*ctChunkBlocks) + waitHydrationRegistration(t, registered, 1) + walkerSignal(t, entered, "the guest's fetch of chunk 5") + w := startWalker(t, layer, context.Background()) + walkerSignal(t, paused, "the walker to yield to the held guest fetch") + if n := len(countGets(remote)); n != 1 { + t.Fatalf("the walker fetched while a guest was waiting: %d distinct gets", n) + } + release() + if r := hydrationOutcome(t, guest); r.err != nil { + t.Fatalf("guest read: %v", r.err) + } + w.wait(t, "after the guest fill") + if w.err != nil || w.p.Remaining != 0 || w.p.Paused == 0 || w.p.Filled != ctNumBlocks/ctChunkBlocks-1 { + t.Fatalf("walker: %+v %v, want paused for the guest and the 7 other chunks filled", w.p, w.err) + } + for key, n := range countGets(remote) { + if n != 1 { + t.Fatalf("chunk %s fetched %d times", key, n) + } + } +} + +type walkerClassKey struct{} + +type walkerBudget struct { + mu sync.Mutex + refuse int + admitted int + released int + classes []any + abort func(error) +} + +func (b *walkerBudget) Admit(ctx context.Context, _ int64, abort func(error)) (uint64, error) { + b.mu.Lock() + defer b.mu.Unlock() + b.classes = append(b.classes, ctx.Value(walkerClassKey{})) + b.abort = abort + if b.refuse > 0 { + b.refuse-- + return 0, errors.New("fill class over budget") + } + b.admitted++ + return uint64(b.admitted), nil +} +func (b *walkerBudget) ReserveCOW(uint64, int64) error { return nil } +func (b *walkerBudget) Release(uint64) { + b.mu.Lock() + b.released++ + b.mu.Unlock() +} + +func (b *walkerBudget) counts() (admitted, released int) { + b.mu.Lock() + defer b.mu.Unlock() + return b.admitted, b.released +} + +func TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass(t *testing.T) { + fastWalker(t) + _, layer, _, _ := hydrationFixture(t, 2, 64) + budget := &walkerBudget{refuse: 2} + layer.cfg.Budget = budget + ctx := boundedCtx(t, context.WithValue(context.Background(), walkerClassKey{}, "fill")) + p, err := layer.HydrateAll(ctx) + if err != nil || p.Remaining != 0 || p.Deferred != 2 { + t.Fatalf("hydrate all: %+v %v, want 2 deferred then everything filled", p, err) + } + waitUntil(t, "every permit is released", func() bool { a, r := budget.counts(); return a == r }) + budget.mu.Lock() + defer budget.mu.Unlock() + if budget.admitted != p.Filled { + t.Fatalf("budget admitted %d, filled %d: every fill admitted once", budget.admitted, p.Filled) + } + for _, c := range budget.classes { + if c != "fill" { + t.Fatalf("the caller's limiter class did not reach Admit: %v", c) + } + } +} + +func TestHydrateAll_CancelReturnsWhileTheFetchIsHeld(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + entered, _ := holdNextGet(t, remote) + w := startWalker(t, layer, context.Background()) + walkerSignal(t, entered, "the walker's first fetch") + w.cancel() + w.wait(t, "cancel with the fetch still held") + if !errors.Is(w.err, context.Canceled) || w.p.Remaining == 0 { + t.Fatalf("cancelled walk: %+v %v, want context.Canceled and chunks remaining", w.p, w.err) + } +} + +// The real limiter refuses a background permit that carries a cut payload: +// every fill must be admitted as a fill permit (no payload) under +// BackgroundFill, fill the HEAD image exactly, and give every permit back. +func TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + lim := fillLimiter(t, t.TempDir(), 2) + rec := &payloadRecorder{Budget: lim} + layer.cfg.Budget = rec + ctx, cancel := context.WithTimeout(bgFill(), ctLocalBound) + defer cancel() + p, err := layer.HydrateAll(ctx) + // A refusal is possible while an earlier permit is still being closed by + // the limiter; it is a deferral, and the limiter counts it as a skip. + if err != nil || p.Remaining != 0 || p.Filled != ctNumBlocks/ctChunkBlocks { + t.Fatalf("hydrate all under the real limiter: %+v %v", p, err) + } + for b := uint32(0); b < ctNumBlocks; b++ { + if got, err := s.Read(b); err != nil || !bytes.Equal(got, makeBlock(ctBlockSize, byte(0x40+b))) { + t.Fatalf("block %d after hydrate: %v", b, err) + } + } + for key, n := range countGets(remote) { + if n != 1 { + t.Fatalf("chunk %s fetched %d times", key, n) + } + } + rec.mu.Lock() + for _, n := range rec.payloads { + if n != 0 { + t.Fatalf("fill admitted with a %d-byte cut payload", n) + } + } + rec.mu.Unlock() + waitUntil(t, "every fill permit is admitted once and released", func() bool { + st := lim.Snapshot().(hostlimit.Stats) + return st.Admitted == uint64(p.Filled) && st.Released == st.Admitted && st.Active == 0 && st.Skipped == p.Deferred + }) +} + +// The permit follows the owned flight, not the walker's wait: a cancelled +// walker returns at once, but its fill permit stays taken until the held +// physical Get settles. +func TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + dir := t.TempDir() + layer.cfg.Budget = fillLimiter(t, dir, 1) + contender := fillLimiter(t, dir, 1) + entered, release := holdNextGet(t, remote) + w := startWalker(t, layer, bgFill()) + walkerSignal(t, entered, "the walker's fetch") + w.cancel() + w.wait(t, "cancel with the fetch still held") + if !errors.Is(w.err, context.Canceled) { + t.Fatalf("cancelled walk: %v", w.err) + } + if tk, err := contender.Acquire(context.Background(), hostlimit.BackgroundFill, nil); err == nil { + contender.Release(tk) + t.Fatal("the fill permit was free while the walker's Get was still running") + } else if !errors.Is(err, hostlimit.ErrBusy) { + t.Fatalf("contender: %v", err) + } + release() + waitUntil(t, "the permit is free after the Get settled", func() bool { + tk, err := contender.Acquire(context.Background(), hostlimit.BackgroundFill, nil) + if err == nil { + contender.Release(tk) + } + return err == nil + }) +} + +// A limiter revocation (the abort callback) stops the walker with the cause; +// the permit is still released only when the owned fetch settles. +func TestHydrateAll_RevocationStopsTheWalker(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + budget := &walkerBudget{} + layer.cfg.Budget = budget + entered, release := holdNextGet(t, remote) + w := startWalker(t, layer, context.Background()) + walkerSignal(t, entered, "the walker's fetch") + budget.mu.Lock() + abort := budget.abort + budget.mu.Unlock() + abort(hostlimit.ErrRevoked) + w.wait(t, "revocation with the fetch still held") + if !errors.Is(w.err, hostlimit.ErrRevoked) { + t.Fatalf("revoked walk: %v, want ErrRevoked", w.err) + } + if _, r := budget.counts(); r != 0 { + t.Fatal("permit released before the owned fetch settled") + } + release() + waitUntil(t, "the permit is released after the fetch settled", func() bool { _, r := budget.counts(); return r == 1 }) +} + +func TestHydrateAll_StatsReportAbsentChunks(t *testing.T) { + fastWalker(t) + _, layer, _, _ := hydrationFixture(t, 2, 64) + if n := layer.Stats().AbsentChunks; n != ctNumBlocks/ctChunkBlocks { + t.Fatalf("absent before the walk: %d, want %d", n, ctNumBlocks/ctChunkBlocks) + } + if _, err := layer.HydrateAll(boundedCtx(t, context.Background())); err != nil { + t.Fatal(err) + } + if n := layer.Stats().AbsentChunks; n != 0 { + t.Fatalf("absent after the walk: %d, want 0", n) + } +} + +// The walker's byte pace bounds the fill rate: 8 chunks at 4 chunks/s take +// at least (8-1)/4 s. +func TestHydrateAll_PacedByByteRate(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + budget := &timedBudget{} + layer.cfg.Budget = budget // admission times witness the pace + rate := int64(4 * ctChunkBytes) + origin := time.Now() // a lower bound of the walker's own pace start + p, err := layer.HydrateAllAt(boundedCtx(t, context.Background()), rate) + want := ctNumBlocks / ctChunkBlocks + if err != nil || p.Remaining != 0 || p.Filled != want { + t.Fatalf("paced walk: %+v %v, want all %d chunks filled", p, err, want) + } + gets := 0 + for _, n := range countGets(remote) { + gets += n + } + if gets != want { + t.Fatalf("%d remote Gets, want %d", gets, want) + } + budget.mu.Lock() + defer budget.mu.Unlock() + if len(budget.at) != want { + t.Fatalf("%d admissions, want %d", len(budget.at), want) + } + for i := 1; i < len(budget.at); i++ { + // fill i is admitted no earlier than i chunks at the rate after the + // walker started, and the walker started after origin + due := origin.Add(time.Duration(i) * time.Second / 4) + if budget.at[i].Before(due) { + t.Fatalf("fill %d admitted %v after the call, before its pace time %v", i, budget.at[i].Sub(origin), due.Sub(origin)) + } + } +} + +// timedBudget admits every fill and records when. +type timedBudget struct { + mu sync.Mutex + at []time.Time +} + +func (b *timedBudget) Admit(context.Context, int64, func(error)) (uint64, error) { + b.mu.Lock() + defer b.mu.Unlock() + b.at = append(b.at, time.Now()) + return uint64(len(b.at)), nil +} +func (b *timedBudget) ReserveCOW(uint64, int64) error { return nil } +func (b *timedBudget) Release(uint64) {} diff --git a/seaweed-block/core/storage/chunk_hydration.go b/seaweed-block/core/storage/chunk_hydration.go index 2291ea22cc..510ed56ed2 100644 --- a/seaweed-block/core/storage/chunk_hydration.go +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -16,16 +16,16 @@ const defaultHydrationQueueDepth = 64 // ChunkHydrationStats separates wait refusals from owned fetch outcomes. // A wait refusal is not necessarily a wire completion (a caller may cancel). type ChunkHydrationStats struct { - WorkerLimit int - QueueDepth int - Active int - Queued int - WaitCalls uint64 - Joined uint64 - WaitRefusals uint64 - Fetches uint64 - Completed uint64 - FetchErrors uint64 + WorkerLimit int // fetch workers allowed (--chunk-hydration-workers) + QueueDepth int // fetch queue capacity (--chunk-hydration-queue-depth) + Active int // fetches running now + Queued int // fetches waiting for a worker now + WaitCalls uint64 // reads that waited for a chunk to arrive + Joined uint64 // of those, reads that joined a fetch already running + WaitRefusals uint64 // waits that ended without the chunk (the caller cancelled, or the fetch was not admitted) + Fetches uint64 // fetches started + Completed uint64 // fetches that installed the chunk + FetchErrors uint64 // fetches that failed } type chunkHydrationFlight struct { @@ -34,6 +34,7 @@ type chunkHydrationFlight struct { ctx context.Context cancel context.CancelFunc done chan struct{} + settled chan struct{} // closed once its I/O is over: after fillOnce, or removal unrun running bool waiters int err error @@ -76,39 +77,15 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b l.stMu.Unlock() return nil, hydrationPending(err) } - gen := l.absentGen[idx] - f := l.hydration[idx] - stale := f != nil && (f.gen != gen || f.ref != ref) - if stale { - f.cancel() - // The old worker remains owned and joined, but cannot delay a - // new generation or remove its replacement when it finishes. - delete(l.hydration, idx) - close(f.done) - f = nil + f, joined, err := l.hydrationFlightLocked(idx, ref) + if err != nil { + l.stats.Hydration.WaitRefusals++ + l.stMu.Unlock() + return nil, err } - if f != nil && !stale { + if joined { l.stats.Hydration.Joined++ } - if f == nil { - if len(l.hydration) >= l.cfg.HydrationQueueDepth { - l.stats.Hydration.WaitRefusals++ - l.stMu.Unlock() - return nil, hydrationPending(nil) - } - if !l.hydrationStarted { - l.hydration = make(map[uint64]*chunkHydrationFlight) - l.hydrationWake = make(chan struct{}, 1) - l.hydrationStarted = true - l.wg.Add(l.cfg.HydrationWorkers) - for i := 0; i < l.cfg.HydrationWorkers; i++ { - go l.hydrationWorker() - } - } - work, cancel := context.WithCancel(l.ctx) - f = &chunkHydrationFlight{idx: idx, gen: gen, ref: ref, ctx: work, cancel: cancel, done: make(chan struct{})} - l.hydration[idx] = f - } f.waiters++ l.wakeHydrationLocked() l.stMu.Unlock() @@ -138,7 +115,7 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b f.waiters-- closed := l.closed changed := l.absentGen[idx] != f.gen || l.head.Chunks[idx] != f.ref - err := f.err + err = f.err if !closed && !changed && errors.Is(err, ErrChunkHydrationPending) { l.stats.Hydration.WaitRefusals++ } @@ -157,6 +134,46 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b } } +// hydrationFlightLocked returns the flight for chunk idx's current absence +// (generation and HEAD ref): an existing one (joined) or a new queued one. A +// stale flight of an older generation is settled and replaced. It refuses with +// hydrationPending when the queue is full. The caller holds stMu, counts its +// own waiter and wakes the workers. +func (l *chunkLayerImpl) hydrationFlightLocked(idx uint64, ref chunkRef) (*chunkHydrationFlight, bool, error) { + gen := l.absentGen[idx] + f := l.hydration[idx] + if f != nil && (f.gen != gen || f.ref != ref) { + f.cancel() + // The old worker remains owned and joined, but cannot delay a + // new generation or remove its replacement when it finishes. + delete(l.hydration, idx) + close(f.done) + if !f.running { + close(f.settled) // never picked up: no I/O will run + } + f = nil + } + if f != nil { + return f, true, nil + } + if len(l.hydration) >= l.cfg.HydrationQueueDepth { + return nil, false, hydrationPending(nil) + } + if !l.hydrationStarted { + l.hydration = make(map[uint64]*chunkHydrationFlight) + l.hydrationWake = make(chan struct{}, 1) + l.hydrationStarted = true + l.wg.Add(l.cfg.HydrationWorkers) + for i := 0; i < l.cfg.HydrationWorkers; i++ { + go l.hydrationWorker() + } + } + work, cancel := context.WithCancel(l.ctx) + f = &chunkHydrationFlight{idx: idx, gen: gen, ref: ref, ctx: work, cancel: cancel, done: make(chan struct{}), settled: make(chan struct{})} + l.hydration[idx] = f + return f, false, nil +} + func (l *chunkLayerImpl) wakeHydrationLocked() { select { case l.hydrationWake <- struct{}{}: @@ -196,6 +213,7 @@ func (l *chunkLayerImpl) hydrationWorker() { resolved, err := l.fillOnce(fetch, next.idx, next.gen, next.ref) cancel() next.cancel() + close(next.settled) l.stMu.Lock() if hydrationContextCauseOnly(err) { err = hydrationPending(err) @@ -225,6 +243,7 @@ func (l *chunkLayerImpl) closeHydrationLocked() { f.err = errChunkLayerClosed delete(l.hydration, idx) close(f.done) + close(f.settled) } } } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index a1e3950549..c7d7b2c21a 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -69,7 +69,12 @@ type chunkLayerImpl struct { ctx context.Context // cancelled by Close cancel context.CancelFunc - wg sync.WaitGroup // captures and fills in flight + // settled: confirmed publications not yet reported to + // cfg.OnPublishSettled, in publication order; settledDraining: a caller + // is delivering them (both stMu). + settled []headTransition + settledDraining bool + wg sync.WaitGroup // captures and fills in flight cowMu sync.Mutex // window admission only; never held during reads or joins cow *cutCOWWindow @@ -116,6 +121,9 @@ type chunkLayerImpl struct { dirty map[uint64]bool // chunks dirtied since the cut in progress or the last HEAD inflight map[uint64]bool // chunks captured by a cut whose HEAD is not yet installed allDirty bool // a BASE block landed: every chunk is dirty + // own names the chunks OwnBatch re-uploads under this layer's own keys in + // the cut it runs (set and cleared under capMu, read under stMu). + own map[uint64]bool cutLSN uint64 // H of the latest cut taken (in flight or installed) // chunkMut counts the mutations of each chunk: every dirty-map insert @@ -127,6 +135,7 @@ type chunkLayerImpl struct { // Test-only scheduling hooks; nil in production. testHydrationWait func(uint64) // after promise registration, outside locks + testHydrateAllPause func() // HydrateAll yielded to a guest waiter, outside locks testCOWWait func() testCOWSaverWait func() testCOWRead func(idx uint64, saved bool) @@ -404,6 +413,7 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { absent[idx] = true } } + l.addOwnCandidatesLocked(out) l.stMu.Unlock() l.s.mu.RLock() for idx, e := range l.s.v3.mapEntries { @@ -530,12 +540,12 @@ func (s *WALStore) installFetchedBlock(lba uint32, data []byte, stillAbsent func func (l *chunkLayerImpl) BeginBaseInstall() error { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() return fmt.Errorf("%w: BASE state must be published by the descriptor install protocol", errV3NotYet) } func (l *chunkLayerImpl) EndBaseInstall(frontier uint64) error { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() if cp := l.s.CheckpointLSN(); cp < frontier { return fmt.Errorf("storage: EndBaseInstall: frontier %d is not durable (checkpoint %d)", frontier, cp) } @@ -594,7 +604,7 @@ func (l *chunkLayerImpl) admit() (err error) { func (l *chunkLayerImpl) Cut(ctx context.Context) (chunkCutResult, error) { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() return l.captureLocked(ctx, false) } @@ -608,7 +618,7 @@ func (l *chunkLayerImpl) Capture(ctx context.Context) (uint64, error) { func (l *chunkLayerImpl) MakeRemoteDurable(ctx context.Context, t uint64) error { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() l.stMu.Lock() fenced, detached := l.fenced, l.detached != nil l.stMu.Unlock() @@ -764,8 +774,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch var staged map[uint64]stagedChunk var intents []string _, guestFrozen := FrozenDetachFromContext(ctx) + spill := l.readCutSpill() if !guestFrozen { - staged, intents, err = l.stage(ctx, &st) + staged, intents, err = l.stage(ctx, &st, spill.bytes) } if st.UploadedBytes > 0 { st.PayloadNs += time.Since(stageStart).Nanoseconds() @@ -910,7 +921,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch { var w *cutCOWWindow windowStart := time.Now() - w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks) + w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks, spill) if copyErr == nil { w.budget = budget } @@ -972,7 +983,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch c.birth = births[c.idx] ref, had := baseHead.Chunks[c.idx] switch { - case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum: + case c.zero && !had, unchangedFromHead(c, ref, had): st.UnchangedChunks++ continue case c.zero: @@ -1164,7 +1175,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() if r, ok := l.storedDetach(); ok { return r, nil } @@ -1185,7 +1196,7 @@ func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) { // successful cancel. resolvePending would re-propose the detach instead. func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (detachSettlement, chunkCutResult, error) { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() if r, ok := l.storedDetach(); ok { return detachApplied, r, nil } @@ -1242,6 +1253,7 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (detachSettlement, ch l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} switch { case sameProposal(cur, *pending): + l.noteSettled(l.head, cur) l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN cut.Head = copyHead(cur) l.detached = &cut @@ -1370,6 +1382,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} switch { case sameProposal(cur, *pending): + l.noteSettled(l.head, cur) l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN if wasDetach { cut.Head = copyHead(cur) @@ -1404,6 +1417,10 @@ func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error switch { case errors.Is(err, errCutSaverCapacity): abortReason = "saver_capacity" + case errors.Is(err, errCutFreeUnreadable): + abortReason = "free_space_unreadable" + case errors.Is(err, errCutNoRoom): + abortReason = "no_room_to_cut" case errors.Is(err, errCutCOWCapacity): abortReason = "cow_capacity" case errors.Is(err, errCutBudgetRevoked): @@ -1474,6 +1491,7 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats { l.stMu.Unlock() out.DirtyChunks = len(l.captureCandidates()) + out.AbsentChunks = l.absentHydratable() return out } @@ -1538,10 +1556,10 @@ func (l *chunkLayerImpl) dropIntents(ctx context.Context, ids []string) { // stage uploads large native dirty sets through logical reads, before fixing H. // It stops when the spill-budget remainder is reached or a round makes no // progress. Versions/HEAD generation bind every reusable immutable result. -func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint64]stagedChunk, []string, error) { +func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap int64) (map[uint64]stagedChunk, []string, error) { // Leave at most half the side budget exposed at the barrier. Streaming // staging uses no local payload file, even for a much larger image. - bound := int(l.cfg.COWSpillLimit / (2 * int64(l.blockSize) * int64(l.chunkBlocks))) + bound := int(spillCap / (2 * int64(l.blockSize) * int64(l.chunkBlocks))) staged := map[uint64]stagedChunk{} var intents []string @@ -1649,6 +1667,7 @@ func (l *chunkLayerImpl) abortCut(all bool) { func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, newKeys map[uint64]string) { l.stMu.Lock() defer l.stMu.Unlock() + l.noteSettled(l.head, head) l.head, l.remoteLSN, l.pending = copyHead(head), h, nil l.reusable = nil l.inflight = map[uint64]bool{} @@ -1677,7 +1696,7 @@ func isAllZero(b []byte) bool { func (l *chunkLayerImpl) EvictChunk(idx uint64) error { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() if idx >= l.numChunks { return fmt.Errorf("%w: chunk %d out of range", errChunkEvictRefused, idx) } @@ -1856,7 +1875,13 @@ func (l *chunkLayerImpl) Close() error { if w != nil { w.join() } + if h := testCloseJoinHook; h != nil { + h() // tests: Close has cancelled the layer and now joins its owners, the drainer among them + } l.wg.Wait() + if h := testCloseJoinedHook; h != nil { + h() // tests: the join returned + } l.stMu.Lock() protected := make(map[string]bool, len(l.pendingIntents)) for _, id := range l.pendingIntents { diff --git a/seaweed-block/core/storage/chunk_layer_contract_test.go b/seaweed-block/core/storage/chunk_layer_contract_test.go index 86dd77f065..4be2a15173 100644 --- a/seaweed-block/core/storage/chunk_layer_contract_test.go +++ b/seaweed-block/core/storage/chunk_layer_contract_test.go @@ -170,9 +170,16 @@ func TestChunkLayer_C2_StalledUploadDoesNotGateLocal(t *testing.T) { } // C3 no torn chunk: chunks are copied under the capture barrier, so every -// HEAD ever installed equals the image at its RemoteLSN even while a writer -// keeps overwriting the same chunk and flushing. Overlap is forced: each -// round holds the upload until the writer has completed rounds after it. +// HEAD ever installed equals the image at its RemoteLSN while the same chunk +// is overwritten and flushed. Each upload-entry event precedes three complete +// writer rounds, and the upload is released only after those rounds finish. +// Complementary capture/barrier witnesses: +// TestChunkLayer_C3_WriteDuringCopyWaitsForTheCut parks a writer on a held +// local copy and checks its exclusion from the at-H image; +// TestChunkPrecopy_RedirtiedStagedChunkIsRecopied checks an overwrite between +// staging and the barrier (both WAL-resident and flushed); +// TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier checks that the barrier +// includes the admitted writer completed by its pre-barrier drain. func TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites(t *testing.T) { s, _ := newChunkTestStore(t) f := newFakeChunkRemote() @@ -183,88 +190,50 @@ func TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites(t *testing.T) { } mustSyncFlush(t, s) - stop := make(chan struct{}) - var stopOnce sync.Once - stopWriter := func() { stopOnce.Do(func() { close(stop) }) } - progress := make(chan struct{}, 1024) - werr := make(chan error, 1) - var rounds atomic.Int64 - t.Cleanup(func() { - stopWriter() - select { - case <-werr: - case <-time.After(ctLocalBound): - t.Errorf("writer not joined within %v", ctLocalBound) + // The test goroutine is the writer: each upload-entry event is followed + // by three complete write/sync/flush rounds before that upload is released. + // This proves overlap without a throughput deadline or free-running writer. + writes := 0 + writeRound := func() { + lba := uint32(writes % ctChunkBlocks) + w.write(t, s, lba, byte(writes)) + if _, err := s.Sync(); err != nil { + t.Fatal(err) } - }) - go func() { - defer close(werr) - for i := 0; ; i++ { - select { - case <-stop: - return - default: - } - lba := uint32(i % ctChunkBlocks) - data := makeBlock(ctBlockSize, byte(i)) - lsn, err := s.Write(lba, data) - if err == nil { - w.record(lsn, lba, data) - _, err = s.Sync() - } - if err == nil { - err = s.flusher.flushOnce() - // A concurrent cut can invalidate a prepared checkpoint map; - // the production worker retries this explicit stale-proof outcome. - if errors.Is(err, ErrMapCoverageStale) { - err = nil - } - } - if err != nil { - werr <- err - return - } - rounds.Add(1) - select { - case progress <- struct{}{}: - default: - } + if err := s.flusher.flushOnce(); err != nil && !errors.Is(err, ErrMapCoverageStale) { + t.Fatal(err) } - }() - + writes++ + } for round := 0; round < 5; round++ { entered, release := holdPuts(t, f) done := startCapture(t, layer) - waitKey(t, entered, "held upload") - for len(progress) > 0 { - <-progress + select { + case <-entered: + case err := <-done: + t.Fatalf("round %d Capture ended before upload entry: %v", round, err) } - for need := 0; need < 3; need++ { // the writer must advance while the upload is held - select { - case <-progress: - case <-time.After(ctLocalBound): - t.Fatalf("round %d: writer made no progress while an upload was held", round) - } + for need := 0; need < 3; need++ { + writeRound() + } + select { + case err := <-done: + t.Fatalf("round %d Capture ended before upload release: %v", round, err) + default: } release() - if err := waitErr(t, done, "held capture"); err != nil { + if err := <-done; err != nil { t.Fatalf("round %d Capture: %v", round, err) } } for i := 0; i < 20; i++ { + writeRound() if _, err := layer.Capture(ctTimeout(t)); err != nil { t.Fatalf("free-running Capture %d: %v", i, err) } } - stopWriter() - if err := waitErr(t, werr, "writer"); err != nil { - t.Fatalf("writer: %v", err) - } - if rounds.Load() < 15 { - t.Fatalf("writer completed only %d rounds; overlap not established", rounds.Load()) - } - // Each held round installs a HEAD; a free-running capture with no new - // LSN since the last cut is idle and may skip its CAS. + // Every held and subsequent unheld capture has new writes. Retain the + // historical minimum of five held HEADs plus one unheld HEAD. if n := len(f.installedHeads()); n < 6 { t.Fatalf("%d HEADs installed, want the 5 held rounds plus at least one free-running", n) } diff --git a/seaweed-block/core/storage/chunk_own.go b/seaweed-block/core/storage/chunk_own.go new file mode 100644 index 0000000000..6b004e08ee --- /dev/null +++ b/seaweed-block/core/storage/chunk_own.go @@ -0,0 +1,142 @@ +package storage + +import ( + "context" + "sort" +) + +// OwnProgress reports one OwnBatch call. +// - Owned: foreign chunks this call's cut re-uploaded under own keys. +// - Remaining: chunks HEAD still names with a foreign key after the call. +// - NotLocal: of those, chunks not local yet (the hydrate walker fills them). +type OwnProgress struct { + Owned int + Remaining int + NotLocal int +} + +// OwnBatch runs one bounded cut (M6.Restore.Owning>Owning): it picks up to n +// chunks, lowest index first, whose HEAD key is foreign (foreign reports +// whether a key names another volume's object) and that are local (present, +// or every block written locally), and cuts +// with them as candidates: each is uploaded under a new own key under the +// cut's intent and published by the cut's one HEAD CAS, even when its bytes +// equal HEAD's. Absent chunks are skipped (never fetched by the cut). The cut +// is an ordinary cut, so guest writes since the last HEAD go with it. With +// nothing to own it runs no cut. A failed cut leaves HEAD as it was; the next +// call picks again from the current HEAD. +func (l *chunkLayerImpl) OwnBatch(ctx context.Context, n int, foreign func(key string) bool) (OwnProgress, error) { + l.capMu.Lock() + defer l.capMu.Unlock() + l.stMu.Lock() + var picked []uint64 + for _, idx := range sortedForeign(l.head.Chunks, foreign) { + if len(picked) < n && l.chunkLocalLocked(idx) { + picked = append(picked, idx) + } + } + if len(picked) == 0 { + p := l.ownProgressLocked(foreign) + l.stMu.Unlock() + return p.OwnProgress, nil + } + l.own = make(map[uint64]bool, len(picked)) + for _, idx := range picked { + l.own[idx] = true + // A payload remembered from an earlier failed cut that matched HEAD + // was never uploaded (no key, data discarded): reusing it would skip + // the re-own upload. Drop it, so this cut reads and uploads the chunk. + if sc, ok := l.reusable[idx]; ok && sc.key == "" { + delete(l.reusable, idx) + } + } + l.stMu.Unlock() + _, err := l.captureLocked(ctx, false) + l.stMu.Lock() + l.own = nil + p := l.ownProgressLocked(foreign) + l.stMu.Unlock() + if err == nil { + for _, idx := range picked { + if ref, ok := p.head[idx]; !ok || !foreign(ref.Key) { + p.Owned++ + } + } + } + return p.OwnProgress, err +} + +type ownCount struct { + OwnProgress + head map[uint64]chunkRef +} + +// ownProgressLocked counts HEAD's foreign chunks. Caller holds stMu. +func (l *chunkLayerImpl) ownProgressLocked(foreign func(string) bool) ownCount { + c := ownCount{head: l.head.Chunks} + for _, idx := range sortedForeign(l.head.Chunks, foreign) { + c.Remaining++ + if !l.chunkLocalLocked(idx) { + c.NotLocal++ + } + } + return c +} + +func sortedForeign(chunks map[uint64]chunkRef, foreign func(string) bool) []uint64 { + var out []uint64 + for idx, ref := range chunks { + if foreign(ref.Key) { + out = append(out, idx) + } + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// owning reports whether chunk idx is re-owned by the running OwnBatch cut: +// it is uploaded under a new own key even when its bytes equal HEAD's. +func (l *chunkLayerImpl) owning(idx uint64) bool { + l.stMu.Lock() + defer l.stMu.Unlock() + return l.own[idx] +} + +// addOwnCandidatesLocked adds the running OwnBatch's chunks to a cut's +// candidates: a re-own reads the local copy, so an absent chunk is left out. +// Caller holds stMu. +func (l *chunkLayerImpl) addOwnCandidatesLocked(out map[uint64]bool) { + for idx := range l.own { + if l.chunkLocalLocked(idx) { + out[idx] = true + } + } +} + +// chunkLocalLocked reports whether a re-own can read chunk idx without a +// fetch: it is present, or absent with every block written locally (a guest +// overwrite flushed before the walker reached it). Caller holds stMu. +func (l *chunkLayerImpl) chunkLocalLocked(idx uint64) bool { + if !l.absent[idx] { + return true + } + first := idx * l.chunkBlocks + for i := uint64(0); i < l.chunkBlocks; i++ { + b := first + i + if b >= uint64(l.s.NumBlocks()) { + break + } + if !l.localBlocks[b] { + return false + } + } + return true +} + +// unchangedFromHead reports whether a captured chunk equals HEAD's and was +// not uploaded: such a chunk keeps its HEAD ref. A re-owned chunk equal to +// HEAD was uploaded by streamCutPayloads under a new own key (c.key set), so +// it is published like a changed chunk. +func unchangedFromHead(c capturedChunk, ref chunkRef, had bool) bool { + return had && !c.zero && ref.SHA256 == c.sum && c.key == "" +} diff --git a/seaweed-block/core/storage/chunk_own_test.go b/seaweed-block/core/storage/chunk_own_test.go new file mode 100644 index 0000000000..75e8496a76 --- /dev/null +++ b/seaweed-block/core/storage/chunk_own_test.go @@ -0,0 +1,192 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + "time" +) + +func seedForeign(key string) bool { return strings.HasPrefix(key, "seed/") } + +func ownCtx(t *testing.T) context.Context { return boundedCtx(t, context.Background()) } + +// M6.Restore.Owning>Owning: each batch is one cut that re-uploads at most n +// foreign chunks under own keys, the image unchanged, until none is left. +func TestOwnBatch_BoundedBatchesReplaceEveryForeignKey(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + before := remote.stats() + want := remote.imageOf(t, before.head) + if p, err := layer.HydrateAll(ownCtx(t)); err != nil || p.Remaining != 0 { + t.Fatalf("hydrate: %+v %v", p, err) + } + total := ctNumBlocks / ctChunkBlocks + left := total + for left > 0 { + puts := remote.stats().puts + cas := remote.stats().cas + p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign) + if err != nil { + t.Fatal(err) + } + step := min(3, left) + if p.Owned != step || p.Remaining != left-step || p.NotLocal != 0 { + t.Fatalf("batch: %+v, want %d owned and %d remaining", p, step, left-step) + } + if got := remote.stats().puts - puts; got != step { + t.Fatalf("batch uploaded %d chunks, want exactly %d (bounded)", got, step) + } + if got := remote.stats().cas - cas; got != 1 { + t.Fatalf("batch made %d HEAD CAS, want one", got) + } + left -= step + } + after := remote.stats().head + for idx, ref := range after.Chunks { + if seedForeign(ref.Key) { + t.Fatalf("chunk %d still foreign after the last batch: %s", idx, ref.Key) + } + } + if !bytes.Equal(remote.imageOf(t, after), want) { + t.Fatal("owning changed the volume image") + } + cas := remote.stats().cas + if p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign); err != nil || p != (OwnProgress{}) || remote.stats().cas != cas { + t.Fatalf("nothing left to own must run no cut: %+v %v", p, err) + } +} + +// A chunk not local yet is never fetched by a batch: it waits for the walker. +func TestOwnBatch_SkipsChunksNotLocal(t *testing.T) { + _, layer, remote, _ := hydrationFixture(t, 2, 64) + before := remote.stats() + p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign) + total := ctNumBlocks / ctChunkBlocks + if err != nil || p.Owned != 0 || p.Remaining != total || p.NotLocal != total { + t.Fatalf("batch before any hydration: %+v %v", p, err) + } + after := remote.stats() + if after.cas != before.cas || after.gets != before.gets { + t.Fatalf("a batch with nothing local cut or fetched: cas %d->%d gets %d->%d", before.cas, after.cas, before.gets, after.gets) + } +} + +// A batch is an ordinary cut: a guest write since the last HEAD goes with it. +func TestOwnBatch_CarriesGuestWrites(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + if _, err := layer.HydrateAll(ownCtx(t)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(ctChunkBlocks*6+1, makeBlock(ctBlockSize, 0xAB)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := layer.OwnBatch(ownCtx(t), 2, seedForeign); err != nil { + t.Fatal(err) + } + img := remote.imageOf(t, remote.stats().head) + off := (ctChunkBlocks*6 + 1) * ctBlockSize + if !bytes.Equal(img[off:off+ctBlockSize], makeBlock(ctBlockSize, 0xAB)) { + t.Fatal("the guest write did not reach HEAD with the batch") + } +} + +// A chunk whose every block the guest overwrote and flushed before the walker +// reached it stays absent but is fully local: a batch owns it with no fetch +// (codex01 #340 S1: otherwise nothing ever cuts it and the driver stalls). +func TestOwnBatch_OwnsAFullyOverwrittenAbsentChunkWithoutAFetch(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + const idx = 3 + for i := uint32(0); i < ctChunkBlocks; i++ { + if _, err := s.Write(idx*ctChunkBlocks+i, makeBlock(ctBlockSize, 0xC0+byte(i))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + layer.stMu.Lock() + absent := layer.absent[idx] + layer.stMu.Unlock() + if !absent { + t.Fatal("fixture: the overwritten chunk must still be absent") + } + if _, err := layer.HydrateAll(ownCtx(t)); err != nil { + t.Fatal(err) + } + seedKey := remote.stats().head.Chunks[idx].Key + // The stall needs this chunk to be the only foreign one left: then no + // other pick triggers the cut that would carry its guest write. + onlyThis := func(key string) bool { return key == seedKey } + p, err := layer.OwnBatch(ownCtx(t), 3, onlyThis) + if err != nil || p.Owned != 1 || p.Remaining != 0 { + t.Fatalf("batch with only the fully overwritten chunk foreign: %+v %v, want it owned", p, err) + } + if n := countGets(remote)[seedKey]; n != 0 { + t.Fatalf("the fully overwritten chunk was fetched %d times", n) + } + img := remote.imageOf(t, remote.stats().head) + for i := 0; i < ctChunkBlocks; i++ { + off := (idx*ctChunkBlocks + i) * ctBlockSize + if !bytes.Equal(img[off:off+ctBlockSize], makeBlock(ctBlockSize, 0xC0+byte(i))) { + t.Fatalf("block %d of the overwritten chunk is not the guest's in HEAD", i) + } + } +} + +// A failed ordinary cut remembers an equal-to-HEAD chunk without a key; the +// next batch must still upload it under an own key (codex01 #340 S2). +func TestOwnBatch_UploadsAChunkRememberedEqualByAFailedCut(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + if _, err := layer.HydrateAll(ownCtx(t)); err != nil { + t.Fatal(err) + } + same := makeBlock(ctBlockSize, 0x40) // block 0 rewritten with HEAD's own bytes + if _, err := s.Write(0, same); err != nil { + t.Fatal(err) + } + if _, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0xEE)); err != nil { // chunk 1 changed + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + remote.mu.Lock() + remote.failPut = errors.New("test: put refused") + remote.mu.Unlock() + failCtx, cancelFail := context.WithTimeout(context.Background(), 2*time.Second) + defer cancelFail() + if _, err := layer.Cut(failCtx); err == nil { + t.Fatal("fixture: the ordinary cut must fail") + } + remote.mu.Lock() + remote.failPut = nil + remote.mu.Unlock() + layer.stMu.Lock() + sc, kept := layer.reusable[0] + layer.stMu.Unlock() + if !kept || sc.key != "" { + t.Fatalf("fixture: the failed cut must remember chunk 0 equal and keyless: kept=%v key=%q", kept, sc.key) + } + p, err := layer.OwnBatch(ownCtx(t), 1, seedForeign) + if err != nil || p.Owned != 1 { + t.Fatalf("batch after the failed cut: %+v %v, want chunk 0 owned", p, err) + } + if k := remote.stats().head.Chunks[0].Key; seedForeign(k) { + t.Fatalf("chunk 0 still names the foreign key %s", k) + } + if !bytes.Equal(remote.imageOf(t, remote.stats().head)[:ctBlockSize], same) { + t.Fatal("chunk 0's bytes changed") + } +} diff --git a/seaweed-block/core/storage/chunk_periodic_cut.go b/seaweed-block/core/storage/chunk_periodic_cut.go index 49822ee959..7803020e59 100644 --- a/seaweed-block/core/storage/chunk_periodic_cut.go +++ b/seaweed-block/core/storage/chunk_periodic_cut.go @@ -17,7 +17,7 @@ var _ ChunkPeriodicCutter = (*chunkLayerImpl)(nil) func (l *chunkLayerImpl) CutUnlessCutSince(ctx context.Context, lastCutNs int64) (chunkCutResult, bool, error) { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() // delivers the cut's OnPublishSettled report after the lock l.stMu.Lock() last := l.stats.LastCutNs l.stMu.Unlock() diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index da22b9a1a9..526e52c9e7 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -80,6 +80,7 @@ type PrecopyAttempt struct { // PrecopyReport records admission estimates, not a worst-case latency proof. type PrecopyReport struct { + FrozenBudget replayed bool // transport-local marker; never replaces the original freeze telemetry. // Live barrier prefix is diagnostic, not additive to the selected forecast. @@ -159,7 +160,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context if err := l.lockPrecopy(ctx); err != nil { return ChunkCutResult{}, err } - defer l.capMu.Unlock() + defer l.unlockCap() defer func() { if result.Precopy.Frozen && !result.Precopy.IsReplay() { l.RememberDetachReport(result.Precopy) @@ -218,6 +219,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context } l.precopyFreeze = func(tail uint64, barrierStart time.Time, current chunkCutStats) bool { report = l.precopyEstimate(tail, report.Attempts) + l.observeFrozen(&report, guestFreeze, externallyFrozen) report.Drain = drain report.DrainTimedOut = errors.Is(drainErr, context.DeadlineExceeded) if drainErr != nil { @@ -524,5 +526,5 @@ func (l *chunkLayerImpl) candidateTailBytes() uint64 { func (l *chunkLayerImpl) estimateCandidateTail(bytes uint64) *ChunkCandidateTail { r := l.precopyEstimate(bytes, 0) - return &ChunkCandidateTail{Bytes: bytes, Estimate: r.TailEstimate, BytesPerSecond: r.BytesPerSecond, RateSamples: r.RateSamples, SampleAge: r.SampleAge, Known: bytes == 0 || r.BytesPerSecond > 0} + return &ChunkCandidateTail{FrozenBudget: r.frozenBudgetEstimate(), Bytes: bytes, Estimate: r.TailEstimate, BytesPerSecond: r.BytesPerSecond, RateSamples: r.RateSamples, SampleAge: r.SampleAge, Known: bytes == 0 || r.BytesPerSecond > 0} } diff --git a/seaweed-block/core/storage/chunk_precopy_retry_errors_test.go b/seaweed-block/core/storage/chunk_precopy_retry_errors_test.go new file mode 100644 index 0000000000..c7e84cdc6e --- /dev/null +++ b/seaweed-block/core/storage/chunk_precopy_retry_errors_test.go @@ -0,0 +1,47 @@ +package storage + +import ( + "errors" + "testing" +) + +// TestPrecopyRoundLoopRetriesOnlyNamedErrors pins that a failed rolling +// pre-copy round starts another round only after a COW abort, an unavailable +// remote or a HEAD precondition failure; any other error ends the loop at once. +func TestPrecopyRoundLoopRetriesOnlyNamedErrors(t *testing.T) { + errNotPrimary := errors.New("test: not primary") + for _, tc := range []struct { + name string + first error + rounds int + }{ + {"other error", errNotPrimary, 1}, + {"COW aborted", errCutCOWAborted, 2}, + {"remote unavailable", errChunkRemoteUnavailable, 2}, + {"HEAD precondition", errChunkHeadPrecondition, 2}, + } { + t.Run(tc.name, func(t *testing.T) { + _, _, l, _ := precopyLayer(t, 1024, 0) + // Every round fails at capture admission: the first with the error + // under test, any later one with an error that is never retried. + calls := 0 + l.cfg.CaptureAllowed = func() error { + calls++ + if calls == 1 { + return tc.first + } + return errNotPrimary + } + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { + t.Error("refused rounds reached the final stop") + return true + }) + if !errors.Is(err, errNotPrimary) { + t.Fatalf("err=%v, want the non-retried refusal", err) + } + if calls != tc.rounds || len(r.Precopy.Rounds) != tc.rounds { + t.Fatalf("rounds: admission calls=%d reported=%d, want %d", calls, len(r.Precopy.Rounds), tc.rounds) + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_precopy_sample_bound_test.go b/seaweed-block/core/storage/chunk_precopy_sample_bound_test.go new file mode 100644 index 0000000000..5be9c0093f --- /dev/null +++ b/seaweed-block/core/storage/chunk_precopy_sample_bound_test.go @@ -0,0 +1,25 @@ +package storage + +import ( + "testing" + "time" +) + +// TestPrecopySampleHistoryKeepsNewest32 pins that the pre-copy cost sample +// history is bounded at 32 entries and keeps the newest ones. +func TestPrecopySampleHistoryKeepsNewest32(t *testing.T) { + l := &chunkLayerImpl{} + const taken = 40 + for i := 1; i <= taken; i++ { + // The fixed cost carries the sample's order. + l.samplePrecopy(chunkCutStats{CASNs: 1}, int64(i)) + } + if len(l.precopySamples) != 32 { + t.Fatalf("sample history holds %d entries, want 32", len(l.precopySamples)) + } + for j, s := range l.precopySamples { + if want := time.Duration(taken - 32 + 1 + j); s.fixed != want { + t.Fatalf("sample %d has fixed=%s, want %s (newest 32 kept in order)", j, s.fixed, want) + } + } +} diff --git a/seaweed-block/core/storage/chunk_publish_settled.go b/seaweed-block/core/storage/chunk_publish_settled.go new file mode 100644 index 0000000000..2895433cca --- /dev/null +++ b/seaweed-block/core/storage/chunk_publish_settled.go @@ -0,0 +1,72 @@ +package storage + +// headTransition is one confirmed publication: HEAD moved from prev to next. +type headTransition struct{ prev, next chunkHead } + +// noteSettled records a confirmed publication for OnPublishSettled, in +// publication order. l.stMu held; prev is the HEAD the layer held before +// next. +func (l *chunkLayerImpl) noteSettled(prev, next chunkHead) { + if l.cfg.OnPublishSettled == nil || next.Gen == prev.Gen { // a no-op cut publishes nothing + return + } + l.settled = append(l.settled, headTransition{prev: copyHead(prev), next: copyHead(next)}) +} + +// unlockCap releases the capture lock, then delivers the publications +// recorded so far. +func (l *chunkLayerImpl) unlockCap() { + l.capMu.Unlock() + l.runPublishSettled() +} + +// runPublishSettled delivers recorded publications to OnPublishSettled one +// at a time, in publication order, outside the capture and state locks. One +// caller at a time drains the queue (any other caller only leaves its +// reports queued for it, so a hook that publishes again cannot deadlock); +// the drainer is registered with Close. Once Close has begun, no further +// report is dequeued and the rest are dropped; a report already dequeued +// may still reach the hook, and Close waits for it. +func (l *chunkLayerImpl) runPublishSettled() { + hook := l.cfg.OnPublishSettled + if hook == nil { + return + } + l.stMu.Lock() + if l.settledDraining || len(l.settled) == 0 { + l.stMu.Unlock() + return + } + if l.closed { + l.settled = nil + l.stMu.Unlock() + return + } + l.settledDraining = true + l.wg.Add(1) // under stMu while not closed: Close's wait covers this drain + l.stMu.Unlock() + defer l.wg.Done() + for { + l.stMu.Lock() + if l.closed { + l.settled = nil + } + if len(l.settled) == 0 { + l.settledDraining = false + l.stMu.Unlock() + return + } + t := l.settled[0] + l.settled = l.settled[1:] + l.stMu.Unlock() + hook(l.ctx, t.prev, t.next) + } +} + +// testCloseJoinHook, set only by tests, runs in Close after the layer is +// cancelled and before it joins its owners (the active drainer among them). +var testCloseJoinHook func() + +// testCloseJoinedHook, set only by tests, runs in Close when that join has +// returned. +var testCloseJoinedHook func() diff --git a/seaweed-block/core/storage/chunk_publish_settled_test.go b/seaweed-block/core/storage/chunk_publish_settled_test.go new file mode 100644 index 0000000000..186c7b25fc --- /dev/null +++ b/seaweed-block/core/storage/chunk_publish_settled_test.go @@ -0,0 +1,366 @@ +package storage + +import ( + "context" + "errors" + "sync" + "testing" + "time" +) + +type settledLog struct { + mu sync.Mutex + got [][2]uint64 // {prev gen, next gen} + // capFree records, per call, whether the capture lock was free. + capFree []bool +} + +func (s *settledLog) hook(l *chunkLayerImpl) func(context.Context, ChunkHead, ChunkHead) { + return func(_ context.Context, prev, next ChunkHead) { + free := l.capMu.TryLock() + if free { + l.capMu.Unlock() + } + s.mu.Lock() + s.got = append(s.got, [2]uint64{prev.Gen, next.Gen}) + s.capFree = append(s.capFree, free) + s.mu.Unlock() + } +} + +func (s *settledLog) snapshot() ([][2]uint64, []bool) { + s.mu.Lock() + defer s.mu.Unlock() + return append([][2]uint64(nil), s.got...), append([]bool(nil), s.capFree...) +} + +func attachWithSettled(t *testing.T, f *fakeChunkRemote) (*WALStore, *chunkLayerImpl, *settledLog) { + t.Helper() + s, _ := newChunkTestStore(t) + layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + log := &settledLog{} + layer.cfg.OnPublishSettled = log.hook(layer) + return s, layer, log +} + +// Each confirmed publication is reported once, with the HEAD before and +// after it, after the capture lock is released; a no-op cut reports nothing. +func TestChunkPublishSettled_ReportsEachPublication(t *testing.T) { + f := newFakeChunkRemote() + s, layer, log := attachWithSettled(t, f) + w := newWriteLog() + w.write(t, s, 2, 0x22) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { // nothing new: no-op + t.Fatal(err) + } + w.write(t, s, 9, 0x29) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + got, free := log.snapshot() + if len(got) != 2 || got[0] != [2]uint64{0, 1} || got[1] != [2]uint64{1, 2} { + t.Fatalf("reports %v; want [0->1 1->2]", got) + } + for i, ok := range free { + if !ok { + t.Fatalf("report %d ran under the capture lock", i) + } + } +} + +// A CAS whose outcome was unknown, found applied by a later cut, is reported +// when it is settled, before that cut's own publication. +func TestChunkPublishSettled_ReportsALatePublication(t *testing.T) { + f := newFakeChunkRemote() + s, layer, log := attachWithSettled(t, f) + w := newWriteLog() + w.write(t, s, 2, 0x22) + f.mu.Lock() + f.casModes = []fakeCASMode{casAppliedLost} + f.afterCAS = func(f *fakeChunkRemote) { f.failGet = errors.New("HEAD unreadable") } + f.mu.Unlock() + if _, err := layer.Cut(ctTimeout(t)); err == nil { + t.Fatal("cut with an unresolved CAS succeeded") + } + if got, _ := log.snapshot(); len(got) != 0 { + t.Fatalf("reports %v before the CAS was resolved", got) + } + f.mu.Lock() + f.failGet = nil + f.mu.Unlock() + w.write(t, s, 9, 0x29) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + got, _ := log.snapshot() + if len(got) != 2 || got[0] != [2]uint64{0, 1} || got[1] != [2]uint64{1, 2} { + t.Fatalf("reports %v; want the late publication 0->1, then 1->2", got) + } +} + +// A closing layer drops reports it has not run; without a hook nothing is +// recorded. +func TestChunkPublishSettled_ClosedAndUnset(t *testing.T) { + f := newFakeChunkRemote() + _, layer, log := attachWithSettled(t, f) + layer.stMu.Lock() + layer.settled = append(layer.settled, headTransition{prev: chunkHead{Gen: 1}, next: chunkHead{Gen: 2}}) + layer.stMu.Unlock() + if err := layer.Close(); err != nil { + t.Fatal(err) + } + layer.runPublishSettled() + if got, _ := log.snapshot(); len(got) != 0 { + t.Fatalf("reports %v after Close", got) + } + + s2, _ := newChunkTestStore(t) + plain := mustAttach(t, s2, newFakeChunkRemote(), ctConfig(1)).(*chunkLayerImpl) + w := newWriteLog() + w.write(t, s2, 2, 0x22) + if _, err := plain.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + plain.stMu.Lock() + n := len(plain.settled) + plain.stMu.Unlock() + if n != 0 { + t.Fatalf("%d publications recorded without a hook", n) + } +} + +func waitClosed(t *testing.T, ch <-chan struct{}, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(10 * time.Second): + t.Fatalf("timed out waiting for %s", what) + } +} + +// worker is a goroutine a test launches. Its bounded join (after release, +// if given) is registered as cleanup before it starts, so a failing test +// never leaves it running; the result is read once and kept. +type worker struct { + name string + done chan error + once sync.Once + err error + ok bool +} + +func launch(t *testing.T, name string, release func(), f func() error) *worker { + t.Helper() + w := &worker{name: name, done: make(chan error, 1)} + t.Cleanup(func() { + if release != nil { + release() + } + if _, ok := w.result(10 * time.Second); !ok { + t.Errorf("%s never returned", name) + } + }) + go func() { w.done <- f() }() + return w +} + +// result waits up to d for the worker; ok is false on timeout. +func (w *worker) result(d time.Duration) (error, bool) { + w.once.Do(func() { + select { + case w.err = <-w.done: + w.ok = true + case <-time.After(d): + } + }) + if !w.ok { + w.once = sync.Once{} // a timed-out wait may be retried + } + return w.err, w.ok +} + +func (w *worker) mustReturn(t *testing.T) { + t.Helper() + err, ok := w.result(10 * time.Second) + if !ok { + t.Fatalf("%s did not return", w.name) + } + if err != nil { + t.Fatalf("%s: %v", w.name, err) + } +} + +// Overlapping publishers: while the first report's hook is held, a second +// publisher's cut completes and returns; its report is delivered after the +// first, never concurrently with it. +func TestChunkPublishSettled_OverlappingPublishersStayOrdered(t *testing.T) { + f := newFakeChunkRemote() + s, _ := newChunkTestStore(t) + layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + entered, release := make(chan struct{}), make(chan struct{}) + var once, rel sync.Once + releaseHook := func() { rel.Do(func() { close(release) }) } + var mu sync.Mutex + var got [][2]uint64 + active, maxActive := 0, 0 + layer.cfg.OnPublishSettled = func(_ context.Context, prev, next ChunkHead) { + mu.Lock() + active++ + maxActive = max(maxActive, active) + got = append(got, [2]uint64{prev.Gen, next.Gen}) + first := len(got) == 1 + mu.Unlock() + if first { + once.Do(func() { close(entered) }) + <-release + } + mu.Lock() + active-- + mu.Unlock() + } + w := newWriteLog() + w.write(t, s, 2, 0x22) + a := launch(t, "the first publisher", releaseHook, func() error { _, err := layer.Cut(context.Background()); return err }) + waitClosed(t, entered, "the first report") + w.write(t, s, 9, 0x29) + b := launch(t, "the second publisher", releaseHook, func() error { _, err := layer.Cut(context.Background()); return err }) + if err, ok := b.result(10 * time.Second); !ok { + t.Fatal("the second publisher waited on the first report's hook") + } else if err != nil { + t.Fatal(err) + } + mu.Lock() + n := len(got) + mu.Unlock() + if n != 1 { + t.Fatalf("%d reports delivered while the first was held; want 1", n) + } + releaseHook() + a.mustReturn(t) + mu.Lock() + defer mu.Unlock() + if len(got) != 2 || got[0] != [2]uint64{0, 1} || got[1] != [2]uint64{1, 2} || maxActive != 1 { + t.Fatalf("reports %v (max concurrent %d); want [0->1 1->2], one at a time", got, maxActive) + } +} + +// Close during the first of two queued reports: the first hook sees its +// context end, Close reaches its join of the active drainer and waits there +// (witnessed, not timed), and the second report is never delivered. +func TestChunkPublishSettled_CloseDropsUnstartedReports(t *testing.T) { + f := newFakeChunkRemote() + s, _ := newChunkTestStore(t) + layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + entered, release := make(chan struct{}), make(chan struct{}) + var rel sync.Once + releaseHook := func() { rel.Do(func() { close(release) }) } + joining := make(chan struct{}) + var joinOnce sync.Once + var order []string // "hook returned" and "Close joined", in the order they happened + var orderMu sync.Mutex + note := func(e string) { orderMu.Lock(); order = append(order, e); orderMu.Unlock() } + testCloseJoinHook = func() { joinOnce.Do(func() { close(joining) }) } + testCloseJoinedHook = func() { note("Close joined") } + t.Cleanup(func() { testCloseJoinHook, testCloseJoinedHook = nil, nil }) + var hookCtx context.Context + var mu sync.Mutex + calls := 0 + layer.cfg.OnPublishSettled = func(ctx context.Context, _, _ ChunkHead) { + mu.Lock() + calls++ + n := calls + if n == 1 { + hookCtx = ctx + } + mu.Unlock() + if n == 1 { + close(entered) + <-release + note("hook returned") + } + } + layer.stMu.Lock() + layer.settled = append(layer.settled, headTransition{prev: chunkHead{Gen: 0}, next: chunkHead{Gen: 1}}, headTransition{prev: chunkHead{Gen: 1}, next: chunkHead{Gen: 2}}) + layer.stMu.Unlock() + drainer := launch(t, "the drainer", releaseHook, func() error { layer.runPublishSettled(); return nil }) + waitClosed(t, entered, "the first report") + closer := launch(t, "Close", releaseHook, layer.Close) + mu.Lock() + ctx := hookCtx + mu.Unlock() + waitClosed(t, ctx.Done(), "Close cancelling the hook's context") + waitClosed(t, joining, "Close reaching its join of the drainer") + releaseHook() + drainer.mustReturn(t) + closer.mustReturn(t) + orderMu.Lock() + seq := append([]string(nil), order...) + orderMu.Unlock() + if len(seq) != 2 || seq[0] != "hook returned" || seq[1] != "Close joined" { + t.Fatalf("order %v; want the running hook to return before Close's join does", seq) + } + mu.Lock() + defer mu.Unlock() + if calls != 1 { + t.Fatalf("%d reports delivered; want the second dropped after Close began", calls) + } +} + +// A hook may publish again: its own report follows, in order, with no +// deadlock. +func TestChunkPublishSettled_HookThatPublishes(t *testing.T) { + f := newFakeChunkRemote() + s, _ := newChunkTestStore(t) + layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + w := newWriteLog() + var mu sync.Mutex + var got [][2]uint64 + nested := false + // One cancellation covers the outer cut and the cut its hook makes; + // cleanup cancels it before the bounded join. + cutCtx, cancelCuts := context.WithCancel(context.Background()) + layer.cfg.OnPublishSettled = func(_ context.Context, prev, next ChunkHead) { + mu.Lock() + got = append(got, [2]uint64{prev.Gen, next.Gen}) + again := !nested + nested = true + mu.Unlock() + if again { + w.write(t, s, 9, 0x29) + if _, err := layer.Cut(cutCtx); err != nil { + t.Errorf("cut from the hook: %v", err) + } + } + } + w.write(t, s, 2, 0x22) + cut := launch(t, "a cut whose hook publishes", cancelCuts, func() error { _, err := layer.Cut(cutCtx); return err }) + if err, ok := cut.result(10 * time.Second); !ok { + t.Fatal("a hook that publishes deadlocked") + } else if err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + if len(got) != 2 || got[0] != [2]uint64{0, 1} || got[1] != [2]uint64{1, 2} { + t.Fatalf("reports %v; want [0->1 1->2]", got) + } +} + +// A periodic cut (CutUnlessCutSince) reports its publication like any other +// cut, after the capture lock is released, before it returns. +func TestChunkPublishSettled_PeriodicCutReports(t *testing.T) { + f := newFakeChunkRemote() + s, layer, log := attachWithSettled(t, f) + w := newWriteLog() + w.write(t, s, 3, 0x33) + if _, skipped, err := layer.CutUnlessCutSince(ctTimeout(t), 0); err != nil || skipped { + t.Fatalf("periodic cut: skipped=%v err=%v", skipped, err) + } + got, free := log.snapshot() + if len(got) != 1 || got[0] != [2]uint64{0, 1} || !free[0] { + t.Fatalf("periodic cut reports %v (capture lock free %v); want one report 0->1 with the lock free", got, free) + } +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index ca42de1f14..d467960d7a 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -310,6 +310,22 @@ func validChunkIntentID(id string) bool { // chunkLayerConfig configures one attachment. type chunkLayerConfig struct { + // OnPublishSettled, when set, is called once per confirmed publication + // (a cut, a detach, or an earlier unresolved CAS found applied), with the + // HEAD before and after it (INV-PUBLISH-SETTLED-001). Calls are + // serialized and in publication order, outside the capture lock, on + // whichever publishing caller is draining the reports (a publisher may + // return before its own report is delivered by the drainer). The drainer + // is registered with Close; ctx ends with Close. Once Close has begun no + // further report is dequeued; a report already dequeued may still reach + // the hook after Close began (Close then waits for it). + // + // The hook MUST return without blocking and without remote calls; enqueue + // work to your own worker. It runs on the cut or detach caller's + // goroutine, before a detach returns: its duration is a guest-visible wait + // (Part C wait sites). While a hook stalls, later reports queue without a + // bound. A hook may publish again (its report is delivered after). + OnPublishSettled func(ctx context.Context, prev, next ChunkHead) // ChunkBlocks is the number of consecutive blocks per chunk (1024 for // 4 KiB blocks and 4 MiB chunks). ChunkBlocks uint32 @@ -359,10 +375,10 @@ type chunkLayerConfig struct { // impl3 uses its owned LSN map and never calls this optional legacy object. Bitmap chunkBitmapStore - // BarrierBound bounds how many chunks a cut copies under its barrier: - // beyond it, chunks are pre-copied outside the barrier in staging - // rounds (at most chunkStageRounds; then the barrier takes the rest). - // Zero: unbounded, no staging. + // BarrierBound is for legacy test fixtures only: it sets + // BarrierOverBound when a cut copies more chunks than this under its + // barrier. Production staging is by the copy-on-write side budget (M5 + // Stage), and production leaves this zero. BarrierBound int // UploadConcurrency bounds capture/pre-copy Put calls (0 defaults to 8). @@ -382,6 +398,11 @@ type chunkLayerConfig struct { // retries), never publishes a partial image or refuses the guest mutation. // 0 defaults to defaultCOWSpillLimit; negative is refused. COWSpillLimit int64 + // COWSpillFree, optional, returns the free bytes of the filesystem that + // holds the side file. When set, it is read at each cut and that cut's + // spill cap is min(COWSpillLimit, free/2 - 1 GiB), at least 0; an error + // counts as no free space. + COWSpillFree func() (int64, error) // testReconcileHold, set only by this package's tests, holds the // reconciler before each slice until a token is received or the @@ -398,14 +419,14 @@ type chunkLayerConfig struct { // value means "not measured". // SyncPhaseStats are nested details of SyncNs; never add them to SyncNs. type SyncPhaseStats struct { - LifecycleWaitNs int64 `json:"lifecycleWaitNs"` - StoreWaitNs int64 `json:"storeWaitNs"` - GroupCommitNs int64 `json:"groupCommitNs"` - CompletionWaitNs int64 `json:"completionWaitNs"` + LifecycleWaitNs int64 `json:"lifecycleWaitNs"` // waiting for the store's lifecycle lock + StoreWaitNs int64 `json:"storeWaitNs"` // waiting for the store lock + GroupCommitNs int64 `json:"groupCommitNs"` // in the group commit that made the data durable + CompletionWaitNs int64 `json:"completionWaitNs"` // waiting for the sync leader role to validate the completion } type chunkCutStats struct { - SyncPhases SyncPhaseStats + SyncPhases SyncPhaseStats // the parts of SyncNs (never added to it) // Disjoint non-payload intervals within barrier-to-settlement fixed cost. CandidateNs int64 WindowSetupNs int64 @@ -443,11 +464,12 @@ type chunkCutStats struct { MapPersistNs int64 CASResult string TotalNs int64 - // Pre-copy (BarrierBound > 0): StageRounds staging rounds staged - // StagedChunks chunks outside the barrier; StagedChunksUsed of the - // uploads in HEAD came from staging. BarrierCopyChunks were copied - // under the barrier; BarrierOverBound: more than the bound (the - // staging rounds did not converge). + // Pre-copy (staging by the copy-on-write side budget, M5 Stage): + // StageRounds staging rounds staged StagedChunks chunks outside the + // barrier; StagedChunksUsed of the uploads in HEAD came from staging. + // BarrierCopyChunks were copied under the barrier. BarrierOverBound: + // more than the legacy fixture BarrierBound; always false in + // production, where that bound is zero. StageRounds int StagedChunks int StagedChunksUsed int @@ -475,25 +497,34 @@ type chunkCutStats struct { // - LastCut, LastCutH and LastCutNs (wall clock, Unix ns) describe the // last successful cut, whatever triggered it. type chunkLayerStats struct { - Hydration ChunkHydrationStats - CutsOK uint64 - CutsNoop uint64 - CutsFailed uint64 - CutsRefused map[string]uint64 - CutsAborted map[string]uint64 // saver_capacity, cow_capacity, budget_revoked, upload - CASConflicts uint64 - CASUnknown uint64 - PendingUnresolved bool - DirtyChunks int - Reconciling bool - ReconcileDone int - ReconcileTotal int - LastCut chunkCutStats - LastCutH uint64 - LastCutNs int64 + Hydration ChunkHydrationStats // lazy fetches of absent chunks from the remote + CutsOK uint64 // cuts that installed a HEAD + CutsNoop uint64 // cuts with nothing new (no CAS) + CutsFailed uint64 // every other cut failure + CutsRefused map[string]uint64 // refusals by reason: admission, fenced, detached + CutsAborted map[string]uint64 // saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload + CASConflicts uint64 // HEAD CAS precondition failures + CASUnknown uint64 // HEAD CAS results still unresolved after the re-read + PendingUnresolved bool // an unresolved HEAD proposal is held now + DirtyChunks int // chunks dirty since the last HEAD (not counting those awaiting reconciliation) + Reconciling bool // the dirty set is being reconciled against HEAD; no cut publishes meanwhile + ReconcileDone int // chunks compared so far + ReconcileTotal int // chunks to compare + LastCut chunkCutStats // the last successful cut's measurements + LastCutH uint64 // the LSN the last successful cut published + LastCutNs int64 // when it completed (wall clock, Unix ns) // BarrierOverBound counts cuts whose barrier copied more than the // bound after the staging rounds. BarrierOverBound uint64 + // AbsentChunks is the number of HEAD-named chunks still absent with a + // block not local (what HydrateAll would still fetch); 0 = fully local. + AbsentChunks int + // COWSpillCap is the last cut's side-file cap in bytes, read once per + // cut; COWSpillCapReason is why it is 0, when the free space made it so: + // no_room_to_cut (half the free space is within the 1 GiB reserve) or + // free_space_unreadable (the free space could not be read). + COWSpillCap int64 + COWSpillCapReason string `json:",omitempty"` } // chunkCutResult is the outcome of one successful cut. @@ -510,6 +541,7 @@ type chunkLayerStats struct { // Bytes and rate/estimate belong to one sampler observation; Known=false must // never be interpreted as a zero-cost tail. Admission rechecks at its barrier. type ChunkCandidateTail struct { + FrozenBudget Bytes uint64 `json:"bytes"` Estimate time.Duration `json:"estimateNs"` BytesPerSecond float64 `json:"bytesPerSecond"` diff --git a/seaweed-block/core/storage/data_sync.go b/seaweed-block/core/storage/data_sync.go index 960cdf8400..d9c09de74e 100644 --- a/seaweed-block/core/storage/data_sync.go +++ b/seaweed-block/core/storage/data_sync.go @@ -38,8 +38,8 @@ func selectedDataSyncMode(f *os.File) (string, string, error) { // DataSyncStatus is immutable for the lifetime of an open volume. type DataSyncStatus struct { - Mode string - Reason string + Mode string // the data-file sync call in use (fsync or fdatasync) + Reason string // why it was chosen (an explicit SWBLOCK_SYNC, or the automatic choice) } func (s *WALStore) DataSyncPolicy() DataSyncStatus { return s.dataSyncStatus } diff --git a/seaweed-block/core/storage/descriptor_v3.go b/seaweed-block/core/storage/descriptor_v3.go index 62310d03a4..8989612a6e 100644 --- a/seaweed-block/core/storage/descriptor_v3.go +++ b/seaweed-block/core/storage/descriptor_v3.go @@ -234,7 +234,7 @@ func (p *descriptorPublisherV3) publishLockedCoreV3(mutate func(next *descriptor if werr != nil && p.io.latch != nil { // Latch inside the leaf, before fileSyncMu is released: a store // Sync queued on fileSyncMu must not fsync and acknowledge - // through this uncertain slot (codex01 row 3 round 2). + // through this uncertain slot. p.io.latch(fmt.Errorf("%w: %w", ErrDescriptorPublishUncertain, werr)) } return werr diff --git a/seaweed-block/core/storage/descriptor_v3_test.go b/seaweed-block/core/storage/descriptor_v3_test.go index 2f490ab2b3..4a76b1c45e 100644 --- a/seaweed-block/core/storage/descriptor_v3_test.go +++ b/seaweed-block/core/storage/descriptor_v3_test.go @@ -420,7 +420,7 @@ func TestDescriptorV3BaseTransitionTable(t *testing.T) { } } -// codex01 row 3 review P1: a slot write error (full or partial), like an +// A slot write error (full or partial), like an // fsync error, latches the store, keeps the candidate pinned and refuses // every further publication, rollover and reuse with no further I/O. // Reopen (read back and select) is the positive control. @@ -492,7 +492,7 @@ func TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate(t *testing.T) { } } -// codex01 row 3 review P2: counters beyond 2^64-2 are refused at +// Counters beyond 2^64-2 are refused at // publication with ErrCounterExhausted, before any write. func TestDescriptorV3PublicationCounterExhaustion(t *testing.T) { const over = counterMaxV3 + 1 @@ -518,7 +518,7 @@ func TestDescriptorV3PublicationCounterExhaustion(t *testing.T) { } } -// codex01 row 3 round 2 P1: the store fault for a slot write error is +// The store fault for a slot write error is // latched inside the leaf, before fileSyncMu is released. An independent // store Sync B queued on fileSyncMu behind A's failing slot write must be // refused and must not fsync or acknowledge. The harness lets B run right diff --git a/seaweed-block/core/storage/durability_latency.go b/seaweed-block/core/storage/durability_latency.go index d72c974cf2..aab547da7e 100644 --- a/seaweed-block/core/storage/durability_latency.go +++ b/seaweed-block/core/storage/durability_latency.go @@ -5,9 +5,9 @@ import "github.com/seaweedfs/seaweed-block/core/iolatency" // DurabilityLatencyStatus separates request queue residence from physical file // sync attempts. A shared sync has one sample, not one sample per waiter. type DurabilityLatencyStatus struct { - WALAppend iolatency.Distribution - GroupCommitWait iolatency.Distribution - FileSync iolatency.Distribution + WALAppend iolatency.Distribution // WAL append latency + GroupCommitWait iolatency.Distribution // time a sync request waited in the group commit queue + FileSync iolatency.Distribution // physical file syncs (one sample per sync, however many waiters) } func (s *WALStore) DurabilityLatency() DurabilityLatencyStatus { diff --git a/seaweed-block/core/storage/install_log_v3_test.go b/seaweed-block/core/storage/install_log_v3_test.go index a0b9bf6a74..00a510f63c 100644 --- a/seaweed-block/core/storage/install_log_v3_test.go +++ b/seaweed-block/core/storage/install_log_v3_test.go @@ -5,7 +5,7 @@ import ( "testing" ) -// Plan row 10a controls (DESIGN r17.4 section 7; owner claude03): the gated +// Install-log controls: the gated // logical Sync and the receiver-only install-log ack. // While installing, Sync returns exactly (0, ErrBaseInstalling) and writes @@ -91,7 +91,7 @@ func TestInstallLogV3IsModeAAndSurvivesACrash(t *testing.T) { } } -// codex01 row 10a P1 (the #172 ack boundary): an append of the same install +// The #172 ack boundary: an append of the same install // that fails and latches the store after SyncInstallLog's publication and // before its ack refuses the ack: no H, no volatile acknowledged frontier. // The held hook runs that append with a failing pwrite (the real latch). Mutant: no diff --git a/seaweed-block/core/storage/recovery_v3.go b/seaweed-block/core/storage/recovery_v3.go index 8e22c340cb..e4b203e3a1 100644 --- a/seaweed-block/core/storage/recovery_v3.go +++ b/seaweed-block/core/storage/recovery_v3.go @@ -161,9 +161,8 @@ func fenceRangesV3(E, floor, walSize uint64, sameNonce bool) ([]fenceRangeV3, er return nil, fmt.Errorf("storage: v3 fence: head %d below the reuse floor %d", E, floor) } // Interval-length arithmetic: floor+walSize is never formed, so a - // history ending at the last representable cursor still recovers - // (codex01 row 5 P2). The logical end may exceed 2^64-2; only the - // physical bytes matter. + // history ending at the last representable cursor still recovers. + // The logical end may exceed 2^64-2; only the physical bytes matter. used := E - floor if used >= walSize { return nil, nil diff --git a/seaweed-block/core/storage/recovery_v3_test.go b/seaweed-block/core/storage/recovery_v3_test.go index 38098bfa2b..dd139ff021 100644 --- a/seaweed-block/core/storage/recovery_v3_test.go +++ b/seaweed-block/core/storage/recovery_v3_test.go @@ -99,7 +99,7 @@ func TestRecoveryV3Decision(t *testing.T) { t.Fatal("intact installing error is not a plain ErrBaseIncomplete") } // A contradictory chain while installing keeps the outer not-ready - // outcome (codex01 row 5). + // outcome. bad := []trustedRecordV3{rec(11, 11, 1100), rec(11, 11, 1200)} if _, err := decideRecoveryV3(inst, bad, 11); !errors.Is(err, ErrBaseIncomplete) || !errors.Is(err, ErrInstallSuffixDamaged) { t.Fatalf("contradictory installing chain: err = %v, want ErrBaseIncomplete wrapping ErrInstallSuffixDamaged", err) @@ -122,7 +122,7 @@ func TestRecoveryV3FenceRangesAreExact(t *testing.T) { sameNonce bool want []fenceRangeV3 }{ - // codex03 r13 example: WALSize 256, fallback tail 0, selected 100, + // WALSize 256, fallback tail 0, selected 100, // E 120. The fence is exactly [120, 256): physical [0, 100), which // the fallback still references, is untouched. {"floor bound, not the selected tail", 120, 0, 256, true, []fenceRangeV3{{120, 136}}}, @@ -158,7 +158,7 @@ func TestRecoveryV3FenceRangesAreExact(t *testing.T) { if _, err := fenceRangesV3(50, 100, 256, true); err == nil { t.Fatal("a head below the floor was accepted") } - // codex01 row 5 P2: a history ending at the last representable cursor + // A history ending at the last representable cursor // still fences exactly; floor+WALSize is never formed. got, err := fenceRangesV3(counterMaxV3, counterMaxV3-100, 256, true) if err != nil { diff --git a/seaweed-block/core/storage/reset_store_v3_test.go b/seaweed-block/core/storage/reset_store_v3_test.go index d06d8e9940..92df3a99ae 100644 --- a/seaweed-block/core/storage/reset_store_v3_test.go +++ b/seaweed-block/core/storage/reset_store_v3_test.go @@ -273,7 +273,7 @@ func TestWALStoreV3HalfResetRefusesWritesUntilRecover(t *testing.T) { readAllV3(t, r, 1, 3) } -// codex01 row 8 P1: a Read that resolved LBA 1's WAL position (cursor 0) +// A Read that resolved LBA 1's WAL position (cursor 0) // parks before its pread; the real flusher checkpoints and releases the // entry, the reset starts the new incarnation at cursor 0, and Write(2, B) // reuses that position. The resumed Read must not return B for LBA 1: it @@ -377,7 +377,7 @@ func TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault(t *testing.T) { } } -// codex01 e72acd40 P2 (1): a same-open Recover can fence a dropped record +// A same-open Recover can fence a dropped record // and re-allocate its LSN to the same LBA at the same position. A read // parked across that saw the fenced bytes; on re-resolution the entry looks // unchanged (same position and LSN), but it is a new write: the read must @@ -426,7 +426,7 @@ func TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage } } -// codex01 e72acd40 P2 (2): a failed pread is substrate I/O, never WAL +// A failed pread is substrate I/O, never WAL // integrity. EOF policy: the WAL region lies inside the file, so a file // shorter than its geometry (io.EOF) is substrate I/O too. func TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity(t *testing.T) { @@ -460,7 +460,7 @@ func TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity(t *testing.T) { }) } -// codex01 2fa56078 P2: a read already admitted (past Read's close check) +// A read already admitted (past Read's close check) // captures the recovery generation AFTER a Recover's start bump and the OLD // dirty entry BEFORE its clear; the recovery fences the dropped record and // a same-LBA write re-allocates the same position and LSN. Tuple and a diff --git a/seaweed-block/core/storage/superblock_v3_test.go b/seaweed-block/core/storage/superblock_v3_test.go index 378a6b2f29..7104c4c8db 100644 --- a/seaweed-block/core/storage/superblock_v3_test.go +++ b/seaweed-block/core/storage/superblock_v3_test.go @@ -93,7 +93,7 @@ func TestSlotV3ReferenceFields(t *testing.T) { d.BaseState != BaseNone || d.WMode != WModeLagged || d.MigrationPhase != MigrationNormal { t.Fatalf("reference fields differ: %+v", d) } - // The slot names codex03's map fixture root (DESIGN 9.5). + // The slot names the map fixture root (DESIGN 9.5). if got := d.MapRootHash; got[0] != 0xb4 || got[1] != 0x7d || got[31] != 0x1b { t.Fatalf("map root hash %x is not the 9.5 rootBodyDigest", got) } diff --git a/seaweed-block/core/storage/testdata/format_v3/slot/gen_slot_vectors.py b/seaweed-block/core/storage/testdata/format_v3/slot/gen_slot_vectors.py index 1fc65cd045..8e2ce8bf30 100644 --- a/seaweed-block/core/storage/testdata/format_v3/slot/gen_slot_vectors.py +++ b/seaweed-block/core/storage/testdata/format_v3/slot/gen_slot_vectors.py @@ -29,7 +29,7 @@ assert crc32c(b"123456789") == 0xE3069283, "crc32c self-check failed" UUID = bytes(range(0x00, 0x10)) LINEAGE = bytes(range(0x10, 0x20)) NONCE = bytes(range(0x20, 0x30)) -# rootBodyDigest of codex03's reference root (DESIGN 9.5): this slot names that map. +# rootBodyDigest of the reference map root (DESIGN 9.5): this slot names that map. ROOT_HASH = bytes.fromhex("b47d24af8db0e0a2cd2494652c981c48f4d2a861c381f4a04cac4b35e2ac321b") diff --git a/seaweed-block/core/storage/walstore_batch_v3_test.go b/seaweed-block/core/storage/walstore_batch_v3_test.go index 1bd91b7e2d..914059ebd5 100644 --- a/seaweed-block/core/storage/walstore_batch_v3_test.go +++ b/seaweed-block/core/storage/walstore_batch_v3_test.go @@ -6,8 +6,8 @@ import ( "testing" ) -// v3 WriteBatch controls (DESIGN r17.4 sections 3.1 and 6.7; owner -// claude03): one multi-block record per batch, its replay and reads. +// v3 WriteBatch controls: +// one multi-block record per batch, its replay and reads. func batchBlocks(first byte, n int) [][]byte { out := make([][]byte, n) @@ -201,7 +201,7 @@ func TestWALStoreV3BatchFlushesEveryBlock(t *testing.T) { readBatchV3(t, r, 10, 0x40, 4, "after reopen") } -// The dark offline reader (codex03's walstore_readonly_v3.go) indexes and +// The dark offline reader (walstore_readonly_v3.go) indexes and // reads every block of a batch record. Mutant: indexing only a batch's // first block fails here. func TestWALStoreV3ReadOnlyReaderServesBatchBlocks(t *testing.T) { @@ -242,8 +242,8 @@ func TestWALStoreV3BatchRecordsMapCoverage(t *testing.T) { } } -// Ordinary replicated ApplyEntry on v3 (DESIGN 8.1, 6.7, r16.1; codex03 -// 12a inventory): applies append in LSN order and survive a crash; an LSN +// Ordinary replicated ApplyEntry on v3 (DESIGN 8.1, 6.7): +// applies append in LSN order and survive a crash; an LSN // at or below the highest is a superseded no-op when the LBA holds a higher // LSN and ErrWALLSNOrder otherwise; an unanchored gap is refused; an // ordinary apply while installing is refused (the install lane is the @@ -329,7 +329,7 @@ func TestWALStoreV3ScanLBAs(t *testing.T) { } } -// codex01 4caac700 P1s: v3 ScanLBAs is all or nothing. A corrupt middle +// v3 ScanLBAs is all or nothing. A corrupt middle // record makes the chain stop short of the head: a typed WAL integrity // failure carrying the scanner's stop cause, with nothing emitted (never // a short success, never WALRecycled). An installing diff --git a/seaweed-block/core/storage/walstore_close_v3_test.go b/seaweed-block/core/storage/walstore_close_v3_test.go index 0dd57c0e78..dd17ff6036 100644 --- a/seaweed-block/core/storage/walstore_close_v3_test.go +++ b/seaweed-block/core/storage/walstore_close_v3_test.go @@ -7,7 +7,7 @@ import ( "testing" ) -// codex01 row 7 slice 4 P1: WALStore.Close serialized the legacy superblock +// Regression: WALStore.Close serialized the legacy superblock // and pwrote it at offset 0, which on a v3 file is descriptor slot A. The // schedule: strict create (A gen 1), Recover (B gen 2), Write+Sync (A gen 3, // W 1), Close (slot A destroyed), reopen (B gen 2, W 0). A v3 Close writes diff --git a/seaweed-block/core/storage/walstore_recovery.go b/seaweed-block/core/storage/walstore_recovery.go index a8442123bb..a6514b8c0f 100644 --- a/seaweed-block/core/storage/walstore_recovery.go +++ b/seaweed-block/core/storage/walstore_recovery.go @@ -65,7 +65,7 @@ func (s *WALStore) CheckpointLSNForPOC() uint64 { } // scanLBAsV3 is ScanLBAs on a v3 store (the primary's catch-up source). -// It is all or nothing (codex01 4caac700 P1s): it captures the recovery +// It is all or nothing: it captures the recovery // generation, the descriptor and the head, refuses an installing source // (ErrBaseInstalling) before emitting anything, scans the trusted v3 chain // into memory, revalidates the capture (a Recover, reset or BASE transition diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index efb4a92aa7..6599c40467 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -38,15 +38,15 @@ type walStoreV3State struct { // leader role) for its whole run, between lifecycleMu and s.mu, and bumps // recoverGen first, under syncMu and s.mu. Every W publisher (the Sync // batch, refreshW, SetWMode) holds syncMu across capture -> publish -> - // acknowledgement, so no publication straddles a recovery (codex01 row - // 5d; Claude01's structural seam). The one boundary that cannot hold - // syncMu across its wait, the outer Sync() completion, captures - // recoverGen with its target and rechecks it under syncMu -> s.mu. + // acknowledgement, so no publication straddles a recovery. The one + // boundary that cannot hold syncMu across its wait, the outer Sync() + // completion, captures recoverGen with its target and rechecks it under + // syncMu -> s.mu. // // recoverGen is bumped at the start AND at the end of every recovery // and reset, the start+end pattern of the map proof epoch: a lock-free // reader whose attempt saw the same value before and after was not cut - // by a recovery's end (codex01 2fa56078 P2: a read admitted between the + // by a recovery's end (the case this closes: a read admitted between the // start bump and the dirty-map clear captured the new value with an old // entry, then a same-tuple rewrite after the recovery). // @@ -478,7 +478,7 @@ func (s *WALStore) recoverV3() (uint64, error) { if err != nil { if d.BaseState == BaseInstalling { // Installing keeps its typed not-ready outcome; the cause is a - // substrate error, not proven install-log damage (codex01 5b P2). + // substrate error, not proven install-log damage. return 0, fmt.Errorf("%w: scan: %w", ErrBaseIncomplete, err) } return 0, err @@ -503,11 +503,11 @@ func (s *WALStore) recoverV3() (uint64, error) { // never reuses an LSN the WAL still holds. // // Only a physical reopen records them: when this open began the - // installing ID, its handle stays valid (DESIGN r17.4: until the next - // begin) and may append and acknowledge past this cut, so a cached E - // would be stale and fencing from it could erase acknowledged - // records (codex01 row 11b P1). A resume or a fenced supersession - // then refuses before any I/O; the live install continues. + // installing ID, its handle stays valid (until the next begin) and + // may append and acknowledge past this cut, so a cached E would be + // stale and fencing from it could erase acknowledged records. A + // resume or a fenced supersession then refuses before any I/O; the + // live install continues. if d.BaseInstallID != v.liveInstallID { ro := &installReopenV3{id: d.BaseInstallID, E: o.E, R: o.R, damaged: o.Damaged, walSize: d.WALSize} for _, r := range scan.Records { @@ -533,11 +533,11 @@ func (s *WALStore) recoverV3() (uint64, error) { // closed; a physical reopen then decides intact or damaged. s.latchV3(fmt.Errorf("storage: v3 same-open installing recovery: recovered cut E %d is not the live writer head", o.E)) } else { - // The live install continues (r17.4). Its trusted install-lane + // The live install continues. Its trusted install-lane // records are republished in the dirty map, which this Recover // cleared, so the completed image serves them and not older BASE // bytes; the volatile map coverage (the BASE writes' UNKNOWN) is - // kept as it is (codex01 04180c33 P1). + // kept as it is. for _, r := range scan.Records { if r.Entry.LSN > o.R { break @@ -623,7 +623,7 @@ func (s *WALStore) recoverV3() (uint64, error) { // The volatile acknowledged frontier is the recovered prefix, never an // older in-memory maximum: a same-open recovery that dropped mode C's // newest batch must not let a later refresh publish a W the WAL no - // longer holds (codex01 5b P1). + // longer holds. v.appended.Store(o.R) v.wack.Store(o.R) return s.syncedLSN, nil @@ -864,7 +864,7 @@ func (s *WALStore) syncWALBatchV3Internal(pressureOnly bool) error { if h := v.testBatchBeforeAck; h != nil { h() } - // The acknowledgement boundary (codex01 row 5 P1): a queued append may + // The acknowledgement boundary: a queued append may // have failed and latched the store fault while this batch's slot I/O // was in flight. Recheck under the store lock, which that append holds // until it has latched, before acknowledging anything. @@ -931,7 +931,7 @@ func (s *WALStore) SetWMode(m WMode) error { // readDirtyV3 serves a v3 read from the dirty map, if the LBA has an entry // (handled false: read the extent). A reader holds no lock across its WAL // read, so the position it resolved may be reused before the pread: after a -// reset (cursor 0 again, codex01 row 8 P1) or a same-open recovery that +// reset (cursor 0 again) or a same-open recovery that // fenced and reused it. The read therefore validates the WHOLE record it // read, payload included (CRC, footer, write type, LBA and LSN against the // resolving entry), and re-resolves on a mismatch. LSN allocation runs on @@ -940,7 +940,7 @@ func (s *WALStore) SetWMode(m WMode) error { // to the same LBA at the same position, so the "entry unchanged" damage // verdict also requires the same recovery generation before and after the // whole attempt. A recovery bumps it at its start and its end, so any -// overlap changes it (codex01 e72acd40 and 2fa56078 P2s; see recoverGen). +// overlap changes it (see recoverGen). // A generation captured while a recovery runs can match only if the // verdict also falls inside that recovery, which holds s.mu: no write can // re-allocate the tuple, and the replay installs only validated records. A pread error is a diff --git a/seaweed-block/core/storage/walstore_v3_test.go b/seaweed-block/core/storage/walstore_v3_test.go index 4e0654e6d8..298cd708c3 100644 --- a/seaweed-block/core/storage/walstore_v3_test.go +++ b/seaweed-block/core/storage/walstore_v3_test.go @@ -409,7 +409,7 @@ func TestWALStoreV3RefusesPathsOfLaterRows(t *testing.T) { } } -// codex01 row 5 P1-1: a batch's acknowledgement rechecks the store fault +// A batch's acknowledgement rechecks the store fault // under the store lock. Schedule, in both modes: batch A's slot write is // parked (A holds descMu); B's Write, already past capacity admission, // takes s.mu exclusively and waits on descMu in the writer's snapshot; @@ -468,7 +468,7 @@ func TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary(t *testing.T) { } } -// codex01 row 5 P2: a history ending at the last representable cursor +// A history ending at the last representable cursor // recovers; only further appends are refused. func TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor(t *testing.T) { const recSize = uint64(walEntryHeaderSizeV3 + v3TestBlock) @@ -496,7 +496,7 @@ func TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor(t *testing } } -// codex01 row 5 P2 (SetWMode evidence): a held mode-C batch completes and +// A held mode-C batch completes and // acknowledges under C before SetWMode(A) publishes the new mode. func TestWALStoreV3SetWModeWaitsForAHeldBatch(t *testing.T) { s, _ := newStoreV3(t, WModeLagged) @@ -629,7 +629,7 @@ func recvErrV3(t *testing.T, ch <-chan error, what string) error { } } -// codex01 5b P1: a SAME-instance recovery that drops mode C's newest batch +// A SAME-instance recovery that drops mode C's newest batch // resets the acknowledged frontier to R, so a later refresh cannot publish // a W the WAL no longer holds and the next Recover does not report a false // corruption. Fresh-open tests mask this (they start from the slot W). @@ -674,7 +674,7 @@ func TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier(t *testing.T) { } } -// codex01 5b P2: a scan failure under an installing descriptor keeps the +// A scan failure under an installing descriptor keeps the // typed not-ready outcome and leaves the file unchanged. func TestWALStoreV3InstallingScanErrorIsTypedNotReady(t *testing.T) { s, path := newStoreV3(t, WModeLagged) @@ -707,7 +707,7 @@ func TestWALStoreV3InstallingScanErrorIsTypedNotReady(t *testing.T) { } } -// codex01 5b P2: the real flusher cycle performs the mode-C idle refresh, +// The real flusher cycle performs the mode-C idle refresh, // also when no dirty entries remain, so the window closes without a Sync. func TestWALStoreV3FlusherCycleRunsTheIdleRefresh(t *testing.T) { s, path := newStoreV3(t, WModeLagged) @@ -731,7 +731,7 @@ func TestWALStoreV3FlusherCycleRunsTheIdleRefresh(t *testing.T) { // heldV3 owns a parked hook and the workers a held control starts. Its // cleanup, registered before any worker starts and after the store crash // cleanup, first releases the hold, then joins every worker with a bound, -// so an early Fatal never strands store shutdown (codex01 row 5d P2). +// so an early Fatal never strands store shutdown. type heldV3 struct { t *testing.T parked chan struct{} @@ -792,7 +792,7 @@ func notDoneV3(t *testing.T, c chan error, what string) { } } -// codex01 row 5d schedule A: a refresh attempted DURING a same-open +// Schedule A: a refresh attempted DURING a same-open // recovery waits for it (Recover holds the leader role), then sees the // recovered frontier and publishes nothing. func TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing(t *testing.T) { @@ -821,7 +821,7 @@ func TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing(t *testing.T) { } } -// codex01 row 5d schedule B: a recovery attempted while a C batch is parked +// Schedule B: a recovery attempted while a C batch is parked // after its publication and before its acknowledgement waits for the batch; // the recovery then lowers the frontier and nothing revives the dropped cut. func TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut(t *testing.T) { @@ -863,7 +863,7 @@ func TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut(t *testing.T) } } -// codex01 row 5d: the outer Sync() completion is validated against the +// The outer Sync() completion is validated against the // recovery generation. A Sync whose batch finished, then waits while a // recovery drops its cut, must not acknowledge it; a fresh Sync after the // recovery acknowledges normally. @@ -899,7 +899,7 @@ func TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery(t *testing.T) { } } -// codex01 row 5c P2: the empty-dirty-set branch of the flusher cycle runs the +// The empty-dirty-set branch of the flusher cycle runs the // idle refresh on its own (discriminated separately from the flush branch). func TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh(t *testing.T) { s, _ := newStoreV3(t, WModeLagged) diff --git a/seaweed-block/core/transport/replica_install_format_v3_test.go b/seaweed-block/core/transport/replica_install_format_v3_test.go index 5050dd6238..ab590de154 100644 --- a/seaweed-block/core/transport/replica_install_format_v3_test.go +++ b/seaweed-block/core/transport/replica_install_format_v3_test.go @@ -15,8 +15,8 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) -// Plan row 10b controls (DESIGN r17.4 section 8.7, caller 2; owner -// claude03): the legacy single-lane rebuild on a dark v3 replica. The +// Replica install controls: +// the legacy single-lane rebuild on a dark v3 replica. The // first admitted rebuild message begins one install at its frontier hint; // blocks go through the handle; done completes, then Syncs, and a failure // closes the connection with no MsgBarrierResp. diff --git a/seaweed-block/deploy/config/blockvolume.env b/seaweed-block/deploy/config/blockvolume.env index cce3021c5c..a40f5f7c7f 100644 --- a/seaweed-block/deploy/config/blockvolume.env +++ b/seaweed-block/deploy/config/blockvolume.env @@ -113,9 +113,6 @@ SWB_CHUNK_REPLICATION= SWB_CHUNK_CAPTURE_INTERVAL=0 # --chunk-upload-concurrency (default 8; 1..64). Parallel dirty-chunk uploads. SWB_CHUNK_UPLOAD_CONCURRENCY=8 -# --chunk-dirty-threshold (default 512 chunks = 2 GiB; 0 = unbounded). Bound -# on one cut's barrier copy; never triggers a cut. -SWB_CHUNK_DIRTY_THRESHOLD=512 # --chunk-control-endpoint (default false). Expose /chunk/* (cut, snapshot, # snapshots, snapshot/delete, detach) on the status listener; needs # SWB_STATUS_ADDR. diff --git a/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service b/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service index 37fdd5fb1a..c15dcbb0a2 100644 --- a/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service +++ b/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service @@ -60,7 +60,6 @@ ExecStart=/usr/local/bin/blockvolume \ --chunk-replication=${SWB_CHUNK_REPLICATION} \ --chunk-capture-interval=${SWB_CHUNK_CAPTURE_INTERVAL} \ --chunk-upload-concurrency=${SWB_CHUNK_UPLOAD_CONCURRENCY} \ - --chunk-dirty-threshold=${SWB_CHUNK_DIRTY_THRESHOLD} \ --chunk-control-endpoint=${SWB_CHUNK_CONTROL_ENDPOINT} \ --workspace-lease=${SWB_WORKSPACE_LEASE} \ $SWB_VOLUME_EXTRA_ARGS diff --git a/seaweed-block/deploy/systemd/sw-blockvolume.service b/seaweed-block/deploy/systemd/sw-blockvolume.service index a17b9d7980..28675f37ce 100644 --- a/seaweed-block/deploy/systemd/sw-blockvolume.service +++ b/seaweed-block/deploy/systemd/sw-blockvolume.service @@ -59,7 +59,6 @@ ExecStart=/usr/local/bin/blockvolume \ --chunk-replication=${SWB_CHUNK_REPLICATION} \ --chunk-capture-interval=${SWB_CHUNK_CAPTURE_INTERVAL} \ --chunk-upload-concurrency=${SWB_CHUNK_UPLOAD_CONCURRENCY} \ - --chunk-dirty-threshold=${SWB_CHUNK_DIRTY_THRESHOLD} \ --chunk-control-endpoint=${SWB_CHUNK_CONTROL_ENDPOINT} \ --workspace-lease=${SWB_WORKSPACE_LEASE} \ $SWB_VOLUME_EXTRA_ARGS diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index d4d621ecd1..930b5f18c0 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -72,8 +72,8 @@ A workspace runs one replica (RF=1). It does not use the replication engine of t | Permanent host loss | the image at the last successful cut (HEAD `RemoteLSN`); writes after it are lost | | Clean move (Detach) | everything written before Detach: guest I/O is stopped, then Detach publishes a final cut before the host releases the volume | -- **When cuts happen.** At semantic points chosen by the integrator (after an agent step, before a risky command, on detach) and on explicit request (`sw-block ops chunk cut`). The periodic timer is off by default (`cmd/blockvolume/chunk_remote.go` `defaultChunkCaptureInterval = 0`); an operator may set one as a host-loss safety net. `--chunk-dirty-threshold` (default 512 chunks, 2 GiB) bounds pre-copy staging work; native COW copies the remainder outside its barrier. It never triggers a cut. -- **So the default RPO is unbounded** until the integrator cuts. This is a design choice for workspaces, where a cut at a semantic point is more useful than a timer. +- **When cuts happen.** At semantic points chosen by the integrator, on explicit request, and by the periodic timer (off by default; when set, at least 5m in the OSS CLI). Periodic cuts update HEAD without creating named snapshots. Dirty chunks never trigger a cut. +- **Recoverable frontier.** The confirmed remote HEAD is the recovery point after host loss. With the periodic timer off (the default), HEAD advances at explicit cuts, snapshots and detach; failed or expired attempts retry with bounded backoff and reusable uploads, and do not claim a newly durable recovery point. - Multi-replica workspaces combined with chunk snapshots are not supported. ## 3. Remote layout @@ -122,7 +122,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto `chunkLayerImpl.captureLocked` (`core/storage/chunk_layer.go`; contract in the `chunk_seam.go` header). A checkpoint is not a prefix image (the extent can already hold blocks newer than the checkpoint), so a cut is a quiesced point, not a checkpoint boundary. 1. **Admit:** refuse when closed, fenced, detached, during a base install, or when `CaptureAllowed` fails (healthy primary, unchanged lineage, valid lease). -2. **Pre-copy:** while more than `BarrierBound` chunks would be copied under the barrier (`--chunk-dirty-threshold`, default 512), stage up to that many per round outside the barrier, for at most `chunkStageRounds` (3) rounds (`stage`). A staged chunk with new bytes is uploaded under a fresh key named by an intent written first. +2. **Pre-copy:** while the chunks that would be copied under the barrier exceed half the copy-on-write side budget, stage the hottest of them per round outside the barrier, repeating only while the remainder shrinks (`stage`). A staged chunk with new bytes is uploaded under a fresh key named by an intent written first. 3. **Quiesce:** take the capture barrier (walstore `captureMu`) exclusively, then `Sync`. H is the synced LSN; no data newer than H exists in the WAL or the extent. 4. **Open and copy:** install the fixed candidate window under the barrier, then release it. Bounded workers copy through the validated reader outside the barrier. A first writer saves a pending candidate before mutation; a writer waits only for its own copying/saving chunk. A staged copy is reused only if its version and HEAD still match. Pause is Sync plus candidate/window installation, independent of copy bytes. 5. **LSN guard:** if H is below HEAD's `RemoteLSN`, refuse (`lsn_behind`). @@ -145,10 +145,10 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto **Design.** 1. **Short barrier; `capMu` held for the whole cut.** The chunk layer's `capMu` stays held from admission to the end of the cut, as today; it already serializes Capture with Evict and Begin/EndBaseInstall, so no BASE install can start inside a window. Under `captureMu` exclusive the cut's `Sync` fixes H and the candidate set D is fixed as today (the owned chunk LSN map relative to HEAD plus retained WAL and in-memory mutations). A COW window `{H, D, state per chunk, refcount}` is installed in the chunk layer, then only `captureMu` is released. The stall becomes `Sync` plus fixing D, independent of the bytes to copy. 2. **Per-chunk state and one owner.** Each chunk of D is `pending`, then exactly one owner moves it on, under a small per-chunk mutex that is never held across I/O: - - the copier: `pending â†' copying â†' done`; - - a writer: `pending â†' saving â†' saved` (the copier later reads the saved bytes: `saved â†' done`). + - the copier: `pending �' copying �' done`; + - a writer: `pending �' saving �' saved` (the copier later reads the saved bytes: `saved �' done`). Everyone else who finds `copying` or `saving` waits on that chunk's condition until it reaches `done` or `saved`, or until the window is aborted (step 5). -3. **The save happens before publication, outside `store.mu`.** Every mutation that can change what a read returns (`Write`, `WriteBatch`, `ApplyEntry`) runs the COW step right after it takes `captureMu` shared and **before** it takes `lifecycleMu` / `mu`, appends to the WAL or inserts into the dirty map. The save reads the chunk through the ordinary read path, which needs `store.mu`, so it cannot run inside the mutation's critical section; a hook after publication (on the WAL append, the dirty-map insert or the flusher's extent write) would see the new bytes and cannot implement this. Lock order: `captureMu` (shared) â†' per-chunk COW mutex (leaf, released before any read) â†' the read path's own locks. +3. **The save happens before publication, outside `store.mu`.** Every mutation that can change what a read returns (`Write`, `WriteBatch`, `ApplyEntry`) runs the COW step right after it takes `captureMu` shared and **before** it takes `lifecycleMu` / `mu`, appends to the WAL or inserts into the dirty map. The save reads the chunk through the ordinary read path, which needs `store.mu`, so it cannot run inside the mutation's critical section; a hook after publication (on the WAL append, the dirty-map insert or the flusher's extent write) would see the new bytes and cannot implement this. Lock order: `captureMu` (shared) �' per-chunk COW mutex (leaf, released before any read) �' the read path's own locks. - chunk not in D, `done` or `saved`: proceed; - `pending`: become the owner (`saving`), read the chunk (still its content at H), put it in the side store, mark `saved`, wake waiters, proceed; - `copying` or `saving`: wait (step 2), then re-check. @@ -186,8 +186,10 @@ stateDiagram-v2 ## 6. Snapshots, forks, retention, GC, volume delete - **Snapshot** (`Catalog.CreateSnapshot`): claim the name with an exclusive name record `{request, attempt}` (a retry gets its own attempt back); check the volume is not being deleted; write an intent with a deadline; re-check the deadline; exclusively create `snaps//` holding a copy of the HEAD root. An unknown outcome keeps the intent; the caller retries with the same request id. -- **Fork** (`Catalog.Fork`): claim the parent snapshot, check the source is not being deleted, write the target `VOLUME` (origin fork), then a HEAD at gen 1, epoch 0, no holder, with the parent's `RemoteLSN` and references. No segment or chunk is copied: the fork's references are owner-qualified, so it reads the parent's objects, and its root alone keeps them live after the parent snapshot is deleted. -- **Retention** (`retention.go`): classes `semantic` and `pinned`; newest N, recent window and log-spaced keeps; a snapshot with a live fork claim is always kept; deletion uses the same conditional mark as `DeleteSnapshot`. +- **Fork** (`Catalog.Fork`): take the deadline start and read the parent snapshot (every attempt reads it again; a parent deleting or gone refuses; the parent is not claimed), check the source is not being deleted, write the target `VOLUME` (origin fork), then a HEAD at gen 1, epoch 0, no holder, with the parent's `RemoteLSN` and references. No segment or chunk is copied: the fork's references are owner-qualified, so it reads the parent's objects, and its root alone keeps them live after the parent snapshot is deleted. +- **Restore** (`Catalog.Restore`, independent restore): the fork steps with `VOLUME` origin `restore`; until its first HEAD the parent stays rooted by GC's grace after any delete, and from then on the target's owner-qualified refs keep the source's chunks live, so deleting the source snapshot or volume mid-restore is normal. The background walker (`HydrateAll`) makes every chunk local through the shared fill flights, under one host fill permit per flight. Bounded batch cuts then upload the chunks under the target's own keys; when the resolved HEAD holds no ref to another volume, the write-once `RESTORE-INDEPENDENT` entry is created (`MarkIndependent`). Snapshots of the target are refused until then, and a snapshot image that still names another volume's chunks is refused even after it. Model: `docs/spec/RestoreIndependence.tla`. +- **Retention** (`retention.go`): classes `semantic` and `pinned`; newest N, recent window and log-spaced keeps; no snapshot is kept because of a fork or restore; deletion uses the same conditional mark as `DeleteSnapshot`. +- **Snapshot delete in any order with forks** (no claims): a fork publishes only before its read time + operation deadline, and GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound (`NewCollector` refuses otherwise); an unknown publish keeps the fork intent, which roots the keys until the target is resolved. Model: `ForkDelete` (`G >= D + E + P`). - **GC** (`gc.go` `Collector.run`, operator-driven through `sw-block ops chunk gc`, preview by default; see also `core/frontend/chunkstore/GC.md`): - roots: every HEAD, every named snapshot (including one whose delete is still in progress), every snapshot attempt that is not aborted, live intents, and segment objects; an unreadable segment aborts the mark. A deleted snapshot's attempt stays a root for one grace period after its delete time, then stops counting (`Collector.snapshotAttemptHeads` in `gc_copy.go`); - a capture intent expires only if it is older than the TTL, blockmaster has issued a higher epoch, and the remote HEAD has moved to a higher epoch; copy intents are settled only by a permanent tombstone at their publication target; @@ -199,13 +201,13 @@ stateDiagram-v2 2. **Run GC with `--apply`.** The deleted attempt stops being a root one grace period after its delete time. A chunk referenced by nothing else then becomes a candidate (if it is itself older than the grace period), and it is deleted only after a second mark at least one grace period later still finds it unreferenced. With the default grace of one hour, a chunk is reclaimed two hours or more after the snapshot delete, and only by GC passes that run after those points. Chunks still referenced by HEAD, another snapshot or a fork are never candidates. 3. **Volume vacuum in SeaweedFS.** GC deletes the needle; SeaweedFS returns the disk space when it vacuums that volume. Until then the bytes stay on the volume servers. - **Why a reachability mark and not reference counts.** Chunks and segments are shared by snapshots and forks of any number of volumes. A reference count kept in filer entries and changed by several hosts can be lost or applied twice by a crash or an unknown outcome; a lost increment would delete live data. The mark recomputes reachability from the roots on every pass, and the two-mark grace covers writers that are about to publish keys they already uploaded. The cost is delay: space comes back hours after a delete, not at once. -- **Volume delete** (`volume_delete.go` `DeleteVolume`): (a) a blockmaster deletion reservation; (b) one HEAD write to `deleting` (refused while HEAD is held); (c) refuse and revert if any snapshot name record exists; (c') commit `deleting â†' purging` bound to the same incarnation; (e) HEAD becomes `deleted` with no chunks and `VOLUME` is marked deleted. A deleted id is never attached or created again. +- **Volume delete** (`volume_delete.go` `DeleteVolume`): (a) a blockmaster deletion reservation; (b) one HEAD write to `deleting` (refused while HEAD is held); (c) refuse and revert if any snapshot name record exists; (c') commit `deleting �' purging` bound to the same incarnation; (e) HEAD becomes `deleted` with no chunks and `VOLUME` is marked deleted. A deleted id is never attached or created again. HEAD states: ```mermaid stateDiagram-v2 - [*] --> active: initial HEAD (gen 1, epoch 0) or fork HEAD + [*] --> active: initial HEAD (gen 1, epoch 0), fork or restore HEAD active --> active: holder's cut CAS (gen+1) active --> detached: Detach final cut detached --> active: takeover CAS (higher epoch, new holder) @@ -227,7 +229,7 @@ stateDiagram-v2 [*] --> NameHeld: exclusive name record {request, attempt} NameHeld --> Published: exclusive create snaps/name/attempt NameHeld --> Aborted: DeleteSnapshot or GC tombstones the attempt path - Published --> Deleting: DeleteSnapshot or retention (no live fork claim) + Published --> Deleting: DeleteSnapshot or retention (forks do not hold it) Deleting --> NameFreed: name record removed Aborted --> NameFreed: name record removed NameFreed --> [*] @@ -235,13 +237,57 @@ stateDiagram-v2 The attempt path is never removed, so a late create can never land after a delete. +Restore (target volume): + +```mermaid +stateDiagram-v2 + [*] --> Forking: read the parent snapshot, write VOLUME (origin restore) + Forking --> Restoring: first HEAD (parent's refs, owner-qualified) before read time + deadline + Forking --> Aborted: GC tombstones the HEAD + Restoring --> Hydrating: driver starts the paced walker + Hydrating --> Owning: batch cuts start (the walker may still run) + Owning --> Owning: one bounded batch cut replaces up to N foreign refs with own keys + Owning --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created + Independent --> [*] + Aborted --> [*]: target deleted +``` + +Snapshots of the target are refused until `Independent`. The driver (`core/host/volume/chunk_restore.go`) runs these steps from the target's own facts; `POST /chunk/restore` starts it and `sw-block ops chunk restore` calls it. + +### Attached-volume scheduling + +Periodic HEAD capture is off by default (opt-in; when set, at least 5 +minutes), and retention runs every hour. Named snapshots remain explicit. +A five-minute context covers the whole cut; completed immutable uploads survive +an expired attempt only under matching version/HEAD generation. Automatic GC is +opt-in until the 50/200-volume metadata/RSS qualification accepts its full-catalog +scan cost. Scoped GC changes candidates, not the catalog root domain; each volume +has independent persisted mark coverage. CLI catalog mutations also check the +single-filer deployment constraint before mutation. + +```mermaid +stateDiagram-v2 + [*] --> PendingAttach + PendingAttach --> Armed: attached and healthy + Armed --> Running: staggered due event + Running --> Armed: retention and optional scoped GC settle + Running --> Draining: detach, fence, close + Armed --> Draining: detach, fence, close + Draining --> Closed: cancel and join every worker + Draining --> Armed: safe detach abort, same current handle +``` + +No catch-up queue is accumulated. Retention failure skips GC; incomplete marks +and configuration changes do not authorize reclamation. Unknown same-epoch CAS +intents remain rooted after restart; elapsed TTL is not a settlement proof. + ## 7. Lease, takeover and host moves **Host guard** (`core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard`, enabled with `blockvolume --workspace-lease`; see [workspace lease](../workspace-lease.md)): frontend I/O and cuts are admitted only with a granted, unexpired lease for the exact `{volume, replica, epoch}`. Validity is anchored to the renewal request's start time, and blockmaster's `ValidForNs` already subtracts half the clock-skew bound (`core/host/master/workspace_service.go` `leaseFact`). A late reply cannot extend admission. A fenced guard never reopens. The lease is 30 s (`core/authority/authority.go`, `workspaceTTL`); the skew bound defaults to 20 s (`blockmaster --workspace-max-clock-skew`). **Master side of a renewal** (`core/authority/workspace_lease_view.go`): blockmaster answers a renewal of an established lease from memory, under a small leaf lock, with no disk write and without waiting for other authority writes. The grant is min(now + TTL, durable horizon), where the horizon is the lease expiry stored on disk; a background extension, an ordinary authority write, keeps the horizon about 1.5·TTL ahead of the last renewal that triggered it. Only the first grant of a lease is written synchronously. If extensions fall behind, grants shrink and the host fences by the horizon minus half the skew bound; a failed extension write makes the volume uncertain and refuses renewals that would issue a new or extended grant (a Revoking lease still gets its bounded drain reply). -**CLEAN move:** Detach publishes the final cut with `State = detached` in one CAS â†' revoke â†' the host drains frontend, replication and provider and acknowledges the stored detached HEAD generation â†' blockmaster checks the detached HEAD and the matching acknowledgement â†' new epoch â†' the new host claims HEAD. +**CLEAN move:** Detach publishes the final cut with `State = detached` in one CAS �' revoke �' the host drains frontend, replication and provider and acknowledges the stored detached HEAD generation �' blockmaster checks the detached HEAD and the matching acknowledgement �' new epoch �' the new host claims HEAD. **FORCED move:** blockmaster waits until both the persisted lease horizon (at least every grant, so at most TTL/2 later than the last grant) and the granted or conservative restart deadline, plus the full skew bound, have passed (`core/authority/workspace.go` `prepareWorkspaceMoveLocked`). The old host's late CAS fails on the epoch; its uploads become orphans for GC. Writes since the old host's last cut are lost. @@ -333,7 +379,7 @@ Not done yet: | Chunks and segments are write-once; keys are never rebound | `chunk_remote.go` `putObject`; `gc.go` tombstones | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | yes | | Intents are durable before the first upload and removed only after the CAS outcome is known | `captureLocked` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS`, `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | yes | | GC never deletes a chunk reachable from a HEAD, snapshot, attempt or intent, and deletes only after two graced marks | `gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | yes | -| A published snapshot is removed only by `DeleteSnapshot` or retention for the planned attempt, never while a fork claim is live | `catalog.go` `DeleteSnapshot`; `retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | yes | +| A published snapshot is removed only by `DeleteSnapshot` or retention for the planned attempt, in any order with forks (no claims) | `catalog.go` `DeleteSnapshot`; `retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestSnapshotDelete_DeleteDuringAForkInFlight` (`core/frontend/chunkstore/snapshot_delete_test.go`) | yes | | Volume delete commits only with no snapshot name records; past the commit point it is irreversible | `volume_delete.go` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne`, `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | yes | | Volume ids are never reused | `core/host/master/services.go`; `catalog.go` `EnsureVolume` | `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | yes | | A host serves and cuts only under a valid lease; a fenced guard never reopens | `workspace_lease.go` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | yes | diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 8ec6e76874..a8d3e6a6e7 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -28,6 +28,8 @@ The design is described in three documents, and this one collects their machines - [M7. Host background-cut admission](#m7-host-background-cut-admission) - [Part B. Invariant ledger](#part-b-invariant-ledger) - [Part C. Change rules](#part-c-change-rules) +- [Part D. Wait ownership](#part-d-wait-ownership) +- [Part E. Quantities](#part-e-quantities) --- @@ -94,10 +96,10 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | -| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` | +| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | -| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | -| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001` | +| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced @`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` | +| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001` | ### M3 Replica role and peer state @@ -198,6 +200,7 @@ stateDiagram-v2 | 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` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | | Holder | (hydration wait) | one request deadline covers all missing chunks; callers may detach, but bounded per-layer workers retain and join each shared fill; HEAD/generation/local-write checks still govern installation | `core/storage/chunk_hydration.go`; `core/frontend/durable/storage_adapter.go` `readStorageBlock` | `INV-CUT-HYDRATION-WAIT-001`, `INV-CUT-READMISS-001` | +| Holder | (background hydrate) | an independent restore's walker fills every HEAD-named absent chunk through the same shared fill flights (never a second fetch, never over a local write); it yields while any flight has guest waiters, takes one host fill permit per flight (no cut payload, class `BackgroundFill` from the caller) and the permit is released only when that flight's I/O is over, also when the walker returns early on cancel, revocation or close | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill`; `core/storage/chunk_hydration.go` `hydrationFlightLocked` | `INV-RESTORE-HYDRATE-001`, `INV-CUT-READMISS-001` | ### M5 The cut pipeline @@ -206,6 +209,7 @@ A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. Th ```mermaid stateDiagram-v2 [*] --> Admit + [*] --> Refused: invalid frozen request; invalid_freeze_budget; no provider mutation Admit --> Refused: budget refused, closed, fenced, detached, base install, or lineage or lease invalid Admit --> PlainStop: plain detach and idle frontend lock acquired PlainStop --> Quiesce: frontend stopped; ordinary detached cut @@ -217,7 +221,7 @@ stateDiagram-v2 Quiesce --> Refused: guest-frozen budget recheck failed; no payload upload Quiesce --> FinalFreeze: measured admission or explicit frozen final override FinalFreeze --> OpenWindow: admission stays closed through detached settlement - Quiesce --> OpenWindow: ordinary round; Sync H and D fixed under barrier + Quiesce --> OpenWindow: ordinary round; Sync H and D fixed under barrier; release all held admission OpenWindow --> Copy: release barrier Copy --> Upload: local entry released, intent durable first Upload --> Copy: next unsent candidate @@ -243,11 +247,11 @@ stateDiagram-v2 | Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | | Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001`, `INV-CUT-READ-LOGICAL-001` | | Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses the ordinary StopIO, final cut and outcome settlement. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | -| Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | +| Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | -| Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and resume in FIFO order after a safe abort | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | -| Guest-frozen detach | `frozen=true` carries a non-future guest freeze origin; forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001` | -| Checkpoint tail | successful cuts sample remaining candidates and transfer cost from one rate observation after publication; zero bytes is known zero, insufficient history for a nonzero tail is unknown. This is advisory; frozen admission rechecks its own candidates. | `chunk_precopy.go` `candidateTail`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001` | +| Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | +| Guest-frozen detach | `frozen=true` carries a non-future guest freeze origin; invalid freeze options return HTTP400 `invalid_freeze_budget` before any provider admission or mutation (generic `bad_request` is not that proof); forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001`, `INV-WS-FREEZE-REFUSAL-001` | +| Checkpoint tail | one cost observation reports remaining bytes, tail cost, frozen admission estimate/known bit, storage limit and quiesce slack after a cut. Same-host duration advice is rechecked at admission before upload. | `chunk_precopy.go` `candidateTail`; `chunk_frozen_budget.go` `frozenBudgetEstimate`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001` | | Pre-copy host drain | a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` | | Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001`, `INV-CUT-READ-LOGICAL-001`, `INV-CUT-GUEST-BOUNDED-WAIT-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | @@ -259,6 +263,11 @@ stateDiagram-v2 | Settled | drop the intents; settle native map capture tokens, keeping chunks dirtied after the cut; a refused current-lineage point retains intent-rooted completed uploads until reuse, supersession or clean Close (unresolved CAS roots excluded) | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | | Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` | +Periodic HEAD cuts default to 15 minutes in blockvolume (OSS minimum 5 minutes; +0 explicitly disables); they do not create named snapshots. One five-minute +context covers a cut, including uploads. Deadline-aborted uploads remain rooted +and reusable only while their chunk version and HEAD generation match. + ### M6 Chunk lifecycle HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete). @@ -267,7 +276,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | +| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork or restore HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork`, `Restore` | `INV-WS-HEAD-CAS-001` | | `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | | `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | @@ -283,9 +292,15 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | -| name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001`, `INV-SNAP-SEAL-POINT-001`, `INV-SNAP-SEAL-DURABLE-001` | -| published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | -| published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001`, `INV-FORK-FROM-SEALED-001` | +| name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | +| published | deleting | `DeleteSnapshot` or retention for this attempt, whatever forks or restores read it (no claim is read); the mark records its delete time and GC keeps the attempt rooted for its grace | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | +| published | fork | take the deadline start, read the parent snapshot (every attempt reads it again; deleting or absent refuses), check the source is not being deleted, write the target `VOLUME`, then its HEAD only before start + deadline; no chunk is copied and the parent is not claimed | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent` | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | +| published | restore | the fork steps with `VOLUME` origin `restore`: until the first HEAD the parent stays rooted by GC's grace after any delete (the fork deadline bound), after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | +| restore (Restoring) | Hydrating | M6.Restore.Restoring>Hydrating: the driver starts the walker, paced at a byte rate under the BackgroundFill class | `core/host/volume/chunk_restore.go` `runRestore`; `core/frontend/durable/provider_restore.go` `HydrateVolume`; `core/storage/chunk_hydrate_all.go` `HydrateAllAt` | `INV-RESTORE-HYDRATE-001`, `INV-RESTORE-DRIVER-001` | +| restore (Hydrating) | Owning | M6.Restore.Hydrating>Owning: batch cuts start once chunks are local; the walker and the batches may overlap | `core/host/volume/chunk_restore.go` `runRestore` | `INV-RESTORE-DRIVER-001` | +| restore (Owning) | Owning | M6.Restore.Owning>Owning: one bounded batch cut re-uploads at most N local chunks with foreign keys under own keys (one intent, one HEAD CAS); absent chunks wait for the walker | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `INV-RESTORE-OWN-BATCH-001` | +| restore (Owning) | Independent | M6.Restore.Owning>Independent: the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs`; `core/host/volume/chunk_restore.go` `runRestore` | `INV-RESTORE-INDEPENDENT-001`, `INV-RESTORE-DRIVER-001` | +| restore (not independent) | name held | refused: `CreateSnapshot` on a restore volume needs the marker, and the supplied image itself must hold no foreign ref; a refused request leaves no name or attempt | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-RESTORE-SNAPSHOT-001` | **Intents and key bindings.** @@ -293,11 +308,26 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th |---|---|---|---|---| | — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | | intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` | -| intent live | expired | older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001` | +| intent live | removed (catalog) | the operation's create is confirmed or can never apply; the delete outlives the caller's cancellation but is bounded by `dropIntentTimeout` | `core/frontend/chunkstore/catalog.go` `dropIntent` | `INV-CAT-INTENT-DROP-BOUNDED-001` | +| intent live | expired | conservative elapsed age exceeds the TTL after pairwise clock skew, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001`, `INV-GC-CLOCK-SKEW-001` | | — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | -| bound | tombstoned, needle deleted | unrooted in two complete marks at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001`, `INV-GC-DELETE-EXACT-FID-001`, `INV-GC-GRACE-RESTART-001` | +| bound | tombstoned, needle deleted | unrooted in two complete marks separated by more than grace plus clock skew, binding age exceeds grace plus skew plus one-second timestamp precision, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001`, `INV-GC-CLOCK-SKEW-001`, `INV-GC-DELETE-EXACT-FID-001`, `INV-GC-GRACE-RESTART-001` | +| tombstoned, DELETE rejected | tombstoned, retry later; continue other bindings | definite HTTP400 is reported per object; no success recorded for the rejected fid; complete mark coverage is saved before returning partial failure; cancellation, unknown/other DELETE errors and metadata errors still stop the pass | `core/frontend/chunkstore/gc.go` `Collector.run`; `gc_execution.go` `executeGC`; `swfs.go` `DeleteBlob` | `INV-GC-DELETE-PROGRESS-001` | | tombstoned | (never rebound) | bindings are never removed | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | +GC clock admission (`INV-GC-CLOCK-SKEW-001`): + +```mermaid +flowchart LR + stamp[Persisted timestamp] --> age[Observed age minus pairwise skew and timestamp precision] + age --> young[Not past grace: retain root or candidate] + age --> old[Past grace: existing authority and complete-mark guards] + future[Future or backward mark clock] --> reset[Discard elapsed coverage and start a fresh mark] + old --> reject[HTTP400: retain tombstone and report failure] + reject --> later[Continue later bindings and save complete mark] +``` + + --- ### Local WAL-pressure durability progress @@ -346,9 +376,19 @@ snapshot lifetime; local persistence does not bypass it. `free -> admitted -> draining -> joined -> released`; process death releases its OS slot. Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; expiry cancels the cut but keeps its slot until workers join. Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. +### M8. Attached-volume maintenance + +`PendingAttach -> Armed -> Due -> Running -> Armed`; elapsed ticks coalesce. +A stable volume phase staggers the one-hour retention schedule. GC is opt-in +pending density qualification. Detach/fence/Close cancels and joins before +catalog/storage release; only a still-current handle may re-arm after safe abort. +A pass has one minute for retention and optional GC; retention failure skips GC. +A scoped GC pass traces the whole catalog but mutates only its target volume, +with a separate scope/config-bound mark. Incomplete marks carry no coverage. + ## Part B. Invariant ledger -130 `INV-` rows: 109 ACTIVE, 19 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 115 new. +160 rows: 138 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 145 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. @@ -385,12 +425,12 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | -| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshAndSetWModeCloseTheWindow` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3AppendWriteErrorLatchesTheStore` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeWaitsForAHeldBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3InstallingScanErrorIsTypedNotReady` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision` (`core/storage/recovery_v3_test.go`); `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | -| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | -| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | -| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | -| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB | -| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB | +| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshAndSetWModeCloseTheWindow` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3AppendWriteErrorLatchesTheStore` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeWaitsForAHeldBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3InstallingScanErrorIsTypedNotReady` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision` (`core/storage/recovery_v3_test.go`); `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model | STUB | +| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` | STUB | +| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB | +| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | +| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack | STUB | +| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records | STUB | | `INV-WAL-V3-MIGRATE-001` | ARCHIVED: the in-place v2 converter is removed. Public opens refuse v2 bytes without mutation; no upgrade path is provided. | M1 open refusal | `core/storage/walstore_v3.go` `openWALStoreV3WithOptions` | `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | none (retired tool) | ARCHIVED | | `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA` (expiry and joined physical-fault wire status); `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | | `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | @@ -408,9 +448,9 @@ Notes: - `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only. - `INV-FE-FLUSH-SYNC-001`: NVMe/TCP also asserts failed-Sync status and reason logging through the actual session dispatch, and success produces no failure log. - `INV-WAL-V3-RESET-001`: Format bump v3, plan row 8 (DESIGN 8.6). Dark: no production path calls the reset, and it must not be activated before the reset model (r4.5) passes. No v3 tail release exists yet, so the precondition is CheckpointLSN >= W rather than an empty retained range: retained old-incarnation bytes at or below the checkpoint are preserved in the extent. The map root is unchanged by a reset, so no map page is retired. -- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). Until the chunk layer's side of the v3 install protocol lands (codex03), a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until codex03's v3 FreshFromHead restore lands; since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from (codex01 row 11b P1); it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). +- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). Until the chunk layer's side of the v3 install protocol lands, a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until the v3 FreshFromHead restore lands; since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from; it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). - `INV-WAL-V3-MIGRATE-001`: Archived with the converter and its legacy fixtures; v2 inputs refuse open without mutation. -- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model (claude05), not by these tests. Installing recovery is row 11. +- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model, not by these tests. Installing recovery is row 11. - `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). It is a STUB until the v3 store is wired in (rows 4 and 5) and activated (row 12b). The v2 checkpoint path (`persistCheckpointReleasing`) is unchanged and is retired in row 14a. The map coverage predicates against the root are added by row 7, and the conditions on BASE edges by rows 9 to 11. - `INV-WAL-V3-DESCRIPTOR-001`: Format bump v3, plan row 1 (DESIGN r15 section 2). It is a STUB until the activation commit (plan row 12b): no production open or create path reaches the v3 codec before then. The map-dependency checks (root and pages present and hash-valid) are added by plan row 7. The tests decode vectors from an independent generator (`core/storage/testdata/format_v3/slot/gen_slot_vectors.py`). @@ -427,13 +467,14 @@ Notes: | `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | -| `INV-MASTER-JOURNAL-ISOLATION-001` | With strict journal isolation, blockmaster refuses with FailedPrecondition a heartbeat from a node whose durable root shares the authority store's file system and that serves no volume, a new workspace placement on such a node, a new product-loop placement on it, and a move whose target is such a node; a node that already serves by durable state, a repeated identical placement and the retry of an issued move are not refused, and without strict mode co-location only raises an alarm. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `MoveWorkspace`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE | +| `INV-MASTER-JOURNAL-ISOLATION-001` | Under strict journal isolation, blockmaster gives no new work to a node whose durable root shares the authority store's file system: it refuses that node's heartbeat while it serves no volume, a new placement on it and a move onto it; work the node already has is kept. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE | Notes: - `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, directory sync failed): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. - `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2). - `INV-WS-RENEW-NONBLOCKING-001`: The cited tests inject delays or holds before or inside the store write; they show sensitivity to a slow store, not a measured disk trace. +- `INV-MASTER-JOURNAL-ISOLATION-001`: a refused heartbeat gets FailedPrecondition. A new placement is either a workspace placement or one the product loop plans. Work the node already has means: the node serves by durable state (a placement slot or a current authority line that names it), a repeated identical placement, or the retry of an issued move. Without strict mode, co-location only raises an alarm. ### B.3 Core: replication and replica roles @@ -464,22 +505,29 @@ Notes: |---|---|---|---|---|---|---| | `INV-WS-HEAD-BELT-001` | A takeover confirms its exact HEAD before serving. The supported single-serialization-point mode has W=0; explicit experimental cooling requires W >= the 2 s HEAD operation deadline plus 100 ms settling. Each CAS and confirmation has its own 2 s deadline. A successful cut CAS requires readback before remoteLSN/map settlement and intent cleanup. Unconfirmed roots remain protected through Close; an observed different publication owner fences without retry, even after epoch regression or when the original HEAD was empty. | M4 Claiming → Cooling → Holder; M5 CAS → Confirmed or Pending/Fenced | `core/storage/chunk_head_belt.go`; `chunk_restore.go` `ClaimChunkHead`; `chunk_layer.go` `captureLocked`, `resolvePending`, `SettleDetach`, `dropIntents`, `Close` | `TestHeadBeltTakeoverRefusesLateOldCAS`; `TestHeadBeltTakeoverWaitsBeforeConfirmation`; `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`; `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`; `TestHeadBeltEmptyBaseForeignPublicationFences`; `TestHeadBeltSinglePointHasNoCoolingDelay`; `TestHeadBeltOperationsHaveOwnDeadline`; `TestHeadBeltCoolingWindowCoversCASAndSettle` (`core/storage/chunk_head_belt_test.go`) | `WorkspaceTakeover` belt extension pending | ACTIVE | | `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`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`); `TestNativeReplacementCutBehindHEADRefuses` (`core/storage/legacy_replacement_v3_test.go`) | `WorkspaceTakeover` `HeadMonotone` | 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-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-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` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_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 | | `INV-WS-STOP-PENDING-001` | Stop-pending changes only when the lease guard renews, never what it admits or acknowledges: from the start of a chunk detach until the guard fences, its sleep after a completed renewal is at most 250 ms; it returns to the normal renewal delay only when that same (latest) detach attempt provably did not happen and serving resumed. It bounds scheduling, not the time from a revocation to its acknowledgement. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/frontend/durable/provider_chunk.go` `DetachVolume`, `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay` | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | | `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | -| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound, of the current holder's lease (a move issue starts it; a predecessor's never admits); the lease reported to the host is the grant, never the horizon, and excludes half of the bound. HEAD is read only after that admission; it must be the expected holder's at the expected epoch or be at an older epoch, and the lost range starts at the remote LSN of that HEAD. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact`, `MoveWorkspace` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE | +| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound, of the current holder's lease (a move issue starts it; a predecessor's never admits); the lease reported to the host is the grant, never the horizon, and excludes half of the bound. HEAD is read only after that admission; it must be the expected holder's at the expected epoch or be at an older epoch, and the lost range starts at the remote LSN of that HEAD. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact`, `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE | +| `INV-WS-LOST-RANGE-READOUT-001` | Every issued forced grant the master returns carries its lost range as stored before the issue (the kept HEAD's remote LSN, LostUntil in master time, the kept HEAD's generation and the HEAD entry's filer mtime read with that HEAD, or "unknown"), also on a replay and after a restart; `QueryWorkspaceLostRange` returns the same stored ranges, all of them in issue order or one by request id, never recomputed. A forced move whose range record is missing or fails its checks (the range checksum or the HEAD-time checksum) makes the readout fail (a grant without a range and with the reason; `DataLoss` from the query; CLI exit 4) and is never reported as no loss. A failure after the issue (e.g. the binding reconciliation) is answered as `Internal` naming the move ISSUED, never as a refusal; the client reports it as an unknown outcome with the same-request-id recovery (never a new request id), and the master's audit log records the issued forced move. An issuing write that may have reached the store but reported an error (memory unissued), and any move on a volume whose workspace persistence is already uncertain, fail with `ErrWorkspaceOutcomeUncertain` and are answered as an unknown outcome (`Internal`, restart then rerun with the same request id), logged as unknown, never as a refusal; admission refusals and failures before the issue stay `FailedPrecondition`. The client accepts a grant only when it matches the request (request id, volume, expected holder and epoch, target replica and host, a higher epoch; else unknown) and its range only when it names the same move and kept HEAD (volume, request id, epochs, old replica, HEAD generation, frontier = remote LSN; else unproven). `PreviewWorkspaceMove` runs the forced admission and writes nothing. | M2 lease: Expired → Moved (forced); Moved → epoch issued | `core/authority/workspace_lost_range.go` `recordLostRangeLocked`, `WorkspaceLostRangeReadouts`, `encodeLostRangeEnvelope`, `decodeLostRangeHeadTimes`; `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `PreviewWorkspaceForcedMove`; `core/host/master/workspace_head.go` `headFilerMtimeNS`; `core/authority/authority.go` `applyWithWorkspaceMove`; `core/host/master/workspace_service.go` `MoveWorkspace`, `grantWithLostRange`, `postIssueError`, `issuedRecord`, `logForcedGrant`, `QueryWorkspaceLostRange`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove`, `checkGrant`, `checkRange`, `LostRanges`, `Readout`; `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `runWorkspaceLostRange`, `shellCommand` | `TestWorkspaceForcedMoveStoresHeadFilerTime`, `TestWorkspaceLostRangeHeadTimeTamperFailsClosed`, `TestWorkspaceLostRangeAccumulatesInIssueOrder`, `TestWorkspaceLostRangeReadoutFailsClosed`, `TestWorkspaceLostRangeSkippedWriteIsDetected`, `TestWorkspaceForcedMovePreviewWritesNothing` (`core/authority/workspace_lost_range_readout_test.go`); `TestWorkspaceUncertainIssueWriteIsTyped` (`core/authority/workspace_outcome_uncertain_test.go`); `TestWorkspaceForcedMoveRecordsTheLostRange`, `TestWorkspaceForcedMoveLostRangeOrdering`, `TestWorkspaceForcedReservationResumeNeedsItsRange` (`core/authority/workspace_lost_range_test.go`); `TestWorkspaceForcedMoveLostRangeOverRPC`, `TestWorkspaceHEADReadsFilerMtime` (`core/host/master/workspace_lost_range_readout_test.go`); `TestForceMoveGrantWithoutRangeIsUnproven`, `TestForceMoveBindsGrantAndRange`, `TestLostRangesBindsTheAnswer`, `TestReadoutWording` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row3and4_SentAndGranted`, `TestWorkspaceForceMove_Row7_ReadoutUnproven`, `TestWorkspaceForceMove_Row8_RerunSameRequestID`, `TestWorkspaceForceMoveRecoveryCommandRuns`, `TestWorkspaceForceMoveRejectsAMismatchedAnswer`, `TestWorkspaceLostRangeListsAllInOrder` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`); `TestWorkspaceForceMovePostIssueFailureKeepsTheOutcome` (`cmd/sw-block/workspace_postissue_test.go`); `TestWorkspaceForceMoveUncertainIssueWriteIsUnknown` (`cmd/sw-block/workspace_uncertain_test.go`) | — | ACTIVE | +| `INV-WS-FORCED-CONFIRM-001` | The OSS operator client (`sw-block ops workspace force-move`, `wsclient.ForceMove`) sends a move with `force: true` only when `--confirm-forced` is exactly `@` (that volume, a positive decimal epoch), and then always as kind forced at that epoch with the operator's request id; anything else is refused before any connection or RPC (exit 2). A confirmation at an epoch the master has no holder for is refused without sending a move. There is no bypass flag, and `--dry-run` is never a confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `ForceMove`, `holderAt`; `cmd/sw-block/workspace.go` `runWorkspaceForceMove` | `TestParseConfirmation`, `TestForceMoveSendsForceOnlyWithTheConfirmation`, `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally`, `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceForceMove_Row3and4_SentAndGranted`, `TestWorkspaceForceMove_Row5_MasterRefusal`, `TestWorkspaceForceMove_Row6_OutcomeUnknown`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`) | — | ACTIVE | Notes: +- `INV-WS-SINGLE-FILER-001`: the same census runs in every `sw-block ops chunk` command that writes chunk metadata (snapshot-delete, fork, retain, volume-delete, gc --apply), and in verify, which writes nothing but would report false findings against a split filer view, before it reads or writes; other read-only commands and modes do not run it. - `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary. - `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits). +- `INV-WS-HEAD-KEY-PROVENANCE-001`: No test asserts it yet in this change. Verify reports a violation it observes during a pass (a key HEAD named, then dropped, then named again is `ROOT_INVALID`): `TestVerify_SchedulesGiveTheSameFindings` (`core/frontend/chunkstore/verify_test.go`), the named-again cases. - `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. Extended for a new holder that dies between its grant and its HEAD claim: the move issue starts its lease, admission uses that grant's lease, HEAD is read after admission, an older-epoch HEAD is accepted (its generation and remote LSN may have moved by an earlier holder's late claim), and a returning holder is refused by two fences, its lease-gated attach and the higher HEAD epoch. `WorkspaceTakeover` models one move from A to B and does not cover a second move away from an unclaimed grant; that model check is open and not claimed here. +- `INV-WS-LOST-RANGE-READOUT-001`: The HEAD time is the HEAD filer entry's mtime from the filer's `Last-Modified` header on the same read as the HEAD content (1 s resolution). chunkstore writes that mtime from the clock of the host that wrote the entry (the cut); the readout labels it "(publishing host clock as recorded in the filer, 1 s resolution)", and it is not a master time; there is no HEAD format change. The HEAD times sit beside the v1 ranges in the lost-range file with their own checksum, so a binary that predates them still verifies the file; a record without one reads as unknown. The readout reads the ranges loaded at startup: damage after startup shows at the next load. The no-HEAD form ("no remote image exists") is defensive: the master refuses a forced move without a published HEAD. The header is checked against test HTTP servers only; the `chunkstore_integration` test does not assert it. Not in the TLA+ models. +- `INV-WS-FORCED-CONFIRM-001`: A client-side rule: the master's own guards (explicit force, admission, expected epoch) are `INV-WS-FORCED-MOVE-001`. The holder's logical replica id is read from `QueryWorkspace` (the lease, or the journal on a rerun). - `INV-WS-STOP-PENDING-001`: `WorkspaceTakeover` has no renewal cadence (a host may renew at any step), so StopPending adds no state to the model and no configuration is re-run; `INV-WS-LEASE-001` and `INV-WS-REVOKE-ACK-001` hold in StopPending unchanged. ### B.5 Workspace: the cut pipeline @@ -489,7 +537,9 @@ Notes: | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | | `INV-CUT-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | -| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Ordinary refusal reopens tentative admission before rolling uploads; guest-frozen refusal instead sends no payload. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Ordinary admission never uses unknown samples. A guest-frozen attempt skips staging, forecasts and rechecks against five seconds minus guest elapsed, and refuses without uploading if it cannot fit. Only an explicit final override can bypass that estimate guard, with over_budget recorded; authority and publication settlement remain mandatory. Checkpoint tails are advisory same-window measurements. Nested Sync phases and live barrier-prefix spans explain fixed cost without double counting. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestCheckpointTailScanIncludedInTotalAndFixedCosts`, `TestCheckpointTailUsesLiteralLatestThreeConservativeRate`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestChunkFrozenDetachWireContractAndPrecedence`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); controlled callers and measured latency are not a model proof | ACTIVE | +| `INV-WS-FREEZE-ACCOUNTING-001` | Frozen detach validates its origin and rechecks elapsed + known estimate against 5 s; override is explicit. Storage reports its admission estimate and quiesce slack using same-host monotonic durations. Stale advice is rechecked before upload; override and actual elapsed remain visible. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess`; `TestCandidateTailReportsCompleteFrozenBudget`, `TestFrozenRefusalRetainsUnknownCompleteEstimate`, `TestChunkFrozenRefusalCarriesServerBudget`, `TestChunkFrozenDrainRefusalCarriesObservedBudget`, `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation`, `TestFrozenSaturatedTailRemainsKnownButNonActionable` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible`, `ReportSlackSound` | ACTIVE | +| `INV-WS-FREEZE-REFUSAL-001` | HTTP400 `invalid_freeze_budget`, retryable=false, is emitted only for frozen-request validation before any provider admission or mutation. Missing/zero/future origin, override without frozen, and frozen+plain preserve that boundary. Generic `bad_request` is not a clean-refusal proof. Terminal and unknown-publication causes retain precedence; no production path emits this typed code after mutation. | G frozen detach: request → refused before admission (M5) | `core/host/volume/chunk_control.go` `handleChunkDetach`, `chunkErrorCode`; `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestChunkFrozenValidationHasDistinctPreMutationCode`, `TestFrozenValidationPrecedesAnyProviderAccess` | — (wire classification; validation/admission guards unchanged) | ACTIVE | +| `INV-CUT-PRECOPY-001` | Resume grants waiters FIFO under one lock; gates and completion are independent. Each command keeps its arrival/caller bound. Only pause refusals requeue; stale and terminal errors survive. Detached handoff requires settled publication. See Notes for admission and freeze guards. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestCheckpointTailScanIncludedInTotalAndFixedCosts`, `TestCheckpointTailUsesLiteralLatestThreeConservativeRate`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestChunkFrozenDetachWireContractAndPrecedence`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyResumeReleasesAllWaiters` (FIFO grants under one lock, concurrent outstanding I/O), `TestPrecopyResumedArrivalDoesNotInheritExpiredPause`, `TestPrecopyQueueBoundStartsAtCommandArrival`, `TestPrecopyResumeGrantVersusExpiry`, `TestPrecopyGrantedWaiterFollowsReplacementPause`, `TestPrecopyNewPauseCannotEraseObservedStalePrimary`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); controlled callers and measured latency are not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED | @@ -501,7 +551,7 @@ Notes: | `INV-CUT-READ-LOGICAL-001` | Every cut read of a chunk (COW copy, COW save and pre-copy staging) resolves each block through the dirty map first, validates the whole WAL record it read and re-resolves on a mismatch, and reads the extent only for a block with no dirty entry; no cut path reads the extent region directly. | M5 Stage / Copy | `core/storage/chunk_cut_cow.go` `readCOWChunk`, `readLocalBlock`; `core/storage/chunk_layer.go` `readChunk`; `core/storage/walstore_v3.go` `readDirtyV3Into` | `TestCutCOWV3_CaptureDoesNotPinWAL` (`core/storage/chunk_cut_alignment_test.go`); `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE | | `INV-CUT-HOOK-BEFORE-APPEND` | The COW hook owns/saves the at-H image before a read-visible WAL mutation, under shared capture admission. | M1 Write / M5 Save | `walstore.go` `Write`, `WriteBatch`; `chunk_cut_cow.go` `beforeChunkMutation` | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 SaveStart before Write | ACTIVE | | `INV-CUT-FILL-FROM-BASE` | Lazily absent blocks are filled from this cut's fixed base HEAD, never a newer remote HEAD. Remote fetch runs after releasing local ownership. | M5 Copy / lazy fill | `chunk_cut_cow.go` `readCOWChunk`, `fillMissing` | `TestCutCOWV3_LazySaverSpillImageIsExact`, `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD` | Remote fill not modelled; native byte-image controls | ACTIVE | -| `INV-CUT-GUEST-BOUNDED-WAIT-001` | Inside an open cut window, a guest write to a candidate chunk waits only for local work: a saver slot for at most 250 ms (then only the cut aborts) and one local capture of that chunk's at-H image, its own or that of the chunk's current copier or saver; lazily absent blocks are left to the copier to fill from the base HEAD after it releases the entry, so a guest write never waits for a remote fetch or upload. | M5 OpenWindow → Copy (guest write during Copy / Upload) | `core/storage/chunk_cut_cow.go` `beforeCOWMutation`, `claim`, `acquireSaver`, `readCOWChunk`, `fillMissing` | `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk`, `TestCutCOWV3_SaverBurstWaitsAndPublishes` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestCutCOWV3_HeldFillIsCancelledByAbortAndDrained` (`core/storage/chunk_cut_cow_fill_test.go`) | `CutCOW2` `Blocked` defines which writes wait; remote I/O is not modelled | ACTIVE | +| `INV-CUT-GUEST-BOUNDED-WAIT-001` | Inside an open cut window, a guest write to a candidate chunk waits only for local work, never for a remote fetch or upload: at most 250 ms for a saver slot (then only the cut aborts) and one local capture of the chunk's at-H image. | M5 OpenWindow → Copy (guest write during Copy / Upload) | `core/storage/chunk_cut_cow.go` `beforeCOWMutation`, `claim`, `acquireSaver`, `readCOWChunk`, `fillMissing` | `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk`, `TestCutCOWV3_SaverBurstWaitsAndPublishes` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestCutCOWV3_HeldFillIsCancelledByAbortAndDrained` (`core/storage/chunk_cut_cow_fill_test.go`) | `CutCOW2` `Blocked` defines which writes wait; remote I/O is not modelled | ACTIVE | | `PROGRESS-DESTRUCTIVE` | Supported guest zero-data writes use ordinary COW and do not abort every update. Unsupported DSM/discard/write-zeroes opcodes reach no storage mutation. Administrative Recover/reset/BASE still invalidate and drain; progress assumes these lifecycle transitions eventually stop. | M1 Write / M5 Save | `chunk_cut_cow.go` `beforeCOWMutation`; frontend dispatch | `TestCutCOWV3_ZeroWritesDoNotAbortUpdates` (`core/storage/chunk_cut_alignment_test.go`); `TestDispatch_UnsupportedOperations` (`core/frontend/ublk/dispatch_test.go`); `TestT2Batch11a_IdentifyController_ONCSAllZero` (`core/frontend/nvme/identify_test.go`) | Guest/lifecycle distinction not modelled; native controls | ACTIVE | | `INV-CUT-PAYLOAD-BOUNDED-001` | Saver-slot admission waits at most 250 ms without a window lock or remote call before aborting only the cut; physical local I/O remains joined. Upload workers, active savers and cached saves share a configurable per-volume payload byte bound independent of candidate count; an explicit budget below six chunks is refused. An optional Budget admits before staging/barrier and accounts each COW save without a window lock; revocation aborts only the cut and its ticket is released after worker joins. Host-wide policy is a separate limiter module. WAL batch validation uses block-sized scratch even when a record spans many chunks. Pre-copy streams one chunk per worker; native at-H reads protect unsent candidates with COW. Only guest overwrites consume side-file bytes. A full side-file cap aborts the update, retains its dirty set and allows guest writes to proceed. Uploads join before cleanup. | M5 Stage / Copy / Upload | `chunk_cut_payload.go`; `chunk_cut_cow.go`; `chunk_upload.go` | `TestCutBudgetRefusesBeforeBarrier`, `TestCutBudgetCOWRefusalAbortsOnlyCut`, `TestCutBudgetRevocationJoinsBeforeRelease` (`core/storage/chunk_cut_budget_test.go`); `TestV3ReadLargeBatchScratchIsBlockBounded`, `TestCutCOWV3_SaverBurstWaitsAndPublishes`; `TestStatusServer_ChunkErrorBodyIsTyped` (local cut abort wins over its cancelled upload; uncertain CAS, fencing and terminal Closed/Detached keep precedence), `TestCutAbortReasonsAreCountedAndCopied`, `TestCutPayloadBudgetBoundsSlots`, `TestChunkLayerPayloadBudgetRejectsUndersized` (`core/storage/chunk_cut_payload_budget_test.go`); `TestWALStoreChunk_InitialWriteAnonymousMemory` (isolated Linux RSS arms, `core/frontend/durable/provider_initial_memory_linux_test.go`); `TestCutCOWV3_ChangedImageExceedsSpillCap`, `TestChunkStageV3_ChangedImageExceedsSpillCap`, `TestCutCOWV3_OverwriteStormAbortsAndRetries`, `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk`, `TestCutCOWV3_SpillCapAbortsTheCut` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestChunkUploads_FailureJoinsBeforeIntentCleanup` (`core/storage/chunk_upload_parallel_test.go`) | `CutPipeline` `AbortPoint` covers refused-point stutter; byte counts and filesystem/transport resource costs are not modelled | ACTIVE | | `INV-HOST-CUT-BUDGET-001` | Cooperating cut processes hold an OS slot before staging/barrier; payload and side caps are reserved per slot, including urgent slots. Cancellation never frees a slot before actual worker settlement. Active coordinated reservations exclude retained crash spill, fallback and RSS. Unavailable pools refuse ordinary background work; urgent/named fallback is explicitly degraded and cannot claim a host resource/rate bound. Pacing debt persists within one process, not across process turnover. | M7 admission/drain/release | `core/hostlimit`; durable `ChunkBudget`; blockvolume host-limit flags | `TestSlotsUrgentAndJoinedRelease`, `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot`, `TestHostCutLimitDoesNotGateGuestIO`, `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin`, `TestCutPolicy_StaggerPreservesExplicitTimerReset`, `TestKilledInitializerDoesNotPublishPartialConfiguration`, `TestUnusablePoolClassPolicy`, `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt`, `TestChunkControl_NamedSnapshotUsesUrgentFallback`, `TestLastFallbackReleaseClearsActiveStatus`, `TestConfigurationLockFailurePreservesPoolPolicy`, `TestConfigurationLockContentionRefusesAllClasses` | `HostBudget` HeldUntilJoined/PayloadBound/SpillBound (bounded OS-lock abstraction; fallback excluded) | ACTIVE | @@ -516,35 +566,69 @@ A guest read has a cooperative arrival budget; internal contextless readers keep Notes: +- `INV-CUT-PRECOPY-001`: Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Ordinary refusal reopens tentative admission before rolling uploads; guest-frozen refusal instead sends no payload. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; on resume every queued waiter is granted in arrival order under one lock hold; each then passes the normal gate; completion is unordered. The ended pause is cleared before those normal gate checks; queue deadlines are measured once from each command arrival and capped by five seconds or its earlier caller deadline, so independent I/O is concurrent and later arrivals cannot inherit an expired pause; host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Ordinary admission never uses unknown samples. A guest-frozen attempt skips staging, forecasts and rechecks against five seconds minus guest elapsed, and refuses without uploading if it cannot fit. Only an explicit final override can bypass that estimate guard, with over_budget recorded; authority and publication settlement remain mandatory. Checkpoint tails are advisory same-window measurements. Nested Sync phases and live barrier-prefix spans explain fixed cost without double counting. + - `INV-CUT-STAGED-REUSE-001`: `captureLocked` also requires HEAD's generation to be the one the stage was compared against (code reading; not asserted by these tests). - `INV-CUT-READ-LOGICAL-001`: the staging clause (`readChunk` through `WALStore.Read`) is enforced by reading; no test captures WAL-only bytes through a staging round. +- `INV-CUT-GUEST-BOUNDED-WAIT-001`: the capture a write waits for is its own or that of the chunk's current copier or saver. Lazily absent blocks are left to the copier, which fills them from the base HEAD after it releases the entry. + +- `INV-WS-FREEZE-ACCOUNTING-001` details retained: A frozen detach validates a positive, non-future origin before admission, converts it once to a local monotonic origin, and subtracts elapsed time from the five-second freeze budget at forecast and barrier. Only explicit final override may exceed the forecast budget, and its report records that override and actual elapsed time. New F2 wire fields are durations, not a changed clock-origin request. Existing Unix-nanosecond origin validation/conversion remains; new advice is same-host only. Estimate growth and request delay may cause a bounded refusal, not a promise every advised cycle admits. No new margin. ### B.6 Workspace: chunk lifecycle, GC and delete | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| | `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | -| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | +| `INV-MAINT-ONE-OWNER` | Only the current attached handle with matching replica/epoch/endpoint admits maintenance; one attached volume admits at most one pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline`, `TestMaintenanceRejectsForeignLineageBeforeAdmission`, `TestMaintenanceSameHandleRearmsAfterJoinedStop` | `MaintenanceOwner` `OneOwner`, `CurrentHandleAtAdmission` | ACTIVE | +| `INV-MAINT-SCOPE` | Per-volume GC traces foreign roots while restricting candidate reclamation, intent expiry and copy settlement to its volume; namespace coverage is not imported. | M8 scoped GC | `gc.go` `Collector.run`; `gc_copy.go` `SweepCopies`; `gc_execution.go` `ExecuteVolumeGC` | `TestVolumeGC_ForeignIntentRootsAndLocalCandidates`, `TestVolumeGC_DoesNotImportGlobalMark`, `TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected`, `TestVolumeGC_ForeignEligibleCopyIsNotSettled` | `ScopedMaintenanceGC` `ForeignRootSurvives`, `ForeignCandidatesUntouched`, `OwnCoverageOnly` | ACTIVE | +| `INV-MAINT-JOIN` | Detach/fence/Close cancels maintenance and joins admitted workers before releasing its catalog/storage lifetime. | M8 Running → Draining → Closed | `provider_chunk.go` `chunkBackground`, `stopChunkLoop` | `TestMaintenanceStopJoinsBeforeRelease`, `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenanceAuthorityLossCancelsHeldPass`, `TestMaintenanceHealthyLineageChangeCancelsHeldPass` | `MaintenanceOwner` `JoinedBeforeRelease` | ACTIVE | +| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. An owner-qualified ref roots the owner's key (load-bearing for forks and restores: a target's HEAD keeps the source's chunks live after the source snapshot and volume are gone). | M6 key: Bound → Tombstoned; M6 snapshot: published → fork \| restore | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`); `TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone` (`core/frontend/chunkstore/restore_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete`; `RestoreIndependence` `NoGap` | ACTIVE | | `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | | `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | -| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | -| `INV-GC-DELETE-EXACT-FID-001` | GC deletes a needle only after tombstoning its key binding, and only by the exact fid recorded in that binding (volume id, needle key and cookie, never rebuilt); a delete response other than 200, 202, 204 or 404 from any replica is an error that fails the pass and leaves the binding tombstoned for a later retry. | M6 key: Bound → Tombstoned, needle deleted | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/swfs.go` `SWFS.DeleteBlob` | `TestSWFS_DeleteBlobStatusesAndExactPath` (`core/frontend/chunkstore/gc_test.go`) | — | ACTIVE | -| `INV-GC-GRACE-RESTART-001` | A binding's grace counts from the first complete mark that finds it unrooted and restarts whenever a mark finds it rooted or changed; a deleted snapshot's attempt stays a root until its deleting time is older than the grace, after which the two-mark rule needs another full grace. | M6 key: Bound → Tombstoned; M6 snapshot: Deleting | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/gc_copy.go` `snapshotAttemptHeads`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace` (`core/frontend/chunkstore/gc_copy_test.go`) | `RetentionGCTiming` `NoLiveDelete` | ACTIVE | -| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | +| `INV-GC-DELETE-PROGRESS-001` | A definite HTTP400 DELETE refusal cannot starve later eligible bindings or erase younger candidates' completed-mark coverage. The rejected fid stays in its immutable tombstone, is retried later and is never counted reclaimed. FailedDeletes reports the object; ExecuteGC saves the complete mark before returning partial failure. Other/unknown errors and cancellation remain pass failures. | M6 bound/tombstoned → physical reclamation | `core/frontend/chunkstore/gc.go` `run`; `gc_execution.go` `executeGC`; `swfs.go` `DeleteBlob` | `TestGCPermanentDeleteDoesNotStarveLaterBindings`, `TestSWFS_DeleteBlobStatusesAndExactPath` | `GCDeleteProgress` `NoFalseSuccess`, `FailureVisible`, `LaterProgress` | ACTIVE | +| `INV-GC-CLOCK-SKEW-001` | Time-based GC eligibility subtracts configured pairwise clock skew (default one minute), plus one second for binding timestamps. Future valid intent/deletion stamps retain roots without blocking unrelated work. Future/backward or differently configured marks supply no elapsed coverage; malformed marks still refuse. This assumes clocks stay within the configured pairwise bound. | M6 intent expiry, deleting snapshot roots, bound → tombstoned | `core/frontend/chunkstore/gc.go` `oldEnough`, `run`; `gc_copy.go` `SweepCopies`, `snapshotAttemptHeads`; `gc_execution.go` `readMark`, `executeGC` | `TestGCSkewSnapshotDeleteGraceBothDirections`, `TestGCSkewIntentExpiryUsesConservativeAge`, `TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress`, `TestGCSkewPersistedCoverageAcrossHosts`, `TestGCSkewBindingAgeIncludesSecondResolution`, `TestGCSkewConfigAndMarkCoverage`, `TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate`, `TestGCSkewFutureCopyDoesNotBlockOtherSettlement` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `NoEarlyExpiry`, `FutureProtects`, `IndependentProgress`, `EventuallyEligibleAtBound` | ACTIVE | +| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period is at least the catalog operation deadline plus the clock skew bound plus the CAS apply bound (default: the operation deadline). | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound` (`core/frontend/chunkstore/gc_volume_test.go`) | `RetentionGCTiming` `NoLiveDelete`; `ForkDelete` `NoGap` (G >= D + E + P) | ACTIVE | +| `INV-GC-DELETE-EXACT-FID-001` | GC deletes a needle only after tombstoning its key binding, and only by the exact fid recorded in that binding (volume id, needle key and cookie), never a rebuilt one. | M6 key: Bound → Tombstoned, needle deleted | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/swfs.go` `SWFS.DeleteBlob` | `TestSWFS_DeleteBlobStatusesAndExactPath` (`core/frontend/chunkstore/gc_test.go`); `TestGCPermanentDeleteDoesNotStarveLaterBindings` (`core/frontend/chunkstore/gc_delete_progress_test.go`) | — | ACTIVE | +| `INV-GC-GRACE-RESTART-001` | A binding's grace counts from the first complete mark that finds it unrooted and past its age bound, and restarts when a mark finds it rooted or its binding changed; a deleting snapshot attempt roots its keys until its deleting time is past the grace. | M6 key: Bound → Tombstoned; M6 snapshot: Deleting | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/gc_copy.go` `snapshotAttemptHeads`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace` (`core/frontend/chunkstore/gc_copy_test.go`) | `RetentionGCTiming` `NoLiveDelete` | ACTIVE | +| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_RetainSkipsASameNameReplacement` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | | `INV-SNAP-SEAL-POINT-001` | A named snapshot request for a free name runs exactly one cut and stores the HEAD that cut installed as the snapshot; a retry of a recorded request replays that snapshot without cutting; if the cut fails (including a COW window abort) the request fails with that error and records no snapshot. | M5 Admit → Settled, then M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`); `TestChunkControl_SnapshotStoresTheCutHead` (`core/host/volume/chunk_control_adapter_test.go`) | — | ACTIVE | | `INV-SNAP-SEAL-DURABLE-001` | A named snapshot is reported done only after its cut's HEAD CAS is confirmed (every referenced chunk uploaded first) and its attempt entry is confirmed by its exclusive create or a read-back; an unknown outcome of either reports failure, and an unknown create keeps the snapshot's intent. | M5 CAS → Settled; M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `createResolved` | `TestCatalog_SnapshotUncertainCreateKeepsIntent`, `TestCatalog_SnapshotAppliedResponseLostIsConfirmed` (`core/frontend/chunkstore/catalog_settle_test.go`); `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`) | — | ACTIVE | -| `INV-FORK-FROM-SEALED-001` | A fork reads only a published, active snapshot: a name with no published attempt or an aborted one is `snapshot_not_found`, a deleting one is `snapshot_deleting`, and the parent claim is conditioned on the attempt still being active. | M6 snapshot: published → fork | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent`, `resolveSnap` | `TestFork_RefusalsAndDeadline` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_SweepTombstonesADeadSnapshotAttempt` (`core/frontend/chunkstore/catalog_held_create_test.go`); `TestCatalog_ForkAfterTheMarkRefuses` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` models the snapshot as a name record plus an attempt path; no fork-from-unpublished property | ACTIVE | +| `INV-FORK-FROM-SEALED-001` | A fork reads only a published, active snapshot: a name with no published attempt or an aborted one is `snapshot_not_found`, a deleting one is `snapshot_deleting`, and every attempt of a fork, a retry included, reads the parent again. | M6 snapshot: published → fork | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `resolveSnap` | `TestFork_RefusalsAndDeadline` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_SweepTombstonesADeadSnapshotAttempt` (`core/frontend/chunkstore/catalog_held_create_test.go`); `TestCatalog_ForkAfterTheMarkRefuses` (`core/frontend/chunkstore/retention_review_test.go`); `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ChunkLifecycleFixed` models the snapshot as a name record plus an attempt path; no fork-from-unpublished property | ACTIVE | +| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` | ACTIVE | | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | +| `INV-VERIFY-READONLY-001` | Verify writes nothing to the filer or the blob store at any depth: no intent, mark, tombstone, binding or needle. | M6 (reader; no transition) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_ReadOnlyAtEveryDepth` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-RECHECK-001` | No finding is reported for a chunk or segment that no root of the final view names: the HEAD the closing read returned (none if it found none or could not decode it), then the selected snapshots still published. | M6 (reader beside GC mark) | `core/frontend/chunkstore/verify.go` `round`, `readHead`, `reconcile` | `TestVerify_SupersededDuringPass`, `TestVerify_SnapshotDeletedDuringPass`, `TestVerify_SharedChunkReportedUnderStillNamingRoot`, `TestVerify_SnapshotDocumentNamingAnotherSnapshot`, `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_ClosingReadWithoutUsableHeadIsIncomplete`, `TestVerify_DroppedReferenceProblemIsCounted` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-ONE-READ-001` | Verify checks each distinct chunk and reads each segment key at most once per pass: a settled object is never checked again, however often or under whatever reference a root names it again. | M6 (reader) | `core/frontend/chunkstore/verify.go` `discover`, `settle`, `segment` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_DedupSharedChunkReadOnce`, `TestVerify_HeadRefreshRewalksChangedSegments`, `TestVerify_SegmentIsOneObjectPerKey` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-NAMED-HAVE-OUTCOME-001` | In a complete pass every chunk the final view names has a settled outcome: the final view is the closing read itself, one that names no chunk the pass had not seen, with no read after it. | M6 (reader) | `core/frontend/chunkstore/verify.go` `run`, `round` | `TestVerify_PublishDuringClosingReadIsChecked`, `TestVerify_QuietClosingReadIsTheFinalView`, `TestVerify_SchedulesGiveTheSameFindings` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-REPORT-ONCE-001` | A complete pass yields at most one finding per chunk or segment key and class, computed only at Reconcile from the outcomes and the final view. | M6 (reader) | `core/frontend/chunkstore/verify.go` `reconcile`, `reconcileSegment` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_TwoWrongReferencesAreOneFinding`, `TestVerify_SameKeyWithAnotherHashIsAFinding`, `TestVerify_SegmentIsOneObjectPerKey` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-ORDER-FREE-001` | Findings and counters are a function of the outcomes, the references seen and the final view, not of the order of reads. | M6 (reader) | `core/frontend/chunkstore/verify.go` `judgeChunk`, `judgeSegment`, `reconcile` | `TestVerify_SegmentFindingsDoNotDependOnOrder`, `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_DroppedReferenceProblemIsCounted` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-NO-FALSE-CLEAN-001` | In a complete pass, a chunk the final view names that was bad when checked, or whose key HEAD dropped earlier in the pass and names again, has a finding. | M6 (reader) | `core/frontend/chunkstore/verify.go` `refresh`, `reconcile` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_PublishDuringClosingReadIsChecked` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-CLOSE-BOUND-001` | A pass completes only on a closing read that returns a decodable HEAD naming no chunk it had not seen, within `ClosingRounds` such reads (default 3); otherwise it is incomplete, with its reason, never clean. | M6 (reader) | `core/frontend/chunkstore/verify.go` `run`, `readHead`, `Catalog.Verify` | `TestVerify_ClosingRoundsExhaustedIsIncomplete`, `TestVerify_ClosingReadWithoutUsableHeadIsIncomplete` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-NOTFOUND-001` | Verify reports `NEEDLE_MISSING` only when the blob store answers that the needle does not exist (for SeaweedFS, every location of a fresh volume lookup answers 404); any other read failure is retried and then reported as `READ_ERROR`, which means not verified. | M6 (reader) | `core/frontend/chunkstore/verify.go` `Catalog.Verify`; `core/frontend/chunkstore/swfs.go` `Get` (`ErrBlobNotFound`) | `TestVerify_PersistentReadErrorIsNotAMissingNeedle`, `TestVerify_TransientReadIsRetried`, `TestSWFS_GetNotFoundIsErrBlobNotFound`, `TestSWFS_GetStaleCachedLocationLooksUpAgain`, `TestVerify_MovedVolumeIsNotAMissingNeedle` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-CANCEL-001` | A failed dispatch of chunk reads (a filer error, or the caller's context ending) cancels the reads in progress before joining them, and Verify returns the originating error. | M6 (reader) | `core/frontend/chunkstore/verify.go` `checkData` | `TestVerify_FailedRefreshCancelsReadInProgress`, `TestVerify_CancelDuringReadJoinsReaders` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-RESTORE-INDEPENDENT-001` | `RESTORE-INDEPENDENT` is written once, only for a restore volume with a live HEAD whose resolved image holds no ref owned by another volume; a restore without a live HEAD (absent or aborted) never attaches and is never marked. | M6 snapshot: restore → independent | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestRestore_MarkIndependentOnlyWithoutQualifiedRefs`, `TestRestore_WithoutLiveHeadNeverAttaches`, `TestRestore_SourceGoneIsNormal` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent`, `NoForeignList` | ACTIVE | +| `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`nc_red_SnapDuringRestore`) | ACTIVE | +| `INV-RESTORE-PARENT-HOLD-001` | Retired: retention no longer keeps a snapshot because of a fork or restore (`INV-SNAP-DELETE-ANY-ORDER-001`). | — | — | — | — | ARCHIVED | +| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `HydrateAllAt`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld`, `TestHydrateAll_PacedByByteRate` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | +| `INV-RESTORE-OWN-BATCH-001` | A batch cut re-uploads at most N local chunks whose HEAD keys name another volume under new own keys, even when their bytes equal HEAD's, in one ordinary cut (one intent, one HEAD CAS); it never fetches an absent chunk. | M6.Restore.Owning>Owning | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`, `TestOwnBatch_SkipsChunksNotLocal`, `TestOwnBatch_CarriesGuestWrites` (`core/storage/chunk_own_test.go`) | `RestoreIndependence` `NoGap` | ACTIVE | +| `INV-RESTORE-DRIVER-001` | The restore driver decides only from the target's VOLUME, HEAD and marker (never the source), writes the marker only after a batch leaves no foreign ref, and a rerun resumes from the target's remote state. | M6.Restore (all transitions) | `core/host/volume/chunk_restore.go` `runRestore`, `chunkControl.Restore` | `TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly`, `TestRestoreDriver_ResumesAfterAFailedBatch`, `TestRestoreDriver_RefusesAVolumeNotMadeByRestore` (`core/host/volume/chunk_restore_test.go`) | `RestoreIndependence` `Independent`, `StateRemote` | ACTIVE | +| `INV-CAT-INTENT-DROP-BOUNDED-001` | Dropping an operation's intent outlives the caller's cancellation (cleanup after a refused or cancelled request) but is bounded by `dropIntentTimeout`; a failed or timed-out delete leaves the intent, which only over-protects. | M6 intent: Live → Removed | `core/frontend/chunkstore/catalog.go` `dropIntent` | `TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled` (`core/frontend/chunkstore/restore_test.go`) | — | ACTIVE | +| `INV-SHARE-ACTIVATION-001` | With a `ShareGuard` installed, a snapshot or fork activates (snapshot entry, child HEAD) only after `Finish` accepts the share; a refused `Begin` or `Finish` aborts before activation and drops the new intent. With no guard, nothing is called or checked. | M6 snapshot: Pending → Published; fork: child HEAD create | `core/frontend/chunkstore/share_guard.go` `beginShare`, `finishShare`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `Fork`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot` | `TestShareGuard_SnapshotFinishesBeforeActivation`, `TestShareGuard_RefusedFinishAbortsTheSnapshot`, `TestShareGuard_StaleHeadIsRefused`, `TestShareGuard_CallerToken`, `TestShareGuard_Fork`, `TestShareGuard_BeginRefused` (`core/frontend/chunkstore/share_guard_test.go`); `TestChunkControl_SnapshotBeginsShareBeforeTheCut`, `TestChunkControl_SnapshotBeginRefusedCutsNothing` (`core/host/volume/chunk_control_order_test.go`) | — | ACTIVE | +| `INV-PUBLISH-SETTLED-001` | With `OnPublishSettled` set, each confirmed publication (a new HEAD generation) is delivered once, in publication order, one at a time, outside the capture and state locks. After Close begins, no report is dequeued. | M5 CAS → Settled; M6 HEAD: published | `core/storage/chunk_publish_settled.go` `noteSettled`, `unlockCap`, `runPublishSettled`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestChunkPublishSettled_ReportsEachPublication`, `TestChunkPublishSettled_ReportsALatePublication`, `TestChunkPublishSettled_ClosedAndUnset`, `TestChunkPublishSettled_OverlappingPublishersStayOrdered`, `TestChunkPublishSettled_CloseDropsUnstartedReports`, `TestChunkPublishSettled_HookThatPublishes`, `TestChunkPublishSettled_PeriodicCutReports` (`core/storage/chunk_publish_settled_test.go`); `TestWALStoreChunk_PublishSettledHook` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | Notes: -- `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace. -- `INV-GC-DELETE-EXACT-FID-001`: the tombstone written before the delete and the retry after a failed delete are enforced by reading; no test fails a GC delete. The cookie check itself is done by the SeaweedFS volume server, not by this repository. -- `INV-GC-GRACE-RESTART-001`: the restart on a rooted mark is enforced by reading; no test re-roots a candidate between marks. A deleted fork volume's keys get only the ordinary two-mark grace from their first unrooted mark, with no deleting-time root and no dedicated test. +- `INV-GC-DELETE-EXACT-FID-001`: what happens after a rejected or failed delete is `INV-GC-DELETE-PROGRESS-001`. The tombstone-before-delete order is asserted only through a rejected delete; on a successful delete it is enforced by reading. The cookie check itself is done by the SeaweedFS volume server, not by this repository. +- `INV-GC-GRACE-RESTART-001`: "past the grace" means past the grace plus the clock-skew bound of `INV-GC-CLOCK-SKEW-001`. The restart on a rooted mark is enforced by reading; no test re-roots a candidate between marks. A deleted fork volume's keys get only the ordinary two-mark grace from their first unrooted mark, with no deleting-time root and no dedicated test. - `INV-SNAP-SEAL-DURABLE-001`: whether a confirmed filer write has reached disk (filer fsync) is a deployment setting of the SeaweedFS filer, not checked by the code. - `INV-FORK-FROM-SEALED-001`: the case of a name whose attempt is still in flight (name record present, attempt entry absent) is enforced by reading; no test forks during a held snapshot create. +- `INV-SNAP-DELETE-ANY-ORDER-001`: a fork takes its deadline start before it reads the parent, and every attempt (a retry included) reads it again, so a parent deleted before the read refuses. GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound (`NewCollector`). An unknown publish keeps the fork intent, which roots the keys until the target is resolved. +- Restore quantities: batch size N = `DefaultRestoreBatchChunks` (64 chunks per batch cut) and the walker pace = `DefaultRestoreBytesPerSecond` (64 MiB/s, plus the host limiter's BackgroundFill class), both in `core/host/volume/chunk_restore.go`. They move to the quantity table when it exists. +- `INV-SHARE-ACTIVATION-001`: the owner's seal calls `Begin` before the cut that produces the sealed HEAD, so a refused `Begin` cuts nothing. +- `INV-PUBLISH-SETTLED-001`: a publication is a cut, a detach, or an earlier unresolved CAS found applied; a no-op cut reports nothing, and with no hook nothing is queued. One registered drainer delivers; a report already dequeued when Close begins may still reach the hook, and Close waits for it. +- `ChunkRemote.ReclaimKey` is the Collector's per-key step (`reclaimBinding`) exported, not a new admission: `INV-GC-REACHABLE-001` (reachability and the two-mark grace) stays the Collector's, and a `ReclaimKey` caller must itself know nothing references the key. The step keeps `INV-CHUNK-WRITE-ONCE-001`: the binding is tombstoned, its exact fid deleted, and the binding kept for ever, never rebound; owner-qualified keys are refused. ### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing @@ -612,6 +696,14 @@ How a fix or a feature is calibrated against this model: 5. **Rows are stable.** IDs are never reused or renumbered. A retired row stays with status `ARCHIVED` and a reason. A narrowed statement says what was dropped in a note. 6. **STUB rows block claims.** A release note or a design document must not claim a property backed only by a `STUB` row. Turning a `STUB` into `ACTIVE` is the test plus the status change. +### C.W Wait sites (SYSTEM-MATH Part C) + +One row per wait in the data and control paths. Guest-visible rows on one path must sum to at most 5 s. + +| Site | Waits for | Bound | Owner that ends it | On expiry | Lock held while waiting | Guest-visible | +|---|---|---|---|---|---|---| +| `core/storage/chunk_publish_settled.go` `runPublishSettled` (from `unlockCap`, on the cut or detach caller's goroutine) | the `OnPublishSettled` hook to return | the hook's duration: the hook must return without blocking and without remote calls, enqueueing its work to its own worker | the hook implementer | none: a stalled hook stalls its caller, and later reports queue without a bound (a nil hook queues nothing) | none (`capMu` and `stMu` released) | yes on detach (the detach caller delivers before returning) | + Format v3 row 4 remains dark. Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The later W/BASE/fence owner must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. ### Dark v3 offline reader (row12a) @@ -624,3 +716,18 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a - `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for dark mapped v3): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu. - The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission. - Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Both installed local presence and the provider durable attach point are required before retirement. The provider removes its fresh marker and fsyncs its directory under the store installMu-exclusive commit, then records per-open owner readiness; the callback never re-enters the store. Layer attach alone never allows retirement. Later completed transitions require owner readiness plus saved full presence before allowing; the next ordinary publication still checks existing retirement coverage. The provider keeps the constructed layer private as chunkPending until this commit succeeds; explicit publication cannot resolve it and the scheduler starts only after commit. Failed commits retain the private layer for retry without reattaching. Held pre-marker controls require Capture/Cut/MakeRemoteDurable to return ErrNotChunkVolume with no new remote writes, intents or HEAD changes, then crash/reopen exact local bytes. Actual subprocess controls crash after presence but before marker removal (both pre-existing installed BASE and attached completion), retaining the installed discriminator and recovering exact local data. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam. + + +## Part D. Wait ownership + +| Wait | Machine / invariant | Bound | Release and cancellation | Locks / remote work | +|---|---|---|---|---| +| Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. | + +Frozen estimate reporting: a tail above the existing 60 s estimator ceiling reports the same 60 s rejection sentinel used by admission. It is known but saturated, not a complete fixed-plus-tail duration; quiesce slack is zero. Consumers must not use it as a completion forecast. Drain refusals retain the observation before their reason changes; this reporting does not reclassify refusal causes. + +## Part E. Quantities + +| Quantity | Unit | Cap | Enforced at (producer) | Drained | Outcome at the cap | +|---|---|---|---|---|---| +| COW side-file spill per cut | bytes | min(`COWSpillLimit` (default 1 GiB, or the host limit's COW bytes), free space on `--durable-root` / 2 - 1 GiB), at least 0; the free space is read once per cut and that cap bounds both staging and the copy window; off Linux, the configured cap. Shown per cut in the layer stats (`COWSpillCap`, `COWSpillCapReason`: `no_room_to_cut` when the free space is within the reserve, `free_space_unreadable` when the read fails) | the saver: `core/storage/chunk_cut_cow.go` `readCutSpill`, the save's cap check | at the cut's end (the side file is removed on publish, abort or close) | that cut aborts (retryable), counted as `cow_capacity`, or as `no_room_to_cut` / `free_space_unreadable` when the free space made the cap 0; the guest write completes and nothing partial is published | diff --git a/seaweed-block/docs/spec/ForkDelete.tla b/seaweed-block/docs/spec/ForkDelete.tla new file mode 100644 index 0000000000..f3014fe1c3 --- /dev/null +++ b/seaweed-block/docs/spec/ForkDelete.tla @@ -0,0 +1,305 @@ +---------------------------- MODULE ForkDelete ---------------------------- +(***************************************************************************) +(* Fork / restore versus snapshot delete with NO lock between them. *) +(* *) +(* Volume V has one published snapshot S naming the chunks 1..NC. A fork *) +(* creates a new volume T whose HEAD will name S's chunks. A delete of S *) +(* never waits for, and is never refused because of, a fork. Safety comes *) +(* from two time rules only: *) +(* (F) the fork reads S at its local time readAt and publishes T's HEAD *) +(* only if its local clock is still < readAt + D (checked right *) +(* before publishing: one atomic step, or, with PublishAtomic=FALSE, *) +(* a check step and a later publish step at most P ticks apart); *) +(* (G) the delete is stamped delAt on the catalog's local clock; GC keeps *) +(* S's chunks rooted while ITS local clock is < delAt + G. *) +(* GC is one atomic step deleting every chunk no root names. Roots: V's *) +(* HEAD (V may overwrite chunks), S while not deleted, S's deleted record *) +(* until the grace has passed, T's HEAD once published. *) +(* *) +(* Time: real time `now` ticks by 1. Actor a reads now + bias[a]; biases *) +(* are fixed at start in -E..E with pairwise difference <= E. Clocks do *) +(* not step and run at the same rate. *) +(* *) +(* Mutant switches are CONSTANTS; the design value is noted on each. *) +(***************************************************************************) +EXTENDS Integers, FiniteSets, TLC + +CONSTANTS + NC, \* chunks 1..NC, all named by S (and by V's HEAD at start) + D, \* operation deadline of the fork (on the fork's clock) + G, \* GC grace after a delete (delAt on the catalog clock, compared on the GC clock) + E, \* pairwise clock skew bound + P, \* max ticks between the deadline check and the publish (PublishAtomic=FALSE only) + MaxNow, \* real-time bound + MaxAttempts, \* fork attempts (1 = no retry) + MaxReads, \* reads of T after its publish (witness only) + VCanOverwrite, \* [TRUE] V may stop naming chunks (nondeterministic action) + \* ---- design switches (design value in brackets) ---- + PublishChecksDeadline, \* [TRUE] publish only if local clock < readAt + D + DeletedRecordRooted, \* [TRUE] deleted S roots its chunks until the grace has passed + PublishAtomic, \* [TRUE] check + publish in one step; FALSE: two steps <= P ticks apart + RetryAfterDelete \* [TRUE] a retry re-reads S (fails if deleted); FALSE: reuses old chunk set + +ASSUME NC \in Nat /\ D \in Nat /\ G \in Nat /\ E \in Nat /\ P \in Nat /\ MaxNow \in Nat + +Chunks == 1..NC +SChunks == Chunks +Actors == {"F", "C", "GC"} \* fork process, catalog (stamps delete), garbage collector +NoTime == -1000 +FStates == {"idle", "read", "created", "checked", "published", "failed", "crashed", "notfound"} + +VARIABLES + now, \* real time + bias, \* actor -> clock bias (fixed after Init) + vNames, \* chunks V's HEAD still names + sDeleted, \* S has been deleted + delAt, \* catalog-local time stamped on the delete (NoTime before) + exists, \* chunk -> still stored + fst, \* fork state + attempts, \* fork attempts started + readAt, \* fork-local time of the current attempt's read + readSet, \* chunk set held by the fork (from the last real read of S) + haveRead, \* some attempt has read S successfully + checkAt, \* real time of the deadline check (two-step publish only) + tPub, \* T's HEAD is published + tHead, \* chunks named by T's HEAD + nReads, \* reads of T done + \* ---- history (witnesses / trace readability) ---- + pubAfterDel, \* T's HEAD was published after S was deleted + lateReadOK, \* T read all its chunks after the grace passed, with V no longer naming them + deadlineLoss, \* a fork attempt failed cleanly on the deadline + retryNotFound, \* a retry got "snapshot not found" + lastAct \* name of the last action (for traces) + +forkVars == <> +tVars == <> +histVars == <> +vars == <> + +LC(a) == now + bias[a] \* local clock of actor a + +TypeOK == + /\ now \in 0..MaxNow + /\ bias \in [Actors -> -E..E] + /\ vNames \subseteq Chunks + /\ sDeleted \in BOOLEAN + /\ delAt \in Int + /\ exists \in [Chunks -> BOOLEAN] + /\ fst \in FStates + /\ attempts \in 0..MaxAttempts + /\ readAt \in Int + /\ readSet \subseteq Chunks + /\ haveRead \in BOOLEAN + /\ checkAt \in Int + /\ tPub \in BOOLEAN + /\ tHead \subseteq Chunks + /\ nReads \in 0..MaxReads + /\ pubAfterDel \in BOOLEAN + /\ lateReadOK \in BOOLEAN + /\ deadlineLoss \in BOOLEAN + /\ retryNotFound \in BOOLEAN + /\ lastAct \in STRING + +Init == + /\ now = 0 + /\ bias \in {b \in [Actors -> -E..E] : (\A x, y \in Actors : b[x] - b[y] <= E)} + /\ vNames = Chunks + /\ sDeleted = FALSE + /\ delAt = NoTime + /\ exists = [c \in Chunks |-> TRUE] + /\ fst = "idle" + /\ attempts = 0 + /\ readAt = NoTime + /\ readSet = {} + /\ haveRead = FALSE + /\ checkAt = NoTime + /\ tPub = FALSE + /\ tHead = {} + /\ nReads = 0 + /\ pubAfterDel = FALSE + /\ lateReadOK = FALSE + /\ deadlineLoss = FALSE + /\ retryNotFound = FALSE + /\ lastAct = "Init" + +(* ============================ time ============================ *) + +\* Real time advances. With a two-step publish, at most P ticks pass between check and publish. +Tick == + /\ now < MaxNow + /\ (PublishAtomic \/ fst # "checked" \/ now < checkAt + P) + /\ now' = now + 1 + /\ lastAct' = "Tick" + /\ UNCHANGED <> + +(* ============================ fork ============================ *) + +\* Start an attempt (first try, or retry after a clean failure or a crash). +ReadSnapshot == + /\ fst \in {"idle", "failed", "crashed"} + /\ attempts < MaxAttempts + /\ attempts' = attempts + 1 + /\ lastAct' = "ReadSnapshot" + /\ (IF ~RetryAfterDelete /\ haveRead + THEN \* mutant: reuse the chunk set of an earlier attempt, no re-read of S + /\ fst' = "read" + /\ readAt' = LC("F") + /\ UNCHANGED <> + ELSE (IF sDeleted + THEN /\ fst' = "notfound" \* "snapshot not found": T never gets a HEAD + /\ retryNotFound' = (retryNotFound \/ attempts > 0) + /\ UNCHANGED <> + ELSE /\ fst' = "read" + /\ readAt' = LC("F") + /\ readSet' = SChunks + /\ haveRead' = TRUE + /\ UNCHANGED retryNotFound)) + /\ UNCHANGED <> + +\* Create T's record (no HEAD yet, no effect on roots). +CreateTarget == + /\ fst = "read" + /\ fst' = "created" + /\ lastAct' = "CreateTarget" + /\ UNCHANGED <> + +DeadlineOK == (~PublishChecksDeadline) \/ (LC("F") < readAt + D) + +\* Publish T's HEAD = the chunk set held by the fork. +DoPublish == + /\ fst' = "published" + /\ tPub' = TRUE + /\ tHead' = readSet + /\ pubAfterDel' = (pubAfterDel \/ sDeleted) + +\* (F) atomic: deadline check and publish in one step. +PublishAtomicStep == + /\ PublishAtomic + /\ fst = "created" + /\ (IF DeadlineOK + THEN /\ DoPublish + /\ lastAct' = "Publish" + /\ UNCHANGED deadlineLoss + ELSE /\ fst' = "failed" + /\ deadlineLoss' = TRUE + /\ lastAct' = "PublishDeadlineFail" + /\ UNCHANGED <>) + /\ UNCHANGED <> + +\* (F) two-step, step 1: the deadline check. +CheckDeadline == + /\ ~PublishAtomic + /\ fst = "created" + /\ (IF DeadlineOK + THEN /\ fst' = "checked" + /\ checkAt' = now + /\ lastAct' = "CheckDeadlineOK" + /\ UNCHANGED deadlineLoss + ELSE /\ fst' = "failed" + /\ deadlineLoss' = TRUE + /\ lastAct' = "CheckDeadlineFail" + /\ UNCHANGED checkAt) + /\ UNCHANGED <> + +\* (F) two-step, step 2: the publish, no new check (Tick bounds it to <= P ticks after the check). +PublishAfterCheck == + /\ fst = "checked" + /\ DoPublish + /\ lastAct' = "PublishAfterCheck" + /\ UNCHANGED <> + +\* The fork crashes in the middle of an attempt; it may later retry or never continue. +Crash == + /\ fst \in {"read", "created", "checked"} + /\ fst' = "crashed" + /\ lastAct' = "Crash" + /\ UNCHANGED <> + +(* ========================== catalog / V ========================== *) + +\* (G) delete S at any time: stamped on the catalog clock; S stops being a live root. +DeleteS == + /\ ~sDeleted + /\ sDeleted' = TRUE + /\ delAt' = LC("C") + /\ lastAct' = "DeleteS" + /\ UNCHANGED <> + +\* V's HEAD stops naming chunk c (V overwrote it). +VOverwrite(c) == + /\ VCanOverwrite + /\ c \in vNames + /\ vNames' = vNames \ {c} + /\ lastAct' = "VOverwrite" + /\ UNCHANGED <> + +(* ============================== GC ============================== *) + +Rooted(c) == + \/ c \in vNames + \/ ~sDeleted + \/ (DeletedRecordRooted /\ LC("GC") < delAt + G) + \/ (tPub /\ c \in tHead) + +\* One step: delete every stored chunk no root names. +GC == + /\ (\E c \in Chunks : exists[c] /\ ~Rooted(c)) + /\ exists' = [c \in Chunks |-> exists[c] /\ Rooted(c)] + /\ lastAct' = "GC" + /\ UNCHANGED <> + +(* ============================ readers of T ============================ *) + +TRead == + /\ tPub + /\ nReads < MaxReads + /\ nReads' = nReads + 1 + /\ lateReadOK' = (lateReadOK \/ + (/\ sDeleted + /\ vNames \cap tHead = {} + /\ LC("GC") >= delAt + G + /\ (\A c \in tHead : exists[c]))) + /\ lastAct' = "TRead" + /\ UNCHANGED <> + +Next == + \/ Tick + \/ ReadSnapshot + \/ CreateTarget + \/ PublishAtomicStep + \/ CheckDeadline + \/ PublishAfterCheck + \/ Crash + \/ DeleteS + \/ (\E c \in Chunks : VOverwrite(c)) + \/ GC + \/ TRead + +Spec == Init /\ [][Next]_vars + +(* ============================ properties ============================ *) + +\* Whenever T's HEAD is published, every chunk it names exists (checked in every state). +NoGap == tPub => (\A c \in tHead : exists[c]) + +(* Witnesses: each is expected VIOLATED (= the behaviour is reachable). *) +\* Benefit: a fork that read S before the delete publishes after the delete and T reads fine +\* after the grace has passed (only T's HEAD roots the chunks then). +WitNoBenefit == ~(pubAfterDel /\ lateReadOK) +\* A fork loses cleanly because the deadline passed. +WitNoDeadlineLoss == ~deadlineLoss +\* A retry gets "snapshot not found". +WitNoRetryNotFound == ~retryNotFound +\* GC deletes some chunk at all (shows GC is not vacuous in a safe configuration). +WitNoGCDelete == \A c \in Chunks : exists[c] +============================================================================= diff --git a/seaweed-block/docs/spec/FrozenDetachBudget.tla b/seaweed-block/docs/spec/FrozenDetachBudget.tla index e8f83cb8ee..e39c3eeffb 100644 --- a/seaweed-block/docs/spec/FrozenDetachBudget.tla +++ b/seaweed-block/docs/spec/FrozenDetachBudget.tla @@ -11,13 +11,15 @@ VARIABLES phase, elapsed, estimate, known, force, authority, admitted, vars == <> Init == /\ phase = "forecast" /\ elapsed \in {0,30,60} - /\ estimate \in {5,30,60} /\ known \in BOOLEAN + /\ estimate \in {0,5,30,60} /\ known \in BOOLEAN /\ force \in BOOLEAN /\ authority \in BOOLEAN /\ admitted = FALSE /\ uploaded = FALSE /\ published = FALSE /\ overBudget = FALSE /\ atElapsed = 0 /\ atEstimate = 0 /\ atKnown = FALSE AuthorityOK == authority \/ OmitAuthority -Fits == known /\ estimate > 0 /\ estimate + (IF OmitElapsed THEN 0 ELSE elapsed) <= Limit +FrozenEstimateKnown == known /\ estimate > 0 +MaxRefreezeQuiesce == IF FrozenEstimateKnown /\ estimate < Limit THEN Limit-estimate ELSE 0 +Fits == FrozenEstimateKnown /\ estimate + (IF OmitElapsed THEN 0 ELSE elapsed) <= Limit Eligible == AuthorityOK /\ (force \/ Fits) Forecast == /\ phase = "forecast" /\ Eligible /\ phase' = "stage" /\ UNCHANGED < admitted BudgetAtAdmission == admitted /\ ~force => atKnown /\ atEstimate > 0 /\ atElapsed + atEstimate <= Limit OverrideVisible == admitted /\ force => overBudget AuthorityAtPublication == published => authority +ReportSlackSound == MaxRefreezeQuiesce >= 0 /\ + (MaxRefreezeQuiesce > 0 => known /\ estimate > 0 /\ MaxRefreezeQuiesce + estimate = Limit) /\ + (~FrozenEstimateKnown => MaxRefreezeQuiesce = 0) ============================================================================= diff --git a/seaweed-block/docs/spec/GCClockSkew.tla b/seaweed-block/docs/spec/GCClockSkew.tla new file mode 100644 index 0000000000..2636df0b73 --- /dev/null +++ b/seaweed-block/docs/spec/GCClockSkew.tla @@ -0,0 +1,24 @@ +------------------------- MODULE GCClockSkew ------------------------- +EXTENDS Integers, TLC +CONSTANTS G, S, Q, MaxT, IgnoreSkew, IgnoreResolution, AbortFuture +VARIABLES t, bias, rounded, stamp, phase, removed, removedOld +vars == <> +Born == 10 +Init == /\ t = Born /\ bias \in {-S,0,S} /\ rounded \in {0,Q} + /\ stamp = Born+bias-rounded /\ phase = "check" + /\ removed = FALSE /\ removedOld = FALSE +Allowance == (IF IgnoreSkew THEN 0 ELSE S)+(IF IgnoreResolution THEN 0 ELSE rounded) +Check == /\ phase = "check" + /\ removed' = (removed \/ (t-stamp > G+Allowance)) + /\ removedOld' = (removedOld \/ ~(AbortFuture /\ stamp > t)) + /\ phase' = "done" + /\ UNCHANGED <> +Tick == /\ phase = "done" /\ t < MaxT /\ t' = t+1 /\ phase' = "check" + /\ UNCHANGED <> +Next == Check \/ Tick +Spec == Init /\ [][Next]_vars +NoEarlyExpiry == removed => t-Born > G +FutureProtects == stamp > t => ~removed +IndependentProgress == phase = "done" => removedOld +EventuallyEligibleAtBound == (phase = "done" /\ t = MaxT) => removed +============================================================================= diff --git a/seaweed-block/docs/spec/GCClockSkew_abort_future.cfg b/seaweed-block/docs/spec/GCClockSkew_abort_future.cfg new file mode 100644 index 0000000000..f310ac305f --- /dev/null +++ b/seaweed-block/docs/spec/GCClockSkew_abort_future.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CONSTANTS G=3 S=1 Q=1 MaxT=17 + IgnoreSkew = FALSE + IgnoreResolution = FALSE + AbortFuture = TRUE +INVARIANTS NoEarlyExpiry FutureProtects IndependentProgress EventuallyEligibleAtBound +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/GCClockSkew_no_resolution.cfg b/seaweed-block/docs/spec/GCClockSkew_no_resolution.cfg new file mode 100644 index 0000000000..e342a736aa --- /dev/null +++ b/seaweed-block/docs/spec/GCClockSkew_no_resolution.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CONSTANTS G=3 S=1 Q=1 MaxT=17 + IgnoreSkew = FALSE + IgnoreResolution = TRUE + AbortFuture = FALSE +INVARIANTS NoEarlyExpiry FutureProtects IndependentProgress EventuallyEligibleAtBound +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/GCClockSkew_no_skew.cfg b/seaweed-block/docs/spec/GCClockSkew_no_skew.cfg new file mode 100644 index 0000000000..a96481126d --- /dev/null +++ b/seaweed-block/docs/spec/GCClockSkew_no_skew.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CONSTANTS G=3 S=1 Q=1 MaxT=17 + IgnoreSkew = TRUE + IgnoreResolution = FALSE + AbortFuture = FALSE +INVARIANTS NoEarlyExpiry FutureProtects IndependentProgress EventuallyEligibleAtBound +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/GCClockSkew_safe.cfg b/seaweed-block/docs/spec/GCClockSkew_safe.cfg new file mode 100644 index 0000000000..ffdf4e61cc --- /dev/null +++ b/seaweed-block/docs/spec/GCClockSkew_safe.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CONSTANTS G=3 S=1 Q=1 MaxT=17 + IgnoreSkew = FALSE + IgnoreResolution = FALSE + AbortFuture = FALSE +INVARIANTS NoEarlyExpiry FutureProtects IndependentProgress EventuallyEligibleAtBound +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/GCDeleteProgress.tla b/seaweed-block/docs/spec/GCDeleteProgress.tla new file mode 100644 index 0000000000..f8fd2f257d --- /dev/null +++ b/seaweed-block/docs/spec/GCDeleteProgress.tla @@ -0,0 +1,24 @@ +------------------------ MODULE GCDeleteProgress ------------------------ +EXTENDS Integers, FiniteSets +CONSTANT StopOnReject +VARIABLES next, deleted, rejected, complete +vars == <> +Bad == 1 +Keys == 1..3 +Init == /\ next = 1 /\ deleted = {} /\ rejected = {} /\ complete = FALSE +Step == /\ next \in Keys + /\ IF next = Bad THEN + /\ rejected' = rejected \cup {next} + /\ deleted' = deleted + /\ next' = IF StopOnReject THEN 4 ELSE next+1 + /\ complete' = StopOnReject + ELSE + /\ deleted' = deleted \cup {next} + /\ rejected' = rejected + /\ next' = next+1 + /\ complete' = (next = 3) +Spec == Init /\ [][Step]_vars +NoFalseSuccess == Bad \notin deleted +FailureVisible == complete => Bad \in rejected +LaterProgress == complete => deleted = Keys \ {Bad} +============================================================================= diff --git a/seaweed-block/docs/spec/GCDeleteProgress_safe.cfg b/seaweed-block/docs/spec/GCDeleteProgress_safe.cfg new file mode 100644 index 0000000000..12d9560fec --- /dev/null +++ b/seaweed-block/docs/spec/GCDeleteProgress_safe.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANT StopOnReject = FALSE +INVARIANTS NoFalseSuccess FailureVisible LaterProgress +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/GCDeleteProgress_stop.cfg b/seaweed-block/docs/spec/GCDeleteProgress_stop.cfg new file mode 100644 index 0000000000..524b8c2f1f --- /dev/null +++ b/seaweed-block/docs/spec/GCDeleteProgress_stop.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANT StopOnReject = TRUE +INVARIANTS NoFalseSuccess FailureVisible LaterProgress +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/MaintenanceOwner.tla b/seaweed-block/docs/spec/MaintenanceOwner.tla new file mode 100644 index 0000000000..b389264468 --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner.tla @@ -0,0 +1,37 @@ +------------------------- MODULE MaintenanceOwner ------------------------- +EXTENDS Naturals, TLC +CONSTANT AllowOverlap, ReleaseBeforeJoin, AllowStaleRearm +VARIABLES state, due, workers, released, owner, current, arms, closing +vars == <> +Init == /\ state = "pending" /\ due = FALSE /\ workers = 0 /\ released = FALSE + /\ owner = 1 /\ current = 1 /\ arms = 0 /\ closing = FALSE +Attach == /\ state = "pending" /\ state' = "armed" /\ arms' = arms+1 + /\ UNCHANGED <> +Tick == /\ state = "armed" /\ due' = TRUE + /\ UNCHANGED <> +Start == /\ state = "armed" /\ due /\ (workers = 0 \/ AllowOverlap) + /\ workers < 2 /\ workers' = workers+1 /\ due' = FALSE + /\ UNCHANGED <> +Finish == /\ workers > 0 /\ workers' = workers-1 + /\ UNCHANGED <> +Stop == /\ state = "armed" /\ state' = "draining" /\ due' = FALSE + /\ closing' \in BOOLEAN /\ UNCHANGED <> +Join == /\ state = "draining" /\ (workers = 0 \/ ReleaseBeforeJoin) + /\ state' = IF closing THEN "closed" ELSE "idle" + /\ released' = TRUE /\ UNCHANGED <> +Rearm == /\ state = "idle" /\ arms < 3 /\ (owner = current \/ AllowStaleRearm) + /\ state' = "armed" /\ released' = FALSE /\ arms' = arms+1 + /\ UNCHANGED <> +ReplaceHandle == /\ state = "idle" /\ workers = 0 /\ current = 1 + /\ current' = 2 + /\ UNCHANGED <> +AttachCurrent == /\ state = "idle" /\ workers = 0 /\ owner # current /\ arms < 3 + /\ owner' = current /\ state' = "armed" /\ released' = FALSE + /\ arms' = arms+1 /\ UNCHANGED <> +Next == Attach \/ Tick \/ Start \/ Finish \/ Stop \/ Join \/ Rearm \/ ReplaceHandle \/ AttachCurrent +Spec == Init /\ [][Next]_vars +OneOwner == workers <= 1 +JoinedBeforeRelease == released => workers = 0 +NoCatchupQueue == due \in BOOLEAN +CurrentHandleAtAdmission == workers > 0 => owner = current +============================================================================= diff --git a/seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg b/seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg new file mode 100644 index 0000000000..a9eb05e357 --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS AllowOverlap = FALSE + ReleaseBeforeJoin = TRUE + AllowStaleRearm = FALSE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg b/seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg new file mode 100644 index 0000000000..6984971b3a --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS AllowOverlap = TRUE + ReleaseBeforeJoin = FALSE + AllowStaleRearm = FALSE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/MaintenanceOwner_safe.cfg b/seaweed-block/docs/spec/MaintenanceOwner_safe.cfg new file mode 100644 index 0000000000..deb0ac7c68 --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner_safe.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS AllowOverlap = FALSE + ReleaseBeforeJoin = FALSE + AllowStaleRearm = FALSE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/MaintenanceOwner_stale_rearm.cfg b/seaweed-block/docs/spec/MaintenanceOwner_stale_rearm.cfg new file mode 100644 index 0000000000..46925d6f86 --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner_stale_rearm.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS AllowOverlap = FALSE + ReleaseBeforeJoin = FALSE + AllowStaleRearm = TRUE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 0fb0a0bd28..2dee559ccc 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -98,6 +98,8 @@ Two kinds of config are **expected to violate**: | `ReplicationFailover.tla` | `cfg/S6_*` | design-level | | `RetentionGCTiming.tla` | `cfg/S9_*` | | | `RetentionGCMulti.tla` | `cfg/S9b_*` | | +| `ForkDelete.tla` | `cfg/ForkDelete_*` | snapshot delete in any order with forks | +| `RestoreIndependence.tla` | `cfg/RestoreIndependence_*` | independent restore | Each `.cfg` names its spec on its first line. @@ -116,6 +118,8 @@ length of TLC's shortest counterexample. | S5 | `ControlPlane` | Blockmaster authority store: one volume record `{epoch, holder, move journal}`, two retried move requests, durable Puts that succeed, fail, or land with the reply lost, and restarts. | `UniqueEpoch` (issued epochs strictly increase), `Idempotent` (one epoch per request id), `JournalComplete` | `S5_code` pass (298). **RED:** `S5_red_noUncertain` UniqueEpoch violated (5-step: a lost-reply Put, then a reservation from stale memory puts the old assignment back). `S5_red_noReserve` passes (the reservation step is not needed for these invariants). | `core/authority/authority.go:436` applyWithWorkspaceMove (uncertain refusal `:442-444`, Put `:564`, mark uncertain `:568`); `core/authority/workspace.go:309` prepareWorkspaceMoveLocked (expected line `:313`, resume a reserved entry `:324-333`, reserve max+1 `:344-355`), journal replay `:192-219`, persist and mark uncertain `:276-288` | | S6 | `ReplicationFailover` | RF=2: P ships to R, R acks what is durable, the client is acked when both are durable; promotion of R at a new epoch with an evidence gate; R refuses old-epoch shipping; cuts and snapshots cover only the replicated-durable frontier; an in-flight snapshot create from the old primary may still land after the failover. Design-level. | `AckedSurvive`, `HeadOnLineage`, `SnapOnLineage`, `NoStaleAck` | `S6_design` pass (52,897), `S6_design_big` (598,353). **RED:** `S6_red_localCut` HeadOnLineage; `S6_red_noFence` AckedSurvive. `S6_red_noEvidence` passes: with synchronous RF=2 acks the gate is redundant (it matters for quorum or async shipping, not modelled). | `core/transport/replica.go:362` replica rejects a stale-lineage ship entry; `core/replication/volume.go:680` RebaseShipLSN; takeover CAS as in S2 | | S9 | `RetentionGCTiming`, `RetentionGCMulti` | GC timing with an explicit clock: a copy operation with deadline D, marks of duration up to MD, deletion only after two marks at least Grace apart; then marks across two volumes with a fork and a snapshot delete. | `NoLiveDelete` | **Single op:** `S9_rule_G4` (G > D + MD) pass (10,798; `_big` 43,780); G = D passes (`S9_red_G2_noguard`, 11,953). **RED:** `S9_red_G1_noguard`, `S9_red_G1_D3` (G < D) NoLiveDelete violated. **Two volumes:** `S9b_G1_MD2`, `_G2_MD2`, `_G2_MD3`, `_G3_MD1` pass (5,743-9,079). | `core/frontend/chunkstore/gc.go:89` grace > operation deadline, `:280` mark-duration margin, `:306-318` two-mark rule, `:214-221` intent expiry; `catalog.go:896-905` intent deadline re-checked before publish; `gc_copy.go:143`, `:177` a deleting attempt stays a root until grace | +| S10 | `RestoreIndependence` | Independent restore: fork of a sealed snapshot, hydrate, bounded batch cuts (own fids uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref; GC, source delete, snapshot retention, and crashes with resume from remote facts at any point. `NoClaim` (the code): no claim; the fork window is safe by two time rules on one clock, ForkEnd only while now < readAt + D and a deleted snapshot rooted while now < delAt + G. The older claim variants stay as regression configurations. | `NoGap`, `Independent`, `NoForeignList`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)**, no-claim: `nc_safe` 405,198 distinct states; `nc_safe_b2` 504,097; `nc_safe_n4` 2,752,518; `nc_safe_G3D2` 379,500; boundary `nc_bnd_G1D1` 444,564 and `nc_bnd_G3D3` 360,615 safe, `nc_bnd_G0D1` and `nc_bnd_G2D3` violate NoGap: safe iff G >= D on one clock, which is `ForkDelete`'s G >= D + E + P with E = P = 0 (the production inequality is ForkDelete's). **RED** (each violated): `nc_red_CasBeforeUpload`, `nc_red_NoIntent`, `nc_red_GltD`, `nc_red_noDeadline`, `nc_red_notRooted`, `nc_red_resumeNoReread` NoGap; `nc_red_MarkerEarly`, `nc_red_MarkerBeforeCas`, `nc_red_SnapDuringRestore` Independent; `nc_red_ListForeign` NoForeignList; `nc_red_ResumeLocal` StateRemote. **Witnesses reached:** `nc_wit_DelInFork` (the source snapshot deleted inside the fork window and the restore completes), `nc_wit_FailNotFound`. Regression (claim frame): `safe` 1,599, `opt1_safe` 3,639, `oldframe` 1,599 safe; `oldframe_drop`, `red_DropClaimAtFork_gap` violate NoGap. Limits: no guest writes to the target while it takes ownership, GC acts immediately, one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAllAt`; `core/storage/chunk_own.go` `OwnBatch`; `core/host/volume/chunk_restore.go` `runRestore` | +| S11 | `ForkDelete` | Fork or restore against snapshot delete with no claim: the fork reads the parent, may crash and retry (a retry re-reads it), and publishes only before its read time + D, as one atomic step or check-then-publish with up to P ticks between; delete stamps its time; GC (one atomic step) keeps a deleted attempt rooted while its clock is below delete time + G. Three clocks with pairwise skew up to E. | `NoGap` (a published fork HEAD names only existing chunks) | **Exhaustive (TLC breadth-first, complete state graph, no error)**: all 11 safe cfgs, from `safe_D2E0G2` (18,672 distinct states) to `safe_na_P2_D1E2G5` (15,730,209), including every boundary G = D + E + P (atomic and two-step, NC = 2). **RED**, each violating NoGap: the boundary minus one (`red_bnd_*`, `red_na_P*`), `red_noDeadlineCheck`, `red_deletedNotRooted`, `red_noRetryReread`. **Witnesses reached:** `wit_benefit`, `wit_benefit_na_P1`, `wit_deadlineLoss`, `wit_gcDeletes`, `wit_retryNotFound`. Safe iff G >= D + E + P. | `core/frontend/chunkstore/catalog.go` `Fork` (deadline start before `readForkParent`, publish before start + deadline); `retention.go` `markDeleting` (no claim); `gc.go` `NewCollector` (grace >= deadline + skew + CAS apply bound); `gc_copy.go` `snapshotAttemptHeads` (deleted attempt rooted for grace) | ## Limits @@ -305,7 +309,7 @@ java -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config cfg/REC_red_noInterna The authored LIGHT receipts report exhaustive safe searches at 2,700 and 25,550 states, plus the expected mutant/witness failures. Source and configs are copied -from the sealed `claude05-walreclaim-tla-r0-20261119` artifact with line-ending +from the sealed authoring artifact with line-ending normalization only. Those are prior author runs, not a claim that this PR reran TLC. This is an abstraction: physical fsync success, byte layout, crash recovery, both-slot retirement, timing and multiple writers remain covered by their other @@ -335,6 +339,53 @@ four negative controls separately remove retirement, the frame join, the readiness guard or ACK progress restoration. This abstracts successful admitted frames and does not prove physical-I/O, authority rollback or timing behavior. +## Attached-volume maintenance + +`MaintenanceOwner.tla` now includes joined-stop re-arm on the same current +handle, and replacement followed by a new attachment. At most three arms and +two handles make the graph finite. Local review-fold run 2026-11-21 03:47 UTC, +TLC2.19 / Java21 /512MiB, jar SHA256 +`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`: + +```sh +java -Xmx512m -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config MaintenanceOwner_safe.cfg MaintenanceOwner +``` + +Positive exited0,105generated/54distinct, queue empty, depth12. Negative configs +`overlap` exited12 at OneOwner (20/14 depth6), `early_release` at +JoinedBeforeRelease (25/14 depth6), and `stale_rearm` at +CurrentHandleAtAdmission (50/33 depth8). Unique `-metadir` paths were used. +Native tests separately bind replica/epoch/endpoint and current handle/layer, +witness cancellation while held, and same-handle stop/join/re-arm. This finite +model does not establish physical-I/O cancellation or a fleet scheduling bound. + +`ScopedMaintenanceGC.tla` extends S9's scope correspondence: three keys across +two volumes, one foreign-only root, independent local coverage and crash/config +invalidation. `ScopedMaintenanceGC_safe.cfg` checks foreign-root preservation, +local candidate scope and coverage ownership: 20 generated / 10 distinct states, +depth 9, with the same TLC/jar. Its three negative configs narrow +the root domain, widen reclamation or import namespace coverage. Native tests +exercise the persisted mark records and real catalog root traversal; the finite +model abstracts the complete mark and grace, whose timing remains in S9. +No 50/200-volume density or metadata-RPC qualification is claimed; automatic GC +remains opt-in, while periodic HEAD capture and retention are enabled by the CLI. + +The unchanged S9 timing models were replayed with the same TLC/jar: +`cfg/S9_rule_G4.cfg` (`RetentionGCTiming`, D=2/G=4/MD=1/MaxT=10) +passed with 26,341 generated / 10,798 distinct states, depth 23; +`cfg/S9b_G3_MD1.cfg` (`RetentionGCMulti`, G=3/MD=1/MaxT=12) +passed with 11,303 / 5,743, depth 23. + +`cfg/Maintenance_lifecycle.cfg` replays unchanged `ChunkLifecycleFixed` with +one snapshot caller/deleter, MaxHostOps=1 and MaxRuns=1, fork/delete/create, +lost replies/pending/sweep enabled. Safety invariants and HeadMonotone passed: +42,133,769 generated / 7,224,016 distinct states, depth 47 (TLC 2.19, same jar). +This config permits terminal stuttering (`CHECK_DEADLOCK FALSE`); it does not +prove deadlock freedom. The original `Fix_mix_small` replay stopped with a +terminal deadlock at depth 23 after 28,242,446 / 5,592,191 states (callers Done, +gc_loop); it is not reported as a completed green run. No protocol guards in +ChunkLifecycleFixed were changed. + `PrecopyFixedAdmission.tla` checks cost admission over five physical rounds. A known estimate fits the 1.2-second allowance, or uses the five-second declared freeze limit when it is at least 90% of the previous comparable known estimate or on the final @@ -408,3 +459,61 @@ The same command with each negative config exited12 at its intended invariant: third `NoUploadBeforeAdmission`, the fourth `OverrideVisible`, and the last `AuthorityAtPublication`. Source tests separately check time/metadata handling, no-upload refusal, preserved bytes, uncertain outcomes and typed API dispatch. + + +## GC clock allowance + +`GCClockSkew.tla` checks the time-admission portion of M6 GC: pairwise clock +bias -S/0/+S, timestamp truncation 0/Q, and retaining future-dated roots while +an independently eligible object progresses. It abstracts the existing complete +root scan, exclusive copy settlement and higher-epoch guards; it does not prove +those protocols or safety with clocks outside the configured bound. + +Local TLC2.19 / Java21 run 2026-11-21, jar SHA256 +`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`: +`java -Xmx512m -cp tlc2.TLC -config GCClockSkew_safe.cfg GCClockSkew` +from `docs/spec`, each run with its own metadir. Bounds G=3, S=1, Q=1, +Born=10, MaxT=17. Positive exhausted: exit0, 96 generated / 96 distinct states, +queue empty, depth16. `GCClockSkew_no_skew.cfg` exited12 at `NoEarlyExpiry` +(43/43, depth8); `GCClockSkew_no_resolution.cfg` exited12 at `NoEarlyExpiry` +(44/44, depth8); `GCClockSkew_abort_future.cfg` exited12 at +`IndependentProgress` (11/11, depth2). Source tests independently cover +persisted-mark compatibility, future-clock resets and authority-preserving expiry. + + +## Per-object GC DELETE progress + +`GCDeleteProgress.tla` models the narrow sweep transition after a complete, +authorised mark: three ordered candidates, first DELETE definitively rejected, +later deletes accepted. It checks that the rejected fid is never reported +successful, the failure is visible, and later candidates progress. Root/epoch +admission, elapsed coverage and persistence are outside this small abstraction; +source tests retain those guards and reopen independent collectors between passes. + +Local TLC2.19 / Java21, same jar SHA256 as GCClockSkew above, 2026-11-21: +`java -Xmx512m -cp tlc2.TLC -config GCDeleteProgress_safe.cfg GCDeleteProgress` +from `docs/spec`, separate metadirs. Positive exhausted exit0, 4 generated /4 +distinct states, depth4. `GCDeleteProgress_stop.cfg` exits12 at `LaterProgress` +(2 generated /2 distinct, depth2). The HTTP source red uses an actual400 and +checks later reclamation, retained failed tombstones, younger-object progress +across separate collectors and permanent no-rebind behavior. + +### Frozen budget response quantities (F2) + +The additive `candidateTail` and typed refusal quantities share storage's +complete estimate, including its existing margin. Tail-known alone is not +complete-estimate-known. `FrozenDetachBudget` now includes estimate zero and +derives `FrozenEstimateKnown` and `MaxRefreezeQuiesce`; `ReportSlackSound` checks +positive slack implies a known positive estimate and slack + estimate = limit. +These durations are same-host advice, not a physical completion bound or a change +to the existing wall-origin request. Admission still rechecks at its barrier. + +TLC 2.19, tools SHA256 `936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`, +local 2026-11-21 10:43Z: `FrozenDetachBudget.cfg` exhausted 829 generated / 535 +distinct states, depth 6, queue empty, no invariant violation. Bounds: elapsed +{0,30,60}, estimate {0,5,30,60} (then barrier growth), known/force/authority Boolean; +limit 50, no physical I/O latency. Raw quantities and JSON preservation are +checked by native Go tests; this derived arithmetic model does not model the HTTP +encoder, sampler atomicity, orchestrator timing or an unbounded estimator overrun. + +#344 review qualification: `TestChunkFrozenDrainRefusalCarriesObservedBudget` drives a real admitted Sync through frontend drain expiry, durable provider and HTTP, with no report injection; `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation` covers the known observation. `TestFrozenSaturatedTailRemainsKnownButNonActionable` and the literal 60 s/61 s candidate cases preserve the existing saturation sentinel (zero slack, not a complete duration). These native controls add no model claim or admission guard. diff --git a/seaweed-block/docs/spec/RestoreIndependence.tla b/seaweed-block/docs/spec/RestoreIndependence.tla new file mode 100644 index 0000000000..66b87257ff --- /dev/null +++ b/seaweed-block/docs/spec/RestoreIndependence.tla @@ -0,0 +1,256 @@ +------------------------------ MODULE RestoreIndependence ------------------------------ +(***************************************************************************) +(* Independent restore of a snapshot into a new volume. *) +(* Source volume V with HEAD and one sealed snapshot S; target T restored *) +(* from S. T's HEAD maps indexes to fids; a fid is owned by V (a "@V/" *) +(* ref) or by T. Steps: 0 claim S; 1 fork (T HEAD = S's fids, all V-owned) *) +(* ; 2 hydrate (local, not modelled beyond "local" flags); 3 OWNING = *) +(* batch cuts, each re-uploads up to Batch V-owned indexes as T-owned fids *) +(* (intent -> upload -> HEAD CAS); 4 marker after the last V ref is gone, *) +(* then drop the claim. A GC (machine E, reduced: deletes only fids that *) +(* no root reaches) may run at any point; V may be deleted at any point; *) +(* the restore process may crash and a new owner resumes from REMOTE facts *) +(* only (forced move). Mutants are constants (FALSE = the design). *) +(* Reuse: the fid/owner/root vocabulary of the chunk GC model; this *) +(* spec models only what the restore adds, not the superseded list/grace. *) +(* NOCLAIM: with NoClaim = TRUE claims are removed; *) +(* a snapshot delete never looks at a fork. Safety of the ForkBegin.. *) +(* ForkEnd window comes from two time rules on one clock: (D) ForkEnd only *) +(* while now < readAt + D, else ForkFail; (G) a deleted S stays a GC root *) +(* while now < delAt + G. With NoClaim = FALSE nothing below changes the *) +(* old model (Tick, ForkFail, ForkNotFound disabled; new variables fixed). *) +(***************************************************************************) +EXTENDS Integers, FiniteSets, TLC + +CONSTANTS + NIdx, \* indexes of the volume (1..NIdx) + Batch, \* indexes per independence batch cut + MaxCrash, \* restore-process crashes (each followed by a resume) + MaxGc, \* GC rounds + \* ---- mutants (FALSE = the design) ---- + DropClaimAtFork, \* r0 mutant: the claim on S is dropped right after the fork + CasBeforeUpload, \* batch CAS swaps a ref before its own upload is durable + ListForeign, \* the batch lists the replaced V fid for GC (rule 8 broken) + MarkerEarly, \* marker written before the last V ref is gone + MarkerBeforeCas, \* marker written before the final batch's HEAD CAS + ResumeLocal, \* a new owner trusts a local "done" flag instead of remote facts + SnapDuringRestore, \* a snapshot of T is allowed before the marker + RetentionIgnoresMarker, \* after the marker, V's retention still treats T as holding S + \* ---- added in review (r0.1) ---- + ClaimUntilHead, \* r0.2 OPTION 1: the claim is dropped when T's HEAD is published (today's fork semantics) + NoIntent, \* uploaded batch fids are not rooted by an intent before the HEAD CAS + \* ---- NOCLAIM variant; old cfgs: NoClaim = FALSE, D = G = MaxTick = 0, the three below TRUE ---- + NoClaim, \* TRUE: no claim ever holds S; DeleteS needs only slive; time rules D and G apply + D, \* fork deadline: ForkEnd only while now < readAt + D (read only when NoClaim) + G, \* grace: a deleted S stays a root while now < delAt + G (read only when NoClaim) + MaxTick, \* bound of the clock (Tick is enabled only when NoClaim) + ForkChecksDeadline,\* design TRUE; mutant FALSE = ForkEnd at any time + DeletedRooted, \* design TRUE; mutant FALSE = a deleted S stops being a root at once + ResumeRereads \* design TRUE; mutant FALSE = a resume in the fork window reuses the old read (fresh deadline, S not re-read) + +Idx == 1..NIdx +VF == [i \in Idx |-> <<"V", i>>] \* the source fid of index i +TF == [i \in Idx |-> <<"T", i>>] \* T's own fid for index i +Fids == {VF[i] : i \in Idx} \cup {TF[i] : i \in Idx} +\* r0.1: "no HEAD yet" is a function too (TLC cannot compare a function with a string) +NoHead == [i \in Idx |-> <<"N", i>>] +None == -1 \* nc: "no tick" encoding for readAt / delAt + +VARIABLES + store, \* Fids -> "none" | "pres" | "del" + vlive, \* V still exists (its HEAD roots V fids) + slive, \* S exists + claim, \* the restore's claim on S + thead, \* T's HEAD: Idx -> fid, or "none" before the fork + step, \* restore step: "c" claimed | "f" forked | "own" | "done" + up, \* T fids uploaded durably but not yet in HEAD (current batch) + marker, \* restore/INDEPENDENT exists (remote) + tsnap, \* a snapshot of T (its fid set), {} if none + gclist, \* fids put on a GC list (rule 8 check) + localdone,\* local "restore done" flag of the current owner (ResumeLocal mutant) + crashes, gcs, + \* ---- nc (all fixed at their Init value when NoClaim = FALSE) ---- + now, \* the one clock + readAt, \* tick at which the current fork attempt read S (None if no attempt in progress) + delAt, \* tick at which S was deleted (None while S lives) + sdelfk, \* history: S was deleted while step = "fk" (for the witness) + ffail \* history: a fork attempt failed on its deadline (for the witness) + +tvars == <> +vars == <> + +THeadFids == IF thead = NoHead THEN {} ELSE {thead[i] : i \in Idx} +VRefs == {i \in Idx : thead # NoHead /\ thead[i][1] = "V"} +\* roots: V's HEAD (while V lives), S (while it lives), T's HEAD, T's snapshot, +\* uploaded-but-unpublished batch fids (intent roots them), S's fids while claimed +SFids == {VF[i] : i \in Idx} +\* nc rule G: a deleted S stays a root for G ticks (FALSE whenever NoClaim = FALSE) +SGrace == NoClaim /\ DeletedRooted /\ ~ slive /\ delAt # None /\ now < delAt + G +Roots == (IF vlive THEN SFids ELSE {}) + \cup (IF (slive \/ SGrace) THEN SFids ELSE {}) + \cup THeadFids \cup tsnap \cup (IF NoIntent THEN {} ELSE up) +\* S may be deleted by retention when nothing holds it +SHeld == claim \/ (RetentionIgnoresMarker /\ thead # NoHead) +\* nc: with NoClaim the snapshot delete never looks at a fork +SDeletable == slive /\ (NoClaim \/ ~ SHeld) +\* nc rule D (TRUE whenever NoClaim = FALSE) +DeadlineOK == (~ NoClaim) \/ (~ ForkChecksDeadline) \/ (now < readAt + D) + +Init == + /\ store = [f \in Fids |-> IF f[1] = "V" THEN "pres" ELSE "none"] + /\ vlive = TRUE /\ slive = TRUE /\ claim = FALSE /\ thead = NoHead + /\ step = "start" /\ up = {} /\ marker = FALSE /\ tsnap = {} /\ gclist = {} + /\ localdone = FALSE /\ crashes = 0 /\ gcs = 0 + /\ now = 0 /\ readAt = None /\ delAt = None /\ sdelfk = FALSE /\ ffail = FALSE + +\* step 0: S is sealed (given) and claimed +\* nc: the step is kept (S found, step counter) but takes no claim +Claim == step = "start" /\ slive /\ claim' = (~ NoClaim) /\ step' = "c" + /\ UNCHANGED <> + /\ UNCHANGED tvars + +\* step 1: fork (T HEAD names S's fids, all V-owned) +\* r0.1: two steps. Between them T exists without a HEAD, so only the claim keeps S (and +\* through S its fids) alive; that window is what the claim is for. +\* nc: ForkBegin reads S (requires S live) and records readAt; ForkEnd only within the deadline +ForkBegin == step = "c" /\ step' = "fk" + /\ (NoClaim => slive) + /\ claim' = (IF DropClaimAtFork THEN FALSE ELSE claim) + /\ readAt' = (IF NoClaim THEN now ELSE readAt) + /\ UNCHANGED <> + /\ UNCHANGED <> +ForkEnd == step = "fk" /\ DeadlineOK /\ thead' = VF /\ step' = "own" + /\ claim' = (IF ClaimUntilHead THEN FALSE ELSE claim) + /\ UNCHANGED <> + /\ UNCHANGED tvars +\* nc: past the deadline the fork fails cleanly: T stays without a HEAD, a retry is a new ForkBegin +ForkFail == NoClaim /\ step = "fk" /\ now >= readAt + D + /\ step' = "c" /\ readAt' = None /\ ffail' = TRUE + /\ UNCHANGED <> + /\ UNCHANGED <> +\* nc: a (re)try that re-reads S and finds it gone ends with "not found" (terminal) +ForkNotFound == NoClaim /\ step = "c" /\ ~ slive /\ step' = "nf" + /\ UNCHANGED <> + /\ UNCHANGED tvars + +\* step 3: one batch: upload own fids for up to Batch V-owned indexes (intent roots them) +BatchSet == {B \in SUBSET VRefs : B # {} /\ Cardinality(B) <= Batch} +Upload(B) == step = "own" /\ up = {} /\ ~ CasBeforeUpload + /\ (\A i \in B : store[VF[i]] = "pres") \* reads its local copy (filled from V) + /\ store' = [f \in Fids |-> IF f \in {TF[j] : j \in B} THEN "pres" ELSE store[f]] + /\ up' = {TF[j] : j \in B} + /\ UNCHANGED <> + /\ UNCHANGED tvars +\* the batch HEAD CAS: swap exactly the uploaded indexes +Cas == step = "own" /\ up # {} + /\ thead' = [i \in Idx |-> IF TF[i] \in up THEN TF[i] ELSE thead[i]] + /\ gclist' = (IF ListForeign THEN gclist \cup {VF[i] : i \in {j \in Idx : TF[j] \in up}} ELSE gclist) + /\ up' = {} + /\ localdone' = (localdone \/ \A i \in Idx : (thead[i][1] = "V") => (TF[i] \in up)) + /\ UNCHANGED <> + /\ UNCHANGED tvars +\* mutant: CAS a batch whose upload is not durable (the T fid is still "none") +CasEarly(B) == CasBeforeUpload /\ step = "own" /\ up = {} + /\ thead' = [i \in Idx |-> IF i \in B THEN TF[i] ELSE thead[i]] + /\ UNCHANGED <> + /\ UNCHANGED tvars +UploadLate == CasBeforeUpload /\ step = "own" + /\ \E i \in Idx : thead[i] = TF[i] /\ store[TF[i]] = "none" + /\ store' = [store EXCEPT ![TF[i]] = "pres"] + /\ UNCHANGED <> + /\ UNCHANGED tvars + +\* step 4: marker after the last V ref is gone (and the final CAS is done), then drop the claim +Marker == step = "own" /\ ~ marker /\ up = {} + /\ (VRefs = {} \/ MarkerEarly \/ (MarkerBeforeCas /\ Cardinality(VRefs) <= Batch)) + /\ marker' = TRUE /\ step' = "done" /\ localdone' = TRUE + /\ UNCHANGED <> + /\ UNCHANGED tvars +DropClaim == marker /\ claim /\ claim' = FALSE + /\ UNCHANGED <> + /\ UNCHANGED tvars + +\* a snapshot of T: refused before the marker (unless the mutant allows it) +SnapT == tsnap = {} /\ thead # NoHead /\ (marker \/ SnapDuringRestore) + /\ tsnap' = THeadFids + /\ UNCHANGED <> + /\ UNCHANGED tvars + +\* crash of the restore process; the new owner resumes from remote facts (thead, marker) +\* nc: a resume in the fork window (no HEAD) is a retry that re-reads S (back to "c", new +\* ForkBegin requires S live); mutant ~ResumeRereads: stays "fk" with a fresh deadline (readAt = now) +\* and the content read before the crash +Crash == crashes < MaxCrash /\ step \in {"fk", "own", "done"} + /\ up' = {} \* an unpublished batch is abandoned; its fids are collectable + /\ step' = (IF ResumeLocal /\ localdone THEN "done" + ELSE IF marker THEN "done" + ELSE IF thead = NoHead THEN (IF (NoClaim /\ ResumeRereads) THEN "c" ELSE "fk") + ELSE "own") + /\ readAt' = (IF (NoClaim /\ thead = NoHead) THEN (IF ResumeRereads THEN None ELSE now) ELSE readAt) + /\ crashes' = crashes + 1 + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* user deletes V; retention deletes S when nothing holds it +DeleteV == vlive /\ vlive' = FALSE + /\ UNCHANGED <> + /\ UNCHANGED tvars +\* nc: whenever S is live (SDeletable = slive); records delAt and whether a fork was in its window +DeleteS == SDeletable /\ slive' = FALSE + /\ delAt' = (IF NoClaim THEN now ELSE delAt) + /\ sdelfk' = (IF (NoClaim /\ step = "fk") THEN TRUE ELSE sdelfk) + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* GC (reduced machine E): deletes present fids no root reaches, and fids put on the list +Gc == gcs < MaxGc + /\ store' = [f \in Fids |-> IF store[f] = "pres" /\ (f \notin Roots \/ f \in gclist) THEN "del" ELSE store[f]] + /\ gcs' = gcs + 1 + /\ UNCHANGED <> + /\ UNCHANGED tvars + +\* nc: time advances by one tick (never when NoClaim = FALSE) +Tick == NoClaim /\ now < MaxTick /\ now' = now + 1 + /\ UNCHANGED <> + /\ UNCHANGED <> + +Next == Claim \/ ForkBegin \/ ForkEnd \/ Cas \/ Marker \/ DropClaim \/ SnapT \/ Crash \/ DeleteV \/ DeleteS \/ Gc \/ UploadLate + \/ (\E B \in BatchSet : Upload(B) \/ CasEarly(B)) + \/ ForkFail \/ ForkNotFound \/ Tick + +Spec == Init /\ [][Next]_vars + +---------------------------------------------------------------------------- +\* INV-RESTORE-NO-GAP: every index of T's HEAD resolves to a present fid +NoGap == thead = NoHead \/ \A i \in Idx : store[thead[i]] = "pres" +\* INV-RESTORE-INDEPENDENT: after the marker, T roots no V fid (HEAD or snapshot) +Independent == marker => (VRefs = {} /\ \A f \in tsnap : f[1] = "T") +\* INV-RESTORE-NO-FOREIGN-LIST: a restore never lists a V fid +NoForeignList == \A f \in gclist : f[1] = "T" +\* INV-RESTORE-CLAIM-UNTIL-INDEPENDENT +ClaimUntilIndependent == (thead # NoHead /\ ~ marker) => claim +\* r0.2 option 1: the claim covers exactly the window in which T exists without a HEAD +ClaimUntilHead_Inv == (step = "fk") => claim +\* lifecycle independence: after the marker and the claim drop, nothing of T holds S +LifecycleFree == (marker /\ ~ claim) => ~ SHeld +\* nc replacement of LifecycleFree: nothing ever holds S; S is deletable at every moment it lives +LifecycleFreeNC == NoClaim => (~ claim /\ (SDeletable = slive)) +\* nc frame check for old cfgs: with NoClaim = FALSE the new variables never move +OldFrame == (~ NoClaim) => (now = 0 /\ readAt = None /\ delAt = None /\ ~ sdelfk /\ ~ ffail) +\* INV-RESTORE-STATE-REMOTE: "done" only when the remote marker exists +StateRemote == step = "done" => marker + +TypeOK == /\ step \in {"start", "c", "fk", "own", "done", "nf"} /\ up \subseteq Fids /\ tsnap \subseteq Fids + /\ now \in 0..MaxTick /\ readAt \in {None} \cup (0..MaxTick) /\ delAt \in {None} \cup (0..MaxTick) + /\ sdelfk \in BOOLEAN /\ ffail \in BOOLEAN +\* witnesses (r0.1): each is an invariant expected to be VIOLATED, proving the state is reachable +W_Done == ~ (marker /\ ~ claim /\ ~ slive /\ ~ vlive /\ \A i \in Idx : store[VF[i]] = "del") +W_CrashResume == ~ (marker /\ crashes = MaxCrash) +\* nc witnesses: S deleted inside the fork window and the restore still completes, every block present, +\* every V fid physically gone +W_nc_DelInFork == ~ (sdelfk /\ marker /\ step = "done" /\ ~ vlive /\ ~ slive + /\ (\A i \in Idx : store[VF[i]] = "del") + /\ (\A i \in Idx : store[thead[i]] = "pres")) +\* nc witness: a fork failed on its deadline and a retry found S gone +W_nc_FailNotFound == ~ (ffail /\ step = "nf") +============================================================================= diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC.tla b/seaweed-block/docs/spec/ScopedMaintenanceGC.tla new file mode 100644 index 0000000000..e04fda664f --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC.tla @@ -0,0 +1,25 @@ +------------------------ MODULE ScopedMaintenanceGC ------------------------ +EXTENDS Naturals, FiniteSets, TLC +CONSTANTS TraceForeign, LocalSweep, ImportGlobal +VARIABLES marks, localPasses, deleted, complete, early +vars == <> +Keys == {"rooted", "local", "foreign"} +Init == /\ marks = 0 /\ localPasses = 0 /\ deleted = {} /\ complete = FALSE /\ early = FALSE +\* A foreign-volume intent is the only root of the target's local key. +Roots == IF TraceForeign THEN {"rooted"} ELSE {} +Start == /\ ~complete /\ complete' = TRUE /\ UNCHANGED <> +Finish == /\ complete /\ localPasses < 2 + /\ LET coverage == IF ImportGlobal THEN 1 ELSE marks + scope == IF LocalSweep THEN {"rooted", "local"} ELSE Keys + IN /\ deleted' = deleted \cup (IF coverage = 1 THEN scope \ Roots ELSE {}) + /\ early' = (early \/ (coverage = 1 /\ localPasses = 0)) + /\ marks' = 1 + /\ localPasses' = localPasses + 1 /\ complete' = FALSE +CrashOrConfigChange == /\ marks' = 0 /\ localPasses' = 0 /\ complete' = FALSE + /\ UNCHANGED <> +Next == Start \/ Finish \/ CrashOrConfigChange +Spec == Init /\ [][Next]_vars +ForeignRootSurvives == "rooted" \notin deleted +OwnCoverageOnly == ~early +ForeignCandidatesUntouched == "foreign" \notin deleted +============================================================================= diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC_import_global.cfg b/seaweed-block/docs/spec/ScopedMaintenanceGC_import_global.cfg new file mode 100644 index 0000000000..25bf2c2d66 --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC_import_global.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS TraceForeign = TRUE + LocalSweep = TRUE + ImportGlobal = TRUE +INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC_narrow_roots.cfg b/seaweed-block/docs/spec/ScopedMaintenanceGC_narrow_roots.cfg new file mode 100644 index 0000000000..80c34ce5a2 --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC_narrow_roots.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS TraceForeign = FALSE + LocalSweep = TRUE + ImportGlobal = FALSE +INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC_safe.cfg b/seaweed-block/docs/spec/ScopedMaintenanceGC_safe.cfg new file mode 100644 index 0000000000..b428924006 --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC_safe.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS TraceForeign = TRUE + LocalSweep = TRUE + ImportGlobal = FALSE +INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC_wide_sweep.cfg b/seaweed-block/docs/spec/ScopedMaintenanceGC_wide_sweep.cfg new file mode 100644 index 0000000000..49e7263fa9 --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC_wide_sweep.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS TraceForeign = TRUE + LocalSweep = FALSE + ImportGlobal = FALSE +INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/WALReclaim.tla b/seaweed-block/docs/spec/WALReclaim.tla index 4895234f72..3214a648d2 100644 --- a/seaweed-block/docs/spec/WALReclaim.tla +++ b/seaweed-block/docs/spec/WALReclaim.tla @@ -1,6 +1,6 @@ ----------------------------- MODULE WALReclaim ----------------------------- (***************************************************************************) -(* Liveness of v3 WAL reclaim under write pressure (claude05, 2026-11-19). *) +(* Liveness of v3 WAL reclaim under write pressure (2026-11-19). *) (* Abstracts core/storage at seaweed-block main 39f11d6a: *) (* head = WAL head LSN (records appended) *) (* wack = durable WAL frontier; today advanced only by Sync *) @@ -14,7 +14,7 @@ (* (walstore.go:829-832, admission at :850). A cut takes the capture *) (* write lock; Go's RWMutex makes a pending writer block new readers. *) (* *) -(* InternalOn: the fix under review (codex03 design r0) - under pressure *) +(* InternalOn: the fix under review - under pressure *) (* the store makes its own WAL durable (wack := head) with no guest Sync. *) (* Mut: *) (* "none" the design *) diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg new file mode 100644 index 0000000000..08a0f98ca5 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 1 + E = 1 + P = 0 + MaxNow = 8 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg new file mode 100644 index 0000000000..2461983061 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1, E=0). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 1 + E = 0 + P = 0 + MaxNow = 7 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg new file mode 100644 index 0000000000..5231a1b4ed --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 2 + E = 1 + P = 0 + MaxNow = 10 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg new file mode 100644 index 0000000000..ccb2842e87 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 3 + G = 4 + E = 2 + P = 0 + MaxNow = 15 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg new file mode 100644 index 0000000000..dde4eaec5e --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg @@ -0,0 +1,19 @@ +\* RED boundary with 2 chunks. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 2 + D = 2 + G = 2 + E = 1 + P = 0 + MaxNow = 10 + MaxAttempts = 3 + MaxReads = 2 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg new file mode 100644 index 0000000000..350144738f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg @@ -0,0 +1,19 @@ +\* RED: a deleted snapshot stops being a root at once. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = FALSE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg new file mode 100644 index 0000000000..51d3895c09 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=0 (G = D+E+P-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 2 + E = 1 + P = 0 + MaxNow = 10 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg new file mode 100644 index 0000000000..95f97f1fd1 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=1 at the atomic grace G = D+E. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 1 + MaxNow = 12 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg new file mode 100644 index 0000000000..ced2c0e10d --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=2, E=2 (G = D+E+P-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 4 + E = 2 + P = 2 + MaxNow = 15 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg new file mode 100644 index 0000000000..7a07ed8ad3 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=2 (G = D+E+P-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 2 + MaxNow = 14 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg new file mode 100644 index 0000000000..aa381427c9 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg @@ -0,0 +1,19 @@ +\* RED: publish without the deadline check. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = FALSE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg new file mode 100644 index 0000000000..6460befc5f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg @@ -0,0 +1,19 @@ +\* RED: a retry reuses the earlier chunk set without re-reading S. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = FALSE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg new file mode 100644 index 0000000000..73d4fdfd71 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 2 + E = 1 + P = 0 + MaxNow = 9 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg new file mode 100644 index 0000000000..e696bfb904 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E, E=0; the brief's 'G <= D' case). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 2 + E = 0 + P = 0 + MaxNow = 8 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg new file mode 100644 index 0000000000..0aa22d44df --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg new file mode 100644 index 0000000000..8cb5038239 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg @@ -0,0 +1,19 @@ +\* SAFE margin (G = D+E+1). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 0 + MaxNow = 12 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg new file mode 100644 index 0000000000..64c5cc8045 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg @@ -0,0 +1,19 @@ +\* SAFE margin (G = D+2E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 6 + E = 2 + P = 0 + MaxNow = 16 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg new file mode 100644 index 0000000000..fbdcd1ee9a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 3 + G = 5 + E = 2 + P = 0 + MaxNow = 16 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg new file mode 100644 index 0000000000..1c85552c5c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=0 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg new file mode 100644 index 0000000000..d95d95dd61 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=1 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 1 + MaxNow = 13 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg new file mode 100644 index 0000000000..22712e7e9f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=2, E=2 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 5 + E = 2 + P = 2 + MaxNow = 16 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg new file mode 100644 index 0000000000..d9ade18294 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=2 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 5 + E = 1 + P = 2 + MaxNow = 15 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg new file mode 100644 index 0000000000..d5b21cec71 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary with 2 chunks, 3 attempts, 2 reads. Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 2 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 3 + MaxReads = 2 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg new file mode 100644 index 0000000000..96ab829d76 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): fork read before the delete, published after it, T reads fine after the grace. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoBenefit diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg new file mode 100644 index 0000000000..c1ad118800 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg @@ -0,0 +1,20 @@ +\* WITNESS two-step P=1 at its safe grace (expected VIOLATED = reachable): benefit still reachable. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 1 + MaxNow = 13 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoBenefit diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg new file mode 100644 index 0000000000..278b224e07 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): a fork fails cleanly on the deadline. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoDeadlineLoss diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg new file mode 100644 index 0000000000..c8e81bc147 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): GC deletes S's chunks in a safe configuration. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoGCDelete diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg new file mode 100644 index 0000000000..ab7b41316a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): a retry gets snapshot-not-found. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoRetryNotFound diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg index 7992b80dde..1fbd6505f5 100644 --- a/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg @@ -5,4 +5,4 @@ CONSTANTS OmitStageGuard = FALSE OmitOverrideRecord = FALSE OmitAuthority = FALSE -INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication ReportSlackSound diff --git a/seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg b/seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg new file mode 100644 index 0000000000..c257d3d0a0 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg @@ -0,0 +1,20 @@ +\* Maintenance safety replay: one snapshot caller/deleter, one host operation/run. +SPECIFICATION Spec +CONSTANTS + SnapCallers = {s1} + Deleters = {d1} + ForkOn = TRUE + DelSnapOn = TRUE + CreateOn = TRUE + MaxHostOps = 1 + MaxRuns = 1 + LostReply = TRUE + PendingOn = TRUE + SweepOn = TRUE + defaultInitValue = defaultInitValue +SYMMETRY Symm +INVARIANT TypeOK GCSafe SnapOnlyExplicitDelete AckedChunksSurvive CommitClean NoPublishAfterCommit NoIdReuse GiveBackReleases +PROPERTY HeadMonotone + +\* Bounded terminal states may stutter; safety, not deadlock freedom. +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G0D1.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G0D1.cfg new file mode 100644 index 0000000000..8102f6b6cf --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G0D1.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 1 + G = 0 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg new file mode 100644 index 0000000000..5b319dceb8 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 1 + G = 1 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg new file mode 100644 index 0000000000..959c1e147f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 3 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg new file mode 100644 index 0000000000..dabec4a948 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 3 + G = 3 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_CasBeforeUpload.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_CasBeforeUpload.cfg new file mode 100644 index 0000000000..b398ea33a7 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_CasBeforeUpload.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = TRUE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg new file mode 100644 index 0000000000..d5a4f2f982 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 1 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ListForeign.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ListForeign.cfg new file mode 100644 index 0000000000..460f66230b --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ListForeign.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = TRUE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerBeforeCas.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerBeforeCas.cfg new file mode 100644 index 0000000000..088e125bd2 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerBeforeCas.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = TRUE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerEarly.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerEarly.cfg new file mode 100644 index 0000000000..de0c18acac --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerEarly.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = TRUE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_NoIntent.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_NoIntent.cfg new file mode 100644 index 0000000000..a9584e358a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_NoIntent.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = TRUE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ResumeLocal.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ResumeLocal.cfg new file mode 100644 index 0000000000..a5690276cb --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ResumeLocal.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = TRUE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_SnapDuringRestore.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_SnapDuringRestore.cfg new file mode 100644 index 0000000000..00961ba3fb --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_SnapDuringRestore.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = TRUE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg new file mode 100644 index 0000000000..1d114c2163 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = FALSE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg new file mode 100644 index 0000000000..cd8b15a2c1 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = FALSE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg new file mode 100644 index 0000000000..a623dd8f51 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg new file mode 100644 index 0000000000..fef3519c2c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg new file mode 100644 index 0000000000..24ee54e48a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 3 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_b2.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_b2.cfg new file mode 100644 index 0000000000..9b33687854 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_b2.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 2 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_n4.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_n4.cfg new file mode 100644 index 0000000000..c0c370f29e --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_n4.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 4 + Batch = 2 + MaxCrash = 2 + MaxGc = 4 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg new file mode 100644 index 0000000000..79708ebd36 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg @@ -0,0 +1,31 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote + W_nc_DelInFork diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg new file mode 100644 index 0000000000..74cc24ef9f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg @@ -0,0 +1,31 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote + W_nc_FailNotFound diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe.cfg new file mode 100644 index 0000000000..ae5548a57e --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe.cfg @@ -0,0 +1,32 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote + OldFrame diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg new file mode 100644 index 0000000000..33e1c88fdb --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg @@ -0,0 +1,31 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = TRUE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFree + StateRemote + OldFrame diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_opt1_safe.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_opt1_safe.cfg new file mode 100644 index 0000000000..c4f0281674 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_opt1_safe.cfg @@ -0,0 +1,31 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = TRUE + NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilHead_Inv + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_DropClaimAtFork_gap.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_DropClaimAtFork_gap.cfg new file mode 100644 index 0000000000..6bd867a906 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_DropClaimAtFork_gap.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = TRUE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg new file mode 100644 index 0000000000..5327a664e4 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg @@ -0,0 +1,31 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index c2c8f5abb4..1e1f3e1d4f 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -124,7 +124,6 @@ the example units, which turn them into flags. blockvolume itself reads only | `SWB_CHUNK_COLLECTION`, `SWB_CHUNK_REPLICATION` | `--chunk-collection`, `--chunk-replication` | empty (filer default) | Placement of chunk needles | | `SWB_CHUNK_CAPTURE_INTERVAL` | `--chunk-capture-interval` | `0` (no timer) | Automatic cut interval, e.g. `15m` | | `SWB_CHUNK_UPLOAD_CONCURRENCY` | `--chunk-upload-concurrency` | `8` | Parallel chunk uploads (1..64) | -| `SWB_CHUNK_DIRTY_THRESHOLD` | `--chunk-dirty-threshold` | `512` | Bound on one cut's barrier copy, in chunks | | `SWB_CHUNK_CONTROL_ENDPOINT` | `--chunk-control-endpoint` | `false` | `/chunk/*` routes on the status listener | | `SWB_WORKSPACE_LEASE` | `--workspace-lease` | `false` | Require a master lease; fail closed without one | | `SWB_VOLUME_EXTRA_ARGS` | any | empty | Other flags (Kubernetes gate and source-gated flags) | diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md new file mode 100644 index 0000000000..25a61677d0 --- /dev/null +++ b/seaweed-block/docs/status-schema.md @@ -0,0 +1,404 @@ +# Status schema + +The blockvolume status listener (`--status-addr`) serves JSON on the routes below. Each table lists every field a route returns: its JSON path (`[]` marks a list, `{}` a map), its type, and its meaning as the field's Go comment states it. A field marked `—` has no comment in the code yet. + +The tables are generated from the Go types, so they list exactly the fields that exist. `go test ./core/host/volume -run TestStatusSchemaDoc` fails when the code and this page disagree; `STATUS_SCHEMA_UPDATE=1` rewrites the generated block. + +All routes take `?volume=` and answer 404 for a volume this host does not serve. + + + +### `GET /status` + +The volume's authority and health projection. Go type `volume.StatusProjection`. + +| Field | Type | Meaning | +|---|---|---| +| `VolumeID` | string | the volume this host serves | +| `ReplicaID` | string | this host's replica of it | +| `Epoch` | uint64 | the authority epoch of the current assignment | +| `EndpointVersion` | uint64 | the assignment's endpoint version within the epoch | +| `Healthy` | bool | the replica may serve I/O at this epoch | +| `Memory` | object | Memory is the process's memory use at the time of the request. | +| `Memory.HeapAllocBytes` | uint64 | Go heap bytes in live objects (runtime.MemStats.HeapAlloc) | +| `Memory.HeapInuseBytes` | uint64 | Go heap bytes in in-use spans (HeapInuse) | +| `Memory.HeapSysBytes` | uint64 | Go heap bytes obtained from the OS (HeapSys) | +| `Memory.HeapReleasedBytes` | uint64 | Go heap bytes returned to the OS (HeapReleased) | +| `Memory.SoftLimitBytes` | int64 | the Go soft memory limit in force (--memory-limit-mib or GOMEMLIMIT) | +| `Memory.RSSBytes` | uint64 | resident set size from /proc/self/status (VmRSS); 0 off Linux | +| `Memory.AnonymousRSSBytes` | uint64 | anonymous resident memory (RssAnon); 0 off Linux | +| `FrontendPrimaryReady` | bool | FrontendPrimaryReady: this replica is the healthy, non-superseded primary and may serve guest I/O. | +| `AuthorityRole` | string | AuthorityRole is primary, superseded or unknown. | +| `ReplicationRole` | string | ReplicationRole is none (a primary), recovering, not_ready, replica_ready or unknown. | +| `RoleAdmissionFailure` | string | RoleAdmissionFailure (G1) explains a not-Healthy projection caused by a failed role call on the replica listener; empty otherwise. (omitted when empty) | +| `UnhealthyReason` | string | UnhealthyReason is the slot's explicit unhealthy report (#128 rule 6), the value its heartbeat carries; empty when healthy. (omitted when empty) | +| `CatchUp` | object | CatchUp shows a supporting replica's catch-up progress while it is not yet replica_ready; it is visible without being an alert. (omitted when empty) | +| `CatchUp.ElapsedMs` | int64 | ElapsedMs is the time since this replica was admitted as a supporting replica at its current epoch. | +| `CatchUp.LagLSN` | uint64 | LagLSN is the engine's H-R (primary head minus this replica's durable frontier) as last observed; 0 when unknown or caught up. | +| `Warnings[]` | string | Warnings are the durable store's typed recovery warnings (e.g. wal_hole_suspected, issue #51). Visible, not an alert: they do not change Healthy or the frontend's readiness. (omitted when empty) | + +### `GET /status/peers` + +Replication peers of the served volume. Go type `volume.peersStatusBody`. + +| Field | Type | Meaning | +|---|---|---| +| `VolumeID` | string | the served volume | +| `ReplicaID` | string | this host's replica | +| `PeerCount` | int | number of entries in Peers | +| `Peers[]` | object | this primary's replication peers | +| `Peers[].ReplicaID` | string | the peer replica | +| `Peers[].State` | string | the peer state (the replica peer table, M3) | +| `Peers[].Epoch` | uint64 | the epoch the peer was assigned at | +| `Peers[].EndpointVersion` | uint64 | the peer's endpoint version within the epoch | +| `Peers[].DataAddr` | string | the peer's data-path address | +| `Peers[].CtrlAddr` | string | the peer's control-path address | +| `Peers[].SessionID` | uint64 | the current recovery or shipping session; 0 when none | +| `Peers[].ProbeInFlight` | bool | a reachability probe of the peer is running | +| `Peers[].Closed` | bool | the peer handle was closed (it no longer ships) | + +### `GET /status/durable` + +Durable store state of the served volume. Go type `volume.durableStatusBody`. + +| Field | Type | Meaning | +|---|---|---| +| `VolumeID` | string | the served volume | +| `ReplicaID` | string | this host's replica | +| `VolumeCount` | int | number of entries in Volumes | +| `Volumes[]` | object | the durable store state of the served volume | +| `Volumes[].VolumeID` | string | the volume | +| `Volumes[].Path` | string | its store path under --durable-root | +| `Volumes[].Impl` | string | the durable implementation (walstore, smartwal, walstore-chunk, ...) | +| `Volumes[].ReplicaID` | string | the replica this store holds | +| `Volumes[].Epoch` | uint64 | the epoch the store is latched to; 0 before an assignment | +| `Volumes[].EndpointVersion` | uint64 | the endpoint version it is latched to | +| `Volumes[].Latched` | bool | an assignment latched the store (epoch and endpoint version set) | +| `Volumes[].Operational` | bool | the backend admits I/O now | +| `Volumes[].FrontierKnown` | bool | DurableLSN, RetainedLSN and HeadLSN are the store's current boundaries | +| `Volumes[].DurableLSN` | uint64 | R: the newest LSN made durable | +| `Volumes[].RetainedLSN` | uint64 | S: the oldest LSN the WAL still retains | +| `Volumes[].HeadLSN` | uint64 | H: the newest LSN written | +| `Volumes[].Evidence` | string | why the backend is or is not operational | +| `Volumes[].Closed` | bool | the backend was closed | +| `Volumes[].WriteProfile` | object | write-path counters since start | +| `Volumes[].WriteProfile.DurabilityLatency` | object | latency distributions of writes, flushes and syncs | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend` | object | per-request latency at the frontend, by stage | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal` | object | end-to-end latency of writes | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal` | object | end-to-end latency of flushes | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal` | object | end-to-end latency of forced-unit-access writes | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend` | object | from request receipt to the backend call | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch` | object | from backend completion to the acknowledgement sent | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal` | object | end-to-end latency of every request | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Writes` | uint64 | writes observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Flushes` | uint64 | flushes observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUAWrites` | uint64 | forced-unit-access writes observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Failed` | uint64 | requests that completed with an error | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync` | object | latency of backend syncs | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.WAL` | object | the WAL's own sync latency, where the store reports it (omitted when empty) | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend` | object | WAL append latency | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait` | object | time a sync request waited in the group commit queue | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync` | object | physical file syncs (one sample per sync, however many waiters) | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.TargetWriteOps` | uint64 | writes the protocol target handed to the volume | +| `Volumes[].WriteProfile.TargetWriteBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.TargetWriteRequestMaxBytes` | uint64 | the largest of them | +| `Volumes[].WriteProfile.TargetWriteDurationNanos` | uint64 | their total time at the target | +| `Volumes[].WriteProfile.BackendWriteRequestOps` | uint64 | write requests that entered the durable backend | +| `Volumes[].WriteProfile.BackendWriteRequestBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.BackendWriteRequestMaxBytes` | uint64 | the largest of them | +| `Volumes[].WriteProfile.BackendWriteOps` | uint64 | backend writes completed | +| `Volumes[].WriteProfile.BackendWriteBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.BackendWriteDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.BackendStorageWriteCalls` | uint64 | single-write calls into the store | +| `Volumes[].WriteProfile.BackendStorageWriteBlocks` | uint64 | blocks they wrote | +| `Volumes[].WriteProfile.BackendStorageBatchCalls` | uint64 | batch-write calls into the store | +| `Volumes[].WriteProfile.BackendStorageBatchBlocks` | uint64 | blocks they wrote | +| `Volumes[].WriteProfile.BackendFullBlockBatchCalls` | uint64 | batch calls made only of whole blocks | +| `Volumes[].WriteProfile.BackendFullBlockBatchBlocks` | uint64 | blocks they wrote | +| `Volumes[].WriteProfile.BackendFullBlockBatchMax` | uint64 | the largest such batch, in blocks | +| `Volumes[].WriteProfile.WALCopyOps` | uint64 | WAL record payload copies | +| `Volumes[].WriteProfile.WALCopyBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALCopyDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.WALEncodeOps` | uint64 | WAL record encodes | +| `Volumes[].WriteProfile.WALEncodeBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALEncodeDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.WALChecksumOps` | uint64 | WAL record checksums | +| `Volumes[].WriteProfile.WALChecksumBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALChecksumDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.WALAppendOps` | uint64 | WAL appends | +| `Volumes[].WriteProfile.WALAppendBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALAppendDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.WALAppendLockWaitOps` | uint64 | appends that waited for the WAL append lock | +| `Volumes[].WriteProfile.WALAppendLockWaitNanos` | uint64 | their total wait | +| `Volumes[].WriteProfile.WriteCommitLockWaitOps` | uint64 | writes that waited for the commit lock | +| `Volumes[].WriteProfile.WriteCommitLockWaitNanos` | uint64 | their total wait | +| `Volumes[].WriteProfile.WALAppendWriteAtCalls` | uint64 | file WriteAt calls made by WAL appends | +| `Volumes[].WriteProfile.WALAppendWriteAtBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALAppendWriteAtMaxBytes` | uint64 | the largest of them | +| `Volumes[].WriteProfile.WALAppendWrapCount` | uint64 | times the WAL append wrapped to the start of the log | +| `Volumes[].WriteProfile.WALAppendPaddingBytes` | uint64 | padding bytes written at those wraps | +| `Volumes[].WriteProfile.DirtyMapUpdateOps` | uint64 | dirty-map updates after writes | +| `Volumes[].WriteProfile.DirtyMapUpdateDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.BackendSyncOps` | uint64 | backend syncs (flush, FUA, explicit sync) | +| `Volumes[].WriteProfile.BackendSyncDurationNanos` | uint64 | their total time | +| `Volumes[].DataSync` | object | data-file sync state, where the store has one (omitted when empty) | +| `Volumes[].DataSync.Mode` | string | the data-file sync call in use (fsync or fdatasync) | +| `Volumes[].DataSync.Reason` | string | why it was chosen (an explicit SWBLOCK_SYNC, or the automatic choice) | +| `Volumes[].CheckpointPersistence` | object | checkpoint persistence state, where the store has one (omitted when empty) | +| `Volumes[].CheckpointPersistence.Successes` | uint64 | checkpoint calls that succeeded (including unchanged ones) | +| `Volumes[].CheckpointPersistence.Refusals` | uint64 | checkpoint calls refused because the map coverage was stale | +| `Volumes[].CheckpointPersistence.Failures` | uint64 | checkpoint calls that failed with an error | +| `Volumes[].CheckpointPersistence.CheckpointLSN` | uint64 | the persisted checkpoint LSN | +| `Volumes[].CheckpointPersistence.Advances` | uint64 | successes that moved CheckpointLSN forward | +| `Volumes[].CheckpointPersistence.LastAdvance` | time (RFC 3339) | when the latest advance happened; zero if none in this open | +| `Volumes[].Chunk` | object | Chunk is the chunk layer's state and cut counters; walstore-chunk volumes only. | +| `Volumes[].Chunk.Attached` | bool | the chunk layer is attached to the remote | +| `Volumes[].Chunk.AwaitingAuthority` | bool | recovered; the layer waits for master authority to attach | +| `Volumes[].Chunk.Fenced` | bool | a newer holder fenced this layer: it publishes nothing | +| `Volumes[].Chunk.RemoteLSN` | uint64 | the LSN of the remote HEAD (what the remote holds durably) | +| `Volumes[].Chunk.Stats` | object | the layer's cut counters; zero until attached | +| `Volumes[].Chunk.Stats.Hydration` | object | lazy fetches of absent chunks from the remote | +| `Volumes[].Chunk.Stats.Hydration.WorkerLimit` | int | fetch workers allowed (--chunk-hydration-workers) | +| `Volumes[].Chunk.Stats.Hydration.QueueDepth` | int | fetch queue capacity (--chunk-hydration-queue-depth) | +| `Volumes[].Chunk.Stats.Hydration.Active` | int | fetches running now | +| `Volumes[].Chunk.Stats.Hydration.Queued` | int | fetches waiting for a worker now | +| `Volumes[].Chunk.Stats.Hydration.WaitCalls` | uint64 | reads that waited for a chunk to arrive | +| `Volumes[].Chunk.Stats.Hydration.Joined` | uint64 | of those, reads that joined a fetch already running | +| `Volumes[].Chunk.Stats.Hydration.WaitRefusals` | uint64 | waits that ended without the chunk (the caller cancelled, or the fetch was not admitted) | +| `Volumes[].Chunk.Stats.Hydration.Fetches` | uint64 | fetches started | +| `Volumes[].Chunk.Stats.Hydration.Completed` | uint64 | fetches that installed the chunk | +| `Volumes[].Chunk.Stats.Hydration.FetchErrors` | uint64 | fetches that failed | +| `Volumes[].Chunk.Stats.CutsOK` | uint64 | cuts that installed a HEAD | +| `Volumes[].Chunk.Stats.CutsNoop` | uint64 | cuts with nothing new (no CAS) | +| `Volumes[].Chunk.Stats.CutsFailed` | uint64 | every other cut failure | +| `Volumes[].Chunk.Stats.CutsRefused{}` | uint64 | refusals by reason: admission, fenced, detached | +| `Volumes[].Chunk.Stats.CutsAborted{}` | uint64 | saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload | +| `Volumes[].Chunk.Stats.CASConflicts` | uint64 | HEAD CAS precondition failures | +| `Volumes[].Chunk.Stats.CASUnknown` | uint64 | HEAD CAS results still unresolved after the re-read | +| `Volumes[].Chunk.Stats.PendingUnresolved` | bool | an unresolved HEAD proposal is held now | +| `Volumes[].Chunk.Stats.DirtyChunks` | int | chunks dirty since the last HEAD (not counting those awaiting reconciliation) | +| `Volumes[].Chunk.Stats.Reconciling` | bool | the dirty set is being reconciled against HEAD; no cut publishes meanwhile | +| `Volumes[].Chunk.Stats.ReconcileDone` | int | chunks compared so far | +| `Volumes[].Chunk.Stats.ReconcileTotal` | int | chunks to compare | +| `Volumes[].Chunk.Stats.LastCut` | object | the last successful cut's measurements | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases` | object | the parts of SyncNs (never added to it) | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.lifecycleWaitNs` | int64 | waiting for the store's lifecycle lock | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.storeWaitNs` | int64 | waiting for the store lock | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.groupCommitNs` | int64 | in the group commit that made the data durable | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.completionWaitNs` | int64 | waiting for the sync leader role to validate the completion | +| `Volumes[].Chunk.Stats.LastCut.CandidateNs` | int64 | Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.WindowSetupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.PublishPrepareNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.ManifestNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.CommitStateNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.IntentCleanupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.NonPayloadCopyNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.PayloadNs` | int64 | disjoint streaming/copy/upload wall intervals | +| `Volumes[].Chunk.Stats.LastCut.COWWALReadAttempts` | uint64 | Local validated WAL attempts and local copy duration, including savers. | +| `Volumes[].Chunk.Stats.LastCut.COWLocalReadNs` | int64 | (group of `COWWALReadAttempts`) Local validated WAL attempts and local copy duration, including savers. | +| `Volumes[].Chunk.Stats.LastCut.COWSavedChunks` | int | (group of `COWWALReadAttempts`) Local validated WAL attempts and local copy duration, including savers. | +| `Volumes[].Chunk.Stats.LastCut.COWSaveNs` | int64 | (group of `COWWALReadAttempts`) Local validated WAL attempts and local copy duration, including savers. | +| `Volumes[].Chunk.Stats.LastCut.COWWaitNs` | int64 | (group of `COWWALReadAttempts`) Local validated WAL attempts and local copy duration, including savers. | +| `Volumes[].Chunk.Stats.LastCut.BarrierPauseNs` | int64 | BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.LockWaitNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.DrainNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CASWriteNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.HeadReadbackNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.SyncNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CopyNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CandidateChunks` | int | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.UploadedChunks` | int | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.UploadedBytes` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.ZeroedChunks` | int | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.UnchangedChunks` | int | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.UploadNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CASNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.MapPersistNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CASResult` | string | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.TotalNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.StageRounds` | int | Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | +| `Volumes[].Chunk.Stats.LastCut.StagedChunks` | int | (group of `StageRounds`) Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | +| `Volumes[].Chunk.Stats.LastCut.StagedChunksUsed` | int | (group of `StageRounds`) Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | +| `Volumes[].Chunk.Stats.LastCut.BarrierCopyChunks` | int | (group of `StageRounds`) Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | +| `Volumes[].Chunk.Stats.LastCut.BarrierOverBound` | bool | (group of `StageRounds`) Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | +| `Volumes[].Chunk.Stats.LastCutH` | uint64 | the LSN the last successful cut published | +| `Volumes[].Chunk.Stats.LastCutNs` | int64 | when it completed (wall clock, Unix ns) | +| `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. | +| `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. | +| `Volumes[].Chunk.Stats.COWSpillCap` | int64 | COWSpillCap is the last cut's side-file cap in bytes, read once per cut; COWSpillCapReason is why it is 0, when the free space made it so: no_room_to_cut (half the free space is within the 1 GiB reserve) or free_space_unreadable (the free space could not be read). | +| `Volumes[].Chunk.Stats.COWSpillCapReason` | string | (group of `COWSpillCap`) COWSpillCap is the last cut's side-file cap in bytes, read once per cut; COWSpillCapReason is why it is 0, when the free space made it so: no_room_to_cut (half the free space is within the 1 GiB reserve) or free_space_unreadable (the free space could not be read). (omitted when empty) | +| `Volumes[].Chunk.HostBudget` | interface | the host background-cut budget state, with --host-limit-dir (omitted when empty) | +| `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | +| `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | + +### `GET /status/recovery` + +The engine's replica projection (only with recovery enabled). Go type `engine.ReplicaProjection`. + +| Field | Type | Meaning | +|---|---|---| +| `Mode` | Mode (string) | the engine mode (idle, recovering, healthy, degraded) | +| `RecoveryDecision` | RecoveryDecision (string) | the recovery class the R/S/H boundaries call for | +| `SessionKind` | SessionKind (string) | the kind of the current recovery session, if any | +| `SessionPhase` | SessionPhase (string) | its phase | +| `Epoch` | uint64 | the authority epoch | +| `EndpointVersion` | uint64 | the endpoint version within the epoch | +| `R` | uint64 | the replica's durable boundary (LSN) | +| `S` | uint64 | the primary's recoverable start boundary (WAL tail LSN) | +| `H` | uint64 | the primary's target boundary (head LSN) | +| `Reason` | string | why the engine is in this mode or decision | + +### `GET /status/chunk` + +Chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint). Go type `chunkstore.VolumeUsage`. + +| Field | Type | Meaning | +|---|---|---| +| `volumeID` | string | the volume | +| `chunkBytes` | uint64 | one full chunk | +| `liveChunks` | int | chunks HEAD references | +| `liveBytes` | uint64 | their bytes (the last chunk clipped) | +| `snapshots[]` | object | one entry per live snapshot | +| `snapshots[].name` | string | the snapshot name | +| `snapshots[].createdNs` | int64 | when it was created (Unix ns) | +| `snapshots[].class` | string | its retention class | +| `snapshots[].pinned` | bool | retention never deletes it | +| `snapshots[].chunks` | int | chunks its manifest references | +| `snapshots[].exclusiveBytes` | uint64 | bytes no other holder references: what deleting it makes eligible for GC | +| `manifestBindings` | int | stored chunk-key bindings some manifest references | +| `manifestBytes` | uint64 | their exact bytes | +| `storedBindings` | int | all chunk-key bindings in the filer, referenced or not | +| `storedBytes` | uint64 | their bytes; unreferenced ones counted at full chunk size | +| `storedUpperBound` | bool | StoredBytes is an upper bound (some bindings are unreferenced) | +| `policy` | object | the snapshot retention policy in force | +| `policy.keepNewest` | int | keep the newest N unpinned snapshots | +| `policy.keepYoungerNs` | int64 | keep every snapshot younger than this (ns) | +| `policy.keepHourly` | int | keep the newest snapshot of each of the last N hours | +| `policy.keepDaily` | int | keep the newest snapshot of each of the last N days | +| `policy.keepWeekly` | int | keep the newest snapshot of each of the last N weeks | +| `policySet` | bool | the volume set its own policy (else the default applies) | + +### `GET /status/nvme` + +NVMe/TCP frontend counters. Go type `volume.NVMeStatus`. + +| Field | Type | Meaning | +|---|---|---| +| `volumeID` | string | the served volume | +| `stats` | object | the NVMe/TCP target's counters since start | +| `stats.sessions_accepted` | uint64 | TCP sessions accepted | +| `stats.admin_connects` | uint64 | admin-queue Connect commands | +| `stats.io_connects` | uint64 | I/O-queue Connect commands | +| `stats.read_commands` | uint64 | Read commands received | +| `stats.write_commands` | uint64 | Write commands received | +| `stats.flush_commands` | uint64 | Flush commands received | +| `stats.inline_write_commands` | uint64 | writes whose data came inline in the command capsule | +| `stats.inline_write_bytes` | uint64 | their data bytes | +| `stats.r2t_write_commands` | uint64 | writes whose data the target requested with R2T | +| `stats.r2t_write_bytes` | uint64 | their data bytes | +| `stats.h2c_data_pdus` | uint64 | host-to-controller data PDUs received | +| `stats.h2c_data_bytes` | uint64 | their bytes | +| `stats.c2h_data_pdus` | uint64 | controller-to-host data PDUs sent (read data) | +| `stats.c2h_data_bytes` | uint64 | their bytes | +| `stats.write_capsule_receive_parse_ops` | uint64 | Write phase attribution: for each phase, the operations timed and their total nanoseconds (overlapping phases can overlap in time). | +| `stats.write_capsule_receive_parse_ns` | uint64 | total nanoseconds of those operations | +| `stats.r2t_data_collection_ops` | uint64 | R2T data collections (R2T send to the last H2CData) | +| `stats.r2t_data_collection_ns` | uint64 | total nanoseconds of those operations | +| `stats.write_dispatch_wait_ops` | uint64 | waits for a write handler to take the command | +| `stats.write_dispatch_wait_ns` | uint64 | total nanoseconds of those operations | +| `stats.write_handler_ops` | uint64 | write handler runs (the backend write) | +| `stats.write_handler_ns` | uint64 | total nanoseconds of those operations | +| `stats.write_completion_queue_wait_ops` | uint64 | waits of a completion for the send queue | +| `stats.write_completion_queue_wait_ns` | uint64 | total nanoseconds of those operations | +| `stats.write_completion_send_ops` | uint64 | completion sends to the host | +| `stats.write_completion_send_ns` | uint64 | total nanoseconds of those operations | + +### `GET /status/ublk` + +Ublk frontend counters. Go type `volume.UblkStatus`. + +| Field | Type | Meaning | +|---|---|---| +| `volumeID` | string | the served volume | +| `stats` | object | the ublk device's request counters since start | +| `stats.read_requests` | uint64 | read requests received | +| `stats.write_requests` | uint64 | write requests received | +| `stats.flush_requests` | uint64 | flush requests received | +| `stats.fua_writes` | uint64 | writes with forced unit access | +| `stats.other_requests` | uint64 | requests of any other operation | +| `stats.errors` | uint64 | requests completed with a negative result | + +### `GET /status/frontend-capabilities` + +The frontends this host can serve. Go type `volume.FrontendCapabilitiesStatus`. + +| Field | Type | Meaning | +|---|---|---| +| `volumeID` | string | the served volume | +| `hostCapabilityIsProductClaim` | bool | always false: host facts, not a supported-product claim | +| `frontendTransports[]` | object | one entry per protocol and transport | +| `frontendTransports[].protocol` | string | the block protocol (iscsi, nvme, ublk) | +| `frontendTransports[].transport` | string | its transport (tcp, rdma, local) | +| `frontendTransports[].supported` | bool | this build and host can serve it | +| `frontendTransports[].listenerImplemented` | bool | a listener exists for it in this binary | +| `frontendTransports[].listenerStarted` | bool | the listener is running now | +| `frontendTransports[].startAllowed` | bool | the preflight checks allow starting it | +| `frontendTransports[].startReason` | string | why it may or may not start (omitted when empty) | +| `frontendTransports[].reason` | string | why it is or is not supported | +| `frontendTransports[].preflight[]` | object | the host facts checked for it (omitted when empty) | +| `frontendTransports[].preflight[].name` | string | the host fact checked (a module, device or privilege) | +| `frontendTransports[].preflight[].available` | bool | the fact holds on this host | +| `frontendTransports[].preflight[].reason` | string | why it holds or not | +| `frontendTransports[].preflight[].detail` | string | extra detail, such as the path probed (omitted when empty) | + + diff --git a/seaweed-block/internal/docs/finished-plans/phase7_finishedplan_iscsi_session_backend_pressure.md b/seaweed-block/internal/docs/finished-plans/phase7_finishedplan_iscsi_session_backend_pressure.md index c41b16790c..e24dd426bb 100644 --- a/seaweed-block/internal/docs/finished-plans/phase7_finishedplan_iscsi_session_backend_pressure.md +++ b/seaweed-block/internal/docs/finished-plans/phase7_finishedplan_iscsi_session_backend_pressure.md @@ -30,7 +30,7 @@ component first -> product-backed gate only when the component boundary is green Milestone bundle: ```text -V:/share/g15d-k8s/testops-runs/iscsi-pressure-close/20260511-091432-d7f6 +/g15d-k8s/testops-runs/iscsi-pressure-close/20260511-091432-d7f6 ``` Remote product checkout used for the milestone gate: @@ -130,7 +130,7 @@ addressed them: Runner-native gate: ```text -swblock run --results-dir V:/share/g15d-k8s/testops-runs/iscsi-pressure-close \ +swblock run --results-dir /g15d-k8s/testops-runs/iscsi-pressure-close \ --env product_root=/tmp/seaweed-block-plan-roadmap-refresh-devrun \ --env ssh_key=C:/work/dev_server/testdev_key \ testops/scenarios/iscsi-os-initiator-compat-chain.yaml @@ -141,7 +141,7 @@ Result: ```text === iscsi-os-initiator-compat-chain === PASS (1m13.531s) 22 actions: 22 passed, 0 failed -run bundle: V:\share\g15d-k8s\testops-runs\iscsi-pressure-close\20260511-091432-d7f6 +run bundle: \g15d-k8s\testops-runs\iscsi-pressure-close\20260511-091432-d7f6 ``` The milestone gate re-proves the real Linux kernel initiator path after the diff --git a/seaweed-block/internal/docs/qa-assignments/cluster-ops-inventory-chain-validation.md b/seaweed-block/internal/docs/qa-assignments/cluster-ops-inventory-chain-validation.md index 5d571c4bcb..597acb24e8 100644 --- a/seaweed-block/internal/docs/qa-assignments/cluster-ops-inventory-chain-validation.md +++ b/seaweed-block/internal/docs/qa-assignments/cluster-ops-inventory-chain-validation.md @@ -29,7 +29,7 @@ From the Windows controller: ```powershell swblock run ` - --results-dir V:/share/g15d-k8s/testops-runs/cluster-ops-inventory ` + --results-dir /g15d-k8s/testops-runs/cluster-ops-inventory ` --env product_root=/tmp/seaweed_block ` --env ssh_key=C:/work/dev_server/testdev_key ` C:/work/seaweed_block/testops/scenarios/cluster-ops-inventory-chain.yaml diff --git a/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-hard-gate.md b/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-hard-gate.md index 9e8b020bf8..3026c649cc 100644 --- a/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-hard-gate.md +++ b/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-hard-gate.md @@ -9,7 +9,7 @@ Dev live gate evidence: - Scenario: `testops/scenarios/cluster-ops-inventory-chain.yaml` - Run id: `20260512-202811-1aa7` -- Bundle: `V:/share/g15d-k8s/testops-runs/lifecycle-gate/20260512-202811-1aa7` +- Bundle: `/g15d-k8s/testops-runs/lifecycle-gate/20260512-202811-1aa7` - Result: PASS, 9/9 phases, 73/73 actions ## Product Question @@ -201,7 +201,7 @@ Runner-native gate: ```powershell swblock run ` - -results-dir V:/share/g15d-k8s/testops-runs/lifecycle-gate ` + -results-dir /g15d-k8s/testops-runs/lifecycle-gate ` -env product_root=/tmp/seaweed-block-lifecycle-devrun ` -env ssh_key=C:/work/dev_server/testdev_key ` testops/scenarios/cluster-ops-inventory-chain.yaml diff --git a/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-report.md b/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-report.md index e1ca0009c0..9092bb704a 100644 --- a/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-report.md +++ b/seaweed-block/internal/docs/qa-assignments/product-owned-blockvolume-lifecycle-mvp-close-report.md @@ -10,7 +10,7 @@ Runner commit: sw-test-runner-standalone @ 6ec7abd (swblock 15.9 MB Windo Host: m02 (192.168.1.184) — Ubuntu 24.04.3 LTS / k3s v1.34.4+k3s1 Run id: 20260512-203746-8cf2 (QA-owned re-run) Dev run id (ref): 20260512-202811-1aa7 -Bundle: V:/share/g15d-k8s/testops-runs/lifecycle-gate/20260512-203746-8cf2 +Bundle: /g15d-k8s/testops-runs/lifecycle-gate/20260512-203746-8cf2 Scenario: testops/scenarios/cluster-ops-inventory-chain.yaml ``` diff --git a/seaweed-block/internal/docs/qa-assignments/same-node-alpha-attach-validation.md b/seaweed-block/internal/docs/qa-assignments/same-node-alpha-attach-validation.md index 830add77fd..235e6b4af6 100644 --- a/seaweed-block/internal/docs/qa-assignments/same-node-alpha-attach-validation.md +++ b/seaweed-block/internal/docs/qa-assignments/same-node-alpha-attach-validation.md @@ -29,7 +29,7 @@ Happy path: ```powershell swblock run ` - --results-dir V:/share/g15d-k8s/testops-runs/same-node-alpha-attach ` + --results-dir /g15d-k8s/testops-runs/same-node-alpha-attach ` --env product_root=/tmp/seaweed_block ` --env ssh_key=C:/work/dev_server/testdev_key ` C:/work/seaweed_block/testops/scenarios/same-node-alpha-attach-chain.yaml @@ -39,7 +39,7 @@ Negative fixture: ```powershell swblock run ` - --results-dir V:/share/g15d-k8s/testops-runs/same-node-alpha-attach-negative ` + --results-dir /g15d-k8s/testops-runs/same-node-alpha-attach-negative ` --env product_root=/tmp/seaweed_block ` --env ssh_key=C:/work/dev_server/testdev_key ` C:/work/seaweed_block/testops/scenarios/same-node-alpha-attach-negative-chain.yaml diff --git a/seaweed-block/internal/docs/ref/product-positioning-v1.md b/seaweed-block/internal/docs/ref/product-positioning-v1.md index f12b63680b..f3490eff08 100644 --- a/seaweed-block/internal/docs/ref/product-positioning-v1.md +++ b/seaweed-block/internal/docs/ref/product-positioning-v1.md @@ -366,7 +366,7 @@ by the SRA/RDMA project, not as a Kubernetes node for seaweed_block. |---|---| | M02 (k3s alpha lab) | `192.168.1.184`, user `testdev` | | SSH key (controller-side) | `C:/work/dev_server/testdev_key` | -| Shared SMB share | `V:/share` on Windows = `/mnt/smb/work/share` on Linux | +| Shared SMB share (``) | the internal evidence store; `/mnt/smb/work/share` on Linux | | TestOps artifact root on M02 | `/mnt/smb/work/share/g15d-k8s/-/` | | Default `KUBECONFIG` on M02 | `/etc/rancher/k3s/k3s.yaml` | | TestOps control directory (when used) | `--control-dir` flag to `sw-testops` | @@ -416,7 +416,7 @@ The `swblock` runner can drive scenarios on M02 over SSH: ```powershell swblock run ` - --results-dir V:/share/g15d-k8s/testops-runs/ ` + --results-dir /g15d-k8s/testops-runs/ ` --env product_root=/tmp/seaweed_block ` --env ssh_key=C:/work/dev_server/testdev_key ` C:/work/seaweed_block/testops/scenarios/.yaml @@ -424,7 +424,7 @@ swblock run ` Scenario artifacts land under both: -- The Windows result bundle at `V:/share/g15d-k8s/testops-runs/...`, +- The Windows result bundle at `/g15d-k8s/testops-runs/...`, - The M02-side artifact dir at `/mnt/smb/work/share/g15d-k8s/-*/`. ### 9.5 Lab Hygiene After A Run diff --git a/seaweed-block/internal/docs/ref/testops-runner-binary-contract.md b/seaweed-block/internal/docs/ref/testops-runner-binary-contract.md index ebed5602ca..a4425ebde3 100644 --- a/seaweed-block/internal/docs/ref/testops-runner-binary-contract.md +++ b/seaweed-block/internal/docs/ref/testops-runner-binary-contract.md @@ -103,7 +103,7 @@ Run the full protocol release gate: ```bash swblock suite \ - --results-dir V:/share/g15d-k8s/testops-runs/protocol-release-gate-native \ + --results-dir /g15d-k8s/testops-runs/protocol-release-gate-native \ --env product_root=/tmp/seaweed-block-nvme-p4l \ --env ssh_key=C:/work/dev_server/testdev_key \ C:/work/seaweed_block/testops/suites/protocol-release-gate.yaml @@ -113,7 +113,7 @@ Validate a finished protocol release gate bundle: ```bash swblock validate-bundle --profile protocol-release-gate \ - V:/share/g15d-k8s/testops-runs/protocol-release-gate-native/ + /g15d-k8s/testops-runs/protocol-release-gate-native/ ``` ## Responsibility Boundary diff --git a/seaweed-block/internal/invcheck/invariants_test.go b/seaweed-block/internal/invcheck/invariants_test.go index 4e5abfbecf..f5ed29ddbd 100644 --- a/seaweed-block/internal/invcheck/invariants_test.go +++ b/seaweed-block/internal/invcheck/invariants_test.go @@ -24,7 +24,7 @@ var ( rowID = regexp.MustCompile("^\\| `(INV-[A-Z0-9-]+)` \\|") testName = regexp.MustCompile("`(Test[A-Za-z0-9_]+)`") testFunc = regexp.MustCompile(`(?m)^func (Test[A-Za-z0-9_]+)\(`) - countLine = regexp.MustCompile("(\\d+) `INV-` rows: (\\d+) ACTIVE, (\\d+) STUB, (\\d+) ARCHIVED") + countLine = regexp.MustCompile("(\\d+) (?:`INV-` )?rows: (\\d+) ACTIVE, (\\d+) STUB, (\\d+) ARCHIVED") ) func repoRoot(t *testing.T) string { @@ -174,8 +174,8 @@ func TestInvariantRowCountMatchesTables(t *testing.T) { for _, r := range rows { by[r.status]++ } - want := fmt.Sprintf("%d `INV-` rows: %d ACTIVE, %d STUB, %d ARCHIVED", len(rows), by["ACTIVE"], by["STUB"], by["ARCHIVED"]) - m := countLine.FindString(doc) + want := fmt.Sprintf("%d rows: %d ACTIVE, %d STUB, %d ARCHIVED", len(rows), by["ACTIVE"], by["STUB"], by["ARCHIVED"]) + m := strings.Replace(countLine.FindString(doc), "`INV-` ", "", 1) if m == "" { t.Fatalf("invariants.md states no row count; the tables hold: %s", want) } diff --git a/seaweed-block/testops/README.md b/seaweed-block/testops/README.md index 3f572c740d..2bab6216a4 100644 --- a/seaweed-block/testops/README.md +++ b/seaweed-block/testops/README.md @@ -154,7 +154,7 @@ controller, pointing it at the remote product checkout on m02: ```powershell swblock suite ` - --results-dir V:/share/g15d-k8s/testops-runs/protocol-release-gate-native ` + --results-dir /g15d-k8s/testops-runs/protocol-release-gate-native ` --env product_root=/tmp/seaweed-block-nvme-p4l ` --env ssh_key=C:/work/dev_server/testdev_key ` C:/work/seaweed_block/testops/suites/protocol-release-gate.yaml @@ -164,7 +164,7 @@ Validate the bundle before manual artifact review: ```powershell swblock validate-bundle --profile protocol-release-gate ` - V:/share/g15d-k8s/testops-runs/protocol-release-gate-native/ + /g15d-k8s/testops-runs/protocol-release-gate-native/ ``` QA close evidence: @@ -264,7 +264,7 @@ Run shape: ```powershell swblock suite ` - --results-dir V:/share/g15d-k8s/testops-runs/beta-hardening-gate ` + --results-dir /g15d-k8s/testops-runs/beta-hardening-gate ` --env product_root=/tmp/seaweed-block-plan-roadmap-refresh-devrun ` --env ssh_key=C:/work/dev_server/testdev_key ` C:/work/seaweed_block/testops/suites/beta-hardening-gate.yaml From 85b6e9c9a0333887dfc4b7b62f91726ef4f63c5f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:30:34 -0800 Subject: [PATCH 30/34] docs: resolve the merge's invariants.md hunks (left unresolved in the merge commit) The Train 9 merge committed conflict markers in docs/design/invariants.md. Both sides added a B.2 row after the same anchor: keep main's INV-MASTER-JOURNAL-ISOLATION-001 and this PR's INV-SEC-CONTROL-BIND-001, and recount the Part B summary from the tables (161 rows: 139 ACTIVE, 19 STUB, 3 ARCHIVED, 146 new). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ed1961e51c..abe4758bc4 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -388,11 +388,7 @@ with a separate scope/config-bound mark. Incomplete marks carry no coverage. ## Part B. Invariant ledger -<<<<<<< HEAD -137 rows: 117 ACTIVE, 17 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 122 new. -======= -160 rows: 138 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 145 new. ->>>>>>> origin/main +161 rows: 139 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 146 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. @@ -471,11 +467,8 @@ Notes: | `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | -<<<<<<< HEAD -| `INV-SEC-CONTROL-BIND-001` | blockmaster's unauthenticated control listeners (--listen, and the runtime HTTP listener when enabled) bind only loopback unless --insecure-external-bind is given; a non-loopback address is refused at startup. | AUTHORITY: control API reachability | `core/host/master/journal_isolation.go` `ValidateControlListen`; `cmd/blockmaster/main.go` `parseFlags` | `TestParseFlags_ControlListenersNeedInsecureExternalBind`, `TestManifests_ExternalBlockmasterBindCarriesTheOptIn` (`cmd/blockmaster/external_bind_test.go`) | — (no state machine; the flag test is the proof form) | ACTIVE | -======= | `INV-MASTER-JOURNAL-ISOLATION-001` | Under strict journal isolation, blockmaster gives no new work to a node whose durable root shares the authority store's file system: it refuses that node's heartbeat while it serves no volume, a new placement on it and a move onto it; work the node already has is kept. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE | ->>>>>>> origin/main +| `INV-SEC-CONTROL-BIND-001` | blockmaster's unauthenticated control listeners (--listen, and the runtime HTTP listener when enabled) bind only loopback unless --insecure-external-bind is given; a non-loopback address is refused at startup. | AUTHORITY: control API reachability | `core/host/master/journal_isolation.go` `ValidateControlListen`; `cmd/blockmaster/main.go` `parseFlags` | `TestParseFlags_ControlListenersNeedInsecureExternalBind`, `TestManifests_ExternalBlockmasterBindCarriesTheOptIn` (`cmd/blockmaster/external_bind_test.go`) | — (no state machine; the flag test is the proof form) | ACTIVE | Notes: From 720fe00f23088264ea76918c7c1c510cb09afc4b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:43:47 -0800 Subject: [PATCH 31/34] sw-block: ops chunk restore creates the restore volume (--source --snapshot --target) sw-block ops chunk restore --source --snapshot --target creates the target from the snapshot with Catalog.Restore (idempotent by --request-id) and, with --status-addr naming the blockvolume that serves the target, starts the restore driver there in the same command and prints both results. Without --status-addr it creates the target and prints the command that starts the driver once the target is attached. --volume keeps driving an existing restore. README lists both forms. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/README.md | 8 ++ seaweed-block/cmd/sw-block/chunk_restore.go | 76 +++++++++++-- .../cmd/sw-block/chunk_restore_test.go | 102 ++++++++++++++++++ 3 files changed, 176 insertions(+), 10 deletions(-) diff --git a/seaweed-block/README.md b/seaweed-block/README.md index 9921dedaa4..88e11dab44 100644 --- a/seaweed-block/README.md +++ b/seaweed-block/README.md @@ -128,6 +128,8 @@ sw-block ops chunk cut --volume v1 --status-addr # publish chang sw-block ops chunk snapshot --volume v1 --status-addr --name s1 # name a snapshot sw-block ops chunk snapshots --volume v1 --chunk-filer # list snapshots sw-block ops chunk fork --chunk-filer --source v1 --snapshot s1 --target v2 # root copy only +sw-block ops chunk restore --chunk-filer --source v1 --snapshot s1 --target v3 --status-addr # independent copy +sw-block ops chunk restore --volume v3 --status-addr --status # restore progress sw-block ops chunk detach --volume v1 --status-addr # final cut and release; resume elsewhere sw-block ops chunk volume-delete --volume v2 --chunk-filer --master --request-id del-v2 sw-block ops chunk gc --chunk-filer --master # preview; --apply to reclaim @@ -135,6 +137,12 @@ sw-block ops chunk verify --volume v1 --chunk-filer # read-only che ``` `volume-delete` is refused while the volume is attached or has snapshots. +`restore` creates the target from the snapshot and, with `--status-addr` naming +the blockvolume that serves the target, starts the background restore there: +the target serves at once, copies every chunk under its own keys and becomes +independent of the source (snapshots of it are refused until then). Without +`--status-addr` it only creates the target and prints the command that starts +the restore once the target is attached. The chunk path (`walstore-chunk`) is a proof of concept. It is not yet a default, a release claim or a production path. diff --git a/seaweed-block/cmd/sw-block/chunk_restore.go b/seaweed-block/cmd/sw-block/chunk_restore.go index 4a94e2f456..cc97080c36 100644 --- a/seaweed-block/cmd/sw-block/chunk_restore.go +++ b/seaweed-block/cmd/sw-block/chunk_restore.go @@ -1,30 +1,86 @@ package main import ( + "context" + "encoding/json" + "fmt" "io" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/ops" ) -// chunkRestore starts (or joins) the independent-restore driver of a volume -// restored from a snapshot and prints its status; with --status it only -// prints the status. The driver runs in blockvolume and outlives this call. +// chunkRestore restores a snapshot into a new independent volume, or drives +// an existing restore. +// +// With --source, --snapshot and --target it creates the target volume from +// the snapshot (Catalog.Restore, idempotent by --request-id) and, when +// --status-addr names the blockvolume serving the target, starts the restore +// driver there and prints both results. With --volume and --status-addr it +// starts (or joins) the driver of an existing restore and prints its status; +// --status only prints the status. The driver runs in blockvolume and +// outlives this call. func chunkRestore(args []string, stdout, stderr io.Writer) int { fs := chunkFlagSet("restore", stderr) var ( - volumeID, statusAddr string - statusOnly bool + volumeID, statusAddr string + filer, base, source, snapshot, target, requestID string + statusOnly bool + timeout time.Duration ) - fs.StringVar(&volumeID, "volume", "", "restored volume id") - fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") + fs.StringVar(&volumeID, "volume", "", "restored volume id (drive an existing restore)") + fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL serving the restored volume (with --chunk-control-endpoint)") fs.BoolVar(&statusOnly, "status", false, "print the restore status without starting a run") + fs.StringVar(&source, "source", "", "source volume id (create a restore)") + fs.StringVar(&snapshot, "snapshot", "", "source snapshot name (create a restore)") + fs.StringVar(&target, "target", "", "new volume id (create a restore)") + fs.StringVar(&requestID, "request-id", "", "idempotency id for the create; generated and printed when empty (reuse it to retry)") + fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port (create a restore)") + fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") + fs.DurationVar(&timeout, "timeout", 6*time.Minute, "filer timeout for the create") if err := fs.Parse(args); err != nil { return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) } - if volumeID == "" || statusAddr == "" { - return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false) + create := source != "" || snapshot != "" || target != "" + switch { + case create && volumeID != "": + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "use --source/--snapshot/--target to create a restore, or --volume to drive one, not both", false) + case create && (source == "" || snapshot == "" || target == ""): + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--source, --snapshot and --target are required to create a restore", false) + case create && statusOnly: + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--status reads an existing restore: use it with --volume", false) + case !create && (volumeID == "" || statusAddr == ""): + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required (or --source, --snapshot and --target to create a restore)", false) } - body := map[string]any{"volumeID": volumeID, "statusOnly": statusOnly} + if !create { + body := map[string]any{"volumeID": volumeID, "statusOnly": statusOnly} + return chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr) + } + + if requestID == "" { + requestID = newRequestID() + fmt.Fprintf(stderr, "sw-block ops chunk restore: request id %s (reuse it to retry)\n", requestID) + } + cat, closeFn, exit := chunkCatalog("restore", filer, base, true, timeout, stdout, stderr) + if exit >= 0 { + return exit + } + defer closeFn() + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + res, err := cat.Restore(ctx, chunkstore.ForkRequest{Source: source, Snapshot: snapshot, Target: target, RequestID: requestID}) + if err != nil || statusAddr == "" { + if err == nil { + fmt.Fprintf(stderr, "sw-block ops chunk restore: %s created; attach it, then run: sw-block ops chunk restore --volume %s --status-addr \n", target, target) + } + return chunkResult("restore", res, err, stdout, stderr) + } + created, err := json.Marshal(res) + if err != nil { + return chunkFail("restore", stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false) + } + fmt.Fprintf(stdout, "%s\n", created) + body := map[string]any{"volumeID": target} return chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr) } diff --git a/seaweed-block/cmd/sw-block/chunk_restore_test.go b/seaweed-block/cmd/sw-block/chunk_restore_test.go index 2c9c32f1c2..f4c6520c01 100644 --- a/seaweed-block/cmd/sw-block/chunk_restore_test.go +++ b/seaweed-block/cmd/sw-block/chunk_restore_test.go @@ -2,11 +2,16 @@ package main import ( "bytes" + "context" + "crypto/sha256" "encoding/json" "net/http" "net/http/httptest" "strings" "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" ) func TestOpsChunk_RestoreStartsAndReportsStatus(t *testing.T) { @@ -37,3 +42,100 @@ func TestOpsChunk_RestoreStartsAndReportsStatus(t *testing.T) { t.Fatal("restore without --volume must be refused") } } + +// restoreSource publishes volume src with one chunk and snapshot s1 in a +// fresh store, and routes the CLI's filer dial to it. +func restoreSource(t *testing.T, base string) (*gcCLIStore, *chunkstore.Catalog) { + t.Helper() + ctx := context.Background() + store := &gcCLIStore{MemFiler: chunkstore.NewMemFiler()} + old := dialChunkFiler + t.Cleanup(func() { dialChunkFiler = old }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil } + cat, err := chunkstore.NewCatalog(store, base) + if err != nil { + t.Fatal(err) + } + geo := chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} + if _, err := cat.EnsureVolume(ctx, "src", geo); err != nil { + t.Fatal(err) + } + r, err := chunkstore.NewChunkRemote(store, store, base+"/src") + if err != nil { + t.Fatal(err) + } + cur, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + data := make([]byte, 8*4096) + data[0] = 0x7 + if err := r.Put(ctx, "chunks/e1/c0/k", data); err != nil { + t.Fatal(err) + } + h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 5, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k", SHA256: sha256.Sum256(data)}}} + h, ids, err := r.PrepareManifest(ctx, cur, h, 8*4096) + if err != nil { + t.Fatal(err) + } + if h.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil { + t.Fatal(err) + } + for _, id := range ids { + _ = r.DeleteIntent(ctx, id) + } + if _, err := cat.CreateSnapshot(ctx, "src", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + return store, cat +} + +// --source/--snapshot/--target creates the restore volume (idempotent by +// request id); without --status-addr it says how to start the driver. +func TestOpsChunk_RestoreCreatesTheTarget(t *testing.T) { + _, cat := restoreSource(t, "/rs") + args := []string{"restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--request-id", "rq", "--chunk-filer", "x", "--chunk-path", "/rs"} + code, out, errs := runChunk(args...) + if code != 0 || !strings.Contains(out, `"dst"`) || !strings.Contains(errs, "--volume dst") { + t.Fatalf("create: exit %d out %s err %s", code, out, errs) + } + v, ok, err := cat.ReadVolume(context.Background(), "dst") + if err != nil || !ok || v.Origin != chunkstore.OriginRestore { + t.Fatalf("target: %+v ok=%v %v, want a restore volume", v, ok, err) + } + if code, out, errs := runChunk(args...); code != 0 { + t.Fatalf("retry with the same request id: exit %d out %s err %s", code, out, errs) + } + for _, bad := range [][]string{ + {"restore", "--source", "src", "--target", "dst", "--chunk-filer", "x"}, + {"restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--volume", "dst", "--chunk-filer", "x"}, + {"restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--status", "--chunk-filer", "x"}, + } { + if code, _, _ := runChunk(bad...); code == 0 { + t.Fatalf("%v accepted", bad) + } + } +} + +// With --status-addr the create then starts the driver for the target on +// that blockvolume, in one command. +func TestOpsChunk_RestoreCreatesAndStartsTheDriver(t *testing.T) { + _, cat := restoreSource(t, "/rs2") + var got map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewDecoder(r.Body).Decode(&got) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"volumeID":"dst","phase":"hydrating","running":true}`)) + })) + defer srv.Close() + code, out, errs := runChunk("restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--request-id", "rq", "--chunk-filer", "x", "--chunk-path", "/rs2", "--status-addr", srv.URL) + if code != 0 || !strings.Contains(out, `"phase":"hydrating"`) { + t.Fatalf("create and start: exit %d out %s err %s", code, out, errs) + } + if got["volumeID"] != "dst" || got["statusOnly"] != nil { + t.Fatalf("driver request %v, want a start for dst", got) + } + if _, ok, _ := cat.ReadVolume(context.Background(), "dst"); !ok { + t.Fatal("the target was not created before the driver start") + } +} From 13000c1d13a3a6573cb4d86825c682cdffe6b6ec Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:46:10 -0800 Subject: [PATCH 32/34] docs: INV-SHARE-ACTIVATION-001 is enforced in sealSnapshot, shared by explicit and scheduled snapshots Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 640ea3c1f9..bbe01cf181 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -628,7 +628,7 @@ Notes: | `INV-RESTORE-OWN-BATCH-001` | A batch cut re-uploads at most N local chunks whose HEAD keys name another volume under new own keys, even when their bytes equal HEAD's, in one ordinary cut (one intent, one HEAD CAS); it never fetches an absent chunk. | M6.Restore.Owning>Owning | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`, `TestOwnBatch_SkipsChunksNotLocal`, `TestOwnBatch_CarriesGuestWrites` (`core/storage/chunk_own_test.go`) | `RestoreIndependence` `NoGap` | ACTIVE | | `INV-RESTORE-DRIVER-001` | The restore driver decides only from the target's VOLUME, HEAD and marker (never the source), writes the marker only after a batch leaves no foreign ref, and a rerun resumes from the target's remote state. | M6.Restore (all transitions) | `core/host/volume/chunk_restore.go` `runRestore`, `chunkControl.Restore` | `TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly`, `TestRestoreDriver_ResumesAfterAFailedBatch`, `TestRestoreDriver_RefusesAVolumeNotMadeByRestore` (`core/host/volume/chunk_restore_test.go`) | `RestoreIndependence` `Independent`, `StateRemote` | ACTIVE | | `INV-CAT-INTENT-DROP-BOUNDED-001` | Dropping an operation's intent outlives the caller's cancellation (cleanup after a refused or cancelled request) but is bounded by `dropIntentTimeout`; a failed or timed-out delete leaves the intent, which only over-protects. | M6 intent: Live → Removed | `core/frontend/chunkstore/catalog.go` `dropIntent` | `TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled` (`core/frontend/chunkstore/restore_test.go`) | — | ACTIVE | -| `INV-SHARE-ACTIVATION-001` | With a `ShareGuard` installed, a snapshot or fork activates (snapshot entry, child HEAD) only after `Finish` accepts the share; a refused `Begin` or `Finish` aborts before activation and drops the new intent. With no guard, nothing is called or checked. | M6 snapshot: Pending → Published; fork: child HEAD create | `core/frontend/chunkstore/share_guard.go` `beginShare`, `finishShare`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `Fork`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot` | `TestShareGuard_SnapshotFinishesBeforeActivation`, `TestShareGuard_RefusedFinishAbortsTheSnapshot`, `TestShareGuard_StaleHeadIsRefused`, `TestShareGuard_CallerToken`, `TestShareGuard_Fork`, `TestShareGuard_BeginRefused` (`core/frontend/chunkstore/share_guard_test.go`); `TestChunkControl_SnapshotBeginsShareBeforeTheCut`, `TestChunkControl_SnapshotBeginRefusedCutsNothing` (`core/host/volume/chunk_control_order_test.go`) | — | ACTIVE | +| `INV-SHARE-ACTIVATION-001` | With a `ShareGuard` installed, a snapshot or fork activates (snapshot entry, child HEAD) only after `Finish` accepts the share; a refused `Begin` or `Finish` aborts before activation and drops the new intent. With no guard, nothing is called or checked. | M6 snapshot: Pending → Published; fork: child HEAD create | `core/frontend/chunkstore/share_guard.go` `beginShare`, `finishShare`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `Fork`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot`, `sealSnapshot` (explicit and scheduled snapshots) | `TestShareGuard_SnapshotFinishesBeforeActivation`, `TestShareGuard_RefusedFinishAbortsTheSnapshot`, `TestShareGuard_StaleHeadIsRefused`, `TestShareGuard_CallerToken`, `TestShareGuard_Fork`, `TestShareGuard_BeginRefused` (`core/frontend/chunkstore/share_guard_test.go`); `TestChunkControl_SnapshotBeginsShareBeforeTheCut`, `TestChunkControl_SnapshotBeginRefusedCutsNothing` (`core/host/volume/chunk_control_order_test.go`) | — | ACTIVE | | `INV-PUBLISH-SETTLED-001` | With `OnPublishSettled` set, each confirmed publication (a new HEAD generation) is delivered once, in publication order, one at a time, outside the capture and state locks. After Close begins, no report is dequeued. | M5 CAS → Settled; M6 HEAD: published | `core/storage/chunk_publish_settled.go` `noteSettled`, `unlockCap`, `runPublishSettled`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestChunkPublishSettled_ReportsEachPublication`, `TestChunkPublishSettled_ReportsALatePublication`, `TestChunkPublishSettled_ClosedAndUnset`, `TestChunkPublishSettled_OverlappingPublishersStayOrdered`, `TestChunkPublishSettled_CloseDropsUnstartedReports`, `TestChunkPublishSettled_HookThatPublishes`, `TestChunkPublishSettled_PeriodicCutReports` (`core/storage/chunk_publish_settled_test.go`); `TestWALStoreChunk_PublishSettledHook` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | Notes: From 0fd141b030497e6a6e5befa795775b3b8b017682 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:46:36 -0800 Subject: [PATCH 33/34] fold: restore create prints one JSON document on stdout; a refused start says the target exists With --status-addr the create result goes to stderr, so stdout carries only the driver status (one JSON document). A driver start refused after the create (for example the target is not attached at that blockvolume yet) adds a line saying the target was created and the --volume command that starts the restore once it is attached. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/chunk_restore.go | 12 ++++++--- .../cmd/sw-block/chunk_restore_test.go | 25 ++++++++++++++++++- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/seaweed-block/cmd/sw-block/chunk_restore.go b/seaweed-block/cmd/sw-block/chunk_restore.go index cc97080c36..bd845e68ba 100644 --- a/seaweed-block/cmd/sw-block/chunk_restore.go +++ b/seaweed-block/cmd/sw-block/chunk_restore.go @@ -17,7 +17,7 @@ import ( // With --source, --snapshot and --target it creates the target volume from // the snapshot (Catalog.Restore, idempotent by --request-id) and, when // --status-addr names the blockvolume serving the target, starts the restore -// driver there and prints both results. With --volume and --status-addr it +// driver there and prints its status (the create result goes to stderr). With --volume and --status-addr it // starts (or joins) the driver of an existing restore and prints its status; // --status only prints the status. The driver runs in blockvolume and // outlives this call. @@ -80,7 +80,13 @@ func chunkRestore(args []string, stdout, stderr io.Writer) int { if err != nil { return chunkFail("restore", stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false) } - fmt.Fprintf(stdout, "%s\n", created) + // stdout stays one JSON document (the driver status); the create result + // goes to stderr. + fmt.Fprintf(stderr, "sw-block ops chunk restore: created %s\n", created) body := map[string]any{"volumeID": target} - return chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr) + code := chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr) + if code != ops.VolumeStatusExitOK { + fmt.Fprintf(stderr, "sw-block ops chunk restore: %s was created, but the restore did not start at %s (is the target attached there?); once it is, run: sw-block ops chunk restore --volume %s --status-addr \n", target, statusAddr, target) + } + return code } diff --git a/seaweed-block/cmd/sw-block/chunk_restore_test.go b/seaweed-block/cmd/sw-block/chunk_restore_test.go index f4c6520c01..6cbd132249 100644 --- a/seaweed-block/cmd/sw-block/chunk_restore_test.go +++ b/seaweed-block/cmd/sw-block/chunk_restore_test.go @@ -129,9 +129,13 @@ func TestOpsChunk_RestoreCreatesAndStartsTheDriver(t *testing.T) { })) defer srv.Close() code, out, errs := runChunk("restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--request-id", "rq", "--chunk-filer", "x", "--chunk-path", "/rs2", "--status-addr", srv.URL) - if code != 0 || !strings.Contains(out, `"phase":"hydrating"`) { + if code != 0 || !strings.Contains(out, `"phase":"hydrating"`) || !strings.Contains(errs, "created ") { t.Fatalf("create and start: exit %d out %s err %s", code, out, errs) } + var one map[string]any + if err := json.Unmarshal([]byte(out), &one); err != nil { + t.Fatalf("stdout is not one JSON document: %v (%s)", err, out) + } if got["volumeID"] != "dst" || got["statusOnly"] != nil { t.Fatalf("driver request %v, want a start for dst", got) } @@ -139,3 +143,22 @@ func TestOpsChunk_RestoreCreatesAndStartsTheDriver(t *testing.T) { t.Fatal("the target was not created before the driver start") } } + +// A start that fails after the create (the target not attached there yet) +// says the target exists and how to start the restore later. +func TestOpsChunk_RestoreCreateThenStartRefusedSaysHowToResume(t *testing.T) { + _, cat := restoreSource(t, "/rs3") + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusConflict) + _, _ = w.Write([]byte(`{"code":"not_chunk_volume","message":"volume dst not open","retryable":false}`)) + })) + defer srv.Close() + code, _, errs := runChunk("restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--request-id", "rq", "--chunk-filer", "x", "--chunk-path", "/rs3", "--status-addr", srv.URL) + if code == 0 || !strings.Contains(errs, "dst was created") || !strings.Contains(errs, "--volume dst") { + t.Fatalf("refused start: exit %d err %s", code, errs) + } + if _, ok, _ := cat.ReadVolume(context.Background(), "dst"); !ok { + t.Fatal("the target must exist after the create") + } +} From 8db62cb989283b9cb473d725b9cf224b135a661b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 08:49:32 -0800 Subject: [PATCH 34/34] docs(invariants): recount the ledger line for the composed train Each member stated the count for its own rows on main; together the tables hold 163 rows (141 ACTIVE, 19 STUB, 3 ARCHIVED). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index f69ac055ec..fdf6aa3ede 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -400,7 +400,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -161 rows: 139 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 146 new. +163 rows: 141 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.