From 248a861fedf22c7ce6d6333fff7c4cd75afc3402 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 15:36:41 -0800 Subject: [PATCH 01/71] 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/71] 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/71] 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/71] 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 a384998a6472587b1b5ddebeb458c557b344501e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 15:51:27 -0800 Subject: [PATCH 05/71] test: snapshot ladder B1 (query) and C1-C3 (restore), not yet gated B1: the list is exactly the committed snapshots, in order, active, with the point, generation and chunk count their creation answered; a prefix shows one; a snapshot being taken is listed only committed and stays; a refused snapshot (a restore volume not yet independent) leaves no name. C1: a five-chunk image restored to independence equals the snapshot block by block. C2: the second and the third incremental snapshots restore to independence as their points. C3: a restored volume, once independent, written and snapshotted, restores with its writes, and the source's snapshot still restores unchanged. Co-Authored-By: Claude Opus 5.5 --- .../snapshot_ladder_integration_test.go | 268 +++++++++++++++++- 1 file changed, 262 insertions(+), 6 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go index 2f39950842..cc4dfd3d38 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go @@ -181,19 +181,143 @@ func (env *handoffEnv) writeDuringSnapshot(t *testing.T, name string, first uint } } -// snapshot takes the named snapshot of vol on its host and checks the answer -// names it. -func (env *handoffEnv) snapshot(t *testing.T, hostID, vol, name string) { +// snapshotInfo is what a snapshot's answer and its list entry say about it. +type snapshotInfo struct { + Name string `json:"name"` + HeadGen uint64 `json:"headGen"` + CutLSN uint64 `json:"cutLSN"` + State string `json:"state"` + ChunkCount int `json:"chunkCount"` +} + +// snapshot takes the named snapshot of vol on its host, checks the answer +// names it, and returns the answer. +func (env *handoffEnv) snapshot(t *testing.T, hostID, vol, name string) snapshotInfo { t.Helper() out, _ := env.h.command(t, "ops", "chunk", "snapshot", "--volume", vol, "--status-addr", env.hosts[hostID].status, "--name", name) - var info struct { - Name string `json:"name"` - } + var info snapshotInfo if err := json.Unmarshal([]byte(out), &info); err != nil || info.Name != name { t.Fatalf("snapshot %s of %s: %v\n%s", name, vol, err, out) } + return info } +// snapshots lists vol's snapshots (with a name prefix when given). +func (env *handoffEnv) snapshots(t *testing.T, vol, prefix string) []snapshotInfo { + t.Helper() + args := []string{"ops", "chunk", "snapshots", "--volume", vol, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath} + if prefix != "" { + args = append(args, "--prefix", prefix) + } + out, _ := env.h.command(t, args...) + var body struct { + Snapshots []snapshotInfo `json:"snapshots"` + } + if err := json.Unmarshal([]byte(out), &body); err != nil { + t.Fatalf("snapshots of %s: %v\n%s", vol, err, out) + } + return body.Snapshots +} + +// restoreAttached creates target from snapshot snap of src and starts its +// blockvolume, but not the restore driver: target serves and stays +// dependent on its source (not independent). +func (env *handoffEnv) restoreAttached(t *testing.T, src, snap, target string) { + t.Helper() + b := env.hosts["n-"+target] + env.h.command(t, "ops", "chunk", "restore", "--source", src, "--snapshot", snap, "--target", target, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + d := env.h.start(t, "blockvolume-"+target, env.h.volume, env.volArgsFor(b)...) + d.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at r1@", target)) + poll(t, 60*time.Second, fmt.Sprintf("%s never reported its frontend ready", target), func() bool { + return volumeFrontendReady(b.status, target) + }) +} + +// TestSnapshotLadderB1SnapshotQuery: three snapshots with writes between +// them. The list is exactly the committed snapshots, in order, each active, +// with the point (cut LSN), HEAD generation and size (chunk count) its +// creation answered; a prefix shows one. A snapshot being taken appears in +// the list only committed, and stays. A snapshot request that is refused +// (a restore volume not yet independent) leaves no name in the list. +func TestSnapshotLadderB1SnapshotQuery(t *testing.T) { + env := startLadderEnv(t, "v2") + var made []snapshotInfo + for i, w := range []struct { + lba uint64 + text string + }{{0, "ladder-b1-blk-A!"}, {2 * ladderChunkBlocks, "ladder-b1-blk-B!"}, {1, "ladder-b1-blk-C!"}} { + env.writeBlock(t, "s1", w.lba, pattern(w.text)) + made = append(made, env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1))) + } + list := env.snapshots(t, "v1", "") + if len(list) != len(made) { + t.Fatalf("list has %d snapshots; want exactly the %d committed: %+v", len(list), len(made), list) + } + wantChunks := []int{1, 2, 2} + for i, got := range list { + m := made[i] + if got.Name != m.Name || got.State != "active" || got.CutLSN != m.CutLSN || got.HeadGen != m.HeadGen || got.ChunkCount != m.ChunkCount { + t.Fatalf("list entry %d %+v; want %+v, active", i, got, m) + } + if got.ChunkCount != wantChunks[i] { + t.Fatalf("%s holds %d chunks; want %d", got.Name, got.ChunkCount, wantChunks[i]) + } + if i > 0 && (got.CutLSN <= list[i-1].CutLSN || got.HeadGen <= list[i-1].HeadGen) { + t.Fatalf("list not in order of points: %+v after %+v", got, list[i-1]) + } + } + if one := env.snapshots(t, "v1", "s2"); len(one) != 1 || one[0].Name != "s2" || one[0].CutLSN != made[1].CutLSN { + t.Fatalf("show s2: %+v", one) + } + + // A snapshot being taken: listed only committed, and then it stays. + done := make(chan int, 1) + go func() { + _, _, code := env.h.run(t, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status, "--name", "s4") + done <- code + }() + env.writeBlock(t, "s1", 3, pattern("ladder-b1-blk-D!")) + seen := false + for running := true; running; { + select { + case code := <-done: + if code != 0 { + t.Fatalf("snapshot s4: exit %d", code) + } + running = false + default: + } + var s4 *snapshotInfo + for _, e := range env.snapshots(t, "v1", "s4") { + e := e + s4 = &e + } + switch { + case s4 == nil && seen: + t.Fatal("s4 was listed, then disappeared") + case s4 != nil && (s4.State != "active" || s4.CutLSN <= made[2].CutLSN || s4.HeadGen <= made[2].HeadGen): + t.Fatalf("s4 listed before it was committed: %+v", *s4) + case s4 != nil: + seen = true + } + } + if !seen && len(env.snapshots(t, "v1", "s4")) != 1 { + t.Fatal("s4 not listed after its snapshot returned") + } + + // A refused snapshot is not a snapshot. + env.restoreAttached(t, "v1", "s1", "v2") + out, errOut, code := env.h.run(t, "ops", "chunk", "snapshot", "--volume", "v2", "--status-addr", env.hosts["n-v2"].status, "--name", "x") + if code == 0 || !strings.Contains(out+errOut, "restore_incomplete") { + t.Fatalf("snapshot of a restore volume not yet independent: exit %d, want restore_incomplete\n%s\n%s", code, out, errOut) + } + if l := env.snapshots(t, "v2", ""); len(l) != 0 { + t.Fatalf("a refused snapshot left %+v in the list", l) + } +} + + // lastCutUploads is the number of chunks the last cut of vol uploaded, from // its host's durable status. func (env *handoffEnv) lastCutUploads(t *testing.T, hostID, vol string) int { @@ -294,3 +418,135 @@ func volumeFrontendReady(statusAddr, vol string) bool { b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) return frontendReady(b) } + +// waitIndependent polls the restore status of target until its phase is +// independent (it then holds every chunk under its own keys). +func (env *handoffEnv) waitIndependent(t *testing.T, target string) { + t.Helper() + poll(t, 120*time.Second, fmt.Sprintf("%s never became independent", target), func() bool { + out, _, code := env.h.run(t, "ops", "chunk", "restore", "--volume", target, "--status-addr", env.hosts["n-"+target].status, "--status") + var st struct { + Phase string `json:"phase"` + ErrorCode string `json:"errorCode"` + } + if code != 0 || json.Unmarshal([]byte(out), &st) != nil { + return false + } + if st.Phase == "failed" { + t.Fatalf("restore of %s failed: %s", target, out) + } + return st.Phase == "independent" + }) +} + +// ladderImage is a written picture of a volume: blocks in several chunks. +func ladderImage(tag string, chunks []uint64, perChunk int) map[uint64][]byte { + img := map[uint64][]byte{} + for _, c := range chunks { + for i := 0; i < perChunk; i++ { + lba := c*ladderChunkBlocks + uint64(i)*37 + img[lba] = pattern(fmt.Sprintf("%-8s%08d", tag, lba)[:16]) + } + } + return img +} + +func (env *handoffEnv) writeImage(t *testing.T, hostID string, img map[uint64][]byte) { + t.Helper() + c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN) + defer c.close() + for lba, b := range img { + c.write(t, lba, b) + } + c.flush(t) +} + +// requireImage reads every block of img on the host and the zeros next to +// each written run, and the edge blocks. +func (env *handoffEnv) requireImage(t *testing.T, hostID string, img map[uint64][]byte) { + t.Helper() + zero := make([]byte, 4096) + c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN) + defer c.close() + for lba, want := range img { + if got := c.read(t, lba, 4096); !bytes.Equal(got, want) { + t.Fatalf("%s: block %d differs from the snapshot", hostID, lba) + } + if _, written := img[lba+1]; !written && lba+1 <= ladderLastBlock { + if got := c.read(t, lba+1, 4096); !bytes.Equal(got, zero) { + t.Fatalf("%s: block %d should be zero", hostID, lba+1) + } + } + } + c.close() + env.requireEdges(t, hostID) +} + +func mergeImages(imgs ...map[uint64][]byte) map[uint64][]byte { + out := map[uint64][]byte{} + for _, img := range imgs { + for k, v := range img { + out[k] = v + } + } + return out +} + +// TestSnapshotLadderC1FullRestore: blocks in five chunks are written and a +// snapshot taken; its restore into a new volume runs to independence (every +// chunk under its own keys) and then equals the snapshot block by block. +func TestSnapshotLadderC1FullRestore(t *testing.T) { + env := startLadderEnv(t, "v2") + img := ladderImage("c1", []uint64{0, 1, 7, 20, 63}, 8) + env.writeImage(t, "s1", img) + env.snapshot(t, "s1", "v1", "full") + env.restoreInto(t, "v1", "full", "v2") + env.waitIndependent(t, "v2") + env.requireImage(t, "n-v2", img) +} + +// TestSnapshotLadderC2IncrementalRestore: three snapshots, each after more +// writes; the restores of the second and the third, each to independence, +// equal those snapshots (the earlier writes and theirs, nothing later). +func TestSnapshotLadderC2IncrementalRestore(t *testing.T) { + env := startLadderEnv(t, "v2", "v3") + img1 := ladderImage("c2one", []uint64{0, 5}, 4) + img2 := ladderImage("c2two", []uint64{5, 9}, 3) // overwrites some of chunk 5 + img3 := ladderImage("c2three", []uint64{0, 30}, 2) + env.writeImage(t, "s1", img1) + env.snapshot(t, "s1", "v1", "s1") + env.writeImage(t, "s1", img2) + env.snapshot(t, "s1", "v1", "s2") + env.writeImage(t, "s1", img3) + env.snapshot(t, "s1", "v1", "s3") + + env.restoreInto(t, "v1", "s2", "v2") + env.waitIndependent(t, "v2") + env.requireImage(t, "n-v2", mergeImages(img1, img2)) + env.restoreInto(t, "v1", "s3", "v3") + env.waitIndependent(t, "v3") + env.requireImage(t, "n-v3", mergeImages(img1, img2, img3)) +} + +// TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt: a restored volume, +// once independent, is written and snapshotted itself; that snapshot holds +// its writes, and the source's snapshot still restores unchanged. +func TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt(t *testing.T) { + env := startLadderEnv(t, "v2", "v3", "v4") + src := ladderImage("c3src", []uint64{0, 3}, 4) + env.writeImage(t, "s1", src) + env.snapshot(t, "s1", "v1", "base") + + env.restoreInto(t, "v1", "base", "v2") + env.waitIndependent(t, "v2") + own := ladderImage("c3own", []uint64{3, 11}, 3) + env.writeImage(t, "n-v2", own) + env.snapshot(t, "n-v2", "v2", "mine") + + env.restoreInto(t, "v2", "mine", "v3") + env.waitIndependent(t, "v3") + env.requireImage(t, "n-v3", mergeImages(src, own)) + env.restoreInto(t, "v1", "base", "v4") // the source's snapshot is unchanged + env.waitIndependent(t, "v4") + env.requireImage(t, "n-v4", src) +} From b9d304317156308426251465c4c4be409a3d6c65 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 16:06:47 -0800 Subject: [PATCH 06/71] test: snapshot ladder D1-D4 (deletes and the collector), not yet gated Co-Authored-By: Claude Opus 5.5 --- .../snapshot_ladder_d_integration_test.go | 203 ++++++++++++++++++ 1 file changed, 203 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go new file mode 100644 index 0000000000..908bc1a075 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go @@ -0,0 +1,203 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "encoding/json" + "fmt" + "testing" + "time" +) + +// Rung D of the snapshot ladder: deletes. A deleted snapshot leaves every +// other snapshot restorable, whichever one is deleted (the newest, a middle +// one, one whose content recurs later), and after the collector has run the +// store holds only what the remaining manifests reference. +// +// The collector's grace may not be shorter than the operation deadline plus +// the clock skew plus the CAS apply bound (11 minutes with the defaults), and +// an unreferenced chunk is reclaimed only by a second mark at least the grace +// after the first, on a chunk older than the grace: D4 runs for about 25 +// minutes. + +const ( + ladderGCGrace = 11 * time.Minute + // ladderGCWait is the grace plus the collector's clock skew allowance + // and its one-second timestamp resolution, with a margin. + ladderGCWait = ladderGCGrace + time.Minute + 15*time.Second +) + +// deleteSnapshot deletes vol's snapshot name and checks the answer names it. +func (env *handoffEnv) deleteSnapshot(t *testing.T, vol, name string) { + t.Helper() + out, _ := env.h.command(t, "ops", "chunk", "snapshot-delete", "--volume", vol, "--name", name, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + var body struct { + VolumeID string `json:"volumeID"` + Name string `json:"name"` + } + if err := json.Unmarshal([]byte(out), &body); err != nil || body.Name != name { + t.Fatalf("delete %s of %s: %v\n%s", name, vol, err, out) + } +} + +// requireSnapshotNames checks vol's snapshot list is exactly names, in order. +func (env *handoffEnv) requireSnapshotNames(t *testing.T, vol string, names ...string) { + t.Helper() + list := env.snapshots(t, vol, "") + ok := len(list) == len(names) + for i := 0; ok && i < len(list); i++ { + ok = list[i].Name == names[i] && list[i].State == "active" + } + if !ok { + t.Fatalf("snapshots of %s: %+v; want exactly %v, active", vol, list, names) + } +} + +// ladderUsage is what the usage command says about a volume's store. +type ladderUsage struct { + ManifestBindings int `json:"manifestBindings"` + StoredBindings int `json:"storedBindings"` + StoredUpperBound bool `json:"storedUpperBound"` +} + +func (env *handoffEnv) usage(t *testing.T, vol string) ladderUsage { + t.Helper() + out, _ := env.h.command(t, "ops", "chunk", "usage", "--volume", vol, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + var u ladderUsage + if err := json.Unmarshal([]byte(out), &u); err != nil { + t.Fatalf("usage of %s: %v\n%s", vol, err, out) + } + return u +} + +// gc runs one applying collector pass and returns how many chunks it +// reclaimed. +func (env *handoffEnv) gc(t *testing.T) int { + t.Helper() + out, _ := env.h.command(t, "ops", "chunk", "gc", "--master", env.h.masterAddr, "--apply", "--grace", ladderGCGrace.String(), + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + var body struct { + MarkSaved bool `json:"mark_saved"` + UnknownOutcomes []string `json:"unknown_outcomes"` + FailedDeletes []any `json:"failed_deletes"` + Candidates int + Reclaimed int + } + if err := json.Unmarshal([]byte(out), &body); err != nil || !body.MarkSaved || len(body.UnknownOutcomes) != 0 || len(body.FailedDeletes) != 0 { + t.Fatalf("gc pass: %v\n%s", err, out) + } + t.Logf("gc pass: %d candidates, %d reclaimed", body.Candidates, body.Reclaimed) + return body.Reclaimed +} + +// restoreChecked restores snap of v1 into target to independence and checks +// it equals img. +func (env *handoffEnv) restoreChecked(t *testing.T, snap, target string, img map[uint64][]byte) { + t.Helper() + env.restoreInto(t, "v1", snap, target) + env.waitIndependent(t, target) + env.requireImage(t, "n-"+target, img) +} + +// TestSnapshotLadderD1DeleteTheNewest: three snapshots over overlapping +// chunks; the newest is deleted; the other two restore as they were. +func TestSnapshotLadderD1DeleteTheNewest(t *testing.T) { + env := startLadderEnv(t, "v2", "v3") + img1 := ladderImage("d1one", []uint64{0, 4}, 4) + img2 := ladderImage("d1two", []uint64{4, 8}, 3) + img3 := ladderImage("d1three", []uint64{0, 8}, 2) + for i, img := range []map[uint64][]byte{img1, img2, img3} { + env.writeImage(t, "s1", img) + env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1)) + } + env.deleteSnapshot(t, "v1", "s3") + env.requireSnapshotNames(t, "v1", "s1", "s2") + env.restoreChecked(t, "s1", "v2", img1) + env.restoreChecked(t, "s2", "v3", mergeImages(img1, img2)) +} + +// TestSnapshotLadderD2DeleteAMiddleOne: four snapshots, each sharing chunks +// with its neighbours; the second is deleted; the first, the third and the +// fourth restore as they were (the deleted one's chunks that a neighbour or a +// later snapshot still uses are kept). +func TestSnapshotLadderD2DeleteAMiddleOne(t *testing.T) { + env := startLadderEnv(t, "v2", "v3", "v4") + img1 := ladderImage("d2one", []uint64{0, 2}, 4) + img2 := ladderImage("d2two", []uint64{2, 5}, 3) // chunk 2 shared with s1, chunk 5 kept by s3 + img3 := ladderImage("d2three", []uint64{0, 9}, 2) + img4 := ladderImage("d2four", []uint64{9, 12}, 2) + for i, img := range []map[uint64][]byte{img1, img2, img3, img4} { + env.writeImage(t, "s1", img) + env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1)) + } + env.deleteSnapshot(t, "v1", "s2") + env.requireSnapshotNames(t, "v1", "s1", "s3", "s4") + env.restoreChecked(t, "s1", "v2", img1) + env.restoreChecked(t, "s3", "v3", mergeImages(img1, img2, img3)) + env.restoreChecked(t, "s4", "v4", mergeImages(img1, img2, img3, img4)) +} + +// TestSnapshotLadderD3DeleteWhenContentRecurs: the A, B, A volume of A4 +// (one block holds A, then B, then A again, a snapshot after each); the +// first snapshot is deleted; the third, whose content equals the first's, +// and the second restore as they were. +func TestSnapshotLadderD3DeleteWhenContentRecurs(t *testing.T) { + env := startLadderEnv(t, "v2", "v3") + a, b := pattern("ladder-d3-blk-A!"), pattern("ladder-d3-blk-B!") + for i, content := range [][]byte{a, b, a} { + env.writeBlock(t, "s1", 7, content) + env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1)) + } + env.deleteSnapshot(t, "v1", "s1") + env.requireSnapshotNames(t, "v1", "s2", "s3") + env.restoreChecked(t, "s3", "v2", map[uint64][]byte{7: a}) + env.restoreChecked(t, "s2", "v3", map[uint64][]byte{7: b}) +} + +// TestSnapshotLadderD4DeleteAllButOneThenCollect: three snapshots, each +// overwriting the same chunks; the second and the third are deleted. The +// second's chunks are then referenced by nothing (the third's are still +// HEAD's), and the store holds more than the manifests reference. Two +// collector passes the grace apart reclaim exactly that surplus: the store +// then holds only what the remaining snapshot and HEAD reference, and the +// remaining snapshot and HEAD read as they were. +func TestSnapshotLadderD4DeleteAllButOneThenCollect(t *testing.T) { + env := startLadderEnv(t, "v2") + chunks := []uint64{0, 1, 2, 3} + imgs := []map[uint64][]byte{ladderImage("d4one", chunks, 4), ladderImage("d4two", chunks, 4), ladderImage("d4three", chunks, 4)} + for i, img := range imgs { + env.writeImage(t, "s1", img) + env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1)) + } + env.deleteSnapshot(t, "v1", "s3") + env.deleteSnapshot(t, "v1", "s2") + env.requireSnapshotNames(t, "v1", "s1") + written := time.Now() + + before := env.usage(t, "v1") + surplus := before.StoredBindings - before.ManifestBindings + t.Logf("before the collector: %+v", before) + if surplus < len(chunks) || !before.StoredUpperBound { + t.Fatalf("after the deletes the store holds %d unreferenced chunks; want at least the %d of s2", surplus, len(chunks)) + } + + time.Sleep(time.Until(written.Add(ladderGCWait))) // the chunks are older than the grace + reclaimed := env.gc(t) + first := time.Now() + time.Sleep(time.Until(first.Add(ladderGCWait))) // a second mark the grace after the first + reclaimed += env.gc(t) + + after := env.usage(t, "v1") + t.Logf("after the collector: %+v", after) + if after.StoredBindings != after.ManifestBindings || after.StoredUpperBound || reclaimed != surplus { + t.Fatalf("after the collector the store holds %d chunks, the manifests reference %d (upper bound %v); reclaimed %d of %d", + after.StoredBindings, after.ManifestBindings, after.StoredUpperBound, reclaimed, surplus) + } + if after.ManifestBindings != before.ManifestBindings { + t.Fatalf("the collector changed what the manifests reference: %d, was %d", after.ManifestBindings, before.ManifestBindings) + } + env.requireImage(t, "s1", imgs[2]) + env.restoreChecked(t, "s1", "v2", imgs[0]) +} From 754fc54404a74307922fb5989ce2f08c0f912d2e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 16:28:23 -0800 Subject: [PATCH 07/71] test: snapshot ladder D4 measures reclaimed chunk data in the store Co-Authored-By: Claude Opus 5.5 --- .../snapshot_ladder_d_integration_test.go | 220 +++++++++++++----- 1 file changed, 157 insertions(+), 63 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go index 908bc1a075..d79fd6b58c 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go @@ -5,14 +5,17 @@ package main_test import ( "encoding/json" "fmt" + "io" + "net/http" + "strings" "testing" "time" ) // Rung D of the snapshot ladder: deletes. A deleted snapshot leaves every // other snapshot restorable, whichever one is deleted (the newest, a middle -// one, one whose content recurs later), and after the collector has run the -// store holds only what the remaining manifests reference. +// one, one whose content recurs later), and the collector then reclaims the +// chunk data only the deleted snapshots referenced. // // The collector's grace may not be shorter than the operation deadline plus // the clock skew plus the CAS apply bound (11 minutes with the defaults), and @@ -54,44 +57,6 @@ func (env *handoffEnv) requireSnapshotNames(t *testing.T, vol string, names ...s } } -// ladderUsage is what the usage command says about a volume's store. -type ladderUsage struct { - ManifestBindings int `json:"manifestBindings"` - StoredBindings int `json:"storedBindings"` - StoredUpperBound bool `json:"storedUpperBound"` -} - -func (env *handoffEnv) usage(t *testing.T, vol string) ladderUsage { - t.Helper() - out, _ := env.h.command(t, "ops", "chunk", "usage", "--volume", vol, - "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) - var u ladderUsage - if err := json.Unmarshal([]byte(out), &u); err != nil { - t.Fatalf("usage of %s: %v\n%s", vol, err, out) - } - return u -} - -// gc runs one applying collector pass and returns how many chunks it -// reclaimed. -func (env *handoffEnv) gc(t *testing.T) int { - t.Helper() - out, _ := env.h.command(t, "ops", "chunk", "gc", "--master", env.h.masterAddr, "--apply", "--grace", ladderGCGrace.String(), - "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) - var body struct { - MarkSaved bool `json:"mark_saved"` - UnknownOutcomes []string `json:"unknown_outcomes"` - FailedDeletes []any `json:"failed_deletes"` - Candidates int - Reclaimed int - } - if err := json.Unmarshal([]byte(out), &body); err != nil || !body.MarkSaved || len(body.UnknownOutcomes) != 0 || len(body.FailedDeletes) != 0 { - t.Fatalf("gc pass: %v\n%s", err, out) - } - t.Logf("gc pass: %d candidates, %d reclaimed", body.Candidates, body.Reclaimed) - return body.Reclaimed -} - // restoreChecked restores snap of v1 into target to independence and checks // it equals img. func (env *handoffEnv) restoreChecked(t *testing.T, snap, target string, img map[uint64][]byte) { @@ -156,47 +121,176 @@ func TestSnapshotLadderD3DeleteWhenContentRecurs(t *testing.T) { env.restoreChecked(t, "s2", "v3", map[uint64][]byte{7: b}) } +// gcObject is one chunk object a collector pass names as eligible. +type gcObject struct { + Volume string `json:"volume"` + Key string `json:"key"` + FID string `json:"fid"` +} + +// gc runs one collector pass (applying or a preview) and returns the chunk +// objects it found eligible and how many it reclaimed. +func (env *handoffEnv) gc(t *testing.T, apply bool) ([]gcObject, int) { + t.Helper() + args := []string{"ops", "chunk", "gc", "--master", env.h.masterAddr, "--grace", ladderGCGrace.String(), + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath} + if apply { + args = append(args, "--apply") + } + out, _ := env.h.command(t, args...) + var body struct { + MarkSaved bool `json:"mark_saved"` + UnknownOutcomes []string `json:"unknown_outcomes"` + FailedDeletes []any `json:"failed_deletes"` + WouldDelete []gcObject `json:"would_delete"` + Candidates int + Reclaimed int + } + if err := json.Unmarshal([]byte(out), &body); err != nil || (apply && !body.MarkSaved) || len(body.UnknownOutcomes) != 0 || len(body.FailedDeletes) != 0 { + t.Fatalf("gc pass (apply %v): %v\n%s", apply, err, out) + } + t.Logf("gc pass (apply %v): %d candidates, %d eligible, %d reclaimed", apply, body.Candidates, len(body.WouldDelete), body.Reclaimed) + return body.WouldDelete, body.Reclaimed +} + +// exclusiveBytes is what the usage command says deleting snapshot name of vol +// makes eligible for collection: the chunk bytes no other holder references. +func (env *handoffEnv) exclusiveBytes(t *testing.T, vol, name string) uint64 { + t.Helper() + out, _ := env.h.command(t, "ops", "chunk", "usage", "--volume", vol, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + var u struct { + Snapshots []struct { + Name string `json:"name"` + ExclusiveBytes uint64 `json:"exclusiveBytes"` + } `json:"snapshots"` + } + if err := json.Unmarshal([]byte(out), &u); err != nil { + t.Fatalf("usage of %s: %v\n%s", vol, err, out) + } + for _, s := range u.Snapshots { + if s.Name == name { + return s.ExclusiveBytes + } + } + t.Fatalf("usage of %s has no snapshot %s\n%s", vol, name, out) + return 0 +} + +// blobStored reports whether the weed store still holds the chunk data of +// fid (a volume server answers 200 for it, 404 once it is deleted). +func (env *handoffEnv) blobStored(t *testing.T, fid string) bool { + t.Helper() + c := &http.Client{Timeout: 10 * time.Second} + vid, _, ok := strings.Cut(fid, ",") + if !ok { + t.Fatalf("chunk object fid %q has no volume id", fid) + } + resp, err := c.Get("http://" + env.cluster.master + "/dir/lookup?volumeId=" + vid) + if err != nil { + t.Fatal(err) + } + var lookup struct { + Locations []struct { + URL string `json:"url"` + } `json:"locations"` + } + err = json.NewDecoder(resp.Body).Decode(&lookup) + resp.Body.Close() + if err != nil || len(lookup.Locations) == 0 { + t.Fatalf("weed lookup of volume %s: %v %+v", vid, err, lookup) + } + resp, err = c.Get("http://" + lookup.Locations[0].URL + "/" + fid) + if err != nil { + t.Fatal(err) + } + io.Copy(io.Discard, resp.Body) + resp.Body.Close() + switch resp.StatusCode { + case http.StatusOK: + return true + case http.StatusNotFound: + return false + } + t.Fatalf("weed read of %s: status %d", fid, resp.StatusCode) + return false +} + // TestSnapshotLadderD4DeleteAllButOneThenCollect: three snapshots, each -// overwriting the same chunks; the second and the third are deleted. The -// second's chunks are then referenced by nothing (the third's are still -// HEAD's), and the store holds more than the manifests reference. Two -// collector passes the grace apart reclaim exactly that surplus: the store -// then holds only what the remaining snapshot and HEAD reference, and the -// remaining snapshot and HEAD read as they were. +// overwriting the same four chunks; the third and then the second are +// deleted. The third's chunks are still HEAD's, so only the chunks the +// second's cut uploaded are referenced by nothing; usage says deleting it +// makes chunk bytes eligible. Two collector passes the grace apart reclaim +// the CHUNK DATA of exactly those chunks: a preview before the second pass +// names one eligible object per chunk the second's cut uploaded, each still +// readable from the weed store; the applying pass reclaims those and only +// those, and each is then gone from the store. HEAD still reads the newest +// content and the remaining snapshot restores as it was. +// +// What is measured is chunk data in the weed store, not filer entries, and +// the bound is exact only for objects the collector can enumerate. Excluded, +// known limits of today's format: +// - a reclaimed binding's filer entry is kept for ever (marked reclaimed), +// so filer entry counts and usage's stored bindings and stored bytes do +// not fall after collection and are not compared; +// - a needle uploaded before its binding was written (a retried upload) +// cannot be enumerated and is never reclaimed; a run without upload +// retries makes none, and the test does not look for them. +// +// So after collection the store's enumerable chunk data is at most what HEAD +// and the remaining snapshot reference; unenumerable needles are not bounded. func TestSnapshotLadderD4DeleteAllButOneThenCollect(t *testing.T) { env := startLadderEnv(t, "v2") chunks := []uint64{0, 1, 2, 3} imgs := []map[uint64][]byte{ladderImage("d4one", chunks, 4), ladderImage("d4two", chunks, 4), ladderImage("d4three", chunks, 4)} + uploads := make([]int, len(imgs)) for i, img := range imgs { env.writeImage(t, "s1", img) env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1)) + uploads[i] = env.lastCutUploads(t, "s1", "v1") + } + if uploads[1] != len(chunks) { + t.Fatalf("the second snapshot's cut uploaded %d chunks; want the %d it overwrote", uploads[1], len(chunks)) } env.deleteSnapshot(t, "v1", "s3") + if b := env.exclusiveBytes(t, "v1", "s2"); b == 0 { + t.Fatal("usage says deleting s2 frees no chunk bytes; its four overwritten chunks are referenced by nothing else") + } else { + t.Logf("deleting s2 makes %d chunk bytes eligible", b) + } env.deleteSnapshot(t, "v1", "s2") env.requireSnapshotNames(t, "v1", "s1") - written := time.Now() + deleted := time.Now() - before := env.usage(t, "v1") - surplus := before.StoredBindings - before.ManifestBindings - t.Logf("before the collector: %+v", before) - if surplus < len(chunks) || !before.StoredUpperBound { - t.Fatalf("after the deletes the store holds %d unreferenced chunks; want at least the %d of s2", surplus, len(chunks)) + time.Sleep(time.Until(deleted.Add(ladderGCWait))) // the chunks are older than the grace + if _, n := env.gc(t, true); n != 0 { + t.Fatalf("the first mark reclaimed %d chunks; a chunk is reclaimed only by a second mark", n) } - - time.Sleep(time.Until(written.Add(ladderGCWait))) // the chunks are older than the grace - reclaimed := env.gc(t) first := time.Now() time.Sleep(time.Until(first.Add(ladderGCWait))) // a second mark the grace after the first - reclaimed += env.gc(t) - after := env.usage(t, "v1") - t.Logf("after the collector: %+v", after) - if after.StoredBindings != after.ManifestBindings || after.StoredUpperBound || reclaimed != surplus { - t.Fatalf("after the collector the store holds %d chunks, the manifests reference %d (upper bound %v); reclaimed %d of %d", - after.StoredBindings, after.ManifestBindings, after.StoredUpperBound, reclaimed, surplus) + eligible, _ := env.gc(t, false) + if len(eligible) != uploads[1] { + t.Fatalf("%d chunk objects eligible: %+v; want the %d the second snapshot's cut uploaded", len(eligible), eligible, uploads[1]) } - if after.ManifestBindings != before.ManifestBindings { - t.Fatalf("the collector changed what the manifests reference: %d, was %d", after.ManifestBindings, before.ManifestBindings) + want := map[string]bool{} + for _, o := range eligible { + if o.Volume != "v1" || !env.blobStored(t, o.FID) { + t.Fatalf("eligible object %+v is not v1 chunk data in the store", o) + } + want[o.FID] = true + } + reclaimedObjs, n := env.gc(t, true) + if n != len(want) || len(reclaimedObjs) != len(want) { + t.Fatalf("the second mark reclaimed %d of %d eligible: %+v", n, len(want), reclaimedObjs) + } + for _, o := range reclaimedObjs { + if !want[o.FID] { + t.Fatalf("the second mark reclaimed %+v, which the preview did not name", o) + } + if env.blobStored(t, o.FID) { + t.Fatalf("reclaimed chunk %+v is still in the store", o) + } } env.requireImage(t, "s1", imgs[2]) env.restoreChecked(t, "s1", "v2", imgs[0]) From 9bd8cb5bc65b273094e0751929e5ec4dcffb0e6f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 16:31:24 -0800 Subject: [PATCH 08/71] 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 76cf29e7e09b2a4204194f2e9133e76817974e99 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 16:56:04 -0800 Subject: [PATCH 09/71] test: snapshot ladder rung F1 harness (N volumes, one server id, one host) V1-SPEC r2.49/r2.52. Opt-in (F1_RUN=1, a large test, never in CI): N blockvolume processes under ONE server id, each its own replica id and ports, snapshotted at the same instant per round under write load; every snapshot restored and verified (ledger exact, load a prefix); the JSON report carries cut time and barrier pause, client write p50/p99/max inside and outside snapshot windows, request-to-commit time, host-slot waits, restore time, chunks/bytes uploaded, filer entries per round and RSS. The procedure harness's bvHost gains optional server and replica ids. Co-Authored-By: Claude Opus 5.5 --- .../planned_handoff_integration_test.go | 15 +- .../snapshot_ladder_f1_integration_test.go | 616 ++++++++++++++++++ 2 files changed, 628 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index a515a3174a..43d8cb8b6d 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -185,10 +185,13 @@ type handoffEnv struct { } // bvHost is one host's blockvolume: its server id, endpoints, local root -// and the volume it serves (v1 when empty). +// and the volume it serves (v1 when empty). server and replica, when set, +// replace id as the server id and r1 as the replica id (several volumes +// under one server id). type bvHost struct { id, data, ctrl, status, nvme, root string volume string + server, replica string } // startHandoffEnv runs the chapter's steps 1-3: a weed cluster, the cluster @@ -267,11 +270,17 @@ func (env *handoffEnv) volArgs(id string) []string { return env.volArgsFor(env.h func (env *handoffEnv) volArgsFor(b bvHost) []string { lockDir := b.root + ".locks" // each simulated host has its own _ = os.MkdirAll(lockDir, 0o700) - vol := b.volume + vol, server, replica := b.volume, b.server, b.replica if vol == "" { vol = "v1" } - return append([]string{"--volume-lock-dir-test-only", lockDir, "--master", env.h.masterAddr, "--server-id", b.id, "--volume-id", vol, "--replica-id", "r1", + if server == "" { + server = b.id + } + if replica == "" { + replica = "r1" + } + return append([]string{"--volume-lock-dir-test-only", lockDir, "--master", env.h.masterAddr, "--server-id", server, "--volume-id", vol, "--replica-id", replica, "--data-addr", b.data, "--ctrl-addr", b.ctrl, "--status-addr", b.status, "--durable-root", b.root, "--durable-impl", "walstore-chunk", "--durable-blocks", "65536", "--durable-blocksize", "4096", diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go new file mode 100644 index 0000000000..5205d5e591 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go @@ -0,0 +1,616 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "math" + "net/http" + "net/url" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/hostlimit" +) + +// Snapshot ladder rung F1 (V1-SPEC r2.49, r2.52): N volumes on one host, +// every volume snapshotted at the same instant, round after round, under +// write load. It must hold: every snapshot restores exactly; no write fails; +// the host limiter paces the cuts and none starves (every snapshot commits +// within ceil(N/slots)+1 times the slowest single cut). It measures, per +// volume and round: the snapshot's cut (total and guest barrier pause), the +// client write latency inside and outside snapshot windows, request to +// commit time, host-slot waits, restore time, chunks and bytes uploaded, +// filer entries per snapshot, and blockvolume RSS. The JSON report goes to +// F1_REPORT. +// +// A large test: it runs only with F1_RUN=1, on a host booked for it, never in +// CI. Knobs: F1_VOLUMES (10), F1_ROUNDS (3), F1_WRITE_SECONDS (120), +// F1_HOST_LIMIT_DIR (a local, non-temporary directory; required for the +// limiter checks, a smoke may leave it unset), F1_HOST_LIMIT_SLOTS +// (the limiter's normal slots; default hostlimit's), F1_REPORT. +// +// Each volume has two regions. The ledger region is written and flushed +// before a round's snapshot, so the snapshot must hold it exactly. The load +// region is written in LBA order during the snapshot, so the snapshot must +// hold a prefix of it (A3's one-point-in-time check). + +type f1Config struct { + Volumes, Rounds int + WriteSeconds int + HostLimitDir string + Slots int + Report string + LedgerBlocksPerRnd int + LoadSpan int +} + +func f1ConfigFromEnv(t *testing.T) f1Config { + t.Helper() + if os.Getenv("F1_RUN") != "1" { + t.Skip("rung F1 is a large test: set F1_RUN=1 on a booked host") + } + num := func(k string, def int) int { + if v := os.Getenv(k); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 1 { + t.Fatalf("%s=%q: want a positive integer", k, v) + } + return n + } + return def + } + c := f1Config{Volumes: num("F1_VOLUMES", 10), Rounds: num("F1_ROUNDS", 3), WriteSeconds: num("F1_WRITE_SECONDS", 120), + HostLimitDir: os.Getenv("F1_HOST_LIMIT_DIR"), Slots: num("F1_HOST_LIMIT_SLOTS", hostlimit.DefaultConfig("").NormalSlots), + Report: os.Getenv("F1_REPORT"), LedgerBlocksPerRnd: 64, LoadSpan: 4096} + if c.Rounds*(c.LedgerBlocksPerRnd+c.LoadSpan) > ladderUntouched { + t.Fatalf("F1_ROUNDS=%d does not fit below the untouched chunk", c.Rounds) + } + return c +} + +// f1Volume is one source volume: its id, host record and daemon. +type f1Volume struct { + id, node string + d *daemon +} + +// f1Sample is one client write. +type f1Sample struct { + start time.Time + d time.Duration +} + +// f1Round is one volume's measurements in one round. +type f1Round struct { + Volume string `json:"volume"` + Round int `json:"round"` + SnapshotMs float64 `json:"snapshot_request_to_commit_ms"` + CutTotalMs float64 `json:"cut_total_ms"` + BarrierPauseMs float64 `json:"cut_barrier_pause_ms"` + UploadedChunks int `json:"uploaded_chunks"` + UploadedBytes int64 `json:"uploaded_bytes"` + HostSlotWaits uint64 `json:"host_slot_waits"` + RestoreMs float64 `json:"restore_ms"` + RestoreExact bool `json:"restore_exact"` + LoadPrefix int `json:"load_prefix_blocks"` + WritesIn int `json:"writes_in_window"` + WritesOut int `json:"writes_outside_window"` + WriteP50InMs float64 `json:"write_p50_in_ms"` + WriteP99InMs float64 `json:"write_p99_in_ms"` + WriteMaxInMs float64 `json:"write_max_in_ms"` + WriteP50OutMs float64 `json:"write_p50_out_ms"` + WriteP99OutMs float64 `json:"write_p99_out_ms"` + WriteMaxOutMs float64 `json:"write_max_out_ms"` + RSSKiB int64 `json:"blockvolume_rss_kib"` + FilerEntriesNew int `json:"filer_entries_added_by_round"` +} + +type f1Report struct { + Config f1Config `json:"config"` + Limiter string `json:"limiter"` + StartedAt time.Time `json:"started_at"` + Rounds []f1Round `json:"rounds"` + CommitBound float64 `json:"commit_bound_ms"` + WriteErrors int `json:"write_errors"` + Verdict string `json:"verdict"` + Failures []string `json:"failures,omitempty"` +} + +func TestSnapshotLadderF1VolumesOneHost(t *testing.T) { + cfg := f1ConfigFromEnv(t) + rep := &f1Report{Config: cfg, StartedAt: time.Now().UTC(), Limiter: "off"} + env := f1StartEnv(t, cfg) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + if cfg.HostLimitDir != "" { + env.volExtra = append(env.volExtra, "--host-limit-dir", cfg.HostLimitDir, "--host-limit-normal-slots", strconv.Itoa(cfg.Slots)) + rep.Limiter = fmt.Sprintf("%s, %d normal slots", cfg.HostLimitDir, cfg.Slots) + } + vols := f1StartSources(t, env, cfg.Volumes) + defer f1WriteReport(t, cfg, rep) + + for round := 1; round <= cfg.Rounds; round++ { + before := f1FilerEntries(t, env) + rounds := f1RunRound(t, env, cfg, vols, round, rep) + added := f1FilerEntries(t, env) - before + for i := range rounds { + rounds[i].FilerEntriesNew = added + } + rep.Rounds = append(rep.Rounds, rounds...) + } + f1Judge(t, cfg, rep) +} + +func f1RestoreTarget(vol, round int) string { return fmt.Sprintf("v%dr%d", vol, round) } + +// f1StartEnv is the procedure harness laid out as one host (V1-SPEC r2.52, +// claude05 00:56Z): ONE server id, s1, and one blockvolume process per +// volume, each with its own replica id and its own data/ctrl/status/NVMe +// ports. Source v is replica r; the restore target of v in round k +// is replica r on the same server. The node record carries the first +// source's pair, as the deployment page writes one node. +func f1StartEnv(t *testing.T, cfg f1Config) *handoffEnv { + t.Helper() + h := newPlannedHandoffHarness(t) + env := &handoffEnv{h: h, cluster: startWorkspaceWeed(t), chunkPath: fmt.Sprintf("/f1-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}} + must, _ := fatalOn(t) + add := func(key, vol string, replica int) { + b := bvHost{id: key, server: "s1", replica: fmt.Sprintf("r%d", replica), volume: vol, root: filepath.Join(h.dir, "vol-"+key), + data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t)} + if key == "v1" { + b.data, b.ctrl, b.status, b.nvme = h.dataAddr, h.ctrlAddr, h.statusAddr, h.nvmeAddr + } + env.hosts[key] = b + } + for i := 1; i <= cfg.Volumes; i++ { + add(fmt.Sprintf("v%d", i), fmt.Sprintf("v%d", i), i) + } + for r := 1; r <= cfg.Rounds; r++ { + for i := 1; i <= cfg.Volumes; i++ { + v := f1RestoreTarget(i, r) + add(v, v, i+cfg.Volumes*r) + } + } + var vols strings.Builder + keys := make([]string, 0, len(env.hosts)) + for k := range env.hosts { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + b := env.hosts[k] + fmt.Fprintf(&vols, " - id: %s\n size_bytes: 268435456\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: %s\n", b.volume, b.replica) + } + spec := filepath.Join(h.dir, "cluster-spec.yaml") + must(os.WriteFile(spec, []byte(fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n%s", h.dataAddr, h.ctrlAddr, vols.String())), 0o644)) + mstate := filepath.Join(h.dir, "master") + master := h.start(t, "blockmaster", h.master, "--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"), + "--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr, + "--workspace-rpc", "--workspace-head-base-url", "http://"+env.cluster.filerHTTP+env.chunkPath) + master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + return env +} + +// f1Up starts the blockvolume of key and waits for its volume to be primary +// and its frontend ready. +func f1Up(t *testing.T, env *handoffEnv, key string) *daemon { + t.Helper() + b := env.hosts[key] + d := env.h.start(t, "blockvolume-"+key, env.h.volume, env.volArgsFor(b)...) + d.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at %s@", b.volume, b.replica)) + poll(t, 60*time.Second, key+" never reported its frontend ready", func() bool { return volumeFrontendReady(b.status, b.volume) }) + return d +} + +// f1StartSources starts the N source volumes. +func f1StartSources(t *testing.T, env *handoffEnv, n int) []f1Volume { + t.Helper() + var vols []f1Volume + for i := 1; i <= n; i++ { + v := fmt.Sprintf("v%d", i) + vols = append(vols, f1Volume{id: v, node: v, d: f1Up(t, env, v)}) + } + return vols +} + +// f1Restore restores snapshot snap of src into target (a new volume on the +// same server) and drives the restore; the target's blockvolume is stopped +// once verified (f1RunRound), so restores do not pile up processes. +func f1Restore(t *testing.T, env *handoffEnv, src, snap, target string) *daemon { + t.Helper() + b := env.hosts[target] + env.h.command(t, "ops", "chunk", "restore", "--source", src, "--snapshot", snap, "--target", target, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + d := f1Up(t, env, target) + env.h.command(t, "ops", "chunk", "restore", "--volume", target, "--status-addr", b.status) + return d +} + +func f1Block(vol string, round int, kind string, lba uint64) []byte { + return pattern(fmt.Sprintf("%s r%d %s %08d|", vol, round, kind, lba)) +} + +func f1LedgerBase(cfg f1Config, round int) uint64 { + return uint64((round - 1) * (cfg.LedgerBlocksPerRnd + cfg.LoadSpan)) +} + +// f1RunRound: write and flush each volume's ledger region, start the load +// writers, snapshot every volume at the same instant, stop the load, then +// restore and verify every snapshot. +func f1RunRound(t *testing.T, env *handoffEnv, cfg f1Config, vols []f1Volume, round int, rep *f1Report) []f1Round { + t.Helper() + for _, v := range vols { + c := dialNVMe(t, env.hosts[v.node].nvme, plannedHandoffNQN) + base := f1LedgerBase(cfg, round) + for i := 0; i < cfg.LedgerBlocksPerRnd; i++ { + c.write(t, base+uint64(i), f1Block(v.id, round, "ledger", base+uint64(i))) + } + c.flush(t) + c.close() + } + type writer struct { + mu sync.Mutex + samples []f1Sample + written int + err error + } + stop := make(chan struct{}) + ws := make([]*writer, len(vols)) + var wg sync.WaitGroup + for i, v := range vols { + ws[i] = &writer{} + c := dialNVMe(t, env.hosts[v.node].nvme, plannedHandoffNQN) + wg.Add(1) + go func(w *writer, c *nvmeInitiator, vol string) { + defer wg.Done() + defer c.close() + first := f1LedgerBase(cfg, round) + uint64(cfg.LedgerBlocksPerRnd) + for n := 0; n < cfg.LoadSpan; n++ { + select { + case <-stop: + return + default: + } + lba := first + uint64(n) + s := time.Now() + err := c.tryWrite(lba, f1Block(vol, round, "load", lba)) + if err == nil && n%16 == 15 { + err = c.tryFlush() + } + w.mu.Lock() + w.samples = append(w.samples, f1Sample{start: s, d: time.Since(s)}) + if err != nil { + w.err = err + } else { + w.written = n + 1 + } + w.mu.Unlock() + if err != nil { + return + } + } + }(ws[i], c, v.id) + } + time.Sleep(time.Duration(cfg.WriteSeconds) * time.Second / 2) // load before the snapshots + + type snapRes struct { + start, end time.Time + out, err string + code int + } + res := make([]snapRes, len(vols)) + var sg sync.WaitGroup + gate := make(chan struct{}) + for i, v := range vols { + sg.Add(1) + go func(i int, v f1Volume) { + defer sg.Done() + <-gate + res[i].start = time.Now() + res[i].out, res[i].err, res[i].code = env.h.run(t, "ops", "chunk", "snapshot", "--volume", v.id, "--status-addr", env.hosts[v.node].status, "--name", fmt.Sprintf("f1-r%d", round)) + res[i].end = time.Now() + }(i, v) + } + close(gate) + sg.Wait() + time.Sleep(time.Duration(cfg.WriteSeconds) * time.Second / 2) // load after the snapshots + close(stop) + wg.Wait() + + out := make([]f1Round, len(vols)) + for i, v := range vols { + r := f1Round{Volume: v.id, Round: round} + w := ws[i] + if w.err != nil { + rep.WriteErrors++ + rep.Failures = append(rep.Failures, fmt.Sprintf("%s round %d: write error: %v", v.id, round, w.err)) + } + if res[i].code != 0 { + rep.Failures = append(rep.Failures, fmt.Sprintf("%s round %d: snapshot exit %d: %s %s", v.id, round, res[i].code, res[i].out, res[i].err)) + out[i] = r + continue + } + r.SnapshotMs = ms(res[i].end.Sub(res[i].start)) + f1Latencies(&r, w.samples, res[i].start, res[i].end) + f1CutStats(t, env, v, &r) + r.RSSKiB = f1RSS(v.d) + target := f1RestoreTarget(i+1, round) + rs := time.Now() + rd := f1Restore(t, env, v.id, fmt.Sprintf("f1-r%d", round), target) + r.RestoreMs = ms(time.Since(rs)) + r.RestoreExact, r.LoadPrefix = f1Verify(t, env, cfg, v.id, target, round, w.written) + rd.term(t, 60*time.Second) + if !r.RestoreExact { + rep.Failures = append(rep.Failures, fmt.Sprintf("%s round %d: the restored snapshot is not the volume at its point", v.id, round)) + } + out[i] = r + } + return out +} + +// f1Verify reads the restored snapshot: every ledger block of rounds 1..round +// exact; each round's load region a prefix, at most what was written. +func f1Verify(t *testing.T, env *handoffEnv, cfg f1Config, vol, target string, round, written int) (bool, int) { + t.Helper() + c := dialNVMe(t, env.hosts[target].nvme, plannedHandoffNQN) + defer c.close() + zero := make([]byte, 4096) + prefix := 0 + for r := 1; r <= round; r++ { + base := f1LedgerBase(cfg, r) + for i := 0; i < cfg.LedgerBlocksPerRnd; i++ { + if !bytes.Equal(c.read(t, base+uint64(i), 4096), f1Block(vol, r, "ledger", base+uint64(i))) { + return false, 0 + } + } + first := base + uint64(cfg.LedgerBlocksPerRnd) + ended, k := false, 0 + for n := 0; n < cfg.LoadSpan; n++ { + got := c.read(t, first+uint64(n), 4096) + switch { + case !ended && bytes.Equal(got, f1Block(vol, r, "load", first+uint64(n))): + k++ + case bytes.Equal(got, zero) && r == round: + ended = true + case r < round && n >= k && bytes.Equal(got, zero): + ended = true + default: + return false, 0 + } + } + if r == round { + prefix = k + if k > written { + return false, k + } + } + } + return true, prefix +} + +// f1Latencies splits the client write latencies at the snapshot window. +func f1Latencies(r *f1Round, samples []f1Sample, from, to time.Time) { + var in, out []time.Duration + for _, s := range samples { + if !s.start.Before(from) && !s.start.After(to) { + in = append(in, s.d) + } else { + out = append(out, s.d) + } + } + r.WritesIn, r.WritesOut = len(in), len(out) + r.WriteP50InMs, r.WriteP99InMs, r.WriteMaxInMs = pct(in, 50), pct(in, 99), pct(in, 100) + r.WriteP50OutMs, r.WriteP99OutMs, r.WriteMaxOutMs = pct(out, 50), pct(out, 99), pct(out, 100) +} + +func pct(d []time.Duration, p float64) float64 { + if len(d) == 0 { + return 0 + } + s := append([]time.Duration(nil), d...) + sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) + i := int(math.Ceil(p/100*float64(len(s)))) - 1 + if i < 0 { + i = 0 + } + return ms(s[i]) +} + +func ms(d time.Duration) float64 { return float64(d) / float64(time.Millisecond) } + +// f1CutStats reads the volume's last cut (the snapshot's) from its durable +// status. +func f1CutStats(t *testing.T, env *handoffEnv, v f1Volume, r *f1Round) { + t.Helper() + c := &http.Client{Timeout: 5 * time.Second} + resp, err := c.Get("http://" + env.hosts[v.node].status + "/status/durable?volume=" + v.id) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var st struct { + Volumes []struct { + VolumeID string + Chunk *struct { + HostSlotWaits uint64 + Stats struct { + LastCut *struct { + TotalNs, BarrierPauseNs int64 + UploadedChunks int + UploadedBytes int64 + } + } + } + } + } + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) + if err := json.Unmarshal(body, &st); err != nil { + t.Fatalf("durable status of %s: %v", v.id, err) + } + for _, s := range st.Volumes { + if s.VolumeID != v.id || s.Chunk == nil || s.Chunk.Stats.LastCut == nil { + continue + } + l := s.Chunk.Stats.LastCut + r.CutTotalMs, r.BarrierPauseMs = float64(l.TotalNs)/1e6, float64(l.BarrierPauseNs)/1e6 + r.UploadedChunks, r.UploadedBytes, r.HostSlotWaits = l.UploadedChunks, l.UploadedBytes, s.Chunk.HostSlotWaits + return + } + t.Fatalf("durable status of %s has no last cut: %s", v.id, body) +} + +// f1RSS is the blockvolume's resident set (KiB), 0 where /proc is absent. +func f1RSS(d *daemon) int64 { + b, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", d.proc.Pid)) + if err != nil { + return 0 + } + for _, l := range strings.Split(string(b), "\n") { + if strings.HasPrefix(l, "VmRSS:") { + f := strings.Fields(l) + if len(f) >= 2 { + n, _ := strconv.ParseInt(f[1], 10, 64) + return n + } + } + } + return 0 +} + +// f1FilerEntries counts the filer entries (files and directories) under the +// chunk path, by the filer's JSON listing. +func f1FilerEntries(t *testing.T, env *handoffEnv) int { + t.Helper() + c := &http.Client{Timeout: 30 * time.Second} + var walk func(dir string) int + walk = func(dir string) int { + n, last := 0, "" + for { + u := "http://" + env.cluster.filerHTTP + dir + "/?limit=1000&lastFileName=" + url.QueryEscape(last) + req, _ := http.NewRequest(http.MethodGet, u, nil) + req.Header.Set("Accept", "application/json") + resp, err := c.Do(req) + if err != nil { + t.Fatalf("filer list %s: %v", dir, err) + } + var page struct { + Entries []struct { + FullPath string + Mode uint32 + } + ShouldDisplayLoadMore bool + LastFileName string + } + err = json.NewDecoder(resp.Body).Decode(&page) + resp.Body.Close() + if err != nil { + t.Fatalf("filer list %s: %v", dir, err) + } + for _, e := range page.Entries { + n++ + if e.Mode&uint32(os.ModeDir) != 0 { + n += walk(e.FullPath) + } + } + if !page.ShouldDisplayLoadMore || page.LastFileName == "" { + return n + } + last = page.LastFileName + } + } + return walk(env.chunkPath) +} + +// f1Judge applies the pass rule: no failure recorded, and every snapshot +// committed within ceil(N/slots)+1 times the slowest single cut (N+1 when +// the limiter is off). +func f1Judge(t *testing.T, cfg f1Config, rep *f1Report) { + t.Helper() + worst, longest := 0.0, 0.0 + for _, r := range rep.Rounds { + worst = math.Max(worst, r.CutTotalMs) + longest = math.Max(longest, r.SnapshotMs) + } + waves := float64(cfg.Volumes + 1) + if cfg.HostLimitDir != "" { + waves = math.Ceil(float64(cfg.Volumes)/float64(cfg.Slots)) + 1 + } + rep.CommitBound = waves * worst + if longest > rep.CommitBound { + rep.Failures = append(rep.Failures, fmt.Sprintf("a snapshot took %.0f ms, above the bound %.0f ms (%.0f waves x the slowest cut %.0f ms): a volume starved", longest, rep.CommitBound, waves, worst)) + } + rep.Verdict = "PASS" + if len(rep.Failures) > 0 { + rep.Verdict = "FAIL" + t.Errorf("rung F1: %s", strings.Join(rep.Failures, "; ")) + } +} + +func f1WriteReport(t *testing.T, cfg f1Config, rep *f1Report) { + b, err := json.MarshalIndent(rep, "", " ") + if err != nil { + t.Errorf("report: %v", err) + return + } + t.Logf("rung F1 report: %s", b) + if cfg.Report != "" { + if err := os.WriteFile(cfg.Report, b, 0o644); err != nil { + t.Errorf("write %s: %v", cfg.Report, err) + } + } +} + +// tryWrite and tryFlush are write and flush returning the error (the load +// writers run off the test goroutine, where t.Fatal is not allowed). +func (c *nvmeInitiator) tryWrite(lba uint64, data []byte) error { + cmd := c.ioCmd(0x01, lba, len(data)/4096) + if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil { + return fmt.Errorf("nvme Write: %w", err) + } + ch, err := c.r.Dequeue() + if err != nil || ch.Type != 0x9 { + return fmt.Errorf("nvme Write: want R2T, got type %v err %v", ch, err) + } + var r2t nvme.R2THeader + if err := c.r.Receive(&r2t); err != nil { + return fmt.Errorf("nvme R2T: %w", err) + } + h2c := nvme.H2CDataHeader{CCCID: cmd.CID, TAG: r2t.TAG, DATAL: uint32(len(data))} + if err := c.w.SendWithData(0x6, 0, &h2c, 16, data); err != nil { + return fmt.Errorf("nvme H2CData: %w", err) + } + return c.tryStatus("Write") +} + +func (c *nvmeInitiator) tryFlush() error { + cmd := c.ioCmd(0x00, 0, 0) + if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil { + return fmt.Errorf("nvme Flush: %w", err) + } + return c.tryStatus("Flush") +} + +func (c *nvmeInitiator) tryStatus(op string) error { + ch, err := c.r.Dequeue() + if err != nil || ch.Type != 0x5 { + return fmt.Errorf("nvme %s response: type %v err %v", op, ch, err) + } + var resp nvme.CapsuleResponse + if err := c.r.Receive(&resp); err != nil { + return fmt.Errorf("nvme %s response body: %w", op, err) + } + if resp.Status != 0 { + return fmt.Errorf("nvme %s status 0x%04x", op, resp.Status) + } + return nil +} From ce2ca830aeb18d865cc6ac65664ed2ed2edfa4aa Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:09:03 -0800 Subject: [PATCH 10/71] test: F1 blocks are exactly 4096 bytes Co-Authored-By: Claude Opus 5.5 --- .../blockvolume/snapshot_ladder_f1_integration_test.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go index 5205d5e591..1189e7b31d 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go @@ -236,8 +236,15 @@ func f1Restore(t *testing.T, env *handoffEnv, src, snap, target string) *daemon return d } +// f1Block is one deterministic 4096-byte block (pattern needs a length that +// divides 4096; these labels do not, so the block is filled explicitly). func f1Block(vol string, round int, kind string, lba uint64) []byte { - return pattern(fmt.Sprintf("%s r%d %s %08d|", vol, round, kind, lba)) + s := fmt.Sprintf("%s r%d %s %08d|", vol, round, kind, lba) + b := make([]byte, 4096) + for i := range b { + b[i] = s[i%len(s)] + } + return b } func f1LedgerBase(cfg f1Config, round int) uint64 { From 80b097c87e354c42871a5803a201c3a579da359b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:10:16 -0800 Subject: [PATCH 11/71] test: F1 load paced across the write period; filer entries per snapshot Co-Authored-By: Claude Opus 5.5 --- .../snapshot_ladder_f1_integration_test.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go index 1189e7b31d..766a59474d 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go @@ -36,6 +36,8 @@ import ( // // A large test: it runs only with F1_RUN=1, on a host booked for it, never in // CI. Knobs: F1_VOLUMES (10), F1_ROUNDS (3), F1_WRITE_SECONDS (120), +// F1_LOAD_SPAN (8192 blocks per volume per round, written evenly across the +// write period, so writes run before, during and after the snapshots), // F1_HOST_LIMIT_DIR (a local, non-temporary directory; required for the // limiter checks, a smoke may leave it unset), F1_HOST_LIMIT_SLOTS // (the limiter's normal slots; default hostlimit's), F1_REPORT. @@ -72,7 +74,7 @@ func f1ConfigFromEnv(t *testing.T) f1Config { } c := f1Config{Volumes: num("F1_VOLUMES", 10), Rounds: num("F1_ROUNDS", 3), WriteSeconds: num("F1_WRITE_SECONDS", 120), HostLimitDir: os.Getenv("F1_HOST_LIMIT_DIR"), Slots: num("F1_HOST_LIMIT_SLOTS", hostlimit.DefaultConfig("").NormalSlots), - Report: os.Getenv("F1_REPORT"), LedgerBlocksPerRnd: 64, LoadSpan: 4096} + Report: os.Getenv("F1_REPORT"), LedgerBlocksPerRnd: 64, LoadSpan: num("F1_LOAD_SPAN", 8192)} if c.Rounds*(c.LedgerBlocksPerRnd+c.LoadSpan) > ladderUntouched { t.Fatalf("F1_ROUNDS=%d does not fit below the untouched chunk", c.Rounds) } @@ -114,6 +116,7 @@ type f1Round struct { WriteMaxOutMs float64 `json:"write_max_out_ms"` RSSKiB int64 `json:"blockvolume_rss_kib"` FilerEntriesNew int `json:"filer_entries_added_by_round"` + FilerPerSnap float64 `json:"filer_entries_per_snapshot"` } type f1Report struct { @@ -145,6 +148,7 @@ func TestSnapshotLadderF1VolumesOneHost(t *testing.T) { added := f1FilerEntries(t, env) - before for i := range rounds { rounds[i].FilerEntriesNew = added + rounds[i].FilerPerSnap = float64(added) / float64(len(rounds)) } rep.Rounds = append(rep.Rounds, rounds...) } @@ -282,7 +286,17 @@ func f1RunRound(t *testing.T, env *handoffEnv, cfg f1Config, vols []f1Volume, ro defer wg.Done() defer c.close() first := f1LedgerBase(cfg, round) + uint64(cfg.LedgerBlocksPerRnd) + // Paced so the span covers the whole write period. + every := time.Duration(cfg.WriteSeconds) * time.Second / time.Duration(cfg.LoadSpan) + begin := time.Now() for n := 0; n < cfg.LoadSpan; n++ { + if wait := time.Until(begin.Add(time.Duration(n) * every)); wait > 0 { + select { + case <-stop: + return + case <-time.After(wait): + } + } select { case <-stop: return From 3b0630ae9d51f302b935c8d32963604170e8e63e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:12:06 -0800 Subject: [PATCH 12/71] test: snapshot ladder B/C folds: later writes read zero, s4 matches its answer, bounded worker and status wait Co-Authored-By: Claude Opus 5.5 --- .../snapshot_ladder_integration_test.go | 174 +++++++++++++----- 1 file changed, 132 insertions(+), 42 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go index cc4dfd3d38..62579cd8ea 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go @@ -4,10 +4,13 @@ package main_test import ( "bytes" + "context" "encoding/json" + "errors" "fmt" "io" "net/http" + "os/exec" "strings" "testing" "time" @@ -237,8 +240,9 @@ func (env *handoffEnv) restoreAttached(t *testing.T, src, snap, target string) { // TestSnapshotLadderB1SnapshotQuery: three snapshots with writes between // them. The list is exactly the committed snapshots, in order, each active, // with the point (cut LSN), HEAD generation and size (chunk count) its -// creation answered; a prefix shows one. A snapshot being taken appears in -// the list only committed, and stays. A snapshot request that is refused +// creation answered; a prefix shows one. A snapshot being taken while a +// write runs appears in the list only committed, with the fields its +// creation answers, and stays. A snapshot request that is refused // (a restore volume not yet independent) leaves no name in the list. func TestSnapshotLadderB1SnapshotQuery(t *testing.T) { env := startLadderEnv(t, "v2") @@ -271,39 +275,73 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) { t.Fatalf("show s2: %+v", one) } - // A snapshot being taken: listed only committed, and then it stays. - done := make(chan int, 1) - go func() { - _, _, code := env.h.run(t, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status, "--name", "s4") - done <- code - }() + // A snapshot being taken: listed only committed, and then it stays. The + // write before it is acknowledged first, so its cut is past s3's; the + // write during it may land before or after its cut. env.writeBlock(t, "s1", 3, pattern("ladder-b1-blk-D!")) - seen := false + type result struct { + out, errOut string + code int + err error + } + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) + done := make(chan result, 1) + joined := false + t.Cleanup(func() { // before the daemons stop: cancel and join the worker + cancel() + if !joined { + select { + case <-done: + case <-time.After(10 * time.Second): + } + } + }) + go func() { + out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status, "--name", "s4") + done <- result{out, errOut, code, err} + }() + env.writeBlock(t, "s1", 4, pattern("ladder-b1-blk-E!")) + var observed []snapshotInfo + var r result + deadline := time.Now().Add(160 * time.Second) for running := true; running; { select { - case code := <-done: - if code != 0 { - t.Fatalf("snapshot s4: exit %d", code) - } - running = false + case r = <-done: + joined, running = true, false default: } + if running && time.Now().After(deadline) { + t.Fatal("snapshot s4 did not return within its bound") + } var s4 *snapshotInfo for _, e := range env.snapshots(t, "v1", "s4") { e := e s4 = &e } switch { - case s4 == nil && seen: + case s4 == nil && len(observed) > 0: t.Fatal("s4 was listed, then disappeared") case s4 != nil && (s4.State != "active" || s4.CutLSN <= made[2].CutLSN || s4.HeadGen <= made[2].HeadGen): t.Fatalf("s4 listed before it was committed: %+v", *s4) case s4 != nil: - seen = true + observed = append(observed, *s4) } } - if !seen && len(env.snapshots(t, "v1", "s4")) != 1 { - t.Fatal("s4 not listed after its snapshot returned") + if r.err != nil || r.code != 0 { + t.Fatalf("snapshot s4: exit %d %v\n%s\n%s", r.code, r.err, r.out, r.errOut) + } + var created snapshotInfo + if err := json.Unmarshal([]byte(r.out), &created); err != nil || created.Name != "s4" { + t.Fatalf("snapshot s4 answer: %v\n%s", err, r.out) + } + final := env.snapshots(t, "v1", "s4") + if len(final) != 1 { + t.Fatalf("s4 not listed after its snapshot returned: %+v", final) + } + for _, o := range append(observed, final[0]) { + if o.State != "active" || o.CutLSN != created.CutLSN || o.HeadGen != created.HeadGen || o.ChunkCount != created.ChunkCount { + t.Fatalf("s4 listed as %+v; its creation answered %+v", o, created) + } } // A refused snapshot is not a snapshot. @@ -317,7 +355,6 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) { } } - // lastCutUploads is the number of chunks the last cut of vol uploaded, from // its host's durable status. func (env *handoffEnv) lastCutUploads(t *testing.T, hostID, vol string) int { @@ -419,24 +456,55 @@ func volumeFrontendReady(statusAddr, vol string) bool { return frontendReady(b) } -// waitIndependent polls the restore status of target until its phase is -// independent (it then holds every chunk under its own keys). +// waitIndependent polls the restore status of target until the restore +// driver reports its phase independent (what the status says; it is not a +// separate measurement of which keys hold the chunks). The bound is end to +// end: every query runs within what is left of it, and a success seen after +// it does not count. func (env *handoffEnv) waitIndependent(t *testing.T, target string) { t.Helper() - poll(t, 120*time.Second, fmt.Sprintf("%s never became independent", target), func() bool { - out, _, code := env.h.run(t, "ops", "chunk", "restore", "--volume", target, "--status-addr", env.hosts["n-"+target].status, "--status") + const bound = 120 * time.Second + end := time.Now().Add(bound) + ctx, cancel := context.WithDeadline(context.Background(), end) + defer cancel() + last := "" + for time.Now().Before(end) { + out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "restore", "--volume", target, "--status-addr", env.hosts["n-"+target].status, "--status") var st struct { - Phase string `json:"phase"` - ErrorCode string `json:"errorCode"` + Phase string `json:"phase"` } - if code != 0 || json.Unmarshal([]byte(out), &st) != nil { - return false + if err == nil && code == 0 && json.Unmarshal([]byte(out), &st) == nil { + if st.Phase == "failed" { + t.Fatalf("restore of %s failed: %s", target, out) + } + if st.Phase == "independent" && time.Now().Before(end) { + return + } } - if st.Phase == "failed" { - t.Fatalf("restore of %s failed: %s", target, out) - } - return st.Phase == "independent" - }) + last = out + errOut + time.Sleep(200 * time.Millisecond) + } + t.Fatalf("%s never became independent within %v; last status: %s", target, bound, last) +} + +// runCLI runs sw-block under ctx and returns its output and exit status. It +// never fails the test, so a worker goroutine may call it; a failure to run +// or a cancelled context comes back as err. +func runCLI(ctx context.Context, h *plannedHandoffHarness, args ...string) (string, string, int, error) { + cmd := exec.CommandContext(ctx, h.cli, args...) + cmd.Dir = h.dir + cmd.WaitDelay = 5 * time.Second + var stdout, stderr strings.Builder + cmd.Stdout, cmd.Stderr = &stdout, &stderr + err := cmd.Run() + var exit *exec.ExitError + switch { + case err == nil: + return stdout.String(), stderr.String(), 0, nil + case errors.As(err, &exit) && ctx.Err() == nil: + return stdout.String(), stderr.String(), exit.ExitCode(), nil + } + return stdout.String(), stderr.String(), -1, fmt.Errorf("sw-block %q: %w", args, err) } // ladderImage is a written picture of a volume: blocks in several chunks. @@ -462,8 +530,10 @@ func (env *handoffEnv) writeImage(t *testing.T, hostID string, img map[uint64][] } // requireImage reads every block of img on the host and the zeros next to -// each written run, and the edge blocks. -func (env *handoffEnv) requireImage(t *testing.T, hostID string, img map[uint64][]byte) { +// each written run, and the edge blocks. Every block of later (writes made +// after the snapshot that img pictures) that img does not hold must read +// zero: data written after the snapshot must not leak into its restore. +func (env *handoffEnv) requireImage(t *testing.T, hostID string, img map[uint64][]byte, later ...map[uint64][]byte) { t.Helper() zero := make([]byte, 4096) c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN) @@ -478,6 +548,16 @@ func (env *handoffEnv) requireImage(t *testing.T, hostID string, img map[uint64] } } } + for _, l := range later { + for lba := range l { + if _, held := img[lba]; held { + continue // an overwrite: img's value was checked above + } + if got := c.read(t, lba, 4096); !bytes.Equal(got, zero) { + t.Fatalf("%s: block %d was written after the snapshot and should read zero", hostID, lba) + } + } + } c.close() env.requireEdges(t, hostID) } @@ -493,16 +573,19 @@ func mergeImages(imgs ...map[uint64][]byte) map[uint64][]byte { } // TestSnapshotLadderC1FullRestore: blocks in five chunks are written and a -// snapshot taken; its restore into a new volume runs to independence (every -// chunk under its own keys) and then equals the snapshot block by block. +// snapshot taken, then some of them overwritten and new chunks written; the +// snapshot's restore into a new volume, once its status says independent, +// equals the snapshot block by block, without the later writes. func TestSnapshotLadderC1FullRestore(t *testing.T) { env := startLadderEnv(t, "v2") img := ladderImage("c1", []uint64{0, 1, 7, 20, 63}, 8) env.writeImage(t, "s1", img) env.snapshot(t, "s1", "v1", "full") + later := mergeImages(ladderImage("c1later", []uint64{1, 20}, 8), ladderImage("c1new", []uint64{9, 33}, 3)) + env.writeImage(t, "s1", later) env.restoreInto(t, "v1", "full", "v2") env.waitIndependent(t, "v2") - env.requireImage(t, "n-v2", img) + env.requireImage(t, "n-v2", img, later) } // TestSnapshotLadderC2IncrementalRestore: three snapshots, each after more @@ -522,31 +605,38 @@ func TestSnapshotLadderC2IncrementalRestore(t *testing.T) { env.restoreInto(t, "v1", "s2", "v2") env.waitIndependent(t, "v2") - env.requireImage(t, "n-v2", mergeImages(img1, img2)) + env.requireImage(t, "n-v2", mergeImages(img1, img2), img3) // nothing written after s2, chunk 30 included env.restoreInto(t, "v1", "s3", "v3") env.waitIndependent(t, "v3") env.requireImage(t, "n-v3", mergeImages(img1, img2, img3)) } // TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt: a restored volume, -// once independent, is written and snapshotted itself; that snapshot holds -// its writes, and the source's snapshot still restores unchanged. +// once its status says independent, is written and snapshotted itself, then +// written again; that snapshot holds its first writes and not the later +// ones, and the source's snapshot, also written past, still restores +// unchanged. Every write to the restored volume comes after it is +// independent. func TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt(t *testing.T) { env := startLadderEnv(t, "v2", "v3", "v4") src := ladderImage("c3src", []uint64{0, 3}, 4) env.writeImage(t, "s1", src) env.snapshot(t, "s1", "v1", "base") + srcLater := ladderImage("c3srclater", []uint64{3, 15}, 2) + env.writeImage(t, "s1", srcLater) env.restoreInto(t, "v1", "base", "v2") env.waitIndependent(t, "v2") own := ladderImage("c3own", []uint64{3, 11}, 3) env.writeImage(t, "n-v2", own) env.snapshot(t, "n-v2", "v2", "mine") + ownLater := ladderImage("c3ownlater", []uint64{0, 11, 25}, 2) + env.writeImage(t, "n-v2", ownLater) env.restoreInto(t, "v2", "mine", "v3") env.waitIndependent(t, "v3") - env.requireImage(t, "n-v3", mergeImages(src, own)) + env.requireImage(t, "n-v3", mergeImages(src, own), ownLater, srcLater) env.restoreInto(t, "v1", "base", "v4") // the source's snapshot is unchanged env.waitIndependent(t, "v4") - env.requireImage(t, "n-v4", src) + env.requireImage(t, "n-v4", src, srcLater, own, ownLater) } From 57432c20da7bd56f4cb7bd62e69dc156e9f6c844 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:12:15 -0800 Subject: [PATCH 13/71] test: F1 comment cites the spec, not a seat Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/snapshot_ladder_f1_integration_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go index 766a59474d..f082641bf5 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go @@ -158,7 +158,7 @@ func TestSnapshotLadderF1VolumesOneHost(t *testing.T) { func f1RestoreTarget(vol, round int) string { return fmt.Sprintf("v%dr%d", vol, round) } // f1StartEnv is the procedure harness laid out as one host (V1-SPEC r2.52, -// claude05 00:56Z): ONE server id, s1, and one blockvolume process per +// the layout ruling): ONE server id, s1, and one blockvolume process per // volume, each with its own replica id and its own data/ctrl/status/NVMe // ports. Source v is replica r; the restore target of v in round k // is replica r on the same server. The node record carries the first From 8fb56ea977a1d6bec1e3b0e74c0e4744fb061f17 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:14:09 -0800 Subject: [PATCH 14/71] test: snapshot ladder D folds: later writes read zero, D3 live HEAD differs, D4 expected set from the filer, budget preflight Co-Authored-By: Claude Opus 5.5 --- .../snapshot_ladder_d_integration_test.go | 170 ++++++++++++++---- 1 file changed, 131 insertions(+), 39 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go index d79fd6b58c..8e45fc8f1b 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go @@ -7,6 +7,8 @@ import ( "fmt" "io" "net/http" + "net/url" + "path" "strings" "testing" "time" @@ -57,13 +59,14 @@ func (env *handoffEnv) requireSnapshotNames(t *testing.T, vol string, names ...s } } -// restoreChecked restores snap of v1 into target to independence and checks -// it equals img. -func (env *handoffEnv) restoreChecked(t *testing.T, snap, target string, img map[uint64][]byte) { +// restoreChecked restores snap of v1 into target until its status says +// independent and checks it equals img, with every block of later that img +// does not hold reading zero. +func (env *handoffEnv) restoreChecked(t *testing.T, snap, target string, img map[uint64][]byte, later ...map[uint64][]byte) { t.Helper() env.restoreInto(t, "v1", snap, target) env.waitIndependent(t, target) - env.requireImage(t, "n-"+target, img) + env.requireImage(t, "n-"+target, img, later...) } // TestSnapshotLadderD1DeleteTheNewest: three snapshots over overlapping @@ -79,8 +82,8 @@ func TestSnapshotLadderD1DeleteTheNewest(t *testing.T) { } env.deleteSnapshot(t, "v1", "s3") env.requireSnapshotNames(t, "v1", "s1", "s2") - env.restoreChecked(t, "s1", "v2", img1) - env.restoreChecked(t, "s2", "v3", mergeImages(img1, img2)) + env.restoreChecked(t, "s1", "v2", img1, img2, img3) + env.restoreChecked(t, "s2", "v3", mergeImages(img1, img2), img3) } // TestSnapshotLadderD2DeleteAMiddleOne: four snapshots, each sharing chunks @@ -99,22 +102,25 @@ func TestSnapshotLadderD2DeleteAMiddleOne(t *testing.T) { } env.deleteSnapshot(t, "v1", "s2") env.requireSnapshotNames(t, "v1", "s1", "s3", "s4") - env.restoreChecked(t, "s1", "v2", img1) - env.restoreChecked(t, "s3", "v3", mergeImages(img1, img2, img3)) + env.restoreChecked(t, "s1", "v2", img1, img2, img3, img4) + env.restoreChecked(t, "s3", "v3", mergeImages(img1, img2, img3), img4) env.restoreChecked(t, "s4", "v4", mergeImages(img1, img2, img3, img4)) } // TestSnapshotLadderD3DeleteWhenContentRecurs: the A, B, A volume of A4 -// (one block holds A, then B, then A again, a snapshot after each); the -// first snapshot is deleted; the third, whose content equals the first's, -// and the second restore as they were. +// (one block holds A, then B, then A again, a snapshot after each), then the +// live block is overwritten with C; the first snapshot is deleted; the +// third, whose content equals the first's, and the second restore as they +// were, not as HEAD is now. No collector runs here: this is the logical +// delete and restore, not the reclamation of a recurring chunk. func TestSnapshotLadderD3DeleteWhenContentRecurs(t *testing.T) { env := startLadderEnv(t, "v2", "v3") - a, b := pattern("ladder-d3-blk-A!"), pattern("ladder-d3-blk-B!") + a, b, c := pattern("ladder-d3-blk-A!"), pattern("ladder-d3-blk-B!"), pattern("ladder-d3-blk-C!") for i, content := range [][]byte{a, b, a} { env.writeBlock(t, "s1", 7, content) env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1)) } + env.writeBlock(t, "s1", 7, c) // HEAD now differs from every snapshot env.deleteSnapshot(t, "v1", "s1") env.requireSnapshotNames(t, "v1", "s2", "s3") env.restoreChecked(t, "s3", "v2", map[uint64][]byte{7: a}) @@ -128,6 +134,73 @@ type gcObject struct { FID string `json:"fid"` } +// chunkKeys lists the names (unescaped) of v1's chunk-key bindings, read +// straight from the filer's directory listing, not through the collector. +func (env *handoffEnv) chunkKeys(t *testing.T, vol string) map[string]bool { + t.Helper() + c := &http.Client{Timeout: 10 * time.Second} + dir := path.Join(env.chunkPath, vol, "keys") + "/" + keys := map[string]bool{} + for last := ""; ; { + req, _ := http.NewRequest("GET", "http://"+env.cluster.filerHTTP+dir+"?limit=1000&lastFileName="+url.QueryEscape(last), nil) + req.Header.Set("Accept", "application/json") + resp, err := c.Do(req) + if err != nil { + t.Fatal(err) + } + var page struct { + Entries []struct { + FullPath string `json:"FullPath"` + } `json:"Entries"` + LastFileName string `json:"LastFileName"` + ShouldDisplayLoadMore bool `json:"ShouldDisplayLoadMore"` + } + err = json.NewDecoder(resp.Body).Decode(&page) + resp.Body.Close() + if err != nil || resp.StatusCode != http.StatusOK { + t.Fatalf("filer listing of %s: status %d %v", dir, resp.StatusCode, err) + } + for _, e := range page.Entries { + name, err := url.PathUnescape(path.Base(e.FullPath)) + if err != nil { + t.Fatalf("chunk key %q: %v", e.FullPath, err) + } + keys[name] = true + } + if !page.ShouldDisplayLoadMore || page.LastFileName == "" || page.LastFileName == last { + return keys + } + last = page.LastFileName + } +} + +// uniqueObjects checks every object is v1's and named once (by key and by +// fid), and returns them by key. +func uniqueObjects(t *testing.T, what string, objs []gcObject) map[string]gcObject { + t.Helper() + byKey, fids := map[string]gcObject{}, map[string]bool{} + for _, o := range objs { + if o.Volume != "v1" || o.Key == "" || o.FID == "" || fids[o.FID] { + t.Fatalf("%s: object %+v is not a distinct v1 chunk object: %+v", what, o, objs) + } + if _, dup := byKey[o.Key]; dup { + t.Fatalf("%s: key %q named twice: %+v", what, o.Key, objs) + } + byKey[o.Key], fids[o.FID] = o, true + } + return byKey +} + +// requireBudget fails the test before it starts anything when the test +// binary's deadline leaves less than need: a wait cut short by the package +// timeout would skip the harness's cleanup. +func requireBudget(t *testing.T, need time.Duration) { + t.Helper() + if dl, ok := t.Deadline(); ok && time.Until(dl) < need { + t.Fatalf("this test needs %v; the test deadline leaves %v (run with -timeout 45m)", need, time.Until(dl).Round(time.Second)) + } +} + // gc runs one collector pass (applying or a preview) and returns the chunk // objects it found eligible and how many it reclaimed. func (env *handoffEnv) gc(t *testing.T, apply bool) ([]gcObject, int) { @@ -218,36 +291,50 @@ func (env *handoffEnv) blobStored(t *testing.T, fid string) bool { // TestSnapshotLadderD4DeleteAllButOneThenCollect: three snapshots, each // overwriting the same four chunks; the third and then the second are -// deleted. The third's chunks are still HEAD's, so only the chunks the -// second's cut uploaded are referenced by nothing; usage says deleting it -// makes chunk bytes eligible. Two collector passes the grace apart reclaim -// the CHUNK DATA of exactly those chunks: a preview before the second pass -// names one eligible object per chunk the second's cut uploaded, each still -// readable from the weed store; the applying pass reclaims those and only -// those, and each is then gone from the store. HEAD still reads the newest -// content and the remaining snapshot restores as it was. +// deleted. The third's chunks are still HEAD's, so only the bindings the +// second's cut created are referenced by nothing; usage says deleting it +// makes chunk bytes eligible. The expected set is taken independently of +// the collector: the chunk-key bindings that appear in the filer between the +// first and the second snapshot. Two collector passes the grace apart then +// reclaim the CHUNK DATA of exactly that set: a preview before the second +// pass names exactly those keys, each once, each still readable from the +// weed store; the applying pass reclaims exactly those, and each is then +// gone from the store. HEAD still reads the newest content and the +// remaining snapshot restores as it was. // -// What is measured is chunk data in the weed store, not filer entries, and -// the bound is exact only for objects the collector can enumerate. Excluded, -// known limits of today's format: +// What is measured is chunk data in the weed store for the bindings the +// deleted snapshot alone created, not filer entries and not the whole store. +// Excluded, known limits of today's format: // - a reclaimed binding's filer entry is kept for ever (marked reclaimed), // so filer entry counts and usage's stored bindings and stored bytes do // not fall after collection and are not compared; // - a needle uploaded before its binding was written (a retried upload) // cannot be enumerated and is never reclaimed; a run without upload -// retries makes none, and the test does not look for them. -// -// So after collection the store's enumerable chunk data is at most what HEAD -// and the remaining snapshot reference; unenumerable needles are not bounded. +// retries makes none, and the test does not look for them; +// - disk space is not measured: a deleted needle's space returns only +// when weed compacts its volume. func TestSnapshotLadderD4DeleteAllButOneThenCollect(t *testing.T) { + requireBudget(t, 2*ladderGCWait+10*time.Minute) env := startLadderEnv(t, "v2") chunks := []uint64{0, 1, 2, 3} imgs := []map[uint64][]byte{ladderImage("d4one", chunks, 4), ladderImage("d4two", chunks, 4), ladderImage("d4three", chunks, 4)} uploads := make([]int, len(imgs)) + keysAfter := make([]map[string]bool, len(imgs)) for i, img := range imgs { env.writeImage(t, "s1", img) env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1)) uploads[i] = env.lastCutUploads(t, "s1", "v1") + keysAfter[i] = env.chunkKeys(t, "v1") + } + expected := map[string]bool{} // the bindings the second snapshot's cut created + for k := range keysAfter[1] { + if !keysAfter[0][k] { + expected[k] = true + } + } + t.Logf("the second snapshot's cut uploaded %d chunks and created %d bindings", uploads[1], len(expected)) + if len(expected) < len(chunks) { + t.Fatalf("the second snapshot's cut created %d bindings; want at least one per overwritten chunk (%d)", len(expected), len(chunks)) } if uploads[1] != len(chunks) { t.Fatalf("the second snapshot's cut uploaded %d chunks; want the %d it overwrote", uploads[1], len(chunks)) @@ -262,30 +349,35 @@ func TestSnapshotLadderD4DeleteAllButOneThenCollect(t *testing.T) { env.requireSnapshotNames(t, "v1", "s1") deleted := time.Now() + requireBudget(t, time.Until(deleted.Add(ladderGCWait))+ladderGCWait+5*time.Minute) time.Sleep(time.Until(deleted.Add(ladderGCWait))) // the chunks are older than the grace if _, n := env.gc(t, true); n != 0 { t.Fatalf("the first mark reclaimed %d chunks; a chunk is reclaimed only by a second mark", n) } first := time.Now() + requireBudget(t, ladderGCWait+5*time.Minute) time.Sleep(time.Until(first.Add(ladderGCWait))) // a second mark the grace after the first eligible, _ := env.gc(t, false) - if len(eligible) != uploads[1] { - t.Fatalf("%d chunk objects eligible: %+v; want the %d the second snapshot's cut uploaded", len(eligible), eligible, uploads[1]) + want := uniqueObjects(t, "preview", eligible) + if len(want) != len(expected) { + t.Fatalf("%d chunk objects eligible: %+v; want exactly the %d bindings the second snapshot's cut created", len(want), eligible, len(expected)) } - want := map[string]bool{} - for _, o := range eligible { - if o.Volume != "v1" || !env.blobStored(t, o.FID) { - t.Fatalf("eligible object %+v is not v1 chunk data in the store", o) + for k, o := range want { + if !expected[k] { + t.Fatalf("eligible object %+v is not one the second snapshot's cut created", o) + } + if !env.blobStored(t, o.FID) { + t.Fatalf("eligible object %+v is not in the store before the applying pass", o) } - want[o.FID] = true } reclaimedObjs, n := env.gc(t, true) - if n != len(want) || len(reclaimedObjs) != len(want) { - t.Fatalf("the second mark reclaimed %d of %d eligible: %+v", n, len(want), reclaimedObjs) + got := uniqueObjects(t, "apply", reclaimedObjs) + if n != len(expected) || len(got) != len(expected) { + t.Fatalf("the second mark reclaimed %d (%d distinct) of the %d expected: %+v", n, len(got), len(expected), reclaimedObjs) } - for _, o := range reclaimedObjs { - if !want[o.FID] { + for k, o := range got { + if w, ok := want[k]; !ok || w.FID != o.FID { t.Fatalf("the second mark reclaimed %+v, which the preview did not name", o) } if env.blobStored(t, o.FID) { @@ -293,5 +385,5 @@ func TestSnapshotLadderD4DeleteAllButOneThenCollect(t *testing.T) { } } env.requireImage(t, "s1", imgs[2]) - env.restoreChecked(t, "s1", "v2", imgs[0]) + env.restoreChecked(t, "s1", "v2", imgs[0], imgs[1], imgs[2]) } From 1f757bb78b0dcefa5ba0632ebbfa873d4e3b0a7e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:16:28 -0800 Subject: [PATCH 15/71] test: F1 watches heartbeat health: slot expiries, their effects, superseded lines V1-SPEC r2.53. The rung polls the master's view of every source volume's replica each second (GetVolumeStatus) and records each span the master does not observe it, epoch changes and frontend-not-ready polls; it counts the master's per-slot "heartbeat superseded" lines per volume. Pass rule: zero slot expiries. Co-Authored-By: Claude Opus 5.5 --- ...pshot_ladder_f1_health_integration_test.go | 148 ++++++++++++++++++ .../snapshot_ladder_f1_integration_test.go | 14 +- 2 files changed, 159 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/snapshot_ladder_f1_health_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_health_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_health_integration_test.go new file mode 100644 index 0000000000..2bb3b27df7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_health_integration_test.go @@ -0,0 +1,148 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "fmt" + "os" + "strings" + "sync" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" +) + +// Rung F1's heartbeat-ordering watch (V1-SPEC r2.53): with N processes under +// one server id, a volume's slot at the master can expire when its +// heartbeats are dropped. The watch polls the master's view of every source +// volume's replica each second and records each span where the master does +// not observe it (a slot expiry), and what the volume shows meanwhile: an +// epoch change or its frontend leaving ready. At the end it counts the +// master's per-slot superseded lines for the volume ('blockmaster: +// heartbeat superseded ... volume= ...'; 0 where the master does not log +// them). + +// f1Health is one source volume's record over the whole run. +type f1Health struct { + Volume string `json:"volume"` + Replica string `json:"replica"` + Polls int `json:"polls"` + PollErrors int `json:"poll_errors"` + SlotExpiries int `json:"slot_expiries"` + SlotUnobservedMs float64 `json:"slot_unobserved_ms"` + EpochChanges int `json:"epoch_changes"` + FrontendNotReady int `json:"frontend_not_ready_polls"` + DuringExpiry []string `json:"during_expiry,omitempty"` + SupersededLogLines int `json:"master_superseded_lines"` +} + +type f1Watch struct { + stop chan struct{} + done chan struct{} + mu sync.Mutex + vols map[string]*f1Health +} + +// f1StartWatch starts polling the master for every source volume. +func f1StartWatch(env *handoffEnv, vols []f1Volume) *f1Watch { + w := &f1Watch{stop: make(chan struct{}), done: make(chan struct{}), vols: map[string]*f1Health{}} + for _, v := range vols { + w.vols[v.id] = &f1Health{Volume: v.id, Replica: env.hosts[v.node].replica} + } + go func() { + defer close(w.done) + conn, err := link.Dial(env.h.masterAddr) + if err != nil { + return + } + defer conn.Close() + cl := control.NewClusterEvidenceServiceClient(conn) + type state struct { + unobservedSince time.Time + epoch uint64 + } + st := map[string]*state{} + t := time.NewTicker(time.Second) + defer t.Stop() + for { + select { + case <-w.stop: + return + case <-t.C: + } + for _, v := range vols { + h, s := w.vols[v.id], st[v.id] + if s == nil { + s = &state{} + st[v.id] = s + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + ev, err := cl.GetVolumeStatus(ctx, &control.GetVolumeStatusRequest{VolumeId: v.id}) + cancel() + w.mu.Lock() + h.Polls++ + if err != nil { + h.PollErrors++ + w.mu.Unlock() + continue + } + observed := false + for _, r := range ev.GetReplicas() { + if r.GetReplicaId() == h.Replica && r.GetObserved() { + observed = true + } + } + now := time.Now() + switch { + case !observed && s.unobservedSince.IsZero(): + s.unobservedSince = now + h.SlotExpiries++ + case observed && !s.unobservedSince.IsZero(): + h.SlotUnobservedMs += ms(now.Sub(s.unobservedSince)) + s.unobservedSince = time.Time{} + } + if e := ev.GetEpoch(); s.epoch != 0 && e != s.epoch { + h.EpochChanges++ + if !s.unobservedSince.IsZero() { + h.DuringExpiry = append(h.DuringExpiry, fmt.Sprintf("epoch %d -> %d", s.epoch, e)) + } + } + s.epoch = ev.GetEpoch() + w.mu.Unlock() + ready := volumeFrontendReady(env.hosts[v.node].status, v.id) + w.mu.Lock() + if !ready { + h.FrontendNotReady++ + if !s.unobservedSince.IsZero() { + h.DuringExpiry = append(h.DuringExpiry, "frontend not ready at "+now.UTC().Format(time.RFC3339)) + } + } + w.mu.Unlock() + } + } + }() + return w +} + +// finish stops the watch and counts the master's superseded lines per +// volume from its log. +func (w *f1Watch) finish(masterLog string) []f1Health { + close(w.stop) + <-w.done + b, _ := os.ReadFile(masterLog) + lines := strings.Split(string(b), "\n") + w.mu.Lock() + defer w.mu.Unlock() + var out []f1Health + for _, h := range w.vols { + for _, l := range lines { + if strings.Contains(l, "heartbeat superseded") && strings.Contains(l, " volume="+h.Volume+" ") { + h.SupersededLogLines++ + } + } + out = append(out, *h) + } + return out +} diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go index f082641bf5..5405edcf9d 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go @@ -124,6 +124,7 @@ type f1Report struct { Limiter string `json:"limiter"` StartedAt time.Time `json:"started_at"` Rounds []f1Round `json:"rounds"` + Health []f1Health `json:"heartbeat_health"` CommitBound float64 `json:"commit_bound_ms"` WriteErrors int `json:"write_errors"` Verdict string `json:"verdict"` @@ -133,7 +134,7 @@ type f1Report struct { func TestSnapshotLadderF1VolumesOneHost(t *testing.T) { cfg := f1ConfigFromEnv(t) rep := &f1Report{Config: cfg, StartedAt: time.Now().UTC(), Limiter: "off"} - env := f1StartEnv(t, cfg) + env, master := f1StartEnv(t, cfg) env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} if cfg.HostLimitDir != "" { env.volExtra = append(env.volExtra, "--host-limit-dir", cfg.HostLimitDir, "--host-limit-normal-slots", strconv.Itoa(cfg.Slots)) @@ -141,6 +142,7 @@ func TestSnapshotLadderF1VolumesOneHost(t *testing.T) { } vols := f1StartSources(t, env, cfg.Volumes) defer f1WriteReport(t, cfg, rep) + watch := f1StartWatch(env, vols) for round := 1; round <= cfg.Rounds; round++ { before := f1FilerEntries(t, env) @@ -152,6 +154,7 @@ func TestSnapshotLadderF1VolumesOneHost(t *testing.T) { } rep.Rounds = append(rep.Rounds, rounds...) } + rep.Health = watch.finish(master.log) f1Judge(t, cfg, rep) } @@ -163,7 +166,7 @@ func f1RestoreTarget(vol, round int) string { return fmt.Sprintf("v%dr%d", vol, // ports. Source v is replica r; the restore target of v in round k // is replica r on the same server. The node record carries the first // source's pair, as the deployment page writes one node. -func f1StartEnv(t *testing.T, cfg f1Config) *handoffEnv { +func f1StartEnv(t *testing.T, cfg f1Config) (*handoffEnv, *daemon) { t.Helper() h := newPlannedHandoffHarness(t) env := &handoffEnv{h: h, cluster: startWorkspaceWeed(t), chunkPath: fmt.Sprintf("/f1-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}} @@ -202,7 +205,7 @@ func f1StartEnv(t *testing.T, cfg f1Config) *handoffEnv { "--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr, "--workspace-rpc", "--workspace-head-base-url", "http://"+env.cluster.filerHTTP+env.chunkPath) master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") - return env + return env, master } // f1Up starts the blockvolume of key and waits for its volume to be primary @@ -567,6 +570,11 @@ func f1Judge(t *testing.T, cfg f1Config, rep *f1Report) { waves = math.Ceil(float64(cfg.Volumes)/float64(cfg.Slots)) + 1 } rep.CommitBound = waves * worst + for _, h := range rep.Health { + if h.SlotExpiries > 0 { + rep.Failures = append(rep.Failures, fmt.Sprintf("%s: the master lost its slot %d time(s) for %.0f ms in total (during: %v)", h.Volume, h.SlotExpiries, h.SlotUnobservedMs, h.DuringExpiry)) + } + } if longest > rep.CommitBound { rep.Failures = append(rep.Failures, fmt.Sprintf("a snapshot took %.0f ms, above the bound %.0f ms (%.0f waves x the slowest cut %.0f ms): a volume starved", longest, rep.CommitBound, waves, worst)) } From b03e43d26f4dd1f726aa1e833911e52bb19818d2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:16:53 -0800 Subject: [PATCH 16/71] 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 17/71] 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 3f42d194011c5bb415f90e68d1553369c760506c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:17:33 -0800 Subject: [PATCH 18/71] test: F1 negative control for the heartbeat watch (F1_CONTROL_PAUSE_SECONDS) Co-Authored-By: Claude Opus 5.5 --- .../snapshot_ladder_f1_integration_test.go | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go index 5405edcf9d..494b282e20 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go @@ -16,6 +16,7 @@ import ( "strconv" "strings" "sync" + "syscall" "testing" "time" @@ -36,6 +37,8 @@ import ( // // A large test: it runs only with F1_RUN=1, on a host booked for it, never in // CI. Knobs: F1_VOLUMES (10), F1_ROUNDS (3), F1_WRITE_SECONDS (120), +// F1_CONTROL_PAUSE_SECONDS (a negative control: stop the last volume's +// process that long after the rounds; the rung must then fail), // F1_LOAD_SPAN (8192 blocks per volume per round, written evenly across the // write period, so writes run before, during and after the snapshots), // F1_HOST_LIMIT_DIR (a local, non-temporary directory; required for the @@ -55,6 +58,7 @@ type f1Config struct { Report string LedgerBlocksPerRnd int LoadSpan int + ControlPauseSecs int } func f1ConfigFromEnv(t *testing.T) f1Config { @@ -75,6 +79,9 @@ func f1ConfigFromEnv(t *testing.T) f1Config { c := f1Config{Volumes: num("F1_VOLUMES", 10), Rounds: num("F1_ROUNDS", 3), WriteSeconds: num("F1_WRITE_SECONDS", 120), HostLimitDir: os.Getenv("F1_HOST_LIMIT_DIR"), Slots: num("F1_HOST_LIMIT_SLOTS", hostlimit.DefaultConfig("").NormalSlots), Report: os.Getenv("F1_REPORT"), LedgerBlocksPerRnd: 64, LoadSpan: num("F1_LOAD_SPAN", 8192)} + if v := os.Getenv("F1_CONTROL_PAUSE_SECONDS"); v != "" { + c.ControlPauseSecs = num("F1_CONTROL_PAUSE_SECONDS", 0) + } if c.Rounds*(c.LedgerBlocksPerRnd+c.LoadSpan) > ladderUntouched { t.Fatalf("F1_ROUNDS=%d does not fit below the untouched chunk", c.Rounds) } @@ -154,6 +161,20 @@ func TestSnapshotLadderF1VolumesOneHost(t *testing.T) { } rep.Rounds = append(rep.Rounds, rounds...) } + if cfg.ControlPauseSecs > 0 { + // Negative control: the last volume's blockvolume is stopped + // (SIGSTOP) past the master's freshness window, so its heartbeats + // stop; the watch must record a slot expiry and the rung must fail. + last := vols[len(vols)-1] + if err := last.d.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatalf("control: SIGSTOP %s: %v", last.id, err) + } + time.Sleep(time.Duration(cfg.ControlPauseSecs) * time.Second) + if err := last.d.proc.Signal(syscall.SIGCONT); err != nil { + t.Fatalf("control: SIGCONT %s: %v", last.id, err) + } + time.Sleep(3 * time.Second) + } rep.Health = watch.finish(master.log) f1Judge(t, cfg, rep) } From d06879b76c57dd4b98e61b930b3fa232c73ece97 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:18:19 -0800 Subject: [PATCH 19/71] 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 20/71] 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 21/71] 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 1fbea05cfd7c53ebeb2102615efcde8edba8ce45 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:21:39 -0800 Subject: [PATCH 22/71] test: snapshot ladder B1 probes within the observation bound; an unjoined worker is reported Co-Authored-By: Claude Opus 5.5 --- .../snapshot_ladder_integration_test.go | 40 ++++++++++++++++--- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go index 62579cd8ea..e527eadd69 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go @@ -205,6 +205,26 @@ func (env *handoffEnv) snapshot(t *testing.T, hostID, vol, name string) snapshot return info } +// listSnapshots lists vol's snapshots (with a name prefix when given) under +// ctx, without failing the test. +func (env *handoffEnv) listSnapshots(ctx context.Context, vol, prefix string) ([]snapshotInfo, error) { + args := []string{"ops", "chunk", "snapshots", "--volume", vol, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath} + if prefix != "" { + args = append(args, "--prefix", prefix) + } + out, errOut, code, err := runCLI(ctx, env.h, args...) + if err != nil { + return nil, err + } + var body struct { + Snapshots []snapshotInfo `json:"snapshots"` + } + if code != 0 || json.Unmarshal([]byte(out), &body) != nil { + return nil, fmt.Errorf("snapshots of %s: exit %d: %s %s", vol, code, out, errOut) + } + return body.Snapshots, nil +} + // snapshots lists vol's snapshots (with a name prefix when given). func (env *handoffEnv) snapshots(t *testing.T, vol, prefix string) []snapshotInfo { t.Helper() @@ -292,7 +312,8 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) { if !joined { select { case <-done: - case <-time.After(10 * time.Second): + case <-time.After(10 * time.Second): // runCLI's 5 s WaitDelay, with a margin + t.Error("snapshot s4 worker did not finish within 10 s of its cancellation: its completion is unresolved") } } }) @@ -303,7 +324,11 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) { env.writeBlock(t, "s1", 4, pattern("ladder-b1-blk-E!")) var observed []snapshotInfo var r result + // The observation bound: every list probe runs within what is left of it, + // and a probe that returns after it fails the test. deadline := time.Now().Add(160 * time.Second) + obs, obsCancel := context.WithDeadline(context.Background(), deadline) + defer obsCancel() for running := true; running; { select { case r = <-done: @@ -313,8 +338,12 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) { if running && time.Now().After(deadline) { t.Fatal("snapshot s4 did not return within its bound") } + list, err := env.listSnapshots(obs, "v1", "s4") + if err != nil || time.Now().After(deadline) { + t.Fatalf("listing s4 within the observation bound: %v", err) + } var s4 *snapshotInfo - for _, e := range env.snapshots(t, "v1", "s4") { + for _, e := range list { e := e s4 = &e } @@ -458,9 +487,10 @@ func volumeFrontendReady(statusAddr, vol string) bool { // waitIndependent polls the restore status of target until the restore // driver reports its phase independent (what the status says; it is not a -// separate measurement of which keys hold the chunks). The bound is end to -// end: every query runs within what is left of it, and a success seen after -// it does not count. +// separate measurement of which keys hold the chunks). 120 s bounds the +// observation: every query runs within what is left of it, and a success +// seen after it does not count. A query cancelled at the bound may take up +// to runCLI's 5 s WaitDelay more to clean up. func (env *handoffEnv) waitIndependent(t *testing.T, target string) { t.Helper() const bound = 120 * time.Second From 6d7435313e2c0944e68cb8b819011c3d1b4d67a1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:21:41 -0800 Subject: [PATCH 23/71] 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 24/71] 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 a0227a27f7edab52f8749164f2d39a8886520a86 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:23:44 -0800 Subject: [PATCH 25/71] test: snapshot ladder D4 reports its collection as a measurement Co-Authored-By: Claude Opus 5.5 --- .../snapshot_ladder_d_integration_test.go | 106 +++++++++--------- 1 file changed, 52 insertions(+), 54 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go index 8e45fc8f1b..265cccfc06 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go @@ -174,21 +174,20 @@ func (env *handoffEnv) chunkKeys(t *testing.T, vol string) map[string]bool { } } -// uniqueObjects checks every object is v1's and named once (by key and by -// fid), and returns them by key. -func uniqueObjects(t *testing.T, what string, objs []gcObject) map[string]gcObject { - t.Helper() - byKey, fids := map[string]gcObject{}, map[string]bool{} +// objectsByKey indexes collector objects by key and counts the records that +// are not distinct v1 chunk objects (another volume, an empty field, or a +// key or fid named again). +func objectsByKey(objs []gcObject) (map[string]gcObject, int) { + byKey, fids, odd := map[string]gcObject{}, map[string]bool{}, 0 for _, o := range objs { - if o.Volume != "v1" || o.Key == "" || o.FID == "" || fids[o.FID] { - t.Fatalf("%s: object %+v is not a distinct v1 chunk object: %+v", what, o, objs) - } - if _, dup := byKey[o.Key]; dup { - t.Fatalf("%s: key %q named twice: %+v", what, o.Key, objs) + _, dup := byKey[o.Key] + if o.Volume != "v1" || o.Key == "" || o.FID == "" || fids[o.FID] || dup { + odd++ + continue } byKey[o.Key], fids[o.FID] = o, true } - return byKey + return byKey, odd } // requireBudget fails the test before it starts anything when the test @@ -289,30 +288,30 @@ func (env *handoffEnv) blobStored(t *testing.T, fid string) bool { return false } -// TestSnapshotLadderD4DeleteAllButOneThenCollect: three snapshots, each -// overwriting the same four chunks; the third and then the second are -// deleted. The third's chunks are still HEAD's, so only the bindings the -// second's cut created are referenced by nothing; usage says deleting it -// makes chunk bytes eligible. The expected set is taken independently of -// the collector: the chunk-key bindings that appear in the filer between the -// first and the second snapshot. Two collector passes the grace apart then -// reclaim the CHUNK DATA of exactly that set: a preview before the second -// pass names exactly those keys, each once, each still readable from the -// weed store; the applying pass reclaims exactly those, and each is then -// gone from the store. HEAD still reads the newest content and the -// remaining snapshot restores as it was. +// TestSnapshotLadderD4DeleteAllButOneThenCollect is a MEASUREMENT, not a +// pass/fail rung: what the collector reclaims after deletes, against an +// expected set taken independently of it. Three snapshots, each overwriting +// the same four chunks; the third and then the second are deleted. The +// third's chunks are still HEAD's, so the bindings the second's cut created +// (those that appear in the filer between the first and the second +// snapshot) are referenced by nothing. Two collector passes the grace apart +// run; the test reports, in one MEASUREMENT line, how many of the expected +// bindings a preview names and the applying pass reclaims, how many of +// those are gone from the weed store, what else either pass named, and the +// surplus left. It fails only when the harness cannot measure (the setup +// did not create the expected bindings, a command failed) or when data is +// lost: HEAD must still read the newest content and the remaining snapshot +// restore as it was. // // What is measured is chunk data in the weed store for the bindings the // deleted snapshot alone created, not filer entries and not the whole store. -// Excluded, known limits of today's format: +// The known surplus of today's format, not measured: // - a reclaimed binding's filer entry is kept for ever (marked reclaimed), // so filer entry counts and usage's stored bindings and stored bytes do -// not fall after collection and are not compared; +// not fall after collection; // - a needle uploaded before its binding was written (a retried upload) -// cannot be enumerated and is never reclaimed; a run without upload -// retries makes none, and the test does not look for them; -// - disk space is not measured: a deleted needle's space returns only -// when weed compacts its volume. +// cannot be enumerated and is never reclaimed; +// - disk space returns only when weed compacts its volume. func TestSnapshotLadderD4DeleteAllButOneThenCollect(t *testing.T) { requireBudget(t, 2*ladderGCWait+10*time.Minute) env := startLadderEnv(t, "v2") @@ -340,50 +339,49 @@ func TestSnapshotLadderD4DeleteAllButOneThenCollect(t *testing.T) { t.Fatalf("the second snapshot's cut uploaded %d chunks; want the %d it overwrote", uploads[1], len(chunks)) } env.deleteSnapshot(t, "v1", "s3") - if b := env.exclusiveBytes(t, "v1", "s2"); b == 0 { - t.Fatal("usage says deleting s2 frees no chunk bytes; its four overwritten chunks are referenced by nothing else") - } else { - t.Logf("deleting s2 makes %d chunk bytes eligible", b) - } + exclusive := env.exclusiveBytes(t, "v1", "s2") env.deleteSnapshot(t, "v1", "s2") env.requireSnapshotNames(t, "v1", "s1") deleted := time.Now() requireBudget(t, time.Until(deleted.Add(ladderGCWait))+ladderGCWait+5*time.Minute) time.Sleep(time.Until(deleted.Add(ladderGCWait))) // the chunks are older than the grace - if _, n := env.gc(t, true); n != 0 { - t.Fatalf("the first mark reclaimed %d chunks; a chunk is reclaimed only by a second mark", n) - } + _, firstReclaimed := env.gc(t, true) first := time.Now() requireBudget(t, ladderGCWait+5*time.Minute) time.Sleep(time.Until(first.Add(ladderGCWait))) // a second mark the grace after the first eligible, _ := env.gc(t, false) - want := uniqueObjects(t, "preview", eligible) - if len(want) != len(expected) { - t.Fatalf("%d chunk objects eligible: %+v; want exactly the %d bindings the second snapshot's cut created", len(want), eligible, len(expected)) - } - for k, o := range want { + named, oddPreview := objectsByKey(eligible) + namedExpected, namedOther, storedBefore := 0, 0, 0 + for k, o := range named { if !expected[k] { - t.Fatalf("eligible object %+v is not one the second snapshot's cut created", o) + namedOther++ + continue } - if !env.blobStored(t, o.FID) { - t.Fatalf("eligible object %+v is not in the store before the applying pass", o) + namedExpected++ + if env.blobStored(t, o.FID) { + storedBefore++ } } reclaimedObjs, n := env.gc(t, true) - got := uniqueObjects(t, "apply", reclaimedObjs) - if n != len(expected) || len(got) != len(expected) { - t.Fatalf("the second mark reclaimed %d (%d distinct) of the %d expected: %+v", n, len(got), len(expected), reclaimedObjs) - } - for k, o := range got { - if w, ok := want[k]; !ok || w.FID != o.FID { - t.Fatalf("the second mark reclaimed %+v, which the preview did not name", o) + reclaimed, oddApply := objectsByKey(reclaimedObjs) + reclaimedExpected, reclaimedOther, goneAfter := 0, 0, 0 + for k, o := range reclaimed { + if !expected[k] { + reclaimedOther++ + continue } - if env.blobStored(t, o.FID) { - t.Fatalf("reclaimed chunk %+v is still in the store", o) + reclaimedExpected++ + if !env.blobStored(t, o.FID) { + goneAfter++ } } + t.Logf("D4 MEASUREMENT: expected %d bindings (s2's cut uploaded %d chunks; usage: deleting s2 frees %d bytes); "+ + "first mark reclaimed %d; preview named %d of them (%d still in the store), %d others, %d malformed; "+ + "apply reclaimed %d (%d of them, %d now gone from the store), %d others, %d malformed; surplus left: %d of the expected", + len(expected), uploads[1], exclusive, firstReclaimed, namedExpected, storedBefore, namedOther, oddPreview, + n, reclaimedExpected, goneAfter, reclaimedOther, oddApply, len(expected)-goneAfter) env.requireImage(t, "s1", imgs[2]) env.restoreChecked(t, "s1", "v2", imgs[0], imgs[1], imgs[2]) } From 7e7bb9cbf8a0e2381c8b9584f631bf0439c94026 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 17:24:44 -0800 Subject: [PATCH 26/71] 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 27/71] 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 28/71] 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 9970fb2c4eee54a77a2dd324e786a8655d3f788e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:16:20 -0800 Subject: [PATCH 29/71] test: refuse attach on filer HEAD lookup errors --- .../chunkstore/attach_lookup_error_test.go | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/attach_lookup_error_test.go diff --git a/seaweed-block/core/frontend/chunkstore/attach_lookup_error_test.go b/seaweed-block/core/frontend/chunkstore/attach_lookup_error_test.go new file mode 100644 index 0000000000..57c5b5c087 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/attach_lookup_error_test.go @@ -0,0 +1,84 @@ +package chunkstore + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type attachLookupProjection struct{} + +func (attachLookupProjection) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1, Healthy: true} +} + +// V1-SPEC r2.55 gap 10; INV-WS-CLAIM-BEFORE-SERVE-001. +// Real gRPC lookup errors pass through SWFS and a fresh durable provider. +// An existing HEAD must never become a bootstrap claim or an I/O-ready volume. +func TestAttachLookupUnavailableIsNotAnAbsentHead(t *testing.T) { + for _, code := range []codes.Code{codes.Unavailable, codes.DeadlineExceeded, codes.PermissionDenied, codes.Internal} { + t.Run(code.String(), func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + head := storage.ChunkHead{Gen: 7, Epoch: 3, Holder: "node/r1", State: storage.ChunkHeadActive} + entry, err := headEntry(head) + if err != nil { + t.Fatal(err) + } + f := &fakeFilerGRPC{lookupResp: &filerpb.LookupDirectoryEntryResponse{Entry: entry}} + swfs := startFakeFiler(t, f) + remote, err := NewChunkRemote(swfs, newFakeBlobs(), "/chunks/v1") + if err != nil { + t.Fatal(err) + } + before, err := remote.GetHead(ctx) + if err != nil || before.Gen != 7 { + t.Fatalf("pre-existing HEAD=%+v error=%v", before, err) + } + f.mu.Lock() + // The absence sentinel inside an Unavailable message is still an error. + f.lookupErr = status.Error(code, "lookup failed: "+filerNotFoundText) + f.mu.Unlock() + if h, err := remote.GetHead(ctx); err == nil || errors.Is(err, ErrNotFound) || status.Code(err) != code { + t.Fatalf("failed lookup became an absent HEAD: head=%+v error=%v", h, err) + } + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16, + ChunkHolder: "node/r1", + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, attachLookupProjection{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(ctx, "v1"); status.Code(err) != code { + t.Fatalf("attach error=%v; want preserved %s", err, code) + } + if err := p.AdmitsIO("v1"); err == nil { + t.Fatal("failed HEAD lookup admitted guest I/O") + } + f.mu.Lock() + created, updated := f.lastCreate, f.lastUpdate + f.lookupErr = nil + f.mu.Unlock() + if created != nil || updated != nil { + t.Fatalf("failed lookup attempted a HEAD CAS: create=%+v update=%+v", created, updated) + } + after, err := remote.GetHead(ctx) + if err != nil || after.Gen != head.Gen || after.Holder != head.Holder || after.Epoch != head.Epoch { + t.Fatalf("failed attach changed HEAD: %+v error=%v", after, err) + } + }) + } +} From f7c329672b21c28b7a51983bdd75e7448c6c7995 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:16:37 -0800 Subject: [PATCH 30/71] test: kill -9 with guest I/O in flight, restart, read back every acked block Single-volume coverage gap 1, cell A2.4 (V1-SPEC r2.55): a qd1 NVMe/TCP writer streams distinct blocks with a Flush every 8 writes; the holder is SIGKILLed mid-stream and restarted inside the lease at the same epoch; every Flush-acknowledged write must read back, and what survives past the last acknowledged Flush must be a prefix of the stream, untorn. Co-Authored-By: Claude Opus 5.5 --- .../procedure_crash_io_integration_test.go | 144 ++++++++++++++++++ 1 file changed, 144 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go new file mode 100644 index 0000000000..3314be24f8 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go @@ -0,0 +1,144 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "fmt" + "sync" + "testing" + "time" +) + +// Single-volume coverage, gap 1 (cell A2.4, V1-SPEC r2.55): kill -9 of the +// holder WITH guest I/O in flight, then a restart inside the lease. Every +// write a Flush acknowledged must read back after the restart +// (INV-WAL-SYNCED-RECOVERED-001); writes not yet acknowledged by a Flush may +// vanish, but what is left of them must be a prefix of the stream in LBA +// order with nothing torn or invented (the writer writes LBAs in order). +// +// The writer is the guest: qd1 NVMe/TCP writes of distinct blocks, a Flush +// every crashIOFlushEvery writes; it records the last LBA a successful +// Flush covered. The holder is killed while the writer is mid-stream. + +const ( + crashIOBase = 2048 // first LBA the writer uses (chunk 2) + crashIOSpan = 40000 + crashIOFlushEvery = 8 +) + +func crashIOBlock(lba uint64) []byte { + s := fmt.Sprintf("crash-io lba %08d|", lba) + b := make([]byte, 4096) + for i := range b { + b[i] = s[i%len(s)] + } + return b +} + +// crashIOWriter writes LBAs crashIOBase.. in order until stopped or an I/O +// fails, and reports how far the Flush acknowledgements reached. +type crashIOWriter struct { + mu sync.Mutex + written int // writes completed (acknowledged by the write itself) + flushed int // writes covered by an acknowledged Flush + err error + done chan struct{} +} + +func startCrashIOWriter(t *testing.T, env *handoffEnv, id string) *crashIOWriter { + t.Helper() + w := &crashIOWriter{done: make(chan struct{})} + c := dialNVMe(t, env.hosts[id].nvme, plannedHandoffNQN) + go func() { + defer close(w.done) + defer c.close() + for n := 0; n < crashIOSpan; n++ { + lba := crashIOBase + uint64(n) + err := c.tryWrite(lba, crashIOBlock(lba)) + if err == nil && n%crashIOFlushEvery == crashIOFlushEvery-1 { + err = c.tryFlush() + if err == nil { + w.mu.Lock() + w.flushed = n + 1 + w.mu.Unlock() + } + } + w.mu.Lock() + if err != nil { + w.err = err + } else { + w.written = n + 1 + } + w.mu.Unlock() + if err != nil { + return + } + } + }() + return w +} + +func (w *crashIOWriter) counts() (written, flushed int, err error) { + w.mu.Lock() + defer w.mu.Unlock() + return w.written, w.flushed, w.err +} + +func TestProcedureCrashWithIOInFlight(t *testing.T) { + env := startHandoffEnv(t, 1) + first := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, first, "s1") + + w := startCrashIOWriter(t, env, "s1") + // Let the stream run until a good number of Flushes acknowledged, so the + // kill lands mid-stream with writes in flight. + poll(t, 60*time.Second, "the writer never got 2000 flushed writes", func() bool { + _, flushed, err := w.counts() + return flushed >= 2000 || err != nil + }) + if _, _, err := w.counts(); err != nil { + t.Fatalf("a write failed before the kill: %v", err) + } + first.kill(t) // SIGKILL while the writer is still writing + select { + case <-w.done: + case <-time.After(70 * time.Second): + t.Fatal("the writer did not stop after the holder was killed") + } + written, flushed, werr := w.counts() + if werr == nil { + t.Fatalf("the writer finished all %d writes before the kill: no I/O was in flight", crashIOSpan) + } + t.Logf("at the kill: %d writes completed, %d covered by an acknowledged Flush; the writer's error: %v", written, flushed, werr) + + again := env.start(t, "blockvolume-s1-again", "s1") + if got := env.adopt(t, again, "s1"); got != e { + t.Fatalf("the restarted holder adopted epoch %d; want %d", got, e) + } + + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + defer c.close() + zero := make([]byte, 4096) + for n := 0; n < flushed; n++ { + lba := crashIOBase + uint64(n) + if got := c.read(t, lba, 4096); !bytes.Equal(got, crashIOBlock(lba)) { + t.Fatalf("flush-acknowledged write %d (LBA %d) is lost or wrong after kill -9 and restart", n, lba) + } + } + // Past the Flush acknowledgements: a prefix of the stream, then zeros. + kept, ended := flushed, false + for n := flushed; n < written+crashIOFlushEvery && n < crashIOSpan; n++ { + lba := crashIOBase + uint64(n) + got := c.read(t, lba, 4096) + switch { + case !ended && bytes.Equal(got, crashIOBlock(lba)): + kept++ + case bytes.Equal(got, zero): + ended = true + default: + t.Fatalf("LBA %d after the last acknowledged Flush holds data out of the stream's order or torn (kept %d)", lba, kept) + } + } + t.Logf("after the restart: all %d flush-acknowledged writes read back; %d of the %d unflushed completed writes survived as a prefix", flushed, kept-flushed, written-flushed) +} From 013a9ac19c9d0def7954e177572cf3036bf163ae Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:17:50 -0800 Subject: [PATCH 31/71] test: kill -9 on a fresh root with fills in flight, restart, read back Single-volume coverage gap 1, cell A3.5 (V1-SPEC r2.55): after a clean move to s2 (fresh root, lazy hydration), a reader walks 60 chunks that only HEAD holds while a writer streams Flush-acknowledged writes into other chunks; s2 is SIGKILLed mid-walk and restarted at the same epoch; every source chunk must read back (fills redone) and every acknowledged write survive. Co-Authored-By: Claude Opus 5.5 --- .../procedure_crash_io_integration_test.go | 181 ++++++++++++++++++ 1 file changed, 181 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go index 3314be24f8..390fbaa8d1 100644 --- a/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go @@ -8,6 +8,8 @@ import ( "sync" "testing" "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" ) // Single-volume coverage, gap 1 (cell A2.4, V1-SPEC r2.55): kill -9 of the @@ -142,3 +144,182 @@ func TestProcedureCrashWithIOInFlight(t *testing.T) { } t.Logf("after the restart: all %d flush-acknowledged writes read back; %d of the %d unflushed completed writes survived as a prefix", flushed, kept-flushed, written-flushed) } + +// Gap 1, cell A3.5: kill -9 of a holder serving on a FRESH root (after a +// clean move) while chunk fills from HEAD are in flight. s1 writes one block +// in each of the first fillChunks chunks; after the hand-over, s2 starts +// with no local copy. A reader walks those chunks (each read misses and +// fills) while a writer streams Flush-acknowledged writes into chunks s1 +// never wrote; s2 is SIGKILLed mid-walk and restarted. Every s1 block must +// read back (the fills are redone from HEAD) and every acknowledged s2 write +// must survive. +const ( + fillChunks = 60 + fillWriterBase = 60 * ladderChunkBlocks + fillWriterSpan = 4 * ladderChunkBlocks + fillFlushEvery = 8 +) + +func fillSourceBlock(c int) []byte { + s := fmt.Sprintf("fill-src chunk %03d|", c) + b := make([]byte, 4096) + for i := range b { + b[i] = s[i%len(s)] + } + return b +} + +func TestProcedureCrashOnAFreshRootWithFillsInFlight(t *testing.T) { + env := startHandoffEnv(t, 2) + must, mustU := fatalOn(t) + h := env.h + + old := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, old, "s1") + for c := 0; c < fillChunks; c++ { + env.writeBlock(t, "s1", uint64(c*ladderChunkBlocks), fillSourceBlock(c)) + } + g := env.seal(t, "s1", e) + l := env.sealedLSN(t, e, g) + env.revoke(t, e, g) + if err := old.wait(30 * time.Second); err != nil { + t.Fatalf("s1 after the revocation: %v", err) + } + env.waitAck(t, e, g) + moved, _ := h.command(t, env.moveClean(e, "s2", "move-fill-1")...) + e2 := mustU(movedEpochTo(moved, e, g, l, "s2")) + nw := env.start(t, "blockvolume-s2", "s2") + must(checkClaimDoneBy(nw.waitLog(t, 60*time.Second, "durable: HEAD claim for volume=v1 done in"), e2, "s2")) + if got := env.adopt(t, nw, "s2"); got != e2 { + t.Fatalf("s2 adopted at epoch %d; want %d", got, e2) + } + + // The reader: read misses fill each source chunk from HEAD. + var rmu sync.Mutex + reads, readErr := 0, error(nil) + readerDone := make(chan struct{}) + rc := dialNVMe(t, env.hosts["s2"].nvme, plannedHandoffNQN) + go func() { + defer close(readerDone) + defer rc.close() + for c := 0; c < fillChunks; c++ { + _, err := rc.tryRead(uint64(c*ladderChunkBlocks), 4096) + rmu.Lock() + if err != nil { + readErr = err + rmu.Unlock() + return + } + reads = c + 1 + rmu.Unlock() + } + }() + // The writer: acknowledged local writes into chunks s1 never wrote. + var wmu sync.Mutex + written, flushed := 0, 0 + writerDone := make(chan struct{}) + wc := dialNVMe(t, env.hosts["s2"].nvme, plannedHandoffNQN) + go func() { + defer close(writerDone) + defer wc.close() + for n := 0; n < fillWriterSpan; n++ { + lba := uint64(fillWriterBase + n) + err := wc.tryWrite(lba, crashIOBlock(lba)) + if err == nil && n%fillFlushEvery == fillFlushEvery-1 { + if err = wc.tryFlush(); err == nil { + wmu.Lock() + flushed = n + 1 + wmu.Unlock() + } + } + if err != nil { + return + } + wmu.Lock() + written = n + 1 + wmu.Unlock() + } + }() + poll(t, 60*time.Second, "s2 never got its first fills and acknowledged writes", func() bool { + rmu.Lock() + r := reads + rmu.Unlock() + wmu.Lock() + f := flushed + wmu.Unlock() + return r >= 3 && f >= 64 + }) + nw.kill(t) // SIGKILL with fills and writes in flight + <-readerDone + <-writerDone + rmu.Lock() + readsAtKill, rerr := reads, readErr + rmu.Unlock() + wmu.Lock() + writtenAtKill, flushedAtKill := written, flushed + wmu.Unlock() + if readsAtKill >= fillChunks { + t.Fatalf("the reader finished all %d fills before the kill: no fill was in flight", fillChunks) + } + t.Logf("at the kill: %d of %d source chunks read (filled), reader error %v; %d writes completed, %d covered by a Flush", readsAtKill, fillChunks, rerr, writtenAtKill, flushedAtKill) + + again := env.start(t, "blockvolume-s2-again", "s2") + if got := env.adopt(t, again, "s2"); got != e2 { + t.Fatalf("the restarted s2 adopted epoch %d; want %d", got, e2) + } + c := dialNVMe(t, env.hosts["s2"].nvme, plannedHandoffNQN) + defer c.close() + for k := 0; k < fillChunks; k++ { + if got := c.read(t, uint64(k*ladderChunkBlocks), 4096); !bytes.Equal(got, fillSourceBlock(k)) { + t.Fatalf("source chunk %d (filled before the kill: %t) does not read back after the restart", k, k < readsAtKill) + } + } + for n := 0; n < flushedAtKill; n++ { + lba := uint64(fillWriterBase + n) + if got := c.read(t, lba, 4096); !bytes.Equal(got, crashIOBlock(lba)) { + t.Fatalf("flush-acknowledged write %d (LBA %d) on the fresh root is lost after kill -9 and restart", n, lba) + } + } + t.Logf("after the restart: all %d source chunks and all %d flush-acknowledged writes read back", fillChunks, flushedAtKill) +} + +// tryRead is read returning the error (for readers off the test goroutine). +func (c *nvmeInitiator) tryRead(lba uint64, n int) ([]byte, error) { + cmd := c.ioCmd(0x02, lba, n/4096) + if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil { + return nil, fmt.Errorf("nvme Read: %w", err) + } + var data []byte + for { + ch, err := c.r.Dequeue() + if err != nil { + return nil, fmt.Errorf("nvme Read: %w", err) + } + if ch.Type == 0x5 { + var resp nvme.CapsuleResponse + if err := c.r.Receive(&resp); err != nil { + return nil, fmt.Errorf("nvme Read response: %w", err) + } + if resp.Status != 0 { + return nil, fmt.Errorf("nvme Read status 0x%04x", resp.Status) + } + break + } + if ch.Type != 0x7 { + return nil, fmt.Errorf("nvme Read: unexpected PDU type 0x%x", ch.Type) + } + var dh nvme.C2HDataHeader + if err := c.r.Receive(&dh); err != nil { + return nil, fmt.Errorf("nvme C2HData: %w", err) + } + part := make([]byte, c.r.Length()) + if err := c.r.ReceiveData(part); err != nil { + return nil, fmt.Errorf("nvme C2HData payload: %w", err) + } + data = append(data, part...) + } + if len(data) != n { + return nil, fmt.Errorf("nvme Read returned %d bytes; want %d", len(data), n) + } + return data, nil +} From 5cf01ed1ba63f386563defc39fdf5d5cb03b0443 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:19:33 -0800 Subject: [PATCH 32/71] test: delete the five WAL test files that hold no test Single-volume coverage side finding (c) (V1-SPEC r2.55): walstore_sticky_fsync_test.go, walstore_midhistory_hole_test.go, walstore_checkpoint_crash_linux_test.go and walstore_checkpoint_safety_test.go held only helpers or constants with no caller (their tests were retired with format v2; docs/design/format-v3-legacy-test-inventory.md lists them and their v3 replacements). walstore_recovery_hardening_test.go keeps its one used helper, crashRecoveryHardeningStore. A comment that pointed at a deleted file is removed. Co-Authored-By: Claude Opus 5.5 --- .../durable_startup_slotcrc_test.go | 1 - .../walstore_checkpoint_crash_linux_test.go | 8 --- .../walstore_checkpoint_safety_test.go | 11 ---- .../storage/walstore_midhistory_hole_test.go | 22 -------- .../walstore_recovery_hardening_test.go | 53 ++----------------- .../storage/walstore_sticky_fsync_test.go | 26 --------- 6 files changed, 4 insertions(+), 117 deletions(-) delete mode 100644 seaweed-block/core/storage/walstore_checkpoint_crash_linux_test.go delete mode 100644 seaweed-block/core/storage/walstore_checkpoint_safety_test.go delete mode 100644 seaweed-block/core/storage/walstore_midhistory_hole_test.go delete mode 100644 seaweed-block/core/storage/walstore_sticky_fsync_test.go diff --git a/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go b/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go index bf0e7a71f7..7cb6b9097c 100644 --- a/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go +++ b/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go @@ -152,7 +152,6 @@ func TestDurableStartup_Issue51_SmartWALTornTailRecovers(t *testing.T) { // V3 replaces the legacy warning-only recovery policy with nonce-bound, // contiguous WAL recovery. Corruption below strict W must block readiness. -// The old v2 warning control is retained in walstore_midhistory_hole_test.go. func TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness(t *testing.T) { const childEnv = "SWBLOCK_V3_STARTUP_CRASH_PATH" if path := os.Getenv(childEnv); path != "" { diff --git a/seaweed-block/core/storage/walstore_checkpoint_crash_linux_test.go b/seaweed-block/core/storage/walstore_checkpoint_crash_linux_test.go deleted file mode 100644 index 9d43987575..0000000000 --- a/seaweed-block/core/storage/walstore_checkpoint_crash_linux_test.go +++ /dev/null @@ -1,8 +0,0 @@ -//go:build linux - -package storage - -const ( - checkpointCrashHelperEnv = "SW_BLOCK_CHECKPOINT_CRASH_HELPER" - checkpointCrashPathEnv = "SW_BLOCK_CHECKPOINT_CRASH_PATH" -) diff --git a/seaweed-block/core/storage/walstore_checkpoint_safety_test.go b/seaweed-block/core/storage/walstore_checkpoint_safety_test.go deleted file mode 100644 index ea5b3cec51..0000000000 --- a/seaweed-block/core/storage/walstore_checkpoint_safety_test.go +++ /dev/null @@ -1,11 +0,0 @@ -package storage - -import ( - "time" -) - -func replaceFlusherForTest(s *WALStore, interval time.Duration) { - s.flusher.Stop() - s.flusher = newFlusher(s, flusherConfig{Interval: interval}) - go s.flusher.run() -} diff --git a/seaweed-block/core/storage/walstore_midhistory_hole_test.go b/seaweed-block/core/storage/walstore_midhistory_hole_test.go deleted file mode 100644 index 50e7e2a2a1..0000000000 --- a/seaweed-block/core/storage/walstore_midhistory_hole_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package storage - -import ( - "strings" -) - -func walOffsetsByLBA(s *WALStore) map[uint64]uint64 { - offs := map[uint64]uint64{} - for _, e := range s.dm.snapshot() { - offs[e.LBA] = e.WALOffset - } - return offs -} - -func holeWarning(s *WALStore) bool { - for _, w := range s.RecoveryWarnings() { - if strings.HasPrefix(w, WarningWALHoleSuspected+":") { - return true - } - } - return false -} diff --git a/seaweed-block/core/storage/walstore_recovery_hardening_test.go b/seaweed-block/core/storage/walstore_recovery_hardening_test.go index 7428036e42..f5ae541ed1 100644 --- a/seaweed-block/core/storage/walstore_recovery_hardening_test.go +++ b/seaweed-block/core/storage/walstore_recovery_hardening_test.go @@ -1,14 +1,10 @@ package storage -import ( - "bytes" - "encoding/binary" - - "hash/crc32" - - "testing" -) +import "testing" +// crashRecoveryHardeningStore drops the store without a clean close: the +// committer stops, the owned map and the file descriptor close, nothing is +// flushed. Tests reopen the file afterwards to observe crash recovery. func crashRecoveryHardeningStore(t *testing.T, s *WALStore) { t.Helper() s.committer.Stop() @@ -22,44 +18,3 @@ func crashRecoveryHardeningStore(t *testing.T, s *WALStore) { t.Fatal(err) } } - -func recoverySnapshotEntriesByLBA(entries []snapshotEntry) map[uint64]snapshotEntry { - result := make(map[uint64]snapshotEntry, len(entries)) - for _, entry := range entries { - result[entry.LBA] = entry - } - return result -} - -func rewriteRecoveryRecordForTest( - t *testing.T, - s *WALStore, - recordSize uint64, - absoluteOffset int64, - mutate func([]byte), -) { - t.Helper() - record := make([]byte, recordSize) - if _, err := s.fd.ReadAt(record, absoluteOffset); err != nil { - t.Fatal(err) - } - mutate(record) - binary.LittleEndian.PutUint32( - record[len(record)-8:], - crc32.ChecksumIEEE(record[:len(record)-8]), - ) - if _, err := s.fd.WriteAt(record, absoluteOffset); err != nil { - t.Fatal(err) - } -} - -func assertRecoveryHardeningBlock(t *testing.T, s *WALStore, lba uint32, want []byte) { - t.Helper() - got, err := s.Read(lba) - if err != nil { - t.Fatal(err) - } - if !bytes.Equal(got, want) { - t.Fatalf("current LBA %d mismatch", lba) - } -} diff --git a/seaweed-block/core/storage/walstore_sticky_fsync_test.go b/seaweed-block/core/storage/walstore_sticky_fsync_test.go deleted file mode 100644 index 344c4e0944..0000000000 --- a/seaweed-block/core/storage/walstore_sticky_fsync_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package storage - -import ( - "errors" - - "testing" -) - -// A failed fsync is sticky for the open store (the "fsyncgate" pattern: on -// Linux the kernel may already have dropped the dirty pages, so a later -// successful fsync proves nothing about them). After the first failure the -// store acknowledges no further Sync, accepts no further write and advances -// no checkpoint, with a typed SubstrateIO failure; only a reopen clears it. - -var errInjectedFsync = errors.New("injected fsync failure") - -func assertStickyFsync(t *testing.T, err error) { - t.Helper() - if !errors.Is(err, ErrFsyncFailed) { - t.Fatalf("err %v; want the sticky ErrFsyncFailed", err) - } - var rf *RecoveryFailure - if !errors.As(err, &rf) || rf.Kind != StorageRecoveryFailureSubstrateIO { - t.Fatalf("err %v; want a SubstrateIO RecoveryFailure (io_error)", err) - } -} From d3a35df524406c71e746c71ae541c1b306fda400 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:19:38 -0800 Subject: [PATCH 33/71] docs: snapshot names and retries Co-Authored-By: Claude Fable 5.2 --- seaweed-block/docs/volume-lifecycle.md | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/volume-lifecycle.md b/seaweed-block/docs/volume-lifecycle.md index 7d0a32b32e..51d1c37bce 100644 --- a/seaweed-block/docs/volume-lifecycle.md +++ b/seaweed-block/docs/volume-lifecycle.md @@ -403,6 +403,26 @@ and step 4 is refused with `live authority requires clean revocation ACK`. Nothi was deleted. Start `blockvolume` again with the same flags and local root, then do step 2 and continue. This recovery is not run by a test in this release. +## Snapshot names and retries + +A snapshot request first takes its name, then publishes the snapshot. Three rules +follow from that order: + +- **A name taken by an unfinished request is not listed, but it is held.** + `sw-block ops chunk snapshots` shows only published snapshots. If a snapshot request + was interrupted after it took its name (the process crashed, or the caller gave up), + the name does not appear in the list, yet another request for that name is refused + with `snapshot_exists`, and deleting the volume is refused with `volume v1 has + snapshots (NAME); delete them first`. Free it with + `sw-block ops chunk snapshot-delete --volume v1 --chunk-filer FILER --name NAME`, + or finish it by repeating the request with the same `--request-id`. +- **After `outcome_unknown`, repeat the request with the same `--request-id` within + 5 minutes.** Later, the unfinished attempt may have been swept, and the request is + then refused with `this request's attempt was aborted; delete the name to reuse + it`: delete the name and take the snapshot again. +- **A `--request-id` protects against a duplicate only while its snapshot name + exists.** After `snapshot-delete`, repeating the same request takes a new snapshot. + ## Symptoms | You see | It means | Do | @@ -411,7 +431,8 @@ step 2 and continue. This recovery is not run by a test in this release. | detach answers `detach_aborted` | Nothing was published; the volume serves here again | Retry step 3 | | detach answers `outcome_unknown` | The seal may have landed; I/O stays stopped | Retry step 3: it settles the outcome | | volume-delete: `volume_in_use: ... live authority requires clean revocation ACK` | The volume was sealed (or only stopped) but never revoked and acknowledged; nothing was deleted | "Delete a volume", step 2 | -| volume-delete: `volume v1 has snapshots (s1); delete them first` | Snapshots still exist; nothing was deleted | "Delete a volume", step 3 | +| volume-delete: `volume v1 has snapshots (s1); delete them first` | Snapshots still exist, or a name is held by an unfinished request (such a name is not in the list); nothing was deleted | "Delete a volume", step 3; for a name that is not listed, "Snapshot names and retries" | +| snapshot: `snapshot_exists ... this request's attempt was aborted; delete the name to reuse it` | An earlier attempt of this request did not finish and was swept | `snapshot-delete` the name, then take the snapshot again | | revoke: `workspace revoke: no matching lease` | `--replica`/`--epoch` are not the current holder | Read them again with `show` | | move: `workspace clean move needs detached HEAD and matching revocation ACK` | No ACK yet, or its generation differs from HEAD | Wait for the ACK line (step 5); compare `G` with `ops chunk show` | | move: `move target node "S2" is not registered` | `S2` is not under `nodes` | Add it to the cluster spec, restart blockmaster | From 6b52cd53ae004ec8b2114fd06498f501b95912dc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:20:00 -0800 Subject: [PATCH 34/71] test: fence invalid workspace renewal replies before expiry --- .../volume/workspace_invalid_reply_test.go | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 seaweed-block/core/host/volume/workspace_invalid_reply_test.go diff --git a/seaweed-block/core/host/volume/workspace_invalid_reply_test.go b/seaweed-block/core/host/volume/workspace_invalid_reply_test.go new file mode 100644 index 0000000000..5dd3eda939 --- /dev/null +++ b/seaweed-block/core/host/volume/workspace_invalid_reply_test.go @@ -0,0 +1,82 @@ +package volume + +import ( + "context" + "strings" + "testing" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// INV-WS-LEASE-001 / V1-SPEC r2.55 gap 9: invalid-reply fencing from a held, +// unexpired lease, rather than passing because a synthetic deadline expired. +func TestWorkspaceGuardFencesOnInvalidReply(t *testing.T) { + for _, tc := range []struct { + name string + change func(*control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact + }{ + {"nil", func(*control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact { return nil }}, + {"volume", func(r *control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact { r.VolumeId = "other"; return r }}, + {"replica", func(r *control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact { r.ReplicaId = "other"; return r }}, + {"epoch", func(r *control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact { r.Epoch++; return r }}, + {"zero validity", func(r *control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact { r.ValidForNs = 0; return r }}, + {"negative validity", func(r *control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact { r.ValidForNs = -1; return r }}, + {"over maximum validity", func(r *control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact { + r.ValidForNs = int64(30*time.Second) + 1 + return r + }}, + } { + t.Run(tc.name, func(t *testing.T) { + now := time.Now() + calls, stops, acks := 0, 0, 0 + client := workspaceTestClient{ + renew: func() (*control.WorkspaceLeaseFact, error) { + calls++ + r := &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(10 * time.Second)} + if calls == 2 { + r = tc.change(r) + } + return r, nil + }, + ack: func() error { acks++; return nil }, + } + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, + &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", ServerId: "node", Epoch: 1}, + func(context.Context) (uint64, error) { stops++; return 7, nil }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if err := g.Refresh(ctx); err != nil || !g.Held() || !g.Projection().Healthy { + t.Fatalf("valid unexpired lease was not held before injection: %v cause=%s", err, g.FenceCause()) + } + if err := g.Refresh(ctx); err == nil || !strings.Contains(err.Error(), "invalid workspace lease reply") { + t.Fatalf("invalid reply did not trigger its own refusal: %v cause=%s", err, g.FenceCause()) + } + if !strings.Contains(g.FenceCause(), "invalid lease reply") || g.Held() || g.Projection().Healthy || stops != 1 || acks != 0 { + t.Fatalf("invalid-reply fence: cause=%s held=%v healthy=%v stops=%d acks=%d", g.FenceCause(), g.Held(), g.Projection().Healthy, stops, acks) + } + if err := g.Refresh(ctx); err == nil || g.Held() || g.Projection().Healthy || calls != 2 || stops != 1 || acks != 0 { + t.Fatalf("fenced guard reopened or renewed: err=%v calls=%d stops=%d acks=%d", err, calls, stops, acks) + } + }) + } +} + +func TestWorkspaceGuardAcceptsMaximumValidReply(t *testing.T) { + now := time.Now() + client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) { + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(30 * time.Second)}, nil + }} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, + &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", ServerId: "node", Epoch: 1}, + func(context.Context) (uint64, error) { t.Fatal("valid lease drained"); return 0, nil }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err != nil || !g.Held() || !g.Projection().Healthy { + t.Fatalf("maximum valid lease refused: %v cause=%s", err, g.FenceCause()) + } +} From ee0fb26cc7cd64c0319839aea03793468e936aa6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:21:20 -0800 Subject: [PATCH 35/71] test: catalog restart after a snapshot create abandoned at each filer step Co-Authored-By: Claude Opus 5.5 --- .../chunkstore/catalog_crash_snapshot_test.go | 233 ++++++++++++++++++ 1 file changed, 233 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/catalog_crash_snapshot_test.go diff --git a/seaweed-block/core/frontend/chunkstore/catalog_crash_snapshot_test.go b/seaweed-block/core/frontend/chunkstore/catalog_crash_snapshot_test.go new file mode 100644 index 0000000000..90b7c5efa0 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/catalog_crash_snapshot_test.go @@ -0,0 +1,233 @@ +package chunkstore + +import ( + "context" + "errors" + "path" + "strings" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" +) + +// errCrashed is what a filer call returns once the process that issued it +// is dead. +var errCrashed = errors.New("crashed") + +// crashFiler models a blockvolume killed in the middle of a catalog +// operation: at the chosen filer call it dies, before or after that call +// reaches the filer, and from then on no call of it reaches the filer, so +// none of its cleanup runs. Blob calls are not intercepted (snapshot create +// writes entries only). +type crashFiler struct { + manifestFilerBlobs + mu sync.Mutex + dead bool + match func(op, p string) bool // the call at which the process dies + after bool // the call reaches the filer, its reply is lost +} + +func (c *crashFiler) gate(op, p string) (pass, die bool) { + c.mu.Lock() + defer c.mu.Unlock() + if c.dead { + return false, false + } + if c.match(op, p) { + c.dead = true + return c.after, true + } + return true, false +} + +func (c *crashFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if pass, _ := c.gate("lookup", path.Join(dir, name)); !pass { + return nil, errCrashed + } + return c.manifestFilerBlobs.LookupEntry(ctx, dir, name) +} + +func (c *crashFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error { + pass, die := c.gate("create", path.Join(dir, e.GetName())) + if !pass { + return errCrashed + } + err := c.manifestFilerBlobs.CreateEntry(ctx, dir, e, oExcl) + if die { + return errCrashed + } + return err +} + +func (c *crashFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error { + pass, die := c.gate("update", path.Join(dir, e.GetName())) + if !pass { + return errCrashed + } + err := c.manifestFilerBlobs.UpdateEntry(ctx, dir, e, expected) + if die { + return errCrashed + } + return err +} + +func (c *crashFiler) ListEntries(ctx context.Context, dir, prefix, startAfter string, limit uint32) ([]*filerpb.Entry, error) { + if pass, _ := c.gate("list", dir); !pass { + return nil, errCrashed + } + return c.manifestFilerBlobs.ListEntries(ctx, dir, prefix, startAfter, limit) +} + +func (c *crashFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { + pass, die := c.gate("delete", path.Join(dir, name)) + if !pass { + return errCrashed + } + err := c.manifestFilerBlobs.DeleteEntry(ctx, dir, name, expected) + if die { + return errCrashed + } + return err +} + +// TestCatalogRestartAfterAbandonedSnapshot: a snapshot create of s1 whose +// process dies at each of its filer steps (after the name record, after the +// intent, with the attempt create lost before or after it applied, after the +// create before the intent is dropped), then a catalog restarted over the +// same filer. Whatever the step: +// - the create never answers success unless its attempt entry was +// written; +// - the list shows s1 only if its attempt entry was written, and then as +// the snapshot of the cut HEAD, never a partial one; +// - a retry with the same request id completes s1, listed once; +// - a new snapshot of another name is taken and listed; +// - when s1 is abandoned unpublished, its name record still holds the name +// (another request gets snapshot_exists) and blocks volume delete +// (volume_has_snapshots), and deleting s1 settles it: the name is free +// and the volume delete completes. +func TestCatalogRestartAfterAbandonedSnapshot(t *testing.T) { + isName := func(p string) bool { return p == path.Join(catBase, "v1", snapNamesDir, "s1") } + isIntent := func(p string) bool { return strings.HasPrefix(p, path.Join(catBase, "v1", intentsDir)+"/") } + isAttempt := func(p string) bool { return isSnapPath(p, "v1", "s1") } + for _, tc := range []struct { + name string + op string + at func(string) bool + after bool + published bool // the attempt entry was written before the crash + }{ + {"after the name record", "create", isName, true, false}, + {"after the intent", "create", isIntent, true, false}, + {"attempt create lost before it applied", "create", isAttempt, false, false}, + {"attempt create applied, reply lost", "create", isAttempt, true, true}, + {"before the intent is dropped", "delete", isIntent, false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + f, b, _, h := deleteFixture(t) + ctx := context.Background() + detachHead(t, f, b, "v1") + crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}, after: tc.after, + match: func(op, p string) bool { return op == tc.op && tc.at(p) }} + dying, err := NewCatalog(crashed, catBase) + if err != nil { + t.Fatal(err) + } + // A crash before the attempt entry is written cannot return success; + // once it is written the create has succeeded (the intent drop + // after it is best effort), whatever the caller then hears. + if _, err := dying.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err == nil && !tc.published { + t.Fatal("the create returned success although its process died before publishing") + } + crashed.mu.Lock() + died := crashed.dead + crashed.mu.Unlock() + if !died { + t.Fatalf("the create never reached the step %q", tc.name) + } + + c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) // the restarted process + if err != nil { + t.Fatal(err) + } + list := func() []SnapshotInfo { + t.Helper() + l, _, err := c.ListSnapshots(ctx, "v1", ListOptions{}) + if err != nil { + t.Fatal(err) + } + return l + } + switch l := list(); { + case !tc.published && len(l) != 0: + t.Fatalf("an unpublished snapshot is listed after the restart: %+v", l) + case tc.published && (len(l) != 1 || l[0].Name != "s1" || l[0].HeadGen != h.Gen || l[0].State != SnapActive): + t.Fatalf("after the restart the list is %+v; want s1 of HEAD gen %d, active", l, h.Gen) + } + + if !tc.published { + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "other"}, h); CodeOf(err) != CodeSnapshotExists { + t.Fatalf("another request for the abandoned name: %v; want snapshot_exists (the name record holds it)", err) + } + if _, err := c.DeleteVolume(ctx, "v1", nil); CodeOf(err) != CodeVolumeHasSnapshots { + t.Fatalf("volume delete with the abandoned name record: %v; want volume_has_snapshots", err) + } + } + + info, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h) + if err != nil || info.Name != "s1" || info.HeadGen != h.Gen { + t.Fatalf("retry with the same request id after the restart: %+v %v", info, err) + } + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s2", RequestID: "r2"}, h); err != nil { + t.Fatalf("the next snapshot after the restart: %v", err) + } + if l := list(); len(l) != 2 || l[0].Name != "s1" || l[1].Name != "s2" { + t.Fatalf("after the retry and the next snapshot the list is %+v; want s1, s2 once each", l) + } + + for _, name := range []string{"s1", "s2"} { + if _, err := c.DeleteSnapshot(ctx, "v1", name); err != nil { + t.Fatalf("delete %s: %v", name, err) + } + } + if l := list(); len(l) != 0 { + t.Fatalf("after deleting both the list is %+v", l) + } + if res, err := c.DeleteVolume(ctx, "v1", nil); err != nil || !res.Completed { + t.Fatalf("volume delete after the snapshots are deleted: %+v %v", res, err) + } + }) + } +} + +// TestCatalogAbandonedUnpublishedSnapshotIsSettledByDelete: an abandoned, +// never-published s1 (the process died after its name record) is settled by +// deleting it without a retry: the name is then free for another request and +// the volume delete is no longer blocked by it. +func TestCatalogAbandonedUnpublishedSnapshotIsSettledByDelete(t *testing.T) { + f, b, _, h := deleteFixture(t) + ctx := context.Background() + detachHead(t, f, b, "v1") + crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}, after: true, + match: func(op, p string) bool { return op == "create" && p == path.Join(catBase, "v1", snapNamesDir, "s1") }} + dying, err := NewCatalog(crashed, catBase) + if err != nil { + t.Fatal(err) + } + if _, err := dying.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err == nil { + t.Fatal("the create returned success although its process died") + } + c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) + if err != nil { + t.Fatal(err) + } + if st, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapDeleting { + t.Fatalf("delete of the abandoned s1: %q %v", st, err) + } + if l, _, err := c.ListSnapshots(ctx, "v1", ListOptions{}); err != nil || len(l) != 0 { + t.Fatalf("list after settling: %+v %v", l, err) + } + if res, err := c.DeleteVolume(ctx, "v1", nil); err != nil || !res.Completed { + t.Fatalf("volume delete after settling the abandoned name: %+v %v", res, err) + } +} From 6515e3f9d9603462a61a9f3e56cf1d4f14417d60 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:23:12 -0800 Subject: [PATCH 36/71] test: snapshot ladder E1 (holder killed during a snapshot, restart), not yet gated Co-Authored-By: Claude Opus 5.5 --- .../snapshot_ladder_e_integration_test.go | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go new file mode 100644 index 0000000000..33b358eff3 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go @@ -0,0 +1,118 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "encoding/json" + "fmt" + "testing" + "time" +) + +// Rung E of the snapshot ladder: faults. E1 kills the holder (SIGKILL) while +// a snapshot is being taken, at several points of the snapshot, and restarts +// it within its lease. The per-step crash cases of the catalog half (after +// the name record, after the intent, with the attempt create unknown) are +// pinned by a unit test of the catalog; this rung is the same property +// through the real processes. + +// TestSnapshotLadderE1CrashDuringASnapshot: four rounds on one volume. In +// each, blocks in two new chunks are written and acknowledged, a snapshot +// with a fixed request id is started, and the holder is killed after a +// different delay (from at once to well into the snapshot), then restarted +// within its lease. After each restart: +// - the snapshot is listed at most once and only active; if its command +// answered success before the kill, it is listed; +// - a retry with the same request id completes it, listed once. +// +// At the end a next snapshot is taken after more writes. Every round's +// snapshot and the next one restore (to independence, per the restore +// status) exactly as the volume was when each was requested, with every +// block written after it reading zero: nothing partial, nothing lost. +func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) { + delays := []time.Duration{0, 50 * time.Millisecond, 200 * time.Millisecond, 600 * time.Millisecond} + targets := []string{"v2", "v3", "v4", "v5", "v6"} + env := startHandoffEnvWith(t, 1, targets) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + holder := env.start(t, "blockvolume-v1", "s1") + e := env.adopt(t, holder, "s1") + marker := pattern("ladder-e1-marker") + env.writeBlock(t, "s1", 0, marker) + + type result struct { + out, errOut string + code int + err error + } + var images []map[uint64][]byte // what each round's snapshot must hold + cum := map[uint64][]byte{0: marker} + for k, delay := range delays { + img := ladderImage(fmt.Sprintf("e1r%d", k), []uint64{uint64(k + 1), uint64(20 + k)}, 3) + env.writeImage(t, "s1", img) + cum = mergeImages(cum, img) + images = append(images, cum) + name, req := fmt.Sprintf("e1-%d", k), fmt.Sprintf("r-e1-%d", k) + + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) + done := make(chan result, 1) + go func() { + out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status, + "--name", name, "--request-id", req) + done <- result{out, errOut, code, err} + }() + time.Sleep(delay) + holder.kill(t) + var r result + select { + case r = <-done: + case <-time.After(60 * time.Second): + cancel() + t.Fatalf("round %d: the snapshot command did not return within 60 s of the holder's kill", k) + } + cancel() + answered := r.err == nil && r.code == 0 + t.Logf("round %d (kill after %v): snapshot command exit %d err %v", k, delay, r.code, r.err) + + // Restarted within the lease, as the unit's RestartSec does: the same + // epoch, serving the blocks written before the kill. + holder = env.start(t, fmt.Sprintf("blockvolume-v1-r%d", k), "s1") + if got := env.adopt(t, holder, "s1"); got != e { + t.Fatalf("round %d: the restarted holder adopted epoch %d; want %d", k, got, e) + } + env.requireImage(t, "s1", cum) + + switch l := env.snapshots(t, "v1", name); { + case len(l) > 1: + t.Fatalf("round %d: %s listed %d times: %+v", k, name, len(l), l) + case len(l) == 1 && l[0].State != "active": + t.Fatalf("round %d: %s listed but not active: %+v", k, name, l[0]) + case len(l) == 0 && answered: + t.Fatalf("round %d: %s answered success before the kill but is not listed: %s", k, name, r.out) + } + out, _ := env.h.command(t, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status, + "--name", name, "--request-id", req) + var info snapshotInfo + if err := json.Unmarshal([]byte(out), &info); err != nil || info.Name != name { + t.Fatalf("round %d: retry of %s: %v %s", k, name, err, out) + } + if l := env.snapshots(t, "v1", name); len(l) != 1 || l[0].State != "active" || l[0].CutLSN != info.CutLSN { + t.Fatalf("round %d: after the retry %s is listed as %+v; its retry answered %+v", k, name, l, info) + } + } + + next := ladderImage("e1next", []uint64{30, 31}, 3) + env.writeImage(t, "s1", next) + env.snapshot(t, "s1", "v1", "e1-next") + final := mergeImages(cum, next) + + for k := range delays { + var later []map[uint64][]byte + for j := k + 1; j < len(images); j++ { + later = append(later, images[j]) + } + later = append(later, next) + env.restoreChecked(t, fmt.Sprintf("e1-%d", k), targets[k], images[k], later...) + } + env.restoreChecked(t, "e1-next", targets[len(delays)], final) +} From 83d4dd1cb6fcd2e73ab150267325fed48f31b8ae Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:23:06 -0800 Subject: [PATCH 37/71] test: enable takeover image checks at the production claim seam --- ...d_test.go => chunk_layer_takeover_test.go} | 42 ++++++++++++------- 1 file changed, 28 insertions(+), 14 deletions(-) rename seaweed-block/core/storage/{chunk_layer_takeover_red_test.go => chunk_layer_takeover_test.go} (75%) diff --git a/seaweed-block/core/storage/chunk_layer_takeover_red_test.go b/seaweed-block/core/storage/chunk_layer_takeover_test.go similarity index 75% rename from seaweed-block/core/storage/chunk_layer_takeover_red_test.go rename to seaweed-block/core/storage/chunk_layer_takeover_test.go index b1169575dd..4c6c0f5be8 100644 --- a/seaweed-block/core/storage/chunk_layer_takeover_red_test.go +++ b/seaweed-block/core/storage/chunk_layer_takeover_test.go @@ -1,12 +1,6 @@ -//go:build chunk_takeover_red - -// RED tests for the takeover CAS at attach (W2 spec §6.3, P5). They are -// written by W2 and implemented by W4; the build tag keeps them out of the -// default suite until then. Run them with: -// -// go test -tags chunk_takeover_red -run TestChunkAttach_TakeOver ./core/storage/ -// -// The implementation should remove the build tag. +// V1-SPEC r2.55 side (a), coverage cell P10.6; +// INV-WS-CLAIM-BEFORE-SERVE-001. The production attach path first claims +// HEAD, then attaches the chunk layer against that exact claim. package storage @@ -36,6 +30,11 @@ func TestChunkAttach_TakeOverRaisesEpoch(t *testing.T) { s, _ := newChunkTestStore(t) cfg := ctConfig(2) cfg.FreshFromHead = true + claimed, err := ClaimChunkHead(ctTimeout(t), f, cfg) + if err != nil { + t.Fatal(err) + } + cfg.RestoreGuard = &ChunkHeadVersion{Gen: claimed.Gen, Epoch: claimed.Epoch} mustAttach(t, s, f, cfg) head := f.stats().head @@ -50,6 +49,12 @@ func TestChunkAttach_TakeOverRaisesEpoch(t *testing.T) { t.Fatalf("takeover changed chunk %d: %+v, want %+v", k, head.Chunks[k], v) } } + for lba := uint32(0); lba < ctNumBlocks; lba++ { + got, err := s.Read(lba) + if err != nil || !bytes.Equal(got, blockOf(takeoverImage(), lba)) { + t.Fatalf("takeover read LBA %d: bytes differ from seeded image, err=%v", lba, err) + } + } // The old holder (epoch 1) can no longer commit. if _, err := f.CASHead(ctTimeout(t), chunkHeadVersion{Gen: seeded.Gen, Epoch: 1}, seeded); !errors.Is(err, errChunkHeadPrecondition) { t.Fatalf("old holder's CAS after takeover: %v, want errChunkHeadPrecondition", err) @@ -86,7 +91,7 @@ func TestChunkAttach_TakeOverRacesOldHolder(t *testing.T) { s, _ := newChunkTestStore(t) cfg := ctConfig(2) cfg.FreshFromHead = true - layer, err := attachChunkLayer(s, f, cfg) + claimed, err := ClaimChunkHead(ctTimeout(t), f, cfg) f.mu.Lock() ran := injected f.mu.Unlock() @@ -101,15 +106,24 @@ func TestChunkAttach_TakeOverRacesOldHolder(t *testing.T) { if h := f.stats().head; h.Holder == cfg.Holder { t.Fatalf("attach failed (%v) but HEAD names the new holder: %+v", err, h) } - return + if !errors.Is(err, ErrChunkHeadPrecondition) { + t.Fatalf("competing publication was not a definite claim refusal: %v", err) + } + // Retry the definite refusal through the same claim seam; the + // successful retry must serve every byte of the competing image. + claimed, err = ClaimChunkHead(ctTimeout(t), f, cfg) + if err != nil { + t.Fatal(err) + } } - t.Cleanup(func() { _ = layer.Close() }) + cfg.RestoreGuard = &ChunkHeadVersion{Gen: claimed.Gen, Epoch: claimed.Epoch} + mustAttach(t, s, f, cfg) head := f.stats().head - if head.Epoch != 2 || head.Holder != cfg.Holder { + if head.Epoch != 2 || head.Holder != cfg.Holder || head.RemoteLSN != 101 { t.Fatalf("attach returned without taking over: HEAD epoch %d holder %q", head.Epoch, head.Holder) } - want := f.imageOf(t, head) + want := newer for lba := uint32(0); lba < ctNumBlocks; lba++ { got, err := s.Read(lba) if err != nil { From 78517f7b34f2424089cc90ea7b3ac8f5b000ec78 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:24:37 -0800 Subject: [PATCH 38/71] test: kill -9 mid-cut at each stage, restart, next cut publishes the volume Single-volume coverage gap 2, unit part (cells P5.4, P6.4, P8.7, P9.4, P10.4, P11.3; V1-SPEC r2.55): a cut dies after admission, at the barrier, during the upload, before the HEAD CAS and after the CAS applied (before its reply). The process death closes the store without cleanup and loses every later remote call. After the restart HEAD is whole (old before the CAS, new after it), every synced local write reads back, and the next cut publishes the volume as it is. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_cut_crash_test.go | 240 ++++++++++++++++++ 1 file changed, 240 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_cut_crash_test.go diff --git a/seaweed-block/core/storage/chunk_cut_crash_test.go b/seaweed-block/core/storage/chunk_cut_crash_test.go new file mode 100644 index 0000000000..3567df0a07 --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_crash_test.go @@ -0,0 +1,240 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "sync" + "testing" +) + +// Single-volume coverage gap 2 (cells P5.4, P6.4, P8.7, P9.4, P10.4, P11.3; +// V1-SPEC r2.55): the holder dies (kill -9) in the middle of a cut, at each +// stage, and restarts. Expected: HEAD is the old image (or, once the CAS +// applied, the new one), never a mix; every synced local write reads back +// after the restart; the next cut succeeds and publishes the volume as it +// is. The crash is modelled as a process death: the store's file is closed +// without any cleanup and every later remote mutation from the dead +// process is lost (crashRemote), so the remote keeps exactly what the dead +// cut had sent. + +var errProcessDead = errors.New("injected: the process is dead") + +// crashRemote forwards to the fake until killed; after that every remote +// call of the dead process fails without reaching the fake: a dead process +// neither writes nor reads. +type crashRemote struct { + *fakeChunkRemote + mu sync.Mutex + dead bool + puts int + onPut func(n int) // after the n-th successful Put + onCAS func(applied bool) + casSeen bool + beforeCAS bool // kill before the CAS is sent +} + +func (r *crashRemote) isDead() bool { r.mu.Lock(); defer r.mu.Unlock(); return r.dead } + +func (r *crashRemote) kill() { r.mu.Lock(); r.dead = true; r.mu.Unlock() } + +func (r *crashRemote) Put(ctx context.Context, key string, data []byte) error { + if r.isDead() { + return errProcessDead + } + if err := r.fakeChunkRemote.Put(ctx, key, data); err != nil { + return err + } + r.mu.Lock() + r.puts++ + n, hook := r.puts, r.onPut + r.mu.Unlock() + if hook != nil { + hook(n) + } + return nil +} + +func (r *crashRemote) CASHead(ctx context.Context, expected chunkHeadVersion, next chunkHead) (uint64, error) { + if r.isDead() { + return 0, errProcessDead + } + r.mu.Lock() + before, hook := r.beforeCAS, r.onCAS + r.mu.Unlock() + if before && hook != nil { + hook(false) + return 0, errProcessDead + } + gen, err := r.fakeChunkRemote.CASHead(ctx, expected, next) + if err == nil && hook != nil { + hook(true) + return 0, errProcessDead // the reply never reaches the dead process + } + return gen, err +} + +func (r *crashRemote) Delete(ctx context.Context, key string) error { + if r.isDead() { + return errProcessDead + } + return r.fakeChunkRemote.Delete(ctx, key) +} + +func (r *crashRemote) PutIntent(ctx context.Context, in chunkIntent) (string, error) { + if r.isDead() { + return "", errProcessDead + } + return r.fakeChunkRemote.PutIntent(ctx, in) +} + +func (r *crashRemote) Get(ctx context.Context, key string) ([]byte, error) { + if r.isDead() { + return nil, errProcessDead + } + return r.fakeChunkRemote.Get(ctx, key) +} + +func (r *crashRemote) GetHead(ctx context.Context) (chunkHead, error) { + if r.isDead() { + return chunkHead{}, errProcessDead + } + return r.fakeChunkRemote.GetHead(ctx) +} + +func (r *crashRemote) ListIntents(ctx context.Context) ([]chunkIntent, error) { + if r.isDead() { + return nil, errProcessDead + } + return r.fakeChunkRemote.ListIntents(ctx) +} + +func (r *crashRemote) DeleteIntent(ctx context.Context, id string) error { + if r.isDead() { + return errProcessDead + } + return r.fakeChunkRemote.DeleteIntent(ctx, id) +} + +// cutCrashImage is the volume's content as a byte image. +func cutCrashImage(t *testing.T, s *WALStore) []byte { + t.Helper() + img := make([]byte, 0, ctNumBlocks*ctBlockSize) + for lba := uint32(0); lba < ctNumBlocks; lba++ { + b, err := s.Read(lba) + if err != nil { + t.Fatalf("read LBA %d: %v", lba, err) + } + img = append(img, b...) + } + return img +} + +func TestChunkCutCrashAtEachStage(t *testing.T) { + stages := []struct { + name string + // arm installs the kill at the stage; applied says whether the + // stage is past the HEAD CAS. + arm func(l *chunkLayerImpl, r *crashRemote, die func()) + applied bool + }{ + {"after admission", func(l *chunkLayerImpl, r *crashRemote, die func()) { l.testAfterAdmitHook = die }, false}, + {"at the barrier, after Sync fixed H", func(l *chunkLayerImpl, r *crashRemote, die func()) { + l.testAfterBarrierSyncHook = func(uint64) { die() } + }, false}, + {"during the upload, after the first chunk", func(l *chunkLayerImpl, r *crashRemote, die func()) { + r.onPut = func(n int) { + if n == 1 { + die() + } + } + }, false}, + {"before the HEAD CAS is sent", func(l *chunkLayerImpl, r *crashRemote, die func()) { + r.beforeCAS = true + r.onCAS = func(bool) { die() } + }, false}, + {"after the HEAD CAS applied, before its reply", func(l *chunkLayerImpl, r *crashRemote, die func()) { + r.onCAS = func(applied bool) { + if applied { + die() + } + } + }, true}, + } + for _, st := range stages { + t.Run(st.name, func(t *testing.T) { + ctx := ctTimeout(t) + s, path, crashStore := crashableStore(t) + f := newFakeChunkRemote() + r := &crashRemote{fakeChunkRemote: f} + cfg := ctConfig(1) + l := mustAttach(t, s, r, cfg).(*chunkLayerImpl) + for lba := uint32(0); lba < ctNumBlocks; lba++ { + if _, err := s.Write(lba, makeBlock(ctBlockSize, byte(0x10+lba))); err != nil { + t.Fatal(err) + } + } + mustSyncFlush(t, s) + if _, err := l.Capture(ctx); err != nil { + t.Fatal(err) + } + old, _ := f.GetHead(ctx) + oldImage := f.imageOf(t, old) + + // New writes, then the cut that dies. + for lba := uint32(4); lba < 12; lba++ { // chunks 1 and 2 + if _, err := s.Write(lba, makeBlock(ctBlockSize, byte(0xC0+lba))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + want := cutCrashImage(t, s) + die := func() { + r.kill() + crashStore() + } + r.mu.Lock() + r.puts = 0 // count this cut's uploads only + r.mu.Unlock() + st.arm(l, r, die) + _, cutErr := l.Capture(ctx) + if !r.isDead() { + t.Fatalf("the stage %q was never reached (puts %d, cut error %v)", st.name, r.puts, cutErr) + } + if cutErr == nil { + t.Fatal("the cut succeeded although the process died during it") + } + if s.v3 != nil && s.v3.ownedMap != nil { // the dead process's map file + _ = s.v3.ownedMap.Close() + s.v3.ownedMap = nil + } + + // Restart: the store recovers its WAL; HEAD is old or new, whole. + s2, _ := reopen(t, path) + head, _ := f.GetHead(ctx) + got := f.imageOf(t, head) + switch { + case st.applied && !bytes.Equal(got, want): + t.Fatalf("the CAS applied but HEAD (gen %d) is not the new image", head.Gen) + case !st.applied && (head.Gen != old.Gen || !bytes.Equal(got, oldImage)): + t.Fatalf("a cut that died before its CAS changed HEAD: gen %d -> %d", old.Gen, head.Gen) + } + if local := cutCrashImage(t, s2); !bytes.Equal(local, want) { + t.Fatal("a synced local write is lost after the crash and restart") + } + l2 := mustAttach(t, s2, f, cfg) + if _, err := l2.Capture(ctx); err != nil { + t.Fatalf("the first cut after the restart: %v", err) + } + final, _ := f.GetHead(ctx) + if !bytes.Equal(f.imageOf(t, final), want) { + t.Fatalf("the cut after the restart (gen %d) does not publish the volume as it is", final.Gen) + } + if intents, err := f.ListIntents(ctx); err == nil { + t.Logf("stage %q: HEAD gen %d -> crash -> %d -> %d after the next cut; %d intent(s) left", st.name, old.Gen, head.Gen, final.Gen, len(intents)) + } + }) + } +} From d27ddb677720f46eee9383496164a0904c276f23 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:24:38 -0800 Subject: [PATCH 39/71] test: snapshot ladder C3 with kills: target killed mid-hydrate and mid-batch, writes while owning Co-Authored-By: Claude Opus 5.5 --- ...snapshot_ladder_c3kill_integration_test.go | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go new file mode 100644 index 0000000000..b97305a71d --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go @@ -0,0 +1,119 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "encoding/json" + "fmt" + "testing" + "time" +) + +// restoreProgress is the restore driver's status of a target. +type restoreProgress struct { + Phase string `json:"phase"` + Running bool `json:"running"` + Filled int `json:"filled"` + Owned int `json:"owned"` + Foreign int `json:"foreign"` + Batches int `json:"batches"` +} + +// awaitRestorePhase polls target's restore status every 50 ms until ok +// holds and returns that status; it fails the test if the restore failed, +// became independent first (the moment was missed), or bound passed. +func (env *handoffEnv) awaitRestorePhase(t *testing.T, target, what string, bound time.Duration, ok func(restoreProgress) bool) restoreProgress { + t.Helper() + end := time.Now().Add(bound) + ctx, cancel := context.WithDeadline(context.Background(), end) + defer cancel() + for time.Now().Before(end) { + out, _, code, err := runCLI(ctx, env.h, "ops", "chunk", "restore", "--volume", target, "--status-addr", env.hosts["n-"+target].status, "--status") + var st restoreProgress + if err == nil && code == 0 && json.Unmarshal([]byte(out), &st) == nil { + switch { + case ok(st): + return st + case st.Phase == "failed": + t.Fatalf("restore of %s failed waiting for %s: %s", target, what, out) + case st.Phase == "independent": + t.Fatalf("restore of %s became independent before %s was seen (the restore is too small to catch it): %s", target, what, out) + } + } + time.Sleep(50 * time.Millisecond) + } + t.Fatalf("restore of %s: %s not seen within %v", target, what, bound) + return restoreProgress{} +} + +// startTarget starts target's blockvolume and waits until it serves. +func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon { + t.Helper() + b := env.hosts["n-"+target] + d := env.h.start(t, name, env.h.volume, env.volArgsFor(b)...) + d.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at r1@", target)) + poll(t, 60*time.Second, fmt.Sprintf("%s never reported its frontend ready", target), func() bool { + return volumeFrontendReady(b.status, target) + }) + return d +} + +// TestSnapshotLadderC3KilledMidHydrateAndMidBatch: a restore of a snapshot +// of 48 written chunks into v2 (about 192 MiB to make local and re-upload). +// Its blockvolume is killed (SIGKILL) while the driver is hydrating, started +// again and the driver started again. While the driver then owns chunks, the +// guest writes to v2 (acknowledged), and the blockvolume is killed again in +// the middle of the batch, restarted, and the driver started again; the +// guest writes once more. The driver resumes from the target's remote facts +// to independence (per its status). Then v2 holds the snapshot with every +// acknowledged write over it, and the source's snapshot, restored again +// into v3, is unchanged (none of v2's writes in it). +func TestSnapshotLadderC3KilledMidHydrateAndMidBatch(t *testing.T) { + env := startLadderEnv(t, "v2", "v3") + var chunks []uint64 + for c := uint64(0); c < 48; c++ { + chunks = append(chunks, c) + } + src := ladderImage("c3ksrc", chunks, 2) + env.writeImage(t, "s1", src) + env.snapshot(t, "s1", "v1", "base") + + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "base", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + target := env.startTarget(t, "v2", "blockvolume-v2") + drive := func() { + t.Helper() + env.h.command(t, "ops", "chunk", "restore", "--volume", "v2", "--status-addr", env.hosts["n-v2"].status) + } + drive() + + // Killed while hydrating: some chunks local, not all. + st := env.awaitRestorePhase(t, "v2", "hydrating with part of the chunks local", 120*time.Second, func(s restoreProgress) bool { + return s.Phase == "hydrating" && s.Filled > 0 && s.Filled < len(chunks) + }) + target.kill(t) + t.Logf("killed while hydrating: %+v", st) + target = env.startTarget(t, "v2", "blockvolume-v2-after-hydrate-kill") + env.requireImage(t, "n-v2", src) // serves the snapshot at once after the restart + drive() + + // Written while owning, then killed in the middle of the batch. + env.awaitRestorePhase(t, "v2", "owning", 180*time.Second, func(s restoreProgress) bool { return s.Phase == "owning" }) + w1 := ladderImage("c3kw1", []uint64{3, 17, 50}, 3) + env.writeImage(t, "n-v2", w1) + st = env.awaitRestorePhase(t, "v2", "owning with chunks still foreign", 180*time.Second, func(s restoreProgress) bool { + return s.Phase == "owning" && s.Foreign > 0 + }) + target.kill(t) + t.Logf("killed while owning: %+v", st) + target = env.startTarget(t, "v2", "blockvolume-v2-after-batch-kill") + env.requireImage(t, "n-v2", mergeImages(src, w1)) // every acknowledged write survived the kill + drive() + w2 := ladderImage("c3kw2", []uint64{17, 40, 60}, 2) + env.writeImage(t, "n-v2", w2) + + env.waitIndependent(t, "v2") + env.requireImage(t, "n-v2", mergeImages(src, w1, w2)) + env.restoreChecked(t, "base", "v3", src, w1, w2) +} From 41332710a7861997c8eeea4f1df00e0245e8417a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:25:36 -0800 Subject: [PATCH 40/71] test: kill -9 during a cut's upload with real binaries, restart, read back Single-volume coverage gap 2, procedure part (cells P8.7, P9.4, P11.3; V1-SPEC r2.55): image A is cut, every block rewritten (image B), and the holder SIGKILLed half-way through the second cut. After the restart HEAD verifies whole at depth data, the volume reads B, and the next cut, restored into a new volume through a snapshot, is B. Co-Authored-By: Claude Opus 5.5 --- .../procedure_crash_io_integration_test.go | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go index 390fbaa8d1..ec37361533 100644 --- a/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go @@ -323,3 +323,94 @@ func (c *nvmeInitiator) tryRead(lba uint64, n int) ([]byte, error) { } return data, nil } + +// Gap 2, procedure part (cells P8.7, P9.4, P11.3): kill -9 of the holder +// during a cut's upload, with real binaries. Image A is cut; every block is +// rewritten (image B, flushed); a second cut starts and the holder is +// SIGKILLed at half the first cut's duration. After the restart: HEAD +// verifies whole at depth data (old or new image, nothing missing), every +// block reads B locally, and the next cut, read back through a snapshot +// restored into a new volume, is B. +const ( + cutCrashChunks = 48 + cutCrashPer = 64 // blocks written per chunk +) + +func cutCrashBlock(img byte, lba uint64) []byte { + s := fmt.Sprintf("cut-crash %c lba %08d|", img, lba) + b := make([]byte, 4096) + for i := range b { + b[i] = s[i%len(s)] + } + return b +} + +func (env *handoffEnv) writeCutCrashImage(t *testing.T, img byte) { + t.Helper() + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + defer c.close() + for ch := 0; ch < cutCrashChunks; ch++ { + for i := 0; i < cutCrashPer; i++ { + lba := uint64(ch*ladderChunkBlocks + i) + c.write(t, lba, cutCrashBlock(img, lba)) + } + } + c.flush(t) +} + +func (env *handoffEnv) requireCutCrashImage(t *testing.T, hostID string, img byte) { + t.Helper() + c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN) + defer c.close() + for ch := 0; ch < cutCrashChunks; ch++ { + for i := 0; i < cutCrashPer; i++ { + lba := uint64(ch*ladderChunkBlocks + i) + if got := c.read(t, lba, 4096); !bytes.Equal(got, cutCrashBlock(img, lba)) { + t.Fatalf("%s: LBA %d is not image %c", hostID, lba, img) + } + } + } +} + +func TestProcedureCrashDuringACut(t *testing.T) { + env := startHandoffEnvWith(t, 1, []string{"v2"}) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + first := env.start(t, "blockvolume-v1", "s1") + e := env.adopt(t, first, "s1") + cut := []string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status} + verify := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data"} + + env.writeCutCrashImage(t, 'A') + cutStart := time.Now() + env.h.command(t, cut...) + full := time.Since(cutStart) + env.writeCutCrashImage(t, 'B') + + done := make(chan int, 1) + go func() { + _, _, code := env.h.run(t, cut...) + done <- code + }() + time.Sleep(full / 2) + select { + case code := <-done: + t.Fatalf("the second cut finished (exit %d) before the kill at %s: no upload was in flight", code, full/2) + default: + } + first.kill(t) + code := <-done + t.Logf("the first cut took %s; the holder was killed at %s into the second (its CLI exit %d)", full, full/2, code) + + if out, errOut, rc := env.h.run(t, verify...); rc != 0 { + t.Fatalf("HEAD is not whole after the kill (verify exit %d):\n%s\n%s", rc, out, errOut) + } + again := env.start(t, "blockvolume-v1-again", "s1") + if got := env.adopt(t, again, "s1"); got != e { + t.Fatalf("the restarted holder adopted epoch %d; want %d", got, e) + } + env.requireCutCrashImage(t, "s1", 'B') + env.h.command(t, cut...) + env.snapshot(t, "s1", "v1", "after-crash") + env.restoreInto(t, "v1", "after-crash", "v2") + env.requireCutCrashImage(t, "n-v2", 'B') +} From eab3a3366e7b41212a0abaf3e1c889d3282fa621 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:26:12 -0800 Subject: [PATCH 41/71] 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 b5d87e313beb4467c819ca8911678ee180ba1922 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:27:25 -0800 Subject: [PATCH 42/71] test: keep attach fixture setup outside the injected-error oracle --- .../core/frontend/chunkstore/attach_lookup_error_test.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/attach_lookup_error_test.go b/seaweed-block/core/frontend/chunkstore/attach_lookup_error_test.go index 57c5b5c087..59fb9245ed 100644 --- a/seaweed-block/core/frontend/chunkstore/attach_lookup_error_test.go +++ b/seaweed-block/core/frontend/chunkstore/attach_lookup_error_test.go @@ -3,6 +3,7 @@ package chunkstore import ( "context" "errors" + "strings" "testing" "time" @@ -26,7 +27,7 @@ func (attachLookupProjection) Projection() frontend.Projection { func TestAttachLookupUnavailableIsNotAnAbsentHead(t *testing.T) { for _, code := range []codes.Code{codes.Unavailable, codes.DeadlineExceeded, codes.PermissionDenied, codes.Internal} { t.Run(code.String(), func(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() head := storage.ChunkHead{Gen: 7, Epoch: 3, Holder: "node/r1", State: storage.ChunkHeadActive} entry, err := headEntry(head) @@ -47,7 +48,7 @@ func TestAttachLookupUnavailableIsNotAnAbsentHead(t *testing.T) { // The absence sentinel inside an Unavailable message is still an error. f.lookupErr = status.Error(code, "lookup failed: "+filerNotFoundText) f.mu.Unlock() - if h, err := remote.GetHead(ctx); err == nil || errors.Is(err, ErrNotFound) || status.Code(err) != code { + if h, err := remote.GetHead(ctx); err == nil || errors.Is(err, ErrNotFound) || status.Code(err) != code || !strings.Contains(err.Error(), "lookup failed: "+filerNotFoundText) { t.Fatalf("failed lookup became an absent HEAD: head=%+v error=%v", h, err) } p, err := durable.NewDurableProvider(durable.ProviderConfig{ @@ -62,7 +63,7 @@ func TestAttachLookupUnavailableIsNotAnAbsentHead(t *testing.T) { if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) } - if _, err := p.RecoverVolume(ctx, "v1"); status.Code(err) != code { + if _, err := p.RecoverVolume(ctx, "v1"); status.Code(err) != code || !strings.Contains(err.Error(), "lookup failed: "+filerNotFoundText) { t.Fatalf("attach error=%v; want preserved %s", err, code) } if err := p.AdmitsIO("v1"); err == nil { From 20fafb4927d330b2bab59536ba7f844327c171ee Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:30:36 -0800 Subject: [PATCH 43/71] docs: state live-lease blockmaster clock safety premise --- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/operator-guide.md | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7831af1871..8b848a73a8 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1066,7 +1066,7 @@ A row that names a function existing only on an open pull request says so ("on # | Term | Meaning | Field(s) | Deciding function (one per side) | Known second derivations to remove | Owner role | |---|---|---|---|---|---| | `TERM-HOLDER-001` Holder identity (the primary of a single-copy workspace volume only; supporting replicas are not holders) | The process that may act as primary of a single-copy workspace volume at an epoch is the pair (server id, replica id) at that epoch. A matching replica id or endpoint alone never names it, and a missing server id is refused. No local-root nonce joins it (V1-SPEC r2.45); one live process per volume on a host is the host lock (`TERM-ONE-PROCESS-001`). | `AssignmentFact` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/control.proto`; `server_id` on [#411](https://github.com/seaweedfs/seaweed-block/pull/411)); `WorkspaceIdentity` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/workspace.proto`; `server_id` on #411); the published line's `PublishedLine.IssuedHost` (`core/authority/workspace_lease_view.go`) and the move journal's `WorkspaceMoveRecord.NewHost` (`core/authority/workspace.go`); the volume's `Config.ServerID`, `Config.ReplicaID` (`core/host/volume/host.go`, from `--server-id`, `--replica-id`); the HEAD `Holder`, written as `/` (`cmd/blockvolume/chunk_remote.go` `chunkHolder`) | Master: `core/host/master/workspace_service.go` `services.holderMatches(volume, replica, server, epoch)`, on #411; it gates `RenewWorkspaceLease` and `AckWorkspaceRevoked`, after the host check of #416, and takes the line's owner server from `core/host/master/workspace_binding.go` `Host.workspaceLineOwner`, on #423, the one owner decision for current and historical lines (through `PublishedLine.Owner`, which the snapshot builder's `expectOwnerForLine` also calls). The line's owner server is carried in the published line; a move's line names the move's new host; placement names the owner only for the initial line; an unknown owner is sent empty and never adopted. A volume that has seen an epoch owned by one server never adopts that epoch for another (this covers replays). The safety rule is the refusal to adopt a line naming another server; fencing on a foreign line is defence in depth, and only a process that has adopted a lineage fences, on a strictly newer foreign line. Volume: `core/host/volume/assignment_holder.go` `Host.assignmentNamesSelf`, on #411; called by `applyFact` and `IsSuperseded`. | `Host.applyFact` adopts a fact on the replica id alone. `Host.IsSuperseded` ignores a same-replica line from another server. `Host.recordOtherLine` lets an older line overwrite a newer one. Lease renewals and revocation ACKs carry no server id. All four are removed by #411. The master's status frontends and CSI publish target take the freshest same-replica heartbeat from any server (`ObservationStore.SlotFact` via `statusFrontendsForAssignedVolume`), and the operator's primary node is the placement slot (`serverForReplica`). Both are removed by [#416](https://github.com/seaweedfs/seaweed-block/pull/416), stacked on #411. The master computed the line's owner server twice; #423 makes it one function. | authority (master side); volume host (volume side) | -| `TERM-LEASE-NOW-001` Lease valid now | The holder may act on its workspace lease at this instant only while the guard has not fenced and host monotonic time is before the start of its last successful renewal plus the granted validity. The granted validity is the master expiry less half the clock-skew bound, capped by the configured TTL. | `WorkspaceLease` `ExpiresAtNS`, `MaxClockSkewNS`, and the lease view's durable horizon and granted deadline (`core/authority/workspace_lease_view.go`); `WorkspaceLeaseFact` `valid_for_ns`, `expires_at_ns`, `revoking` (`core/rpc/proto/workspace.proto`); `WorkspaceLeaseGuard` `until`, `fenced` (`core/host/volume/workspace_lease.go`) | Holder: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.permits`. Master: `core/authority/workspace_lease_view.go` `Publisher.WorkspaceLeaseValidity` / `workspaceLeaseValidityAt` is shared by renewal admission, `leaseFact` and `AckWorkspaceRevocation`. `WorkspaceLeaseValidity` reads the publisher clock; its leaf calculation uses the larger configured/persisted skew and configured TTL. `Publisher.RenewWorkspaceLease`. `firstWorkspaceGrant` and `regrantWorkspaceLease` are reached only from it, and only it starts the extender `extendWorkspaceLease`. | `WorkspaceLeaseGuard.drain` checks `now < until` again inline before the ACK, and `WorkspaceLeaseGuard.Refresh` repeats the expiry check of `permits`: open (both should call one predicate). The host reply sanity bound in `Refresh` still repeats the publisher's default 30 s TTL: open. Not a duplicate: `Publisher.forcedMoveBarrierLocked` decides the opposite term, "the lease is over for the master" (the horizon and the deadline each plus the full skew bound), which a forced move and a re-grant need. | authority (grant); volume host (guard) | +| `TERM-LEASE-NOW-001` Lease valid now | The holder may act on its workspace lease at this instant only while the guard has not fenced and host monotonic time is before the start of its last successful renewal plus the granted validity. The granted validity is the master expiry less half the clock-skew bound, capped by the configured TTL. Safety premise for v1.0, alongside one live process per holder (`TERM-ONE-PROCESS-001`): blockmaster's host slews its wall clock, not steps it, while volumes are served; a step larger than the configured skew bound while a lease is live is unsupported (see `docs/operator-guide.md`, Clock safety requirement). This closes coverage gap 8 by a documented premise, not a wall-step test. | `WorkspaceLease` `ExpiresAtNS`, `MaxClockSkewNS`, and the lease view's durable horizon and granted deadline (`core/authority/workspace_lease_view.go`); `WorkspaceLeaseFact` `valid_for_ns`, `expires_at_ns`, `revoking` (`core/rpc/proto/workspace.proto`); `WorkspaceLeaseGuard` `until`, `fenced` (`core/host/volume/workspace_lease.go`) | Holder: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.permits`. Master: `core/authority/workspace_lease_view.go` `Publisher.WorkspaceLeaseValidity` / `workspaceLeaseValidityAt` is shared by renewal admission, `leaseFact` and `AckWorkspaceRevocation`. `WorkspaceLeaseValidity` reads the publisher clock; its leaf calculation uses the larger configured/persisted skew and configured TTL. `Publisher.RenewWorkspaceLease`. `firstWorkspaceGrant` and `regrantWorkspaceLease` are reached only from it, and only it starts the extender `extendWorkspaceLease`. | `WorkspaceLeaseGuard.drain` checks `now < until` again inline before the ACK, and `WorkspaceLeaseGuard.Refresh` repeats the expiry check of `permits`: open (both should call one predicate). The host reply sanity bound in `Refresh` still repeats the publisher's default 30 s TTL: open. Not a duplicate: `Publisher.forcedMoveBarrierLocked` decides the opposite term, "the lease is over for the master" (the horizon and the deadline each plus the full skew bound), which a forced move and a re-grant need. Follow-up for 1.0.1: split `workspaceNow` into wall and monotonic sources so the barrier for in-memory lines uses monotonic time, and add a real independent wall-step test. No new clock seam is added in v1.0. | authority (grant); volume host (guard) | | `TERM-SERVING-001` Serving / ready | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now and its durable backend is operational. Without a granted lease it holds at the gate and exits 75 after the start-time wait. | `frontend.Projection.Healthy`; the `StorageBackend` operational flag and its evidence, reported as `VolumeStatus.Operational` (`core/frontend/durable`); `StatusProjection.FrontendPrimaryReady` (and `NotReadyReason`, on [#410](https://github.com/seaweedfs/seaweed-block/pull/410)); the ALUA and ANA state; `HeartbeatSlot.frontends` | Authority side: `core/host/volume/projection_bridge.go` `AdapterProjectionView.projectionWithSupersede`, which ANDs in `WorkspaceLeaseGuard.permits` for workspace volumes. Storage side: the `StorageBackend` operational flag (`core/frontend/durable/storage_adapter.go`), written only by `SetOperational` and read by `readyCheck`. The one decision of both sides together is `StorageBackend.AdmitsIO` (the guarded AND), read by the status, the frontend start gate and every I/O: on #410 (today `StorageBackend.gate` on `main`). | `StatusServer.authorityProjection` derives `FrontendPrimaryReady` from the authority view alone, and it repeats the supersede and supporting tests that `Healthy` already contains. #410 adds the backend half in `statusProjection`; the repeated tests remain open. The frontends listen whether or not the backend admits I/O: #410 holds them in `awaitBackendAdmitsIO` until it does. #410 replaces its earlier `backendAdmitsIO` (which read only `VolumeStatus.Operational`) with `StorageBackend.AdmitsIO`. A later lease fence ends the process on [#409](https://github.com/seaweedfs/seaweed-block/pull/409). `projectionALUAProvider.ALUAState` and `projectionANAProvider.ANAState` (`cmd/blockvolume`) follow the projection only: open. The start-time wait (`chunkAuthorityWait`; `ProviderConfig.ChunkAssignmentTimeout`, 30 s by default) ends once, and the process then stays up without serving: #409 makes it exit 75. iSCSI reports a not-ready or busy backend as a medium error, while NVMe retries the same error: [#415](https://github.com/seaweedfs/seaweed-block/pull/415) (`frontend.ClassifyBackendError`). The heartbeat `Frontends` are set when the listeners start and cleared only at shutdown: open. | volume host | | `TERM-STOP-SUPERSEDED-001` Superseded | A newer published line for this volume names another holder (another replica, or the same replica on another server) at or above this process's epoch and endpoint version. From then on the process is not healthy. | `Host.lastOther` (an `AssignmentFact`); the process's own epoch and endpoint version | Volume: `core/host/volume/host.go` `Host.IsSuperseded`. Its same-replica branch, and the ordered `recordOtherLine` it reads, are on #411. | The status repeat listed under `TERM-SERVING-001`. `Host.IsCurrentReplicaSuperseded` (on #409) and `Host.promotionReady` call `IsSuperseded` with other lineages. They are wrappers, not second derivations. | volume host | | `TERM-STOP-LEASE-FENCED-001` Lease fenced / revoked | The lease guard has latched: its deadline passed, a reply was invalid or late, the lease is revoking, or the process is stopping. A fenced guard never reopens. The host drains, and only when the lease was revoked does it acknowledge with the HEAD generation. | `WorkspaceLeaseGuard` `fenced`, `cause`, `revoked` (`core/host/volume/workspace_lease.go`) | Volume: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.fenceLocked`, the one writer of `fenced`; it is read through `permits`. | `Host.FenceWorkspaceLease` and `runWorkspaceLease` (`core/host/volume/workspace_runtime.go`) set `fenced` directly, with no cause, and keep a second latch, `Host.workspaceLeaseFenced`: open. On `main` a guard fence ends the process with status 0: #409 makes it exit 75. | volume host | diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index c611d56232..4fee8764a1 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -14,6 +14,16 @@ that runs it. - Why: a forced move after a host loss needs the authority record, the lease horizon and the lost range. - If those lived on the lost host, the volume could not be moved anywhere. +## Clock safety requirement + +While volumes are served, blockmaster's host must keep its wall clock **slewed, not stepped**. Configure chrony to +allow `makestep` only at boot (for example, `makestep 1 3` for the initial updates), and do not run `ntpdate` from a +timer. Do not restart an initial-step clock configuration while leases are live. A wall-clock step larger than the +configured clock-skew bound while a lease is live is **outside the v1.0 supported envelope**. + +This is a safety premise, not a tested wall-step guarantee. The host's monotonic lease deadline does not remove this +requirement on blockmaster's clock. See Part T `TERM-LEASE-NOW-001` in the [invariant contract](design/invariants.md). + ## Install [Standalone deployment](standalone-deployment.md): From 13565c7638183238fada42bc5e23470193e88ef8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:32:39 -0800 Subject: [PATCH 44/71] 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 e4ee17cdfca2c2da8e911285038528f37958d840 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:32:49 -0800 Subject: [PATCH 45/71] test: fresh-root crash test uses the move request id the harness checks; clearer survivor log Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/procedure_crash_io_integration_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go index ec37361533..3a4963f44f 100644 --- a/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go @@ -142,7 +142,7 @@ func TestProcedureCrashWithIOInFlight(t *testing.T) { t.Fatalf("LBA %d after the last acknowledged Flush holds data out of the stream's order or torn (kept %d)", lba, kept) } } - t.Logf("after the restart: all %d flush-acknowledged writes read back; %d of the %d unflushed completed writes survived as a prefix", flushed, kept-flushed, written-flushed) + t.Logf("after the restart: all %d flush-acknowledged writes read back; %d writes past the last acknowledged Flush survived as a prefix (%d had completed; one in flight may persist without its reply)", flushed, kept-flushed, written-flushed) } // Gap 1, cell A3.5: kill -9 of a holder serving on a FRESH root (after a @@ -186,7 +186,7 @@ func TestProcedureCrashOnAFreshRootWithFillsInFlight(t *testing.T) { t.Fatalf("s1 after the revocation: %v", err) } env.waitAck(t, e, g) - moved, _ := h.command(t, env.moveClean(e, "s2", "move-fill-1")...) + moved, _ := h.command(t, env.moveClean(e, "s2", "move-v1-1")...) e2 := mustU(movedEpochTo(moved, e, g, l, "s2")) nw := env.start(t, "blockvolume-s2", "s2") must(checkClaimDoneBy(nw.waitLog(t, 60*time.Second, "durable: HEAD claim for volume=v1 done in"), e2, "s2")) From de858e67fca1603b658716998d3e3886a4b9f800 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:33:02 -0800 Subject: [PATCH 46/71] test: register source server in workspace move fixture --- .../core/host/master/workspace_move_integration_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/seaweed-block/core/host/master/workspace_move_integration_test.go b/seaweed-block/core/host/master/workspace_move_integration_test.go index 8d1a0643fd..dd1c65a997 100644 --- a/seaweed-block/core/host/master/workspace_move_integration_test.go +++ b/seaweed-block/core/host/master/workspace_move_integration_test.go @@ -69,6 +69,9 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) { if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-b", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101"}); err != nil { t.Fatal(err) } + if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-a", DataAddr: "127.0.0.1:9202", CtrlAddr: "127.0.0.1:9102"}); err != nil { + t.Fatal(err) + } seedVerifiedExistingReplicaPlacement(t, h) if _, err = h.RunLifecycleProductTick(); err != nil { t.Fatal(err) From d8128044435637fa1f17e09d1fbd28a00e4577dc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:33:20 -0800 Subject: [PATCH 47/71] 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 91c2510d5b4fdb7c8661c0d4ec743b1870686f2f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:34:05 -0800 Subject: [PATCH 48/71] test: expect current segmented HEAD format in clean move --- .../core/host/master/workspace_move_integration_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/host/master/workspace_move_integration_test.go b/seaweed-block/core/host/master/workspace_move_integration_test.go index dd1c65a997..88306e70b2 100644 --- a/seaweed-block/core/host/master/workspace_move_integration_test.go +++ b/seaweed-block/core/host/master/workspace_move_integration_test.go @@ -150,7 +150,7 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) { Format int `json:"format"` Segments map[string]json.RawMessage `json:"segments"` } - if err = json.Unmarshal(stored.Content, &root); err != nil || root.Format != 2 || len(root.Segments) == 0 { + if err = json.Unmarshal(stored.Content, &root); err != nil || root.Format != 3 || len(root.Segments) == 0 { t.Fatalf("CLEAN move must exercise upgraded segmented root: %s %v", stored.Content, err) } From 9fa795b3ad9845aa846fa8b71b9b11984a7122f7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:34:48 -0800 Subject: [PATCH 49/71] test: wait for authoritative forced-move admission preview --- .../master/workspace_move_integration_test.go | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/host/master/workspace_move_integration_test.go b/seaweed-block/core/host/master/workspace_move_integration_test.go index 88306e70b2..5e0aab1895 100644 --- a/seaweed-block/core/host/master/workspace_move_integration_test.go +++ b/seaweed-block/core/host/master/workspace_move_integration_test.go @@ -84,7 +84,7 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) { defer conn.Close() client := control.NewWorkspaceServiceClient(conn) id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-a", ReplicaId: line.ReplicaID, Epoch: line.Epoch} - lease, err := client.RenewWorkspaceLease(ctx, id) + _, err = client.RenewWorkspaceLease(ctx, id) if err != nil { t.Fatal(err) } @@ -171,13 +171,23 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) { t.Fatal(err) } } else { - // Actual master lease expiry, no test clock and no revocation ACK. - timer := time.NewTimer(time.Until(time.Unix(0, lease.ExpiresAtNs)) + 100*time.Millisecond + 20*time.Millisecond) - defer timer.Stop() - select { - case <-timer.C: - case <-ctx.Done(): - t.Fatal(ctx.Err()) + // The master owns the full horizon/deadline/skew barrier. Wait + // for its affirmative preview, not a locally copied expiry formula. + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() + for { + preview, err := client.PreviewWorkspaceMove(ctx, q) + if err != nil { + t.Fatal(err) + } + if preview.Admitted { + break + } + select { + case <-ticker.C: + case <-ctx.Done(): + t.Fatalf("forced preview never admitted: %v (last reason %q)", ctx.Err(), preview.Reason) + } } q.Force = false if _, err = client.MoveWorkspace(ctx, q); err == nil { From e3c6505797e78f1fd45b8944cc343b8233852493 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:43:07 -0800 Subject: [PATCH 50/71] test: cut crash tests: the dying cut has its own deadline; the procedure kill adapts until it lands mid-upload The unit ladder's dying cut retried its failing uploads until a context it shared with the restarted process expired; it now has its own short context. The procedure test proves the kill landed mid-upload (new chunk objects on the filer, HEAD unchanged) and otherwise adapts the delay and repeats with a new image. The fresh-root test kills once 8 writes are flushed, so the reader is still filling. Co-Authored-By: Claude Opus 5.5 --- .../procedure_crash_io_integration_test.go | 92 ++++++++++++------- .../core/storage/chunk_cut_crash_test.go | 10 +- 2 files changed, 68 insertions(+), 34 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go index 3a4963f44f..0f59881dc5 100644 --- a/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go @@ -247,7 +247,7 @@ func TestProcedureCrashOnAFreshRootWithFillsInFlight(t *testing.T) { wmu.Lock() f := flushed wmu.Unlock() - return r >= 3 && f >= 64 + return r >= 3 && f >= 8 }) nw.kill(t) // SIGKILL with fills and writes in flight <-readerDone @@ -326,11 +326,16 @@ func (c *nvmeInitiator) tryRead(lba uint64, n int) ([]byte, error) { // Gap 2, procedure part (cells P8.7, P9.4, P11.3): kill -9 of the holder // during a cut's upload, with real binaries. Image A is cut; every block is -// rewritten (image B, flushed); a second cut starts and the holder is -// SIGKILLed at half the first cut's duration. After the restart: HEAD -// verifies whole at depth data (old or new image, nothing missing), every -// block reads B locally, and the next cut, read back through a snapshot -// restored into a new volume, is B. +// rewritten and a second cut starts; the holder is SIGKILLed after a delay. +// The kill counts as mid-upload only if chunk objects of the second cut +// reached the filer while HEAD stayed at the first cut's generation; else the +// delay is adapted (shorter if the cut had committed, longer if nothing was +// uploaded) and the step repeats with a new image, up to cutCrashAttempts +// times. After the mid-upload kill and a restart: HEAD verifies whole at +// depth data, every block reads the last image locally, and the next cut, +// read back through a snapshot restored into a new volume, is that image. +const cutCrashAttempts = 6 + const ( cutCrashChunks = 48 cutCrashPer = 64 // blocks written per chunk @@ -375,42 +380,63 @@ func (env *handoffEnv) requireCutCrashImage(t *testing.T, hostID string, img byt func TestProcedureCrashDuringACut(t *testing.T) { env := startHandoffEnvWith(t, 1, []string{"v2"}) env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} - first := env.start(t, "blockvolume-v1", "s1") - e := env.adopt(t, first, "s1") + holder := env.start(t, "blockvolume-v1", "s1") + e := env.adopt(t, holder, "s1") cut := []string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status} verify := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data"} + headGen := func() uint64 { + out, _ := env.h.command(t, env.chunkShow()...) + h, err := parseHead(out) + if err != nil { + t.Fatal(err) + } + return h.Gen + } env.writeCutCrashImage(t, 'A') cutStart := time.Now() env.h.command(t, cut...) - full := time.Since(cutStart) - env.writeCutCrashImage(t, 'B') - - done := make(chan int, 1) - go func() { - _, _, code := env.h.run(t, cut...) - done <- code - }() - time.Sleep(full / 2) - select { - case code := <-done: - t.Fatalf("the second cut finished (exit %d) before the kill at %s: no upload was in flight", code, full/2) - default: + delay := time.Since(cutStart) / 2 + img, landed := byte('A'), false + for attempt := 1; attempt <= cutCrashAttempts && !landed; attempt++ { + img++ + env.writeCutCrashImage(t, img) + gen, entries := headGen(), f1FilerEntries(t, env) + done := make(chan int, 1) + go func() { + _, _, code := env.h.run(t, cut...) + done <- code + }() + time.Sleep(delay) + holder.kill(t) + code := <-done + uploaded := f1FilerEntries(t, env) - entries + after := headGen() + switch { + case after != gen: + t.Logf("attempt %d: the cut committed before the kill at %s (HEAD gen %d -> %d, CLI exit %d); shorter", attempt, delay, gen, after, code) + delay /= 2 + case uploaded <= 0: + t.Logf("attempt %d: nothing was uploaded before the kill at %s; longer", attempt, delay) + delay *= 2 + default: + landed = true + t.Logf("attempt %d: killed at %s mid-upload: %d new filer entries, HEAD still gen %d (CLI exit %d)", attempt, delay, uploaded, gen, code) + } + if out, errOut, rc := env.h.run(t, verify...); rc != 0 { + t.Fatalf("attempt %d: HEAD is not whole after the kill (verify exit %d):\n%s\n%s", attempt, rc, out, errOut) + } + holder = env.start(t, fmt.Sprintf("blockvolume-v1-%d", attempt), "s1") + if got := env.adopt(t, holder, "s1"); got != e { + t.Fatalf("attempt %d: the restarted holder adopted epoch %d; want %d", attempt, got, e) + } + env.requireCutCrashImage(t, "s1", img) } - first.kill(t) - code := <-done - t.Logf("the first cut took %s; the holder was killed at %s into the second (its CLI exit %d)", full, full/2, code) - - if out, errOut, rc := env.h.run(t, verify...); rc != 0 { - t.Fatalf("HEAD is not whole after the kill (verify exit %d):\n%s\n%s", rc, out, errOut) + if !landed { + t.Fatalf("no kill landed mid-upload in %d attempts", cutCrashAttempts) } - again := env.start(t, "blockvolume-v1-again", "s1") - if got := env.adopt(t, again, "s1"); got != e { - t.Fatalf("the restarted holder adopted epoch %d; want %d", got, e) - } - env.requireCutCrashImage(t, "s1", 'B') env.h.command(t, cut...) env.snapshot(t, "s1", "v1", "after-crash") env.restoreInto(t, "v1", "after-crash", "v2") - env.requireCutCrashImage(t, "n-v2", 'B') + env.requireCutCrashImage(t, "n-v2", img) } diff --git a/seaweed-block/core/storage/chunk_cut_crash_test.go b/seaweed-block/core/storage/chunk_cut_crash_test.go index 3567df0a07..4abd8439dd 100644 --- a/seaweed-block/core/storage/chunk_cut_crash_test.go +++ b/seaweed-block/core/storage/chunk_cut_crash_test.go @@ -6,6 +6,7 @@ import ( "errors" "sync" "testing" + "time" ) // Single-volume coverage gap 2 (cells P5.4, P6.4, P8.7, P9.4, P10.4, P11.3; @@ -199,7 +200,13 @@ func TestChunkCutCrashAtEachStage(t *testing.T) { r.puts = 0 // count this cut's uploads only r.mu.Unlock() st.arm(l, r, die) - _, cutErr := l.Capture(ctx) + // The dying cut gets its own short context: after the death its + // remote calls fail and it may retry them until its deadline (a + // real dead process does not); the restarted process below runs + // on fresh contexts. + dyingCtx, cancelDying := context.WithTimeout(context.Background(), 5*time.Second) + _, cutErr := l.Capture(dyingCtx) + cancelDying() if !r.isDead() { t.Fatalf("the stage %q was never reached (puts %d, cut error %v)", st.name, r.puts, cutErr) } @@ -212,6 +219,7 @@ func TestChunkCutCrashAtEachStage(t *testing.T) { } // Restart: the store recovers its WAL; HEAD is old or new, whole. + ctx = ctTimeout(t) s2, _ := reopen(t, path) head, _ := f.GetHead(ctx) got := f.imageOf(t, head) From 523b0f03c5a20fddeca3555beafc8f5f1208cd5d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 18:48:37 -0800 Subject: [PATCH 51/71] test: chunk verify at depth data needs its explicit --timeout Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/procedure_crash_io_integration_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go index 0f59881dc5..4bb7226ae6 100644 --- a/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go @@ -383,7 +383,7 @@ func TestProcedureCrashDuringACut(t *testing.T) { holder := env.start(t, "blockvolume-v1", "s1") e := env.adopt(t, holder, "s1") cut := []string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status} - verify := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data"} + verify := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data", "--timeout", "5m"} headGen := func() uint64 { out, _ := env.h.command(t, env.chunkShow()...) h, err := parseHead(out) From 399bc7699f516bcf979eea366b3298642bbd9901 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 19:01:21 -0800 Subject: [PATCH 52/71] test: sync control child runs to the parent test deadline, not a fixed 45 s Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/data_sync_linux_test.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index e91897834f..fc5fab3489 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -290,7 +290,13 @@ func TestSyncControlsIgnoreAmbientAllocation(t *testing.T) { {"crash-matrix", "TestFdatasyncAcknowledgedWritesSurviveSIGKILL", "prezero"}, } { t.Run(tc.name, func(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + // The crash-matrix child is fdatasync-bound and takes 1-35 s on a + // slow disk, so it runs until the parent test's deadline rather + // than a fixed budget. + ctx, cancel := context.WithCancel(context.Background()) + if d, ok := t.Deadline(); ok { + ctx, cancel = context.WithDeadline(context.Background(), d.Add(-10*time.Second)) + } defer cancel() cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+tc.test+"$") cmd.Env = append(os.Environ(), "SWBLOCK_TEST_SYNC_CRASH=", "SWBLOCK_TEST_SYNC_CHILD_FAILURE=", "SWBLOCK_ALLOCATION="+tc.allocation, "SWBLOCK_PREZERO=0") From 4744b8a4c0c955b8e5c0809ab95b44e1ca440cf7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 19:26:09 -0800 Subject: [PATCH 53/71] test: one context assignment per branch so no cancel is lost Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/data_sync_linux_test.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index fc5fab3489..55e54ac79a 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -293,9 +293,12 @@ func TestSyncControlsIgnoreAmbientAllocation(t *testing.T) { // The crash-matrix child is fdatasync-bound and takes 1-35 s on a // slow disk, so it runs until the parent test's deadline rather // than a fixed budget. - ctx, cancel := context.WithCancel(context.Background()) + var ctx context.Context + var cancel context.CancelFunc if d, ok := t.Deadline(); ok { ctx, cancel = context.WithDeadline(context.Background(), d.Add(-10*time.Second)) + } else { + ctx, cancel = context.WithCancel(context.Background()) } defer cancel() cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+tc.test+"$") From 800b3924281b68064dbaf427c5021dc17e820ee5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 20:31:26 -0800 Subject: [PATCH 54/71] docs: state the SeaweedFS durability premise Co-Authored-By: Claude Fable 5.2 --- seaweed-block/docs/operator-guide.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index c611d56232..1aee01fe18 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -13,6 +13,8 @@ that runs it. example the SeaweedFS master or filer node), with durable storage. A volume host holds no authority state. - Why: a forced move after a host loss needs the authority record, the lease horizon and the lost range. - If those lived on the lost host, the volume could not be moved anywhere. +- **SeaweedFS durability (a premise):** sw-block assumes SeaweedFS acknowledges a write only when it is durable; + configuring SeaweedFS for that is the SeaweedFS deployment's responsibility. ## Install From 814fb36a92de0c6c8f4a159c42b0f4e5dcc0ec84 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 20:44:09 -0800 Subject: [PATCH 55/71] 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 56/71] 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 57/71] 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 58/71] 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 59/71] 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 | From 4be8d84b84e0ff4991f3aafe06122ea784523497 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 20:59:15 -0800 Subject: [PATCH 60/71] test: restore kill test uses 32 full chunks of incompressible data so its phases can be caught Co-Authored-By: Claude Opus 5.5 --- ...snapshot_ladder_c3kill_integration_test.go | 28 +++++++++++++++++-- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go index b97305a71d..5e6afea3e9 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go @@ -6,6 +6,7 @@ import ( "context" "encoding/json" "fmt" + "math/rand" "testing" "time" ) @@ -47,6 +48,26 @@ func (env *handoffEnv) awaitRestorePhase(t *testing.T, target, what string, boun return restoreProgress{} } +// denseImage fills every block of the given chunks with incompressible +// bytes (seeded by tag and LBA), so that their chunks are full size in the +// store and a restore of them takes measurable time at the driver's rate. +func denseImage(tag string, chunks []uint64) map[uint64][]byte { + img := map[uint64][]byte{} + var seed int64 + for _, c := range tag { + seed = seed*31 + int64(c) + } + for _, c := range chunks { + for i := uint64(0); i < ladderChunkBlocks; i++ { + lba := c*ladderChunkBlocks + i + b := make([]byte, 4096) + rand.New(rand.NewSource(seed ^ int64(lba))).Read(b) + img[lba] = b + } + } + return img +} + // startTarget starts target's blockvolume and waits until it serves. func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon { t.Helper() @@ -60,7 +81,8 @@ func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon { } // TestSnapshotLadderC3KilledMidHydrateAndMidBatch: a restore of a snapshot -// of 48 written chunks into v2 (about 192 MiB to make local and re-upload). +// of 32 full chunks of incompressible data into v2 (128 MiB to make local +// and re-upload at the driver's 64 MiB/s). // Its blockvolume is killed (SIGKILL) while the driver is hydrating, started // again and the driver started again. While the driver then owns chunks, the // guest writes to v2 (acknowledged), and the blockvolume is killed again in @@ -72,10 +94,10 @@ func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon { func TestSnapshotLadderC3KilledMidHydrateAndMidBatch(t *testing.T) { env := startLadderEnv(t, "v2", "v3") var chunks []uint64 - for c := uint64(0); c < 48; c++ { + for c := uint64(0); c < 32; c++ { chunks = append(chunks, c) } - src := ladderImage("c3ksrc", chunks, 2) + src := denseImage("c3ksrc", chunks) env.writeImage(t, "s1", src) env.snapshot(t, "s1", "v1", "base") From 0291522081ee9f7bc1ca3c53bf1a74ecab1df242 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 21:29:39 -0800 Subject: [PATCH 61/71] test: restore kill test triggers on the phase and its time, polls the status endpoint, keeps chunk 40 untouched Co-Authored-By: Claude Opus 5.5 --- ...snapshot_ladder_c3kill_integration_test.go | 104 ++++++++++++------ 1 file changed, 71 insertions(+), 33 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go index 5e6afea3e9..29d262bb5d 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go @@ -3,10 +3,11 @@ package main_test import ( - "context" "encoding/json" "fmt" + "io" "math/rand" + "net/http" "testing" "time" ) @@ -21,33 +22,67 @@ type restoreProgress struct { Batches int `json:"batches"` } -// awaitRestorePhase polls target's restore status every 50 ms until ok -// holds and returns that status; it fails the test if the restore failed, -// became independent first (the moment was missed), or bound passed. +// restoreStatus reads target's restore status straight from its status +// server (a GET answers the status without starting a run). +func (env *handoffEnv) restoreStatus(c *http.Client, target string) (restoreProgress, string, bool) { + resp, err := c.Get("http://" + env.hosts["n-"+target].status + "/chunk/restore?volume=" + target) + if err != nil { + return restoreProgress{}, "", false + } + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + resp.Body.Close() + var st restoreProgress + if resp.StatusCode != http.StatusOK || json.Unmarshal(b, &st) != nil { + return restoreProgress{}, string(b), false + } + return st, string(b), true +} + +// awaitRestorePhase polls target's restore status every 10 ms until ok +// holds and returns that status, logging each change with when it was seen +// (the record of where a kill landed). It fails the test if the restore +// failed, became independent first (the moment was missed), or bound passed. +// The driver's counters (filled, owned, foreign) are written when a step +// ends, not while it runs: a moment inside a step is chosen by the phase and +// the time spent in it, not by a counter. func (env *handoffEnv) awaitRestorePhase(t *testing.T, target, what string, bound time.Duration, ok func(restoreProgress) bool) restoreProgress { t.Helper() - end := time.Now().Add(bound) - ctx, cancel := context.WithDeadline(context.Background(), end) - defer cancel() - for time.Now().Before(end) { - out, _, code, err := runCLI(ctx, env.h, "ops", "chunk", "restore", "--volume", target, "--status-addr", env.hosts["n-"+target].status, "--status") - var st restoreProgress - if err == nil && code == 0 && json.Unmarshal([]byte(out), &st) == nil { + c := &http.Client{Timeout: 2 * time.Second} + began := time.Now() + last := restoreProgress{Phase: "-"} + for time.Since(began) < bound { + if st, raw, good := env.restoreStatus(c, target); good { + if st != last { + t.Logf("restore of %s at +%v (waiting for %s): %+v", target, time.Since(began).Round(time.Millisecond), what, st) + last = st + } switch { case ok(st): return st case st.Phase == "failed": - t.Fatalf("restore of %s failed waiting for %s: %s", target, what, out) + t.Fatalf("restore of %s failed waiting for %s: %s", target, what, raw) case st.Phase == "independent": - t.Fatalf("restore of %s became independent before %s was seen (the restore is too small to catch it): %s", target, what, out) + t.Fatalf("restore of %s became independent before %s was seen (the restore is too small to catch it): %s", target, what, raw) } } - time.Sleep(50 * time.Millisecond) + time.Sleep(10 * time.Millisecond) } t.Fatalf("restore of %s: %s not seen within %v", target, what, bound) return restoreProgress{} } +// requireRestoreState reads target's restore status once and fails the test +// unless the run is still going and ok holds: the check, right before a +// kill, that the kill lands where the test says. +func (env *handoffEnv) requireRestoreState(t *testing.T, target, what string, ok func(restoreProgress) bool) restoreProgress { + t.Helper() + st, raw, good := env.restoreStatus(&http.Client{Timeout: 2 * time.Second}, target) + if !good || !st.Running || !ok(st) { + t.Fatalf("restore of %s is no longer %s before the kill: %s", target, what, raw) + } + return st +} + // denseImage fills every block of the given chunks with incompressible // bytes (seeded by tag and LBA), so that their chunks are full size in the // store and a restore of them takes measurable time at the driver's rate. @@ -81,13 +116,17 @@ func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon { } // TestSnapshotLadderC3KilledMidHydrateAndMidBatch: a restore of a snapshot -// of 32 full chunks of incompressible data into v2 (128 MiB to make local -// and re-upload at the driver's 64 MiB/s). -// Its blockvolume is killed (SIGKILL) while the driver is hydrating, started -// again and the driver started again. While the driver then owns chunks, the -// guest writes to v2 (acknowledged), and the blockvolume is killed again in -// the middle of the batch, restarted, and the driver started again; the -// guest writes once more. The driver resumes from the target's remote facts +// of 32 full chunks of incompressible data into v2 (128 MiB to make local at +// the driver's 64 MiB/s: about 2 s of hydrating). Its blockvolume is killed +// (SIGKILL) one second into hydrating (about half the chunks local, by the +// pace), started again and the driver started again; nothing is read in +// between, so the restart finds the chunks the walker had not reached still +// remote. When the walker has made every chunk local and the first batch cut +// (Hydrating>Owning, one batch for 32 chunks) is running, which the status +// shows as running with every chunk filled and no batch done, the guest +// writes to v2 (acknowledged) and, the batch still running, the blockvolume +// is killed again, restarted, and the driver started again; the guest writes +// once more. The driver resumes from the target's remote facts // to independence (per its status). Then v2 holds the snapshot with every // acknowledged write over it, and the source's snapshot, restored again // into v3, is unchanged (none of v2's writes in it). @@ -110,29 +149,28 @@ func TestSnapshotLadderC3KilledMidHydrateAndMidBatch(t *testing.T) { } drive() - // Killed while hydrating: some chunks local, not all. - st := env.awaitRestorePhase(t, "v2", "hydrating with part of the chunks local", 120*time.Second, func(s restoreProgress) bool { - return s.Phase == "hydrating" && s.Filled > 0 && s.Filled < len(chunks) - }) + // Killed one second into hydrating: by the pace, about half the chunks + // are local. + env.awaitRestorePhase(t, "v2", "hydrating", 120*time.Second, func(s restoreProgress) bool { return s.Phase == "hydrating" }) + time.Sleep(time.Second) + st := env.requireRestoreState(t, "v2", "hydrating", func(s restoreProgress) bool { return s.Phase == "hydrating" }) target.kill(t) - t.Logf("killed while hydrating: %+v", st) + t.Logf("killed 1 s into hydrating: %+v", st) target = env.startTarget(t, "v2", "blockvolume-v2-after-hydrate-kill") - env.requireImage(t, "n-v2", src) // serves the snapshot at once after the restart drive() // Written while owning, then killed in the middle of the batch. - env.awaitRestorePhase(t, "v2", "owning", 180*time.Second, func(s restoreProgress) bool { return s.Phase == "owning" }) + inBatch := func(s restoreProgress) bool { return s.Filled == len(chunks) && s.Batches == 0 && s.Phase != "independent" } + env.awaitRestorePhase(t, "v2", "the first batch cut running", 180*time.Second, func(s restoreProgress) bool { return s.Running && inBatch(s) }) w1 := ladderImage("c3kw1", []uint64{3, 17, 50}, 3) env.writeImage(t, "n-v2", w1) - st = env.awaitRestorePhase(t, "v2", "owning with chunks still foreign", 180*time.Second, func(s restoreProgress) bool { - return s.Phase == "owning" && s.Foreign > 0 - }) + st = env.requireRestoreState(t, "v2", "in its first batch cut", inBatch) target.kill(t) - t.Logf("killed while owning: %+v", st) + t.Logf("killed in the first batch cut, after the write: %+v", st) target = env.startTarget(t, "v2", "blockvolume-v2-after-batch-kill") env.requireImage(t, "n-v2", mergeImages(src, w1)) // every acknowledged write survived the kill drive() - w2 := ladderImage("c3kw2", []uint64{17, 40, 60}, 2) + w2 := ladderImage("c3kw2", []uint64{17, 44, 60}, 2) // not chunk 40: requireEdges keeps it untouched env.writeImage(t, "n-v2", w2) env.waitIndependent(t, "v2") From f58a1e261f224b7b2457343da4952bd8e30de3b9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 21:29:49 -0800 Subject: [PATCH 62/71] test: gofmt Co-Authored-By: Claude Opus 5.5 --- .../blockvolume/snapshot_ladder_c3kill_integration_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go index 29d262bb5d..4370316a68 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go @@ -160,7 +160,9 @@ func TestSnapshotLadderC3KilledMidHydrateAndMidBatch(t *testing.T) { drive() // Written while owning, then killed in the middle of the batch. - inBatch := func(s restoreProgress) bool { return s.Filled == len(chunks) && s.Batches == 0 && s.Phase != "independent" } + inBatch := func(s restoreProgress) bool { + return s.Filled == len(chunks) && s.Batches == 0 && s.Phase != "independent" + } env.awaitRestorePhase(t, "v2", "the first batch cut running", 180*time.Second, func(s restoreProgress) bool { return s.Running && inBatch(s) }) w1 := ladderImage("c3kw1", []uint64{3, 17, 50}, 3) env.writeImage(t, "n-v2", w1) From 2d38216f6dcdc4429408d82439c74a0dd53522e2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 21:32:53 -0800 Subject: [PATCH 63/71] test: snapshot ladder B1 fails as inconclusive unless a listing ran while s4 was in flight Co-Authored-By: Claude Opus 5.5 --- .../snapshot_ladder_integration_test.go | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go index e527eadd69..928d509adb 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go @@ -260,9 +260,10 @@ func (env *handoffEnv) restoreAttached(t *testing.T, src, snap, target string) { // TestSnapshotLadderB1SnapshotQuery: three snapshots with writes between // them. The list is exactly the committed snapshots, in order, each active, // with the point (cut LSN), HEAD generation and size (chunk count) its -// creation answered; a prefix shows one. A snapshot being taken while a -// write runs appears in the list only committed, with the fields its -// creation answers, and stays. A snapshot request that is refused +// creation answered; a prefix shows one. A snapshot being taken appears in +// the list only committed, with the fields its creation answers, and stays; +// the test fails as inconclusive unless at least one listing ran while the +// snapshot was in flight and did not show it. A snapshot request that is refused // (a restore volume not yet independent) leaves no name in the list. func TestSnapshotLadderB1SnapshotQuery(t *testing.T) { env := startLadderEnv(t, "v2") @@ -296,8 +297,9 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) { } // A snapshot being taken: listed only committed, and then it stays. The - // write before it is acknowledged first, so its cut is past s3's; the - // write during it may land before or after its cut. + // write before it is acknowledged first, so its cut is past s3's; a + // second write follows its start, and may land before or after its cut + // (the test claims nothing about it). env.writeBlock(t, "s1", 3, pattern("ladder-b1-blk-D!")) type result struct { out, errOut string @@ -324,6 +326,7 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) { env.writeBlock(t, "s1", 4, pattern("ladder-b1-blk-E!")) var observed []snapshotInfo var r result + inFlightUnlisted := 0 // listings begun before s4 answered that did not show it // The observation bound: every list probe runs within what is left of it, // and a probe that returns after it fails the test. deadline := time.Now().Add(160 * time.Second) @@ -347,6 +350,9 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) { e := e s4 = &e } + if running && s4 == nil { + inFlightUnlisted++ + } switch { case s4 == nil && len(observed) > 0: t.Fatal("s4 was listed, then disappeared") @@ -359,6 +365,10 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) { if r.err != nil || r.code != 0 { t.Fatalf("snapshot s4: exit %d %v\n%s\n%s", r.code, r.err, r.out, r.errOut) } + if inFlightUnlisted == 0 { + t.Fatalf("inconclusive: no listing ran while s4 was in flight and unlisted (%d listings saw it committed)", len(observed)) + } + t.Logf("s4: %d listings while in flight did not show it; %d showed it committed", inFlightUnlisted, len(observed)) var created snapshotInfo if err := json.Unmarshal([]byte(r.out), &created); err != nil || created.Name != "s4" { t.Fatalf("snapshot s4 answer: %v\n%s", err, r.out) From 53563342eaa534f8cd4e0d2da182a8bf3ae18484 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 21:33:24 -0800 Subject: [PATCH 64/71] test: snapshot ladder D1-D3 comments claim the logical delete only Co-Authored-By: Claude Opus 5.5 --- .../snapshot_ladder_d_integration_test.go | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go index 265cccfc06..f746773426 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go @@ -14,10 +14,12 @@ import ( "time" ) -// Rung D of the snapshot ladder: deletes. A deleted snapshot leaves every -// other snapshot restorable, whichever one is deleted (the newest, a middle -// one, one whose content recurs later), and the collector then reclaims the -// chunk data only the deleted snapshots referenced. +// Rung D of the snapshot ladder: deletes. D1-D3 are the logical delete: a +// deleted snapshot leaves every other snapshot restorable, whichever one is +// deleted (the newest, a middle one, one whose content recurs later). No +// collector runs in them (a delete only marks the snapshot and frees its +// name), so they prove nothing about reclamation. D4 runs the collector and +// measures what it reclaims. // // The collector's grace may not be shorter than the operation deadline plus // the clock skew plus the CAS apply bound (11 minutes with the defaults), and @@ -88,8 +90,9 @@ func TestSnapshotLadderD1DeleteTheNewest(t *testing.T) { // TestSnapshotLadderD2DeleteAMiddleOne: four snapshots, each sharing chunks // with its neighbours; the second is deleted; the first, the third and the -// fourth restore as they were (the deleted one's chunks that a neighbour or a -// later snapshot still uses are kept). +// fourth restore as they were. No collector runs: whether the deleted one's +// chunks that a neighbour still uses would survive collection is not tested +// here. func TestSnapshotLadderD2DeleteAMiddleOne(t *testing.T) { env := startLadderEnv(t, "v2", "v3", "v4") img1 := ladderImage("d2one", []uint64{0, 2}, 4) From 170cd8818ec7bc9f197903f6ff1c81bde0076cda Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 21:34:29 -0800 Subject: [PATCH 65/71] test: snapshot ladder E1 classifies each kill, fails as inconclusive without one inside a snapshot, writes after each restart Co-Authored-By: Claude Opus 5.5 --- .../snapshot_ladder_e_integration_test.go | 126 ++++++++++++++---- 1 file changed, 98 insertions(+), 28 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go index 33b358eff3..5248355f76 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go @@ -6,6 +6,10 @@ import ( "context" "encoding/json" "fmt" + "io" + "net/http" + "net/url" + "path" "testing" "time" ) @@ -17,22 +21,55 @@ import ( // pinned by a unit test of the catalog; this rung is the same property // through the real processes. -// TestSnapshotLadderE1CrashDuringASnapshot: four rounds on one volume. In -// each, blocks in two new chunks are written and acknowledged, a snapshot -// with a fixed request id is started, and the holder is killed after a -// different delay (from at once to well into the snapshot), then restarted -// within its lease. After each restart: -// - the snapshot is listed at most once and only active; if its command -// answered success before the kill, it is listed; -// - a retry with the same request id completes it, listed once. +// nameRecorded reports whether vol's catalog holds a name record for the +// snapshot name, read from the filer (not through the product). +func (env *handoffEnv) nameRecorded(t *testing.T, vol, name string) bool { + t.Helper() + c := &http.Client{Timeout: 10 * time.Second} + p := path.Join(env.chunkPath, vol, "snapnames", url.PathEscape(name)) + resp, err := c.Get("http://" + env.cluster.filerHTTP + p + "?metadata=true") + if err != nil { + t.Fatal(err) + } + io.Copy(io.Discard, resp.Body) + resp.Body.Close() + switch resp.StatusCode { + case http.StatusOK: + return true + case http.StatusNotFound: + return false + } + t.Fatalf("filer lookup of %s: status %d", p, resp.StatusCode) + return false +} + +// TestSnapshotLadderE1CrashDuringASnapshot: rounds on one volume. In each, +// blocks in two new chunks are written and acknowledged, a snapshot with a +// fixed request id is started, and the holder is killed after a different +// delay (from at once to well after the answer), then restarted within its +// lease. Each round is classified from what the kill left: ANSWERED (the +// command answered success first), MID (no answer, but the catalog holds the +// snapshot's name record: the kill landed inside the snapshot), or BEFORE +// (no answer and no name record). The test fails as inconclusive unless at +// least one round is MID. After each restart, before the retry: +// - the snapshot is listed at most once and only active; an ANSWERED one +// is listed, at the cut its answer gave; +// - one more block is written (acknowledged). // -// At the end a next snapshot is taken after more writes. Every round's -// snapshot and the next one restore (to independence, per the restore -// status) exactly as the volume was when each was requested, with every -// block written after it reading zero: nothing partial, nothing lost. +// Then a retry with the same request id completes the snapshot, listed once: +// at the cut listed before the retry if it was listed (a replay), else at a +// new cut that holds the post-restart block. At the end a next snapshot is +// taken after more writes. Every round's snapshot and the next one restore +// (to independence, per the restore status) exactly as expected: the blocks +// acknowledged before it, the post-restart block only when the retry cut +// anew, and every block written after it reading zero. func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) { - delays := []time.Duration{0, 50 * time.Millisecond, 200 * time.Millisecond, 600 * time.Millisecond} - targets := []string{"v2", "v3", "v4", "v5", "v6"} + delays := []time.Duration{0, 25 * time.Millisecond, 50 * time.Millisecond, 75 * time.Millisecond, + 100 * time.Millisecond, 125 * time.Millisecond, 150 * time.Millisecond, 200 * time.Millisecond, 600 * time.Millisecond} + var targets []string + for i := 0; i <= len(delays); i++ { + targets = append(targets, fmt.Sprintf("v%d", i+2)) + } env := startHandoffEnvWith(t, 1, targets) env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} holder := env.start(t, "blockvolume-v1", "s1") @@ -47,11 +84,11 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) { } var images []map[uint64][]byte // what each round's snapshot must hold cum := map[uint64][]byte{0: marker} + classes := map[string]int{} for k, delay := range delays { img := ladderImage(fmt.Sprintf("e1r%d", k), []uint64{uint64(k + 1), uint64(20 + k)}, 3) env.writeImage(t, "s1", img) cum = mergeImages(cum, img) - images = append(images, cum) name, req := fmt.Sprintf("e1-%d", k), fmt.Sprintf("r-e1-%d", k) ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) @@ -63,42 +100,79 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) { }() time.Sleep(delay) holder.kill(t) + killed := time.Now() var r result select { case r = <-done: case <-time.After(60 * time.Second): cancel() + select { // join the worker before failing + case <-done: + case <-time.After(10 * time.Second): + t.Error("the snapshot worker did not finish within 10 s of its cancellation") + } t.Fatalf("round %d: the snapshot command did not return within 60 s of the holder's kill", k) } cancel() answered := r.err == nil && r.code == 0 - t.Logf("round %d (kill after %v): snapshot command exit %d err %v", k, delay, r.code, r.err) + class := "BEFORE" + switch { + case answered: + class = "ANSWERED" + case env.nameRecorded(t, "v1", name): + class = "MID" + } + classes[class]++ // Restarted within the lease, as the unit's RestartSec does: the same // epoch, serving the blocks written before the kill. holder = env.start(t, fmt.Sprintf("blockvolume-v1-r%d", k), "s1") if got := env.adopt(t, holder, "s1"); got != e { - t.Fatalf("round %d: the restarted holder adopted epoch %d; want %d", k, got, e) + t.Fatalf("round %d: the restarted holder adopted epoch %d; want %d (restarted %v after the kill: within the lease?)", k, got, e, time.Since(killed).Round(time.Millisecond)) } + t.Logf("round %d (kill after %v): %s (exit %d err %v); serving again %v after the kill", k, delay, class, r.code, r.err, time.Since(killed).Round(time.Millisecond)) env.requireImage(t, "s1", cum) - switch l := env.snapshots(t, "v1", name); { - case len(l) > 1: - t.Fatalf("round %d: %s listed %d times: %+v", k, name, len(l), l) - case len(l) == 1 && l[0].State != "active": - t.Fatalf("round %d: %s listed but not active: %+v", k, name, l[0]) - case len(l) == 0 && answered: + pre := env.snapshots(t, "v1", name) + switch { + case len(pre) > 1: + t.Fatalf("round %d: %s listed %d times: %+v", k, name, len(pre), pre) + case len(pre) == 1 && pre[0].State != "active": + t.Fatalf("round %d: %s listed but not active: %+v", k, name, pre[0]) + case answered && len(pre) == 0: t.Fatalf("round %d: %s answered success before the kill but is not listed: %s", k, name, r.out) } + if answered { + var a snapshotInfo + if err := json.Unmarshal([]byte(r.out), &a); err != nil || a.CutLSN != pre[0].CutLSN || a.HeadGen != pre[0].HeadGen { + t.Fatalf("round %d: %s answered %s before the kill but is listed as %+v", k, name, r.out, pre[0]) + } + } + post := map[uint64][]byte{uint64(50+k) * ladderChunkBlocks: pattern(fmt.Sprintf("e1-post-%02d-blk!", k))} + env.writeImage(t, "s1", post) + out, _ := env.h.command(t, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status, "--name", name, "--request-id", req) var info snapshotInfo if err := json.Unmarshal([]byte(out), &info); err != nil || info.Name != name { t.Fatalf("round %d: retry of %s: %v %s", k, name, err, out) } + if len(pre) == 1 && (info.CutLSN != pre[0].CutLSN || info.HeadGen != pre[0].HeadGen) { + t.Fatalf("round %d: %s was listed as %+v before the retry, which answered %+v: a listed snapshot was taken again", k, name, pre[0], info) + } if l := env.snapshots(t, "v1", name); len(l) != 1 || l[0].State != "active" || l[0].CutLSN != info.CutLSN { t.Fatalf("round %d: after the retry %s is listed as %+v; its retry answered %+v", k, name, l, info) } + if len(pre) == 1 { + images = append(images, cum) // a replay: the post-restart block is not in it + } else { + images = append(images, mergeImages(cum, post)) // cut anew after the restart + } + cum = mergeImages(cum, post) + } + t.Logf("rounds: %v", classes) + if classes["MID"] == 0 { + t.Fatalf("inconclusive: no kill landed inside a snapshot (rounds %v)", classes) } next := ladderImage("e1next", []uint64{30, 31}, 3) @@ -107,11 +181,7 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) { final := mergeImages(cum, next) for k := range delays { - var later []map[uint64][]byte - for j := k + 1; j < len(images); j++ { - later = append(later, images[j]) - } - later = append(later, next) + later := []map[uint64][]byte{final} env.restoreChecked(t, fmt.Sprintf("e1-%d", k), targets[k], images[k], later...) } env.restoreChecked(t, "e1-next", targets[len(delays)], final) From e536e100db9cdd570891aede980201ab6e35b1c0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 21:34:56 -0800 Subject: [PATCH 66/71] test: restore kill test claims what its kills show: hydrating, and after hydration before independence; read back after the first restart Co-Authored-By: Claude Opus 5.5 --- ...snapshot_ladder_c3kill_integration_test.go | 50 ++++++++++--------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go index 4370316a68..6345de3af7 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go @@ -115,22 +115,26 @@ func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon { return d } -// TestSnapshotLadderC3KilledMidHydrateAndMidBatch: a restore of a snapshot -// of 32 full chunks of incompressible data into v2 (128 MiB to make local at -// the driver's 64 MiB/s: about 2 s of hydrating). Its blockvolume is killed -// (SIGKILL) one second into hydrating (about half the chunks local, by the -// pace), started again and the driver started again; nothing is read in -// between, so the restart finds the chunks the walker had not reached still -// remote. When the walker has made every chunk local and the first batch cut -// (Hydrating>Owning, one batch for 32 chunks) is running, which the status -// shows as running with every chunk filled and no batch done, the guest -// writes to v2 (acknowledged) and, the batch still running, the blockvolume -// is killed again, restarted, and the driver started again; the guest writes -// once more. The driver resumes from the target's remote facts -// to independence (per its status). Then v2 holds the snapshot with every -// acknowledged write over it, and the source's snapshot, restored again -// into v3, is unchanged (none of v2's writes in it). -func TestSnapshotLadderC3KilledMidHydrateAndMidBatch(t *testing.T) { +// TestSnapshotLadderC3KilledHydratingAndBeforeIndependence: a restore of a +// snapshot of 32 full chunks of incompressible data into v2 (128 MiB to make +// local at the driver's 64 MiB/s: about 2 s of hydrating). Its blockvolume +// is killed (SIGKILL) one second into hydrating, started again, and read +// back in full (a partly filled chunk must never be served), and the driver +// is started again. When the status then shows every chunk filled and no +// batch done, still running and not independent (after hydration completed, +// before independence), the guest writes to v2 (acknowledged) and the +// blockvolume is killed again, restarted (every acknowledged write reads +// back), and the driver started again; the guest writes once more. The +// driver resumes from the target's remote facts to independence (per its +// status). Then v2 holds the snapshot with every acknowledged write over it, +// and the source's snapshot, restored again into v3, is unchanged (none of +// v2's writes in it). +// +// Not covered: guest writes while the driver reports Owning. With one batch +// (32 chunks, under the 64-chunk batch) the status goes from hydrating to +// independent without ever showing owning, so the second kill is only known +// to land after hydration completed and before independence. +func TestSnapshotLadderC3KilledHydratingAndBeforeIndependence(t *testing.T) { env := startLadderEnv(t, "v2", "v3") var chunks []uint64 for c := uint64(0); c < 32; c++ { @@ -149,26 +153,26 @@ func TestSnapshotLadderC3KilledMidHydrateAndMidBatch(t *testing.T) { } drive() - // Killed one second into hydrating: by the pace, about half the chunks - // are local. + // Killed one second into hydrating. env.awaitRestorePhase(t, "v2", "hydrating", 120*time.Second, func(s restoreProgress) bool { return s.Phase == "hydrating" }) time.Sleep(time.Second) st := env.requireRestoreState(t, "v2", "hydrating", func(s restoreProgress) bool { return s.Phase == "hydrating" }) target.kill(t) t.Logf("killed 1 s into hydrating: %+v", st) target = env.startTarget(t, "v2", "blockvolume-v2-after-hydrate-kill") + env.requireImage(t, "n-v2", src) // serves the snapshot, no partly filled chunk drive() - // Written while owning, then killed in the middle of the batch. - inBatch := func(s restoreProgress) bool { + // Written after hydration completed and before independence, then killed. + afterFill := func(s restoreProgress) bool { return s.Filled == len(chunks) && s.Batches == 0 && s.Phase != "independent" } - env.awaitRestorePhase(t, "v2", "the first batch cut running", 180*time.Second, func(s restoreProgress) bool { return s.Running && inBatch(s) }) + env.awaitRestorePhase(t, "v2", "hydration completed, not independent", 180*time.Second, func(s restoreProgress) bool { return s.Running && afterFill(s) }) w1 := ladderImage("c3kw1", []uint64{3, 17, 50}, 3) env.writeImage(t, "n-v2", w1) - st = env.requireRestoreState(t, "v2", "in its first batch cut", inBatch) + st = env.requireRestoreState(t, "v2", "after hydration and before independence", afterFill) target.kill(t) - t.Logf("killed in the first batch cut, after the write: %+v", st) + t.Logf("killed after hydration completed and before independence, after the write: %+v", st) target = env.startTarget(t, "v2", "blockvolume-v2-after-batch-kill") env.requireImage(t, "n-v2", mergeImages(src, w1)) // every acknowledged write survived the kill drive() From 0436ca03c607554d49c7b404647adac16ff8b2c6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 21:40:36 -0800 Subject: [PATCH 67/71] test: snapshot ladder E1 waits for the restarted frontend before reading back Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/snapshot_ladder_e_integration_test.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go index 5248355f76..eaff60cd15 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go @@ -130,7 +130,12 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) { if got := env.adopt(t, holder, "s1"); got != e { t.Fatalf("round %d: the restarted holder adopted epoch %d; want %d (restarted %v after the kill: within the lease?)", k, got, e, time.Since(killed).Round(time.Millisecond)) } - t.Logf("round %d (kill after %v): %s (exit %d err %v); serving again %v after the kill", k, delay, class, r.code, r.err, time.Since(killed).Round(time.Millisecond)) + adopted := time.Since(killed) + poll(t, 60*time.Second, fmt.Sprintf("round %d: the restarted holder never reported its frontend ready", k), func() bool { + return env.frontendReadyAt("s1") + }) + t.Logf("round %d (kill after %v): %s (exit %d err %v); adopted %v and frontend ready %v after the kill", k, delay, class, r.code, r.err, + adopted.Round(time.Millisecond), time.Since(killed).Round(time.Millisecond)) env.requireImage(t, "s1", cum) pre := env.snapshots(t, "v1", name) From d393d93c4c0eba85502c14c198ebcfde2ecb39f1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 21:40:39 -0800 Subject: [PATCH 68/71] test: restore kill test kills inside the resumed run, every chunk local, before independence Co-Authored-By: Claude Opus 5.5 --- ...snapshot_ladder_c3kill_integration_test.go | 34 +++++++++++-------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go index 6345de3af7..bb7dbbccd6 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go @@ -120,20 +120,22 @@ func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon { // local at the driver's 64 MiB/s: about 2 s of hydrating). Its blockvolume // is killed (SIGKILL) one second into hydrating, started again, and read // back in full (a partly filled chunk must never be served), and the driver -// is started again. When the status then shows every chunk filled and no -// batch done, still running and not independent (after hydration completed, -// before independence), the guest writes to v2 (acknowledged) and the -// blockvolume is killed again, restarted (every acknowledged write reads +// is started again: the read-back has made every chunk local, so the +// resumed run has nothing left to fill (its status then reports filled 0) +// and spends its time re-uploading the chunks under v2's own keys. 150 ms +// into that run, still running and not independent, the guest writes to v2 +// (acknowledged) and, the run checked still running and not independent, +// the blockvolume is killed again, restarted (every acknowledged write reads // back), and the driver started again; the guest writes once more. The // driver resumes from the target's remote facts to independence (per its // status). Then v2 holds the snapshot with every acknowledged write over it, // and the source's snapshot, restored again into v3, is unchanged (none of // v2's writes in it). // -// Not covered: guest writes while the driver reports Owning. With one batch -// (32 chunks, under the 64-chunk batch) the status goes from hydrating to -// independent without ever showing owning, so the second kill is only known -// to land after hydration completed and before independence. +// Not covered: guest writes while the driver reports Owning. The status +// shows owning only once the single batch (32 chunks, under the 64-chunk +// batch) has ended, a few ms before independent, so the second kill is only +// known to land in the resumed run, every chunk local, before independence. func TestSnapshotLadderC3KilledHydratingAndBeforeIndependence(t *testing.T) { env := startLadderEnv(t, "v2", "v3") var chunks []uint64 @@ -163,16 +165,18 @@ func TestSnapshotLadderC3KilledHydratingAndBeforeIndependence(t *testing.T) { env.requireImage(t, "n-v2", src) // serves the snapshot, no partly filled chunk drive() - // Written after hydration completed and before independence, then killed. - afterFill := func(s restoreProgress) bool { - return s.Filled == len(chunks) && s.Batches == 0 && s.Phase != "independent" - } - env.awaitRestorePhase(t, "v2", "hydration completed, not independent", 180*time.Second, func(s restoreProgress) bool { return s.Running && afterFill(s) }) + // In the resumed run, every chunk local, before independence: written, + // then killed. + notDone := func(s restoreProgress) bool { return s.Phase != "independent" } + resumed := time.Now() + env.awaitRestorePhase(t, "v2", "the resumed run", 30*time.Second, func(s restoreProgress) bool { return s.Running && notDone(s) }) + time.Sleep(time.Until(resumed.Add(150 * time.Millisecond))) + env.requireRestoreState(t, "v2", "running and not independent", notDone) w1 := ladderImage("c3kw1", []uint64{3, 17, 50}, 3) env.writeImage(t, "n-v2", w1) - st = env.requireRestoreState(t, "v2", "after hydration and before independence", afterFill) + st = env.requireRestoreState(t, "v2", "running and not independent", notDone) target.kill(t) - t.Logf("killed after hydration completed and before independence, after the write: %+v", st) + t.Logf("killed %v into the resumed run, after the write: %+v", time.Since(resumed).Round(time.Millisecond), st) target = env.startTarget(t, "v2", "blockvolume-v2-after-batch-kill") env.requireImage(t, "n-v2", mergeImages(src, w1)) // every acknowledged write survived the kill drive() From fbeee4463781df43006929159baf114ac75d863d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 21:52:11 -0800 Subject: [PATCH 69/71] test: snapshot ladder E1 post-restart block pattern is 16 bytes (a whole block) Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/snapshot_ladder_e_integration_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go index eaff60cd15..d2011ba0ef 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go @@ -153,7 +153,8 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) { t.Fatalf("round %d: %s answered %s before the kill but is listed as %+v", k, name, r.out, pre[0]) } } - post := map[uint64][]byte{uint64(50+k) * ladderChunkBlocks: pattern(fmt.Sprintf("e1-post-%02d-blk!", k))} + // 16 bytes: pattern repeats it to exactly one block. + post := map[uint64][]byte{uint64(50+k) * ladderChunkBlocks: pattern(fmt.Sprintf("e1-post-%02d-blk!!", k))} env.writeImage(t, "s1", post) out, _ := env.h.command(t, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status, From 852aaa0795de6f670f398e078f5a0da24a29fb81 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 21:54:18 -0800 Subject: [PATCH 70/71] test: snapshot ladder E1 counts a kill inside the cut (a new intent) as inside the snapshot; twelve dirty chunks per round Co-Authored-By: Claude Opus 5.5 --- .../snapshot_ladder_e_integration_test.go | 72 ++++++++++++++++--- 1 file changed, 61 insertions(+), 11 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go index d2011ba0ef..03708fa5e6 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go @@ -43,14 +43,58 @@ func (env *handoffEnv) nameRecorded(t *testing.T, vol, name string) bool { return false } +// filerNames lists the entry names (unescaped) of a filer directory, read +// straight from the filer (not through the product); a missing directory +// lists as empty. +func (env *handoffEnv) filerNames(t *testing.T, dir string) map[string]bool { + t.Helper() + c := &http.Client{Timeout: 10 * time.Second} + names := map[string]bool{} + for last := ""; ; { + req, _ := http.NewRequest("GET", "http://"+env.cluster.filerHTTP+dir+"/?limit=1000&lastFileName="+url.QueryEscape(last), nil) + req.Header.Set("Accept", "application/json") + resp, err := c.Do(req) + if err != nil { + t.Fatal(err) + } + var page struct { + Entries []struct { + FullPath string `json:"FullPath"` + } `json:"Entries"` + LastFileName string `json:"LastFileName"` + ShouldDisplayLoadMore bool `json:"ShouldDisplayLoadMore"` + } + err = json.NewDecoder(resp.Body).Decode(&page) + resp.Body.Close() + if resp.StatusCode == http.StatusNotFound { + return names + } + if err != nil || resp.StatusCode != http.StatusOK { + t.Fatalf("filer listing of %s: status %d %v", dir, resp.StatusCode, err) + } + for _, e := range page.Entries { + name, err := url.PathUnescape(path.Base(e.FullPath)) + if err != nil { + t.Fatalf("filer entry %q: %v", e.FullPath, err) + } + names[name] = true + } + if !page.ShouldDisplayLoadMore || page.LastFileName == "" || page.LastFileName == last { + return names + } + last = page.LastFileName + } +} + // TestSnapshotLadderE1CrashDuringASnapshot: rounds on one volume. In each, -// blocks in two new chunks are written and acknowledged, a snapshot with a -// fixed request id is started, and the holder is killed after a different -// delay (from at once to well after the answer), then restarted within its -// lease. Each round is classified from what the kill left: ANSWERED (the -// command answered success first), MID (no answer, but the catalog holds the -// snapshot's name record: the kill landed inside the snapshot), or BEFORE -// (no answer and no name record). The test fails as inconclusive unless at +// blocks in twelve chunks are written and acknowledged (so the snapshot's cut +// has twelve chunks to upload), a snapshot with a fixed request id is +// started, and the holder is killed after a different delay (from at once to +// well after the answer), then restarted within its lease. Each round is +// classified from what the kill left in the filer: ANSWERED (the command +// answered success first), MID (no answer, but the snapshot's name record or +// an intent that was not there before the request: the kill landed inside +// the snapshot, in its cut or its catalog steps), or BEFORE (neither). The test fails as inconclusive unless at // least one round is MID. After each restart, before the retry: // - the snapshot is listed at most once and only active; an ANSWERED one // is listed, at the cut its answer gave; @@ -86,11 +130,13 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) { cum := map[uint64][]byte{0: marker} classes := map[string]int{} for k, delay := range delays { - img := ladderImage(fmt.Sprintf("e1r%d", k), []uint64{uint64(k + 1), uint64(20 + k)}, 3) + img := ladderImage(fmt.Sprintf("e1r%d", k), []uint64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, 3) env.writeImage(t, "s1", img) cum = mergeImages(cum, img) name, req := fmt.Sprintf("e1-%d", k), fmt.Sprintf("r-e1-%d", k) + intents := path.Join(env.chunkPath, "v1", "intents") + before := env.filerNames(t, intents) ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) done := make(chan result, 1) go func() { @@ -115,11 +161,15 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) { } cancel() answered := r.err == nil && r.code == 0 + newIntent := false + for n := range env.filerNames(t, intents) { + newIntent = newIntent || !before[n] + } class := "BEFORE" switch { case answered: class = "ANSWERED" - case env.nameRecorded(t, "v1", name): + case env.nameRecorded(t, "v1", name) || newIntent: class = "MID" } classes[class]++ @@ -134,8 +184,8 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) { poll(t, 60*time.Second, fmt.Sprintf("round %d: the restarted holder never reported its frontend ready", k), func() bool { return env.frontendReadyAt("s1") }) - t.Logf("round %d (kill after %v): %s (exit %d err %v); adopted %v and frontend ready %v after the kill", k, delay, class, r.code, r.err, - adopted.Round(time.Millisecond), time.Since(killed).Round(time.Millisecond)) + t.Logf("round %d (kill after %v): %s (exit %d err %v; new intent %v); adopted %v and frontend ready %v after the kill", k, delay, class, r.code, r.err, + newIntent, adopted.Round(time.Millisecond), time.Since(killed).Round(time.Millisecond)) env.requireImage(t, "s1", cum) pre := env.snapshots(t, "v1", name) From 2e4d4d112bb0f7467140846c077bdf901cb4c863 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 22:01:09 -0800 Subject: [PATCH 71/71] test: restore kill test resumes from a partly local volume (subset read-back, 0 < filled < 32), checks the marker before and after Co-Authored-By: Claude Opus 5.5 --- ...snapshot_ladder_c3kill_integration_test.go | 117 ++++++++++++++---- 1 file changed, 92 insertions(+), 25 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go index bb7dbbccd6..113bdad1a3 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go @@ -8,6 +8,7 @@ import ( "io" "math/rand" "net/http" + "path" "testing" "time" ) @@ -83,6 +84,19 @@ func (env *handoffEnv) requireRestoreState(t *testing.T, target, what string, ok return st } +// requireBlocksOf reads every block of img on the host and requires each to +// equal img (whole 4 KiB blocks compared byte for byte). +func (env *handoffEnv) requireBlocksOf(t *testing.T, hostID string, img map[uint64][]byte) { + t.Helper() + c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN) + defer c.close() + for lba, want := range img { + if got := c.read(t, lba, 4096); string(got) != string(want) { + t.Fatalf("%s: block %d differs from what was written", hostID, lba) + } + } +} + // denseImage fills every block of the given chunks with incompressible // bytes (seeded by tag and LBA), so that their chunks are full size in the // store and a restore of them takes measurable time at the driver's rate. @@ -103,6 +117,44 @@ func denseImage(tag string, chunks []uint64) map[uint64][]byte { return img } +// independent reports whether target's independence marker exists, read +// from the filer (not through the product's status, which reports only a +// run of this process). +func (env *handoffEnv) independent(t *testing.T, target string) bool { + t.Helper() + c := &http.Client{Timeout: 10 * time.Second} + p := path.Join(env.chunkPath, target, "RESTORE-INDEPENDENT") + resp, err := c.Get("http://" + env.cluster.filerHTTP + p + "?metadata=true") + if err != nil { + t.Fatal(err) + } + io.Copy(io.Discard, resp.Body) + resp.Body.Close() + switch resp.StatusCode { + case http.StatusOK: + return true + case http.StatusNotFound: + return false + } + t.Fatalf("filer lookup of %s: status %d", p, resp.StatusCode) + return false +} + +// subsetOf returns the blocks of img in the given chunks. +func subsetOf(img map[uint64][]byte, chunks []uint64) map[uint64][]byte { + in := map[uint64]bool{} + for _, c := range chunks { + in[c] = true + } + out := map[uint64][]byte{} + for lba, b := range img { + if in[lba/ladderChunkBlocks] { + out[lba] = b + } + } + return out +} + // startTarget starts target's blockvolume and waits until it serves. func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon { t.Helper() @@ -117,25 +169,28 @@ func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon { // TestSnapshotLadderC3KilledHydratingAndBeforeIndependence: a restore of a // snapshot of 32 full chunks of incompressible data into v2 (128 MiB to make -// local at the driver's 64 MiB/s: about 2 s of hydrating). Its blockvolume -// is killed (SIGKILL) one second into hydrating, started again, and read -// back in full (a partly filled chunk must never be served), and the driver -// is started again: the read-back has made every chunk local, so the -// resumed run has nothing left to fill (its status then reports filled 0) -// and spends its time re-uploading the chunks under v2's own keys. 150 ms -// into that run, still running and not independent, the guest writes to v2 -// (acknowledged) and, the run checked still running and not independent, -// the blockvolume is killed again, restarted (every acknowledged write reads -// back), and the driver started again; the guest writes once more. The -// driver resumes from the target's remote facts to independence (per its -// status). Then v2 holds the snapshot with every acknowledged write over it, -// and the source's snapshot, restored again into v3, is unchanged (none of -// v2's writes in it). +// local at the driver's 64 MiB/s: about 2 s of hydrating). +// +// 1. Its blockvolume is killed (SIGKILL) one second into hydrating and +// started again. Every other chunk is read back (a partly filled chunk +// must never be served), which makes those chunks local and leaves the +// rest to the driver, and the driver is started again. +// 2. The resumed run must report, when its hydrating step ends, that it +// filled some chunks and not all (0 < filled < 32: it resumed from a +// partly local volume). Then, the run still going and not independent, +// the guest writes to v2 (acknowledged); checked still running and not +// independent, the blockvolume is killed again and restarted. Before the +// driver is started again the independence marker must be absent (the +// kill landed before independence); every acknowledged write reads back. +// 3. The driver is started again, the guest writes once more, and the run +// reaches independence (per its status and the marker). Then v2 holds +// the snapshot with every acknowledged write over it, read back in full, +// and the source's snapshot, restored again into v3, is unchanged (none +// of v2's writes in it). // // Not covered: guest writes while the driver reports Owning. The status // shows owning only once the single batch (32 chunks, under the 64-chunk -// batch) has ended, a few ms before independent, so the second kill is only -// known to land in the resumed run, every chunk local, before independence. +// batch) has ended, a few ms before independent. func TestSnapshotLadderC3KilledHydratingAndBeforeIndependence(t *testing.T) { env := startLadderEnv(t, "v2", "v3") var chunks []uint64 @@ -162,28 +217,40 @@ func TestSnapshotLadderC3KilledHydratingAndBeforeIndependence(t *testing.T) { target.kill(t) t.Logf("killed 1 s into hydrating: %+v", st) target = env.startTarget(t, "v2", "blockvolume-v2-after-hydrate-kill") - env.requireImage(t, "n-v2", src) // serves the snapshot, no partly filled chunk + var even []uint64 + for c := uint64(0); c < 32; c += 2 { + even = append(even, c) + } + env.requireBlocksOf(t, "n-v2", subsetOf(src, even)) // no partly filled chunk is served drive() - // In the resumed run, every chunk local, before independence: written, - // then killed. + // The resumed run: it fills what is not local yet; then, before + // independence, written and killed. notDone := func(s restoreProgress) bool { return s.Phase != "independent" } - resumed := time.Now() - env.awaitRestorePhase(t, "v2", "the resumed run", 30*time.Second, func(s restoreProgress) bool { return s.Running && notDone(s) }) - time.Sleep(time.Until(resumed.Add(150 * time.Millisecond))) - env.requireRestoreState(t, "v2", "running and not independent", notDone) + st = env.awaitRestorePhase(t, "v2", "the resumed run's hydrating step ended", 60*time.Second, func(s restoreProgress) bool { + return s.Running && s.Filled > 0 && notDone(s) + }) + if st.Filled >= len(chunks) { + t.Fatalf("the resumed run filled %d chunks: it did not resume from a partly local volume (%d read back before it)", st.Filled, len(even)) + } w1 := ladderImage("c3kw1", []uint64{3, 17, 50}, 3) env.writeImage(t, "n-v2", w1) st = env.requireRestoreState(t, "v2", "running and not independent", notDone) target.kill(t) - t.Logf("killed %v into the resumed run, after the write: %+v", time.Since(resumed).Round(time.Millisecond), st) + t.Logf("killed in the resumed run after it filled %d of %d chunks, after the write: %+v", st.Filled, len(chunks), st) target = env.startTarget(t, "v2", "blockvolume-v2-after-batch-kill") - env.requireImage(t, "n-v2", mergeImages(src, w1)) // every acknowledged write survived the kill + if env.independent(t, "v2") { + t.Fatal("the independence marker exists after the second kill: the kill did not land before independence") + } + env.requireBlocksOf(t, "n-v2", w1) // every acknowledged write survived the kill drive() w2 := ladderImage("c3kw2", []uint64{17, 44, 60}, 2) // not chunk 40: requireEdges keeps it untouched env.writeImage(t, "n-v2", w2) env.waitIndependent(t, "v2") + if !env.independent(t, "v2") { + t.Fatal("the restore status says independent but the marker is absent") + } env.requireImage(t, "n-v2", mergeImages(src, w1, w2)) env.restoreChecked(t, "base", "v3", src, w1, w2) }