From 248a861fedf22c7ce6d6333fff7c4cd75afc3402 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 15:36:41 -0800 Subject: [PATCH 01/23] test: require clean-revocation cure in workspace delete refusal --- seaweed-block/core/host/master/volume_deleting_test.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/seaweed-block/core/host/master/volume_deleting_test.go b/seaweed-block/core/host/master/volume_deleting_test.go index a1a7bdb54f..50a52582ec 100644 --- a/seaweed-block/core/host/master/volume_deleting_test.go +++ b/seaweed-block/core/host/master/volume_deleting_test.go @@ -2,6 +2,7 @@ package master import ( "context" + "strings" "testing" "time" @@ -55,6 +56,10 @@ func TestMarkVolumeDeleting_RefusedWhileAssigned(t *testing.T) { if status.Code(err) != codes.FailedPrecondition { t.Fatalf("mark of an assigned volume: %v; want FailedPrecondition", err) } + want := "revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete; if the process was stopped by a signal, start it again first" + if !strings.Contains(status.Convert(err).Message(), want) { + t.Fatalf("delete refusal lacks the clean-revocation cure: %v", err) + } if h.Lifecycle().Deletions.Reserved("live") { t.Fatal("a refused mark reserved the id") } From 8fe4231095e7f5fadb38a5818a0cd8dde221c25b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 15:36:59 -0800 Subject: [PATCH 02/23] fix: explain clean-revocation recovery before workspace delete --- seaweed-block/core/authority/workspace.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 8382c23230..857128e0eb 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -144,7 +144,7 @@ func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string, } if _, line, ok := p.workspaceLineLocked(volume); ok { if s == nil || s.Ack == nil || s.Ack.Epoch != line.info.Epoch || s.Ack.ReplicaID != line.info.ReplicaID { - return fmt.Errorf("workspace delete: live authority requires clean revocation ACK") + return fmt.Errorf("workspace delete: live authority requires clean revocation ACK: revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete; if the process was stopped by a signal, start it again first") } } else if pendingPlacement { return fmt.Errorf("workspace delete: placement may have queued authority") From 7ab19a3ff7ea9e34a11f0cc70b663f0842dc1a20 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 15:38:19 -0800 Subject: [PATCH 03/23] docs: trace workspace deletion ACK requirement and cure --- 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 7831af1871..b8f282e657 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -467,7 +467,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -315 rows: 244 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 300 new. +316 rows: 245 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 301 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. @@ -724,6 +724,7 @@ Notes: | `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` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`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-SAME-HOST-CLEAN-MOVE-001` | A clean move may name the source host as its target only when HEAD is sealed by the current holder and the revocation ACK is recorded for that HEAD generation; it issues a higher epoch. A forced move to the source host is refused. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | ACTIVE | +| `INV-WS-DELETE-NEEDS-ACK-001` | A workspace volume with a live authority line is not marked deleting until that line has a clean revocation ACK; the refusal names the cure (revoke with the sealed generation, wait for the recorded ACK; a signal-stopped process must be started again first). | M2 live authority: deletion refused until ACK | `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting` | `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`: refusal, cure and no deletion reservation) | — | 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 admitted only after the persisted lease horizon and the granted or restart deadline, each plus the clock-skew bound, have passed for the lease the last move issue started (never a predecessor's): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `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-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry, never the persisted horizon. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE | From aa4cc46549108f0159147b4fdce2e831d2d45b2d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 15:39:58 -0800 Subject: [PATCH 04/23] docs: state one deletion ACK property per invariant row --- 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 b8f282e657..1fa8177367 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -724,7 +724,7 @@ Notes: | `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` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`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-SAME-HOST-CLEAN-MOVE-001` | A clean move may name the source host as its target only when HEAD is sealed by the current holder and the revocation ACK is recorded for that HEAD generation; it issues a higher epoch. A forced move to the source host is refused. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | ACTIVE | -| `INV-WS-DELETE-NEEDS-ACK-001` | A workspace volume with a live authority line is not marked deleting until that line has a clean revocation ACK; the refusal names the cure (revoke with the sealed generation, wait for the recorded ACK; a signal-stopped process must be started again first). | M2 live authority: deletion refused until ACK | `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting` | `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`: refusal, cure and no deletion reservation) | — | ACTIVE | +| `INV-WS-DELETE-NEEDS-ACK-001` | A workspace volume with a live authority line is not marked deleting until that line has a clean revocation ACK. | M2 live authority: deletion refused until ACK | `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting` | `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`: refusal, cure and no deletion reservation) | — | 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 admitted only after the persisted lease horizon and the granted or restart deadline, each plus the clock-skew bound, have passed for the lease the last move issue started (never a predecessor's): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `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-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry, never the persisted horizon. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE | From 9bd8cb5bc65b273094e0751929e5ec4dcffb0e6f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 16:31:24 -0800 Subject: [PATCH 05/23] fix: keep delete refusal guidance to verified revocation steps --- seaweed-block/core/authority/workspace.go | 2 +- seaweed-block/core/host/master/volume_deleting_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 857128e0eb..1d6375ceb8 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -144,7 +144,7 @@ func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string, } if _, line, ok := p.workspaceLineLocked(volume); ok { if s == nil || s.Ack == nil || s.Ack.Epoch != line.info.Epoch || s.Ack.ReplicaID != line.info.ReplicaID { - return fmt.Errorf("workspace delete: live authority requires clean revocation ACK: revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete; if the process was stopped by a signal, start it again first") + return fmt.Errorf("workspace delete: live authority requires clean revocation ACK: revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete") } } else if pendingPlacement { return fmt.Errorf("workspace delete: placement may have queued authority") diff --git a/seaweed-block/core/host/master/volume_deleting_test.go b/seaweed-block/core/host/master/volume_deleting_test.go index 50a52582ec..7cdbfcb9b8 100644 --- a/seaweed-block/core/host/master/volume_deleting_test.go +++ b/seaweed-block/core/host/master/volume_deleting_test.go @@ -56,7 +56,7 @@ func TestMarkVolumeDeleting_RefusedWhileAssigned(t *testing.T) { if status.Code(err) != codes.FailedPrecondition { t.Fatalf("mark of an assigned volume: %v; want FailedPrecondition", err) } - want := "revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete; if the process was stopped by a signal, start it again first" + want := "revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete" if !strings.Contains(status.Convert(err).Message(), want) { t.Fatalf("delete refusal lacks the clean-revocation cure: %v", err) } From b03e43d26f4dd1f726aa1e833911e52bb19818d2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:16:53 -0800 Subject: [PATCH 06/23] test: interleave independent heartbeat slots on one server --- .../observation_store_slot_order_test.go | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 seaweed-block/core/authority/observation_store_slot_order_test.go diff --git a/seaweed-block/core/authority/observation_store_slot_order_test.go b/seaweed-block/core/authority/observation_store_slot_order_test.go new file mode 100644 index 0000000000..e41191a2fd --- /dev/null +++ b/seaweed-block/core/authority/observation_store_slot_order_test.go @@ -0,0 +1,42 @@ +package authority + +import ( + "fmt" + "testing" + "time" +) + +// V1-SPEC r2.53: independent processes on one server order only their +// own (volume, replica) reports; another slot's later timestamp is irrelevant. +func TestObservationStore_InterleavedSendersOrderPerSlot(t *testing.T) { + for _, n := range []int{10, 100} { + t.Run(fmt.Sprintf("%d slots", n), func(t *testing.T) { + base := time.Unix(1000, 0) + now := base.Add(3 * time.Second) + s := NewObservationStore(FreshnessConfig{FreshnessWindow: 10 * time.Second}, func() time.Time { return now }) + for round := 0; round < 2; round++ { + for i := n - 1; i >= 0; i-- { + slot := healthySlot(fmt.Sprintf("v%d", i/2), fmt.Sprintf("r%d", i%2+1)) + slot.DataAddr = fmt.Sprintf("round-%d-slot-%d", round, i) + at := base.Add(time.Duration(round)*time.Second + time.Duration(i)*time.Millisecond) + obs, err := HeartbeatToObservation(serverObs("one-host", at, slot)) + if err != nil { + t.Fatal(err) + } + if err := s.Ingest(obs); err != nil { + t.Fatal(err) + } + } + } + for i := 0; i < n; i++ { + got, ok := s.SlotFactOnServer("one-host", fmt.Sprintf("v%d", i/2), fmt.Sprintf("r%d", i%2+1)) + if !ok || got.DataAddr != fmt.Sprintf("round-1-slot-%d", i) { + t.Errorf("slot %d lost an independent sender's heartbeat: fact=%+v present=%v", i, got, ok) + } + } + if got := s.SupersededCount(); got != 0 { + t.Fatalf("other senders superseded %d slot reports", got) + } + }) + } +} From f305ecd6cf28372774abcf53c89efb6803041751 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:17:25 -0800 Subject: [PATCH 07/23] fix: order heartbeat reports within each replica slot --- .../core/authority/observation_store.go | 49 ++++++++++--------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index fbf1bb65f2..343d584df8 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -35,18 +35,18 @@ type ObservationStore struct { revision uint64 onMutation func() - // supersededCount counts heartbeat ingests that were dropped - // because a newer ObservedAt was already stored for the same - // ServerID. Diagnostic only — PCDD-DELAYED-HB-001 evidence + // supersededCount counts slot reports that were dropped because a + // newer ObservedAt was stored for that server/volume/replica slot. + // Diagnostic only — PCDD-DELAYED-HB-001 evidence // surface. Not an authority input; publisher / controller / // evidence minting paths MUST NOT read it. Exposed via // SupersededCount(). supersededCount uint64 } -// SupersededCount returns the total number of ingests that were -// dropped because a newer observation from the same server was -// already stored. Diagnostic surface for PCDD-DELAYED-HB-001. +// SupersededCount returns the total number of slot reports dropped +// because a newer report of that same server/volume/replica was stored. +// Diagnostic surface for PCDD-DELAYED-HB-001. // NOT authority input. Monotonic across the lifetime of the store. func (s *ObservationStore) SupersededCount() uint64 { s.mu.Lock() @@ -292,42 +292,45 @@ func (s *ObservationStore) ingest(obs Observation) ([]SlotHealthTransition, erro var transitions []SlotHealthTransition s.mu.Lock() prev, hadPrev := s.observations[obs.ServerID] - if hadPrev { - if prev.ObservedAt.After(obs.ObservedAt) { - // Out-of-order ingest: keep the newer one already - // stored. No mutation fired. - // - // Diagnostic counter for PCDD-DELAYED-HB-001. Not an - // authority input. Must never be read by publisher / - // controller / evidence minting path — it exists so - // tests and operators can see that a superseded - // heartbeat was observed and recorded-as-superseded, - // distinct from "silently dropped". - s.supersededCount++ - s.mu.Unlock() - return nil, nil - } - } // Health transitions, from this accepted report against the same - // server's previously stored fact for each slot it carries. + // slot's stored fact. V1-SPEC r2.53: timestamps order one sender's + // slot only; a later report from another slot cannot supersede it. + accepted := make([]SlotFact, 0, len(obs.Slots)) for _, slot := range obs.Slots { old := "" + superseded := false if hadPrev { for _, p := range prev.Slots { if slotKey(p) == slotKey(slot) { old = p.UnhealthyReason + superseded = slotObservedAt(p, prev).After(slot.ObservedAt) break } } } + if superseded { + s.supersededCount++ + continue + } + accepted = append(accepted, slot) if old != slot.UnhealthyReason { transitions = append(transitions, SlotHealthTransition{ VolumeID: slot.VolumeID, ReplicaID: slot.ReplicaID, Old: old, New: slot.UnhealthyReason, }) } } + if len(obs.Slots) > 0 && len(accepted) == 0 { + s.mu.Unlock() + return nil, nil + } + obs.Slots = accepted if hadPrev { obs.Slots = mergeServerSlots(prev.Slots, obs.Slots) + if prev.ObservedAt.After(obs.ObservedAt) { + // Preserve the newest server metadata without lending its + // timestamp or freshness to another process's slot. + obs.ObservedAt, obs.ExpiresAt, obs.Server = prev.ObservedAt, prev.ExpiresAt, prev.Server + } } s.observations[obs.ServerID] = obs s.revision++ From d06879b76c57dd4b98e61b930b3fa232c73ece97 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:18:19 -0800 Subject: [PATCH 08/23] test: pin mixed-slot supersession and independent expiry --- .../core/authority/observation_store.go | 11 ++--- .../observation_store_slot_order_test.go | 48 +++++++++++++++++++ 2 files changed, 53 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index 343d584df8..74e0ec43b8 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -10,7 +10,7 @@ import ( // ============================================================ // P14 S4 — Observation Store // -// Push-ingested latest-wins observation store per ServerID. The +// Push-ingested latest-wins observation store per replica slot. The // store computes derived freshness on read, based on wall-clock // time vs ObservedAt + FreshnessWindow. Expired observations stay // visible; they are just semantically ineligible for supported @@ -231,11 +231,10 @@ var ErrInvalidObservation = errors.New("observation_store: invalid observation") // ExpiresAt, and fires the registered mutation callback if // anything changed. // -// Latest-wins per ServerID. If an incoming observation has an -// ObservedAt strictly older than the currently-stored one from -// the same server, the store keeps the newer one (ignores the -// stale ingest). No error is returned for that case; it's a -// routine ordering event, not a bug. +// Latest-wins per (ServerID, volume, replica). A slot report strictly +// older than that slot's stored fact is ignored; other slots in the +// observation are accepted independently. No error is returned for +// superseded reports. func (s *ObservationStore) Ingest(obs Observation) error { _, err := s.ingest(obs) return err diff --git a/seaweed-block/core/authority/observation_store_slot_order_test.go b/seaweed-block/core/authority/observation_store_slot_order_test.go index e41191a2fd..33f191ce2e 100644 --- a/seaweed-block/core/authority/observation_store_slot_order_test.go +++ b/seaweed-block/core/authority/observation_store_slot_order_test.go @@ -40,3 +40,51 @@ func TestObservationStore_InterleavedSendersOrderPerSlot(t *testing.T) { }) } } + +func TestObservationStore_MixedSlotReportKeepsOnlyNewerFacts(t *testing.T) { + base := time.Unix(1000, 0) + now := base.Add(4 * time.Second) + s := NewObservationStore(FreshnessConfig{FreshnessWindow: 10 * time.Second}, func() time.Time { return now }) + report := func(at time.Duration, slots ...SlotFact) []SlotHealthTransition { + t.Helper() + tr, err := s.IngestWithHealthTransitions(Observation{ServerID: "one-host", ObservedAt: base.Add(at), Slots: slots}) + if err != nil { + t.Fatal(err) + } + return tr + } + a, b, c := healthySlot("a", "r1"), healthySlot("b", "r1"), healthySlot("c", "r1") + report(3*time.Second, a) + report(time.Second, b) + a.UnhealthyReason, b.UnhealthyReason, c.UnhealthyReason = "stale", "new-b", "new-c" + mutations := 0 + s.SetOnMutation(func() { mutations++ }) + tr := report(2*time.Second, a, b, c) + if len(tr) != 2 || tr[0].VolumeID != "b" || tr[0].New != "new-b" || tr[1].VolumeID != "c" || tr[1].New != "new-c" { + t.Fatalf("mixed report transitions=%+v; want only b and c", tr) + } + if got, ok := s.SlotFactOnServer("one-host", "a", "r1"); !ok || got.UnhealthyReason != "" { + t.Fatalf("stale a replaced its newer fact: %+v, %v", got, ok) + } + if s.SupersededCount() != 1 || mutations != 1 { + t.Fatalf("mixed report: superseded=%d mutations=%d; want 1/1", s.SupersededCount(), mutations) + } + rev := s.Snapshot().revision + if tr := report(time.Second, a, b, c); len(tr) != 0 { + t.Fatalf("all-stale report emitted transitions: %+v", tr) + } + if s.SupersededCount() != 4 || mutations != 1 || s.Snapshot().revision != rev { + t.Fatalf("all-stale report: superseded=%d mutations=%d revision=%d; want 4/1/%d", s.SupersededCount(), mutations, s.Snapshot().revision, rev) + } + // The server's timestamp stays at its newest report; each accepted slot + // keeps its own expiry, including after a delayed mixed report. + now = base.Add(12500 * time.Millisecond) + if _, ok := s.SlotFactOnServer("one-host", "a", "r1"); !ok { + t.Fatal("a lost its later expiry to another slot's older report") + } + for _, volume := range []string{"b", "c"} { + if _, ok := s.SlotFactOnServer("one-host", volume, "r1"); ok { + t.Fatalf("%s inherited a's later freshness", volume) + } + } +} From 69e5951dc615fbe532c423a06602644b5267169f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:20:13 -0800 Subject: [PATCH 09/23] docs: state the heartbeat slot clock limit --- seaweed-block/docs/operator-guide.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index c611d56232..cbff179009 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -54,6 +54,11 @@ one live blockvolume per volume ([one process per volume](releases/one-process-p - **SeaweedFS space:** every cut and snapshot stores the chunks that changed since the previous one. Space comes back only by GC and then a SeaweedFS vacuum (below). +Each volume process reports its own heartbeat slot (server, volume and replica). +The master orders each slot against that slot's previous report. In version 1.0, +a backward host-clock step longer than the freshness window (10 seconds by +default) can expire the host's slots; keep host clocks synchronized. + ## Recovery point and sync policy - **A stopped volume** keeps everything it acknowledged, on its host. From 41e70e6a6a88e7f68dbf99fa16121f072c7c7b1e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:21:17 -0800 Subject: [PATCH 10/23] test: require unlocked per-slot superseded heartbeat diagnostics --- .../observation_store_slot_order_test.go | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/seaweed-block/core/authority/observation_store_slot_order_test.go b/seaweed-block/core/authority/observation_store_slot_order_test.go index 33f191ce2e..71e25c106e 100644 --- a/seaweed-block/core/authority/observation_store_slot_order_test.go +++ b/seaweed-block/core/authority/observation_store_slot_order_test.go @@ -1,11 +1,68 @@ package authority import ( + "bytes" "fmt" + "log" + "strings" "testing" "time" ) +type unlockedHeartbeatLog struct { + bytes.Buffer + store *ObservationStore + locked bool +} + +func (w *unlockedHeartbeatLog) Write(p []byte) (int, error) { + if w.store.mu.TryLock() { + w.store.mu.Unlock() + } else { + w.locked = true + } + return w.Buffer.Write(p) +} + +func TestObservationStore_SupersededSlotLogsAfterUnlock(t *testing.T) { + base := time.Unix(1000, 0) + s := NewObservationStore(FreshnessConfig{}, func() time.Time { return base }) + w := &unlockedHeartbeatLog{store: s} + old := log.Writer() + log.SetOutput(w) + t.Cleanup(func() { log.SetOutput(old) }) + for _, server := range []string{"one-host", "other-host"} { + for _, volume := range []string{"a", "b"} { + slot := healthySlot(volume, "r1") + if err := s.Ingest(Observation{ServerID: server, ObservedAt: base, Slots: []SlotFact{slot}}); err != nil { + t.Fatal(err) + } + } + } + for _, tc := range []struct{ server, volume string }{{"one-host", "a"}, {"one-host", "a"}, {"one-host", "b"}, {"other-host", "a"}} { + if err := s.Ingest(Observation{ServerID: tc.server, ObservedAt: base.Add(-time.Second), Slots: []SlotFact{healthySlot(tc.volume, "r1")}}); err != nil { + t.Fatal(err) + } + } + if w.locked { + t.Fatal("superseded diagnostic was emitted while the store lock was held") + } + lines := strings.Split(strings.TrimSpace(w.String()), "\n") + if len(lines) != 4 { + t.Fatalf("diagnostics=%q; want one line per dropped slot", w.String()) + } + for i, want := range []string{ + "server=one-host volume=a replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=1", + "server=one-host volume=a replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=2", + "server=one-host volume=b replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=1", + "server=other-host volume=a replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=1", + } { + if !strings.Contains(lines[i], "heartbeat superseded "+want) { + t.Errorf("diagnostic %d=%q; want %q", i, lines[i], want) + } + } +} + // V1-SPEC r2.53: independent processes on one server order only their // own (volume, replica) reports; another slot's later timestamp is irrelevant. func TestObservationStore_InterleavedSendersOrderPerSlot(t *testing.T) { From 6d7435313e2c0944e68cb8b819011c3d1b4d67a1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:21:41 -0800 Subject: [PATCH 11/23] feat: report superseded heartbeat counts per slot after unlock --- .../core/authority/observation_store.go | 45 ++++++++++++++++--- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index 74e0ec43b8..5bd3b4f8a7 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -2,6 +2,7 @@ package authority import ( "errors" + "log" "sort" "sync" "time" @@ -42,6 +43,7 @@ type ObservationStore struct { // evidence minting paths MUST NOT read it. Exposed via // SupersededCount(). supersededCount uint64 + supersededSlots map[[3]string]uint64 } // SupersededCount returns the total number of slot reports dropped @@ -54,6 +56,14 @@ func (s *ObservationStore) SupersededCount() uint64 { return s.supersededCount } +// SupersededSlotCount is the diagnostic count for one reporting slot. +// Like SupersededCount, it is not an authority input. +func (s *ObservationStore) SupersededSlotCount(serverID, volumeID, replicaID string) uint64 { + s.mu.Lock() + defer s.mu.Unlock() + return s.supersededSlots[[3]string{serverID, volumeID, replicaID}] +} + // SlotFact returns the most-recently-observed SlotFact for a // (volumeID, replicaID) pair across all reporting servers, or // (zero, false) if no server has reported that slot. @@ -201,10 +211,11 @@ func NewObservationStore(config FreshnessConfig, now func() time.Time) *Observat } cfg := config.withDefaults() return &ObservationStore{ - config: cfg, - now: now, - startedAt: now(), - observations: map[string]Observation{}, + config: cfg, + now: now, + startedAt: now(), + observations: map[string]Observation{}, + supersededSlots: make(map[[3]string]uint64), } } @@ -289,6 +300,19 @@ func (s *ObservationStore) ingest(obs Observation) ([]SlotHealthTransition, erro var fn func() var transitions []SlotHealthTransition + var dropped []struct { + volume, replica string + sentAt, newest time.Time + total uint64 + } + // Both the all-superseded and mixed-report paths release mu before + // returning. Logging never runs under the store lock. + defer func() { + for _, d := range dropped { + log.Printf("heartbeat superseded server=%s volume=%s replica=%s sent_at=%s newest=%s total=%d", + obs.ServerID, d.volume, d.replica, d.sentAt.UTC().Format(time.RFC3339Nano), d.newest.UTC().Format(time.RFC3339Nano), d.total) + } + }() s.mu.Lock() prev, hadPrev := s.observations[obs.ServerID] // Health transitions, from this accepted report against the same @@ -297,18 +321,25 @@ func (s *ObservationStore) ingest(obs Observation) ([]SlotHealthTransition, erro accepted := make([]SlotFact, 0, len(obs.Slots)) for _, slot := range obs.Slots { old := "" - superseded := false + var newest time.Time if hadPrev { for _, p := range prev.Slots { if slotKey(p) == slotKey(slot) { old = p.UnhealthyReason - superseded = slotObservedAt(p, prev).After(slot.ObservedAt) + newest = slotObservedAt(p, prev) break } } } - if superseded { + if newest.After(slot.ObservedAt) { s.supersededCount++ + key := [3]string{obs.ServerID, slot.VolumeID, slot.ReplicaID} + s.supersededSlots[key]++ + dropped = append(dropped, struct { + volume, replica string + sentAt, newest time.Time + total uint64 + }{slot.VolumeID, slot.ReplicaID, slot.ObservedAt, newest, s.supersededSlots[key]}) continue } accepted = append(accepted, slot) From 7e0648a1a6b25cf53fdf9a77cc64bf5bff9eaecb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:22:11 -0800 Subject: [PATCH 12/23] test: check readable per-slot superseded totals --- seaweed-block/core/authority/observation_store.go | 9 +++------ .../core/authority/observation_store_slot_order_test.go | 6 ++++++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index 5bd3b4f8a7..424c89da21 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -300,11 +300,12 @@ func (s *ObservationStore) ingest(obs Observation) ([]SlotHealthTransition, erro var fn func() var transitions []SlotHealthTransition - var dropped []struct { + type supersededReport struct { volume, replica string sentAt, newest time.Time total uint64 } + var dropped []supersededReport // Both the all-superseded and mixed-report paths release mu before // returning. Logging never runs under the store lock. defer func() { @@ -335,11 +336,7 @@ func (s *ObservationStore) ingest(obs Observation) ([]SlotHealthTransition, erro s.supersededCount++ key := [3]string{obs.ServerID, slot.VolumeID, slot.ReplicaID} s.supersededSlots[key]++ - dropped = append(dropped, struct { - volume, replica string - sentAt, newest time.Time - total uint64 - }{slot.VolumeID, slot.ReplicaID, slot.ObservedAt, newest, s.supersededSlots[key]}) + dropped = append(dropped, supersededReport{slot.VolumeID, slot.ReplicaID, slot.ObservedAt, newest, s.supersededSlots[key]}) continue } accepted = append(accepted, slot) diff --git a/seaweed-block/core/authority/observation_store_slot_order_test.go b/seaweed-block/core/authority/observation_store_slot_order_test.go index 71e25c106e..cbcc535ef4 100644 --- a/seaweed-block/core/authority/observation_store_slot_order_test.go +++ b/seaweed-block/core/authority/observation_store_slot_order_test.go @@ -61,6 +61,12 @@ func TestObservationStore_SupersededSlotLogsAfterUnlock(t *testing.T) { t.Errorf("diagnostic %d=%q; want %q", i, lines[i], want) } } + if s.SupersededSlotCount("one-host", "a", "r1") != 2 || + s.SupersededSlotCount("one-host", "b", "r1") != 1 || + s.SupersededSlotCount("other-host", "a", "r1") != 1 || + s.SupersededSlotCount("other-host", "b", "r1") != 0 || s.SupersededCount() != 4 { + t.Fatal("per-slot diagnostics disagree with emitted totals or aggregate count") + } } // V1-SPEC r2.53: independent processes on one server order only their From 7e7bb9cbf8a0e2381c8b9584f631bf0439c94026 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:24:44 -0800 Subject: [PATCH 13/23] test: expose expired fork metadata writes --- .../chunkstore/catalog_deadline_test.go | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/seaweed-block/core/frontend/chunkstore/catalog_deadline_test.go b/seaweed-block/core/frontend/chunkstore/catalog_deadline_test.go index e661566511..0eaf5813f4 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_deadline_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_deadline_test.go @@ -75,3 +75,69 @@ func TestCatalog_PublishIsBoundedByTheDeadline(t *testing.T) { f.stallCreate = nil } } + +// A delayed source read must not create a target, and an expired attempt +// after VOLUME must not create a copy intent, even one it later deletes. +func TestFork_ExpiredAttemptWritesNoNewMetadata(t *testing.T) { + for _, origin := range []string{OriginFork, OriginRestore} { + for _, stage := range []string{"source_read", "volume_written", "live"} { + t.Run(origin+"/"+stage, func(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + now := time.Unix(1800000000, 0) + c.SetClock(func() time.Time { return now }) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h); err != nil { + t.Fatal(err) + } + start := now + volumeWrites, intentWrites := 0, 0 + f.afterLookup = func(p string) { + if stage == "source_read" && isSnapPath(p, "v1", "s1") { + now = start.Add(DefaultOpDeadline) + } + } + f.beforeCreate = func(p string) { + if p == catBase+"/v2/VOLUME" { + volumeWrites++ + if stage == "volume_written" { + now = start.Add(DefaultOpDeadline) + } + } + if strings.HasPrefix(p, catBase+"/v2/intents/") { + intentWrites++ + } + } + req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"} + var err error + if origin == OriginFork { + _, err = c.Fork(ctx, req) + } else { + _, err = c.Restore(ctx, req) + } + f.afterLookup, f.beforeCreate = nil, nil + if stage == "live" { + if err != nil || volumeWrites != 1 || intentWrites != 1 { + t.Fatalf("live attempt: err=%v VOLUME=%d intents=%d", err, volumeWrites, intentWrites) + } + return + } + if CodeOf(err) != CodeDeadlineExceeded { + t.Fatalf("expired attempt: %v", err) + } + wantVolume := 0 + if stage == "volume_written" { + wantVolume = 1 + } + if volumeWrites != wantVolume || intentWrites != 0 { + t.Fatalf("expired attempt wrote VOLUME=%d intents=%d; want %d and 0", volumeWrites, intentWrites, wantVolume) + } + if _, err := f.LookupEntry(ctx, catBase+"/v2", headName); err == nil { + t.Fatal("expired attempt published HEAD") + } + if intents := intentsOf(t, f, "v2"); len(intents) != 0 { + t.Fatalf("expired attempt left intents: %+v", intents) + } + }) + } + } +} From d59c640128a92f6ba6e8db80158f112c9df77eab Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:26:07 -0800 Subject: [PATCH 14/23] docs: trace heartbeat slot ordering to its invariant --- seaweed-block/core/authority/observation_store.go | 3 ++- .../core/authority/observation_store_slot_order_test.go | 2 +- seaweed-block/docs/design/invariants.md | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index 424c89da21..dbf1229678 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -317,7 +317,8 @@ func (s *ObservationStore) ingest(obs Observation) ([]SlotHealthTransition, erro s.mu.Lock() prev, hadPrev := s.observations[obs.ServerID] // Health transitions, from this accepted report against the same - // slot's stored fact. V1-SPEC r2.53: timestamps order one sender's + // slot's stored fact. INV-OBS-SLOT-ORDER-001 / V1-SPEC r2.53: + // timestamps order one sender's // slot only; a later report from another slot cannot supersede it. accepted := make([]SlotFact, 0, len(obs.Slots)) for _, slot := range obs.Slots { diff --git a/seaweed-block/core/authority/observation_store_slot_order_test.go b/seaweed-block/core/authority/observation_store_slot_order_test.go index cbcc535ef4..e13d0ca8d5 100644 --- a/seaweed-block/core/authority/observation_store_slot_order_test.go +++ b/seaweed-block/core/authority/observation_store_slot_order_test.go @@ -69,7 +69,7 @@ func TestObservationStore_SupersededSlotLogsAfterUnlock(t *testing.T) { } } -// V1-SPEC r2.53: independent processes on one server order only their +// INV-OBS-SLOT-ORDER-001 / V1-SPEC r2.53: processes on one server order only their // own (volume, replica) reports; another slot's later timestamp is irrelevant. func TestObservationStore_InterleavedSendersOrderPerSlot(t *testing.T) { for _, n := range []int{10, 100} { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7831af1871..ac65b7368d 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -467,7 +467,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -315 rows: 244 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 300 new. +316 rows: 245 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 301 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. @@ -930,6 +930,7 @@ Notes: | `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE | | `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE | | `INV-OBS-PRODUCT-EVENTS-001` | blockmaster records placement-verified, promotion-candidate-evaluation and authority-published events, and the CSI node reports `csi_reattach_observed` after a successful stage. | M3 promotion decision (observation) | `core/host/master/product_loop.go` `recordPlacementVerifiedEvents`, `recordPromotionEvaluationEvents`, `recordAuthorityPublishedEvent` | `TestMasterTimeline_RecordsPlacementVerified`, `TestMasterTimeline_RecordsPromotionCandidateEvaluation`, `TestMasterTimeline_RecordsAuthorityPublishedAfterMint` (`core/host/master/event_ring_test.go`); `TestNodeStage_ReportsCSIReattachObservedAfterSuccessfulStage` (`core/csi/node_test.go`) | — | ACTIVE | +| `INV-OBS-SLOT-ORDER-001` | A heartbeat slot (server, volume, replica) is ordered only against that slot's own previous heartbeat: a later-stamped heartbeat of another slot of the same server never supersedes it. | AUTHORITY/ORDER: per-slot heartbeat ingest (V1-SPEC r2.53) | `core/authority/observation_store.go` `ingest` (per-slot comparison), `slotObservedAt`; `SupersededSlotCount` (diagnostic only) | `TestObservationStore_InterleavedSendersOrderPerSlot`, `TestObservationStore_MixedSlotReportKeepsOnlyNewerFacts`, `TestObservationStore_SupersededSlotLogsAfterUnlock` (`core/authority/observation_store_slot_order_test.go`) | 1.0 limit: a backward wall-clock step longer than the freshness window expires that host's slots; 1.0.1: per-process sequence. | ACTIVE | | `INV-OBS-SLOT-FROM-EXPECTED-SERVER-001` | A replica's slot in the assembled topology takes addresses and health only from a fresh fact reported by the server its expected slot names; another server's fact for the same replica is never used, so with none from that server the slot is a placeholder. | AUTHORITY/ORDER: observation to assignment line | `core/authority/snapshot_builder.go` `assembleVolumeTopology` | `TestAssembleVolumeTopology_SlotFactOnlyFromTheExpectedServer` (`core/authority/snapshot_slot_server_test.go`) | — (pure assembly; the unit test is the proof form) | ACTIVE | | `INV-HELM-RF-NODECOUNT-001` | Generated Helm values fail closed when the requested replication factor exceeds the selected Ready schedulable node count. | M3 (configuration) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`, `selectHelmValuesNodes` | `TestOpsGenerateHelmValuesRejectsRFAboveSelectedNodes` (`cmd/sw-block/main_test.go`) | — | ACTIVE | | `INV-HOSTPATH-TRANSPARENT-001` | The read model reports transparent host-path recovery only with a multipathed, Active/Optimized, stale-fenced path, writer and reader checks, and the same pod UID. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume`, `deriveManagedVolumeStates` | `TestManagedVolumeProjection_TransparentISCSIALUARecovered`, `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | From d89943503ea733283c430a788077fffc9f638796 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:26:17 -0800 Subject: [PATCH 15/23] fix: refuse expired fork metadata publication --- .../core/frontend/chunkstore/catalog.go | 8 +++++- .../core/frontend/chunkstore/catalog_test.go | 2 +- .../chunkstore/retention_integration_test.go | 25 +++++++++++++++++-- .../chunkstore/snapshot_delete_test.go | 10 +++++--- seaweed-block/docs/design/invariants.md | 6 ++--- 5 files changed, 41 insertions(+), 10 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index ade786fa78..dcbf98c020 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -1285,6 +1285,7 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For // readAt + deadline, the last moment this fork can publish // (INV-SNAP-DELETE-ANY-ORDER-001). The parent is not claimed. readAt := c.now() + deadline := readAt.Add(c.deadline()) 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 { @@ -1334,6 +1335,9 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For req.Target, req.Source, req.Snapshot, existing.Fork.SourceGen, snap.HeadGen) } } else { + if !c.now().Before(deadline) { + return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: deadline passed; VOLUME not written", req.Target) + } 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) @@ -1365,7 +1369,9 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For return ForkResult{}, err } he.Extended[extReq] = []byte(req.RequestID) - deadline := readAt.Add(c.deadline()) + if !c.now().Before(deadline) { + return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: deadline passed; copy intent not written", req.Target) + } id, err := putIntent(ctx, c.f, dstRoot, storage.ChunkIntent{Gen: 0, Epoch: 0, Holder: tag, Keys: headKeys(head), Segments: head.Segments, ChunkBytes: head.ChunkBytes, DeadlineNs: deadline.UnixNano()}) if err != nil { diff --git a/seaweed-block/core/frontend/chunkstore/catalog_test.go b/seaweed-block/core/frontend/chunkstore/catalog_test.go index 33ade710d3..0a93987366 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_test.go @@ -370,7 +370,7 @@ func TestFork_RefusalsAndDeadline(t *testing.T) { t.Fatal("a fork past its deadline wrote a HEAD") } c.SetClock(time.Now) - // The VOLUME from the late attempt is reused by its own retry. + // A retry of the expired attempt succeeds under a fresh deadline. if res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v4", RequestID: "late"}); err != nil || res.Replayed { t.Fatalf("retry after the late attempt: %+v %v", res, err) } diff --git a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go index acc5b07125..1b06bdd46d 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -178,9 +179,13 @@ func TestIntegration_RetainIgnoresIncompleteForks(t *testing.T) { var pinnedAttempt string stoppedFork := func(snap, target string) { t.Helper() - cat.OpDeadline = time.Nanosecond + start := clock + cat.SetClock(func() time.Time { return clock }) + original := cat.f + cat.f = expireForkVolumeFiler{Filer: original, target: path.Join(base, target, volumeName), expire: func() { clock = start.Add(DefaultOpDeadline) }} _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: snap, Target: target, RequestID: "f"}) - cat.OpDeadline = 0 + cat.f = original + cat.SetClock(func() time.Time { clock = clock.Add(time.Second); return clock }) if CodeOf(err) != CodeDeadlineExceeded { t.Fatalf("fork %s past its deadline: %v; want deadline_exceeded", target, err) } @@ -231,3 +236,19 @@ func TestIntegration_RetainIgnoresIncompleteForks(t *testing.T) { } } } + +// expireForkVolumeFiler advances only after the target identity was stored; +// the retention test therefore exercises an incomplete fork, not an absent one. +type expireForkVolumeFiler struct { + Filer + target string + expire func() +} + +func (f expireForkVolumeFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, exclusive bool) error { + err := f.Filer.CreateEntry(ctx, dir, e, exclusive) + if err == nil && path.Join(dir, e.Name) == f.target { + f.expire() + } + return err +} diff --git a/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go index 35b05e3ed0..d1c9eda111 100644 --- a/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go +++ b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go @@ -25,12 +25,16 @@ func TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent(t *testing.T) { } 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 + c.SetClock(func() time.Time { return clock }) + f.beforeCreate = func(p string) { + if p == catBase+"/v2/VOLUME" { + clock = clock.Add(DefaultOpDeadline) + } + } if _, err := c.Fork(ctx, req); CodeOf(err) != CodeDeadlineExceeded { t.Fatalf("fork past its deadline: %v, want deadline_exceeded", err) } - c.OpDeadline = 0 + f.beforeCreate = nil if _, ok, err := c.ReadVolume(ctx, "v2"); !ok || err != nil { t.Fatalf("the stopped fork's VOLUME: ok=%v %v", ok, err) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7831af1871..204ae4e441 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -349,7 +349,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | 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 | 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, check start + deadline before the target `VOLUME`, copy intent and HEAD writes; 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` | @@ -874,7 +874,7 @@ Notes: | `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 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-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`); `TestFork_ExpiredAttemptWritesNoNewMetadata` (`core/frontend/chunkstore/catalog_deadline_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 | @@ -911,7 +911,7 @@ Notes: - `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. +- `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. The same deadline is checked before creating target VOLUME, its copy intent and its HEAD; an expired source read creates no target, and expiry after VOLUME leaves it retryable without a new copy intent. 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. From eab3a3366e7b41212a0abaf3e1c889d3282fa621 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:26:12 -0800 Subject: [PATCH 16/23] test: retain permanent recovery faults at the guest gate --- .../durable/recovery_permanent_test.go | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/recovery_permanent_test.go diff --git a/seaweed-block/core/frontend/durable/recovery_permanent_test.go b/seaweed-block/core/frontend/durable/recovery_permanent_test.go new file mode 100644 index 0000000000..7ef566f531 --- /dev/null +++ b/seaweed-block/core/frontend/durable/recovery_permanent_test.go @@ -0,0 +1,70 @@ +package durable_test + +import ( + "context" + "errors" + "path/filepath" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// INV-FE-ERROR-RETRY-CLASS-001 / V1-SPEC r2.55 side (d), coverage A9.1. +// A real strict-W WAL integrity failure must survive recovery readiness gating +// as a permanent cause. Ordinary awaiting-recovery readiness stays retryable. +func TestRecoveryStoreFaultRemainsPermanentAtGuestIO(t *testing.T) { + root := t.TempDir() + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + WALRecoveryTestDisableFlusher: true, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + b := p.Backend("v1") + if _, err := b.Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) || + frontend.ClassifyBackendError(ctx, err) != frontend.BackendErrorNotReady { + t.Fatalf("ordinary pre-recovery gate is not retryable not-ready: %v", err) + } + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if _, err := s.Write(5, block(0xA7)); err != nil { + t.Fatal(err) + } + ws, ok := s.(*storage.WALStore) + if !ok { + t.Fatalf("unexpected store %T", s) + } + if err := ws.SetWMode(storage.WModeStrict); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + restore := corruptWALWrite(t, filepath.Join(root, "v1.bin"), 0xA7) + t.Cleanup(restore) + if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrWALIntegrityFault) { + t.Fatalf("expected real WAL integrity recovery failure: %v", err) + } + _, err = b.Read(ctx, 5, make([]byte, 4096)) + if err == nil { + t.Fatal("failed recovery admitted a guest read") + } + if got := frontend.ClassifyBackendError(ctx, err); got != frontend.BackendErrorPermanent { + t.Errorf("store-fault recovery became guest retry class %v, want permanent: %v", got, err) + } + if !errors.Is(err, storage.ErrWALIntegrityFault) { + t.Errorf("guest error lost permanent WAL-integrity cause: %v", err) + } +} From 13565c7638183238fada42bc5e23470193e88ef8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:32:39 -0800 Subject: [PATCH 17/23] fix: preserve typed store recovery failures through readiness --- .../core/frontend/durable/provider.go | 2 +- .../core/frontend/durable/storage_adapter.go | 21 ++++++++++++++++--- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index e99ada32b2..7dfc67abfc 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -1084,7 +1084,7 @@ func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (R } report := Recover(h.storage, volumeID) if report.Err != nil { - h.backend.SetOperational(false, report.Evidence) + h.backend.setRecoveryFailure(report.Evidence, report.Err) return report, report.Err } if chunked { diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 47249f558a..57ce1b1805 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -206,6 +206,9 @@ type StorageBackend struct { // could not follow the store's next LSN). While set, every I/O is // refused, so a volume never serves without its observer. Under mu. observerErr error + // recoveryErr retains the typed cause while the operational gate is shut. + // INV-FE-ERROR-RETRY-CLASS-001: permanent leaves survive readiness markers. + recoveryErr error // protected by mu; cleared only by successful readiness // observerMu serializes moving the store's next LSN (the frontier // seed) together with rebasing the observer, against installing an // observer together with its rebase: whichever runs second sees the @@ -494,6 +497,13 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) { b.mu.Unlock() } +func (b *StorageBackend) setRecoveryFailure(evidence string, cause error) { + b.mu.Lock() + b.setOperationalLocked(false, evidence) + b.recoveryErr = cause + b.mu.Unlock() +} + // FirstServing is closed the first time the backend admits I/O (for a chunk // volume: after its storage claim succeeded) and never reopens. A later loss // of readiness does not reopen it: the process exit of @@ -503,6 +513,9 @@ func (b *StorageBackend) FirstServing() <-chan struct{} { return b.firstServing // The caller owns mu; publication never calls the store or waits for I/O. func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) { flipped := !ok && b.operational.Load() + if ok { + b.recoveryErr = nil + } b.opEvidence.Store(evidence) b.operational.Store(ok) if ok && !b.served { @@ -914,6 +927,9 @@ func (b *StorageBackend) readyCheck() error { closed := b.closed chunkFenced := b.chunkFenced observerErr := b.observerErr + recoveryErr := b.recoveryErr + operational := b.operational.Load() + ev, _ := b.opEvidence.Load().(string) precopyPending := b.precopy != nil && b.precopy.active b.mu.Unlock() if closed { @@ -928,9 +944,8 @@ func (b *StorageBackend) readyCheck() error { if precopyPending { return errPrecopyPaused } - if !b.operational.Load() { - ev, _ := b.opEvidence.Load().(string) - return fmt.Errorf("%w: %s", frontend.ErrNotReady, ev) + if !operational { + return fmt.Errorf("%w: %s", errors.Join(frontend.ErrNotReady, recoveryErr), ev) } return nil } From d8128044435637fa1f17e09d1fbd28a00e4577dc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:33:20 -0800 Subject: [PATCH 18/23] test: clear repaired recovery causes before later readiness pauses --- .../frontend/durable/recovery_permanent_test.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/seaweed-block/core/frontend/durable/recovery_permanent_test.go b/seaweed-block/core/frontend/durable/recovery_permanent_test.go index 7ef566f531..8c9cb1ca18 100644 --- a/seaweed-block/core/frontend/durable/recovery_permanent_test.go +++ b/seaweed-block/core/frontend/durable/recovery_permanent_test.go @@ -67,4 +67,17 @@ func TestRecoveryStoreFaultRemainsPermanentAtGuestIO(t *testing.T) { if !errors.Is(err, storage.ErrWALIntegrityFault) { t.Errorf("guest error lost permanent WAL-integrity cause: %v", err) } + // A later successful recovery clears the old cause. A subsequent ordinary + // readiness pause must not inherit a repaired fault's permanent class. + restore() + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatalf("recovery after repair: %v", err) + } + readEq(t, s, 5, block(0xA7), "repaired acknowledged record") + b.SetOperational(false, "maintenance pause") + _, err = b.Read(ctx, 5, make([]byte, 4096)) + if !errors.Is(err, frontend.ErrNotReady) || errors.Is(err, storage.ErrWALIntegrityFault) || + frontend.ClassifyBackendError(ctx, err) != frontend.BackendErrorNotReady { + t.Fatalf("ordinary pause retained the repaired recovery fault: %v", err) + } } From 814fb36a92de0c6c8f4a159c42b0f4e5dcc0ec84 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 20:44:09 -0800 Subject: [PATCH 19/23] docs: trace per-slot heartbeat ingest guards and freshness default --- seaweed-block/docs/design/invariants.md | 28 ++++++++++++++++++++++++- seaweed-block/docs/operator-guide.md | 2 +- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ac65b7368d..a2818d5a82 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -81,6 +81,32 @@ Recovery warnings such as `wal_hole_suspected` are recorded in Serving without c blockmaster's publisher is the only component that mints epochs. Diagrams: the assignment lifecycle in [core §1.5](block-design.md#15-authority-blockmaster-assignments-epochs-leases), and the workspace lease and move in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves). +**Heartbeat observations, per server/volume/replica slot.** + +`ObservationStore.ingest` compares each reported slot only with that slot's +stored timestamp (`slotObservedAt`). An older slot is dropped and counted; +an equal or newer slot is accepted. A mixed report merges accepted slots and +retains every other stored slot. An all-superseded nonempty report changes no +observation or health transition. Accepted slots keep their own freshness; +server metadata keeps its newest timestamp without lending it to another slot. + +```mermaid +flowchart LR + Report[Receive heartbeat report] --> Compare{Each slot: stored timestamp newer?} + Compare -->|yes| Drop[Drop and count only that slot] + Compare -->|no| Accept[Accept that slot and its health transition] + Drop --> Mixed{Any accepted slots or an empty report?} + Accept --> Mixed + Mixed -->|yes| Merge[Merge accepted slots; retain other slots and newest server metadata] + Mixed -->|no| Keep[Keep stored observations unchanged] +``` + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| Stored observations | Stored observations (slot refused) | stored timestamp for this server/volume/replica is strictly newer than the report; drop and count only this slot | `core/authority/observation_store.go` `ingest`, `slotObservedAt` | `INV-OBS-SLOT-ORDER-001` | +| Stored observations | Stored observations (mixed report merged) | accept equal/newer slots against their own stored timestamp; merge only accepted slots, preserving other slots and independent freshness | `core/authority/observation_store.go` `ingest`, `mergeServerSlots` | `INV-OBS-SLOT-ORDER-001` | +| Stored observations | Stored observations (no mutation) | a nonempty report has no accepted slot; publish no observation mutation or health transition | `core/authority/observation_store.go` `ingest` | `INV-OBS-SLOT-ORDER-001` | + **Assignment line, per volume.** | From | To | Event and guard | Enforced in | Protects | @@ -930,7 +956,7 @@ Notes: | `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE | | `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE | | `INV-OBS-PRODUCT-EVENTS-001` | blockmaster records placement-verified, promotion-candidate-evaluation and authority-published events, and the CSI node reports `csi_reattach_observed` after a successful stage. | M3 promotion decision (observation) | `core/host/master/product_loop.go` `recordPlacementVerifiedEvents`, `recordPromotionEvaluationEvents`, `recordAuthorityPublishedEvent` | `TestMasterTimeline_RecordsPlacementVerified`, `TestMasterTimeline_RecordsPromotionCandidateEvaluation`, `TestMasterTimeline_RecordsAuthorityPublishedAfterMint` (`core/host/master/event_ring_test.go`); `TestNodeStage_ReportsCSIReattachObservedAfterSuccessfulStage` (`core/csi/node_test.go`) | — | ACTIVE | -| `INV-OBS-SLOT-ORDER-001` | A heartbeat slot (server, volume, replica) is ordered only against that slot's own previous heartbeat: a later-stamped heartbeat of another slot of the same server never supersedes it. | AUTHORITY/ORDER: per-slot heartbeat ingest (V1-SPEC r2.53) | `core/authority/observation_store.go` `ingest` (per-slot comparison), `slotObservedAt`; `SupersededSlotCount` (diagnostic only) | `TestObservationStore_InterleavedSendersOrderPerSlot`, `TestObservationStore_MixedSlotReportKeepsOnlyNewerFacts`, `TestObservationStore_SupersededSlotLogsAfterUnlock` (`core/authority/observation_store_slot_order_test.go`) | 1.0 limit: a backward wall-clock step longer than the freshness window expires that host's slots; 1.0.1: per-process sequence. | ACTIVE | +| `INV-OBS-SLOT-ORDER-001` | A heartbeat slot (server, volume, replica) is ordered only against that slot's own previous heartbeat: a later-stamped heartbeat of another slot of the same server never supersedes it. | M2 heartbeat observations: per-slot refusal / mixed merge / all-superseded no mutation (V1-SPEC r2.53) | `core/authority/observation_store.go` `ingest` (per-slot comparison), `slotObservedAt`; `SupersededSlotCount` (diagnostic only) | `TestObservationStore_InterleavedSendersOrderPerSlot`, `TestObservationStore_MixedSlotReportKeepsOnlyNewerFacts`, `TestObservationStore_SupersededSlotLogsAfterUnlock` (`core/authority/observation_store_slot_order_test.go`) | 1.0 limit: a backward wall-clock step longer than the freshness window expires that host's slots; 1.0.1: per-process sequence. | ACTIVE | | `INV-OBS-SLOT-FROM-EXPECTED-SERVER-001` | A replica's slot in the assembled topology takes addresses and health only from a fresh fact reported by the server its expected slot names; another server's fact for the same replica is never used, so with none from that server the slot is a placeholder. | AUTHORITY/ORDER: observation to assignment line | `core/authority/snapshot_builder.go` `assembleVolumeTopology` | `TestAssembleVolumeTopology_SlotFactOnlyFromTheExpectedServer` (`core/authority/snapshot_slot_server_test.go`) | — (pure assembly; the unit test is the proof form) | ACTIVE | | `INV-HELM-RF-NODECOUNT-001` | Generated Helm values fail closed when the requested replication factor exceeds the selected Ready schedulable node count. | M3 (configuration) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`, `selectHelmValuesNodes` | `TestOpsGenerateHelmValuesRejectsRFAboveSelectedNodes` (`cmd/sw-block/main_test.go`) | — | ACTIVE | | `INV-HOSTPATH-TRANSPARENT-001` | The read model reports transparent host-path recovery only with a multipathed, Active/Optimized, stale-fenced path, writer and reader checks, and the same pod UID. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume`, `deriveManagedVolumeStates` | `TestManagedVolumeProjection_TransparentISCSIALUARecovered`, `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index cbff179009..a3e6d5b7c3 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -56,7 +56,7 @@ one live blockvolume per volume ([one process per volume](releases/one-process-p Each volume process reports its own heartbeat slot (server, volume and replica). The master orders each slot against that slot's previous report. In version 1.0, -a backward host-clock step longer than the freshness window (10 seconds by +a backward host-clock step longer than the freshness window (30 seconds by default) can expire the host's slots; keep host clocks synchronized. ## Recovery point and sync policy From 1cb54e69a4365af83e3478c33cafe7d7397d370c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 20:46:10 -0800 Subject: [PATCH 20/23] test: verify recovery faults and repaired reads through backend gate --- .../frontend/durable/recovery_permanent_test.go | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/frontend/durable/recovery_permanent_test.go b/seaweed-block/core/frontend/durable/recovery_permanent_test.go index 8c9cb1ca18..ed0ad1ff80 100644 --- a/seaweed-block/core/frontend/durable/recovery_permanent_test.go +++ b/seaweed-block/core/frontend/durable/recovery_permanent_test.go @@ -1,6 +1,7 @@ package durable_test import ( + "bytes" "context" "errors" "path/filepath" @@ -57,9 +58,9 @@ func TestRecoveryStoreFaultRemainsPermanentAtGuestIO(t *testing.T) { if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrWALIntegrityFault) { t.Fatalf("expected real WAL integrity recovery failure: %v", err) } - _, err = b.Read(ctx, 5, make([]byte, 4096)) - if err == nil { - t.Fatal("failed recovery admitted a guest read") + n, err := b.Read(ctx, 5*4096, make([]byte, 4096)) + if n != 0 || !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("failed recovery guest read: n=%d, want 0 and not-ready: %v", n, err) } if got := frontend.ClassifyBackendError(ctx, err); got != frontend.BackendErrorPermanent { t.Errorf("store-fault recovery became guest retry class %v, want permanent: %v", got, err) @@ -73,9 +74,14 @@ func TestRecoveryStoreFaultRemainsPermanentAtGuestIO(t *testing.T) { if _, err := p.RecoverVolume(ctx, "v1"); err != nil { t.Fatalf("recovery after repair: %v", err) } - readEq(t, s, 5, block(0xA7), "repaired acknowledged record") + want := block(0xA7) + got := make([]byte, len(want)) + n, err = b.Read(ctx, 5*4096, got) + if err != nil || n != len(want) || !bytes.Equal(got, want) { + t.Fatalf("repaired acknowledged record through backend: n=%d, want %d; matching bytes=%t: %v", n, len(want), bytes.Equal(got, want), err) + } b.SetOperational(false, "maintenance pause") - _, err = b.Read(ctx, 5, make([]byte, 4096)) + _, err = b.Read(ctx, 5*4096, make([]byte, 4096)) if !errors.Is(err, frontend.ErrNotReady) || errors.Is(err, storage.ErrWALIntegrityFault) || frontend.ClassifyBackendError(ctx, err) != frontend.BackendErrorNotReady { t.Fatalf("ordinary pause retained the repaired recovery fault: %v", err) From a3b43ed86dce875c2d4f42b2450d1ed5192bfd99 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 20:47:32 -0800 Subject: [PATCH 21/23] docs: recompute the Part B count for train 29 #453 and #448 each add one ACTIVE row. 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 43aea02dcd..d82663bad3 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -493,7 +493,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -316 rows: 245 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 301 new. +317 rows: 246 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 302 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. From d031cb004017433d5cf18cbace604f07e1d9355e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 20:49:06 -0800 Subject: [PATCH 22/23] chunkstore: test expired legacy fork preparation --- .../chunkstore/catalog_deadline_test.go | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/seaweed-block/core/frontend/chunkstore/catalog_deadline_test.go b/seaweed-block/core/frontend/chunkstore/catalog_deadline_test.go index 0eaf5813f4..e8efff29a3 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_deadline_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_deadline_test.go @@ -2,6 +2,7 @@ package chunkstore import ( "context" + "fmt" "strings" "testing" "time" @@ -141,3 +142,52 @@ func TestFork_ExpiredAttemptWritesNoNewMetadata(t *testing.T) { } } } + +// The frozen flat snapshot forces the manifest-upgrade path to create an +// intent before uploading its segment; count creates, even if later removed. +func TestFork_ExpiredLegacyPreparationWritesNoIntent(t *testing.T) { + for _, origin := range []string{OriginFork, OriginRestore} { + for _, expired := range []bool{true, false} { + t.Run(fmt.Sprintf("%s/expired=%t", origin, expired), func(t *testing.T) { + f, c, r := preF4ForkFixture(t, false) + now := time.Unix(1800000000, 0) + start := now + c.SetClock(func() time.Time { return now }) + intents := 0 + f.beforeCreate = func(p string) { + if p == catBase+"/v3/VOLUME" && expired { + now = start.Add(DefaultOpDeadline) + } + if strings.HasPrefix(p, catBase+"/v3/intents/") { + intents++ + } + } + req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "legacy-deadline"} + var err error + if origin == OriginFork { + _, err = c.Fork(context.Background(), req) + } else { + _, err = c.Restore(context.Background(), req) + } + f.beforeCreate = nil + if expired { + if CodeOf(err) != CodeDeadlineExceeded || intents != 0 { + t.Fatalf("expired legacy attempt: err=%v intent creates=%d; want deadline and zero", err, intents) + } + if _, err := f.LookupEntry(context.Background(), catBase+"/v3", headName); err == nil { + t.Fatal("expired legacy attempt published HEAD") + } + } else { + if err != nil || intents != 2 { + t.Fatalf("live legacy attempt: err=%v intent creates=%d; want success and upgrade+copy intents", err, intents) + } + dst, err := NewChunkRemote(f, r.b, catBase+"/v3") + if err != nil { + t.Fatal(err) + } + assertLegacyImage(t, dst) + } + }) + } + } +} From 5e42d8eeee0276791ec2de097233d220e2d07b0e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 20:51:03 -0800 Subject: [PATCH 23/23] chunkstore: check fork deadline before legacy manifest preparation --- seaweed-block/core/frontend/chunkstore/catalog.go | 3 +++ seaweed-block/docs/design/agent-workspace-design.md | 2 ++ seaweed-block/docs/design/invariants.md | 4 ++-- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index dcbf98c020..0ffd60eb65 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -1359,6 +1359,9 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For existing = vol } + if !c.now().Before(deadline) { + return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: deadline passed; manifest preparation not started", req.Target) + } head, upgradeIDs, err := c.prepareLegacyHead(ctx, dstRoot, storage.ChunkHead{}, head, snap.geo) defer c.dropManifestIntents(ctx, dstRoot, upgradeIDs) if err != nil { diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index ef5d1db91a..1877eaed89 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -230,6 +230,8 @@ stateDiagram-v2 NameHeld --> Published: exclusive create snaps/name/attempt NameHeld --> Aborted: DeleteSnapshot or GC tombstones the attempt path Published --> Deleting: DeleteSnapshot or retention (forks do not hold it) + Published --> ForkTarget: deadline live before VOLUME, legacy preparation, copy intent and HEAD + ForkTarget --> ActiveTarget: exclusive HEAD create before deadline (fork or restore) Deleting --> NameFreed: name record removed Aborted --> NameFreed: name record removed NameFreed --> [*] diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 204ae4e441..d9f0c46fd6 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -349,7 +349,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | 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, check start + deadline before the target `VOLUME`, copy intent and HEAD writes; 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 | 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, check start + deadline before the target `VOLUME`, legacy manifest preparation, copy intent and HEAD writes; 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` | @@ -874,7 +874,7 @@ Notes: | `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 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`); `TestFork_ExpiredAttemptWritesNoNewMetadata` (`core/frontend/chunkstore/catalog_deadline_test.go`) | `ForkDelete` `NoGap` | 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` | `TestFork_ExpiredAttemptWritesNoNewMetadata`, `TestFork_ExpiredLegacyPreparationWritesNoIntent` (`core/frontend/chunkstore/catalog_deadline_test.go`); `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 |