From 77483c0c244143c5e61be24b99b998947183b434 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 20:58:32 -0800 Subject: [PATCH 001/150] test(chunkstore): require HEAD CAS to read only root metadata --- .../frontend/chunkstore/head_cas_root_test.go | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/head_cas_root_test.go diff --git a/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go b/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go new file mode 100644 index 0000000000..d65183c90e --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go @@ -0,0 +1,62 @@ +package chunkstore + +import ( + "context" + "errors" + "path" + "reflect" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type rootCASFiler struct { + Filer + roots, children int + refuseChildren bool +} + +func (f *rootCASFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if name == headName { + f.roots++ + } else { + f.children++ + if f.refuseChildren { + return nil, errors.New("segment service unavailable") + } + } + return f.Filer.LookupEntry(ctx, dir, name) +} + +// A HEAD CAS validates root authority, not the availability of every immutable +// segment. Ordinary GetHead still resolves and verifies all segment contents. +func TestManifest_CASReadsOnlyRoot(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + _, h := publishSegmented(t, f, b) + tracked := &rootCASFiler{Filer: f, refuseChildren: true} + r, err := NewChunkRemote(tracked, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + next := h + next.RemoteLSN++ + gen, err := r.CASHead(context.Background(), storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next) + if err != nil { + t.Fatalf("root-only CAS must not depend on segments: %v", err) + } + if gen != h.Gen+1 || tracked.roots != 1 || tracked.children != 0 { + t.Fatalf("CAS gen=%d root reads=%d child reads=%d", gen, tracked.roots, tracked.children) + } + if _, err := r.GetHead(context.Background()); err == nil { + t.Fatal("GetHead skipped segment resolution") + } + tracked.refuseChildren = false + got, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if got.Gen != gen || got.RemoteLSN != next.RemoteLSN || !reflect.DeepEqual(got.Chunks, h.Chunks) || !reflect.DeepEqual(got.Segments, h.Segments) { + t.Fatalf("CAS changed content or lost frontier: %+v", got) + } +} From 51f4b2409b56845bea23dfce45d84dc31576a9c7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 20:59:07 -0800 Subject: [PATCH 002/150] fix(chunkstore): validate only root metadata during HEAD CAS --- .../core/frontend/chunkstore/chunk_remote.go | 18 +- seaweed-block/docs/design/invariants.md | 200 +++++++++--------- 2 files changed, 115 insertions(+), 103 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 3fbfde5f9d..e204667cdc 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -370,6 +370,16 @@ type refDoc struct { // was ever published. An entry that exists but does not decode is an // error, never the zero HEAD. func (r *ChunkRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + h, err := r.getHeadRoot(ctx) + if err != nil { + return h, err + } + return r.resolveManifest(ctx, h) +} + +// getHeadRoot validates the root and its CAS attributes without reading any +// immutable segment. CASHead only needs authority and lineage from this root. +func (r *ChunkRemote) getHeadRoot(ctx context.Context) (storage.ChunkHead, error) { e, err := r.f.LookupEntry(ctx, r.root, headName) if errors.Is(err, ErrNotFound) { return storage.ChunkHead{}, nil @@ -377,11 +387,7 @@ func (r *ChunkRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { if err != nil { return storage.ChunkHead{}, err } - h, err := decodeHead(path.Join(r.root, headName), e) - if err != nil { - return h, err - } - return r.resolveManifest(ctx, h) + return decodeHead(path.Join(r.root, headName), e) } // CASHead installs next, at generation expected.Gen+1, only if the stored @@ -397,7 +403,7 @@ func (r *ChunkRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVer // Read the LSN under the same generation/epoch guard used by UpdateEntry. // A competing write after this read makes the conditional update fail; // no successful CAS can lower the committed lineage frontier. - current, err := r.GetHead(ctx) + current, err := r.getHeadRoot(ctx) if err != nil { return 0, err } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b032a37af0..7d8f9772f2 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -36,7 +36,7 @@ Each machine lists its states, the allowed transitions, the guard that must hold ### M1 walstore: open, recover, serve, fault -The local storage engine and the durable backend in front of it. Diagrams in the core design: the per-I/O gate in [§1.1](block-design.md#11-frontends-and-the-backend-contract), and the life of one write (appended, synced, in the extent, checkpointed, reusable) in [§1.2](block-design.md#12-walstore-wal-plus-extent). +The local storage engine and the durable backend in front of it. Diagrams in the core design: the per-I/O gate in [§1.1](block-design.md#11-frontends-and-the-backend-contract), and the life of one write (appended, synced, in the extent, checkpointed, reusable) in [§1.2](block-design.md#12-walstore-wal-plus-extent). ```mermaid stateDiagram-v2 @@ -53,7 +53,7 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | +| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | @@ -61,7 +61,7 @@ stateDiagram-v2 | Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse (C11 bitmap/superblock path remains legacy-fixture-only) | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001` | | Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `noteAppendFailure`, `syncFile` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | | FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | -| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | +| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. @@ -71,7 +71,7 @@ Recovery warnings such as `wal_hole_suspected` are recorded in Serving without c ### M2 Authority: assignment, epoch, lease -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). +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). **Assignment line, per volume.** @@ -88,8 +88,8 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | From | To | Event and guard | Enforced in | Protects | |---|---|---|---|---| -| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | -| Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | +| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | +| Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | @@ -99,7 +99,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a ### M3 Replica role and peer state -The role a blockvolume takes from each assignment, its replica listener's admission, and the primary's view of each replica. This is the replication engine of [core §1.6](block-design.md#16-replication-and-failover) (which has the peer-state diagram) as the Kubernetes line uses it; promotion is in [Kubernetes §6](kubernetes-block-design.md#6-authority-promotion) (diagram) and the failover sequence in [Kubernetes §4](kubernetes-block-design.md#4-replication-and-failover). +The role a blockvolume takes from each assignment, its replica listener's admission, and the primary's view of each replica. This is the replication engine of [core §1.6](block-design.md#16-replication-and-failover) (which has the peer-state diagram) as the Kubernetes line uses it; promotion is in [Kubernetes §6](kubernetes-block-design.md#6-authority-promotion) (diagram) and the failover sequence in [Kubernetes §4](kubernetes-block-design.md#4-replication-and-failover). ```mermaid stateDiagram-v2 @@ -123,7 +123,7 @@ stateDiagram-v2 | Unassigned, Primary | Supporting at e | the fact names another primary and lists this replica as a peer; the floor e is persisted first; the frontend stays gated | `core/host/volume/host.go` `applyFact`; `core/transport/replica.go` `AdmitAsReplica` | `INV-FENCE-FLOOR-DURABLE-001` | | Primary, Supporting | Excluded | the fact names another primary and does not list this replica; ingress is closed, the other line is recorded and the frontend is unhealthy | `core/host/volume/host.go` `applyFact`, `recordOtherLine`; `core/host/volume/projection_bridge.go` `projectionWithSupersede` | `INV-ROLE-SUPERSEDED-001`, `INV-FENCE-STALE-PRIMARY-001` | | any | role admission failed | the listener cannot be fenced or its floor cannot be persisted; the role is not adopted and the projection is not healthy | `core/host/volume/host.go` `latchRoleAdmission` | `INV-FENCE-FLOOR-DURABLE-001` | -| (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | +| (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | | Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | **Peer state, as the primary sees each replica** (type `ReplicaState` in `core/replication/peer.go`). A new peer starts `Healthy` (`NewReplicaPeer`). @@ -134,13 +134,13 @@ stateDiagram-v2 | `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001` | | `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | | any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | -| `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | +| `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.Invalidate`, called on a ship, barrier or fence error, goes through the same gate as `SetState` (`replicaStateTransitionAllowed`): `Healthy`, `Degraded` and `CatchingUp` move to `Degraded`; from `NeedsRebuild` the state is kept and the reason is still logged ([#182](https://github.com/seaweedfs/seaweed-block/issues/182)). A replicated `Sync` is judged per durability mode (`core/replication/durability.go` `EvaluateBarrierAcks`; `INV-REPL-DURABILITY-MODE-001`). ### M4 Workspace HEAD holder and takeover -One host at a time holds a workspace volume's HEAD in SeaweedFS. The sequence diagram of a clean and a forced move is in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves); blockmaster's side of the lease is in M2. +One host at a time holds a workspace volume's HEAD in SeaweedFS. The sequence diagram of a clean and a forced move is in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves); blockmaster's side of the lease is in M2. ```mermaid stateDiagram-v2 @@ -179,7 +179,7 @@ stateDiagram-v2 ### M5 The cut pipeline -A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. The steps are described in [agent workspace §5](agent-workspace-design.md#5-the-cut), and the figure in [§3](agent-workspace-design.md#3-remote-layout) shows them against the remote layout. All steps are in `core/storage/chunk_layer.go` `captureLocked` unless stated. +A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. The steps are described in [agent workspace §5](agent-workspace-design.md#5-the-cut), and the figure in [§3](agent-workspace-design.md#3-remote-layout) shows them against the remote layout. All steps are in `core/storage/chunk_layer.go` `captureLocked` unless stated. ```mermaid stateDiagram-v2 @@ -223,13 +223,13 @@ stateDiagram-v2 ### M6 Chunk lifecycle -HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete). +HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete). **HEAD states** (`active`, `detached`, `deleting`, `purging`, `deleted`, `aborted`). | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | +| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | | `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | | `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | @@ -237,14 +237,14 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | `deleting` | previous state | a snapshot name record exists: the delete is refused and reverted | `core/frontend/chunkstore/volume_delete.go` `snapshotsBlock`, `revertHeadDeleting` | `INV-VOLDEL-COMMIT-001` | | `deleting` | `purging` | commit point, bound to the same delete incarnation | `core/frontend/chunkstore/volume_delete.go` `commitHeadPurging` | `INV-VOLDEL-COMMIT-001` | | `purging` | `deleted` | chunks dropped and `VOLUME` marked deleted | `core/frontend/chunkstore/volume_delete.go` `finishHeadDeleted`, `markVolumeDeleted` | `INV-VOL-ID-NO-REUSE-001` | -| `deleting`, `purging`, `deleted` | — | no claim or cut moves HEAD; only the delete's own transitions | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-HEAD-DELETE-FROZEN-001` | -| — | `aborted` | a GC copy sweep settles a dead fork by an exclusive create of an aborted HEAD tombstone, so the fork can never publish | `core/frontend/chunkstore/catalog.go` `AbortFork`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies` | — | +| `deleting`, `purging`, `deleted` | — | no claim or cut moves HEAD; only the delete's own transitions | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-HEAD-DELETE-FROZEN-001` | +| — | `aborted` | a GC copy sweep settles a dead fork by an exclusive create of an aborted HEAD tombstone, so the fork can never publish | `core/frontend/chunkstore/catalog.go` `AbortFork`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies` | — | **Snapshots and forks.** | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | +| — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | | name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001` | @@ -253,10 +253,10 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | +| — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | | intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` | | intent live | expired | older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001` | -| — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | +| — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | | bound | tombstoned, needle deleted | unrooted in two complete marks at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001` | | tombstoned | (never rebound) | bindings are never removed | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | @@ -272,22 +272,22 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | +| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | | `INV-WAL-REPLAY-LWW-001` | Replay applies the highest LSN per LBA, independent of the physical scan order. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALStoreRecoverLastWriterWinsAcrossScanOrder` (`core/storage/walstore_recovery_lww_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | -| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the on-disk superblock has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_writer.go` `spaceUsed`, `tailPersisted`; `core/storage/walstore.go` `persistCheckpointReleasing` | `TestWALWriterReuseIsBoundedByTheDurableTail`, `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherSnapshotCutPreservesSyncedWrites` (`core/storage/flusher_snapshot_cut_test.go`); `TestWALStoreCheckpointSIGKILLCrashWindows` (`core/storage/walstore_checkpoint_crash_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the on-disk superblock has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_writer.go` `spaceUsed`, `tailPersisted`; `core/storage/walstore.go` `persistCheckpointReleasing` | `TestWALWriterReuseIsBoundedByTheDurableTail`, `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherSnapshotCutPreservesSyncedWrites` (`core/storage/flusher_snapshot_cut_test.go`); `TestWALStoreCheckpointSIGKILLCrashWindows` (`core/storage/walstore_checkpoint_crash_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-FRONTIER-GAP-001` | Synced entries above an intentional LSN gap (a rebuild's frontier jump) are kept by recovery. | M1 Recovering | `core/storage/recovery.go` `recoverWAL` | `TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump` (`core/storage/walstore_recovery_frontier_gap_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore.go` `persistCheckpointReleasing` | `TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle` (`core/storage/walstore_checkpoint_safety_test.go`) | — | ACTIVE | -| `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent or superblock), the open store refuses every later `Sync`, write and checkpoint without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestWALStoreWALFsyncFailureIsSticky`, `TestWALStoreExtentFsyncFailureIsSticky`, `TestWALStoreCheckpointFsyncFailureIsSticky` (`core/storage/walstore_sticky_fsync_test.go`); `TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | -| `INV-WAL-APPEND-STICKY-001` | A WAL append whose write failed latches the store fault; writers already queued behind it are refused. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteAppendFailure`, `WALStore.Write` | `TestWALStoreWritersQueuedBehindAFailedAppendAreRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | -| `INV-WAL-SYNC-FRONTIER-001` | `Sync` never reports an uncovered write durable: it returns the global synced frontier, which is at least the caller's own write and is covered by a completed `fsync`. It may include later writes whose covering `fsync` completed before the caller resumed. | M1 write lifecycle: Appended → Synced | `core/storage/walstore.go` `WALStore.Sync` | `TestWALStore_SyncDoesNotClaimConcurrentWrite` (`core/storage/walstore_test.go`); `TestWALGenerationFirstCallerReturnOrdering` (`core/storage/walstore_sync_frontier_order_test.go`) | — | ACTIVE | -| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt` (`cmd/blockvolume/durable_startup_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE | -| `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE | +| `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore.go` `persistCheckpointReleasing` | `TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle` (`core/storage/walstore_checkpoint_safety_test.go`) | — | ACTIVE | +| `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent or superblock), the open store refuses every later `Sync`, write and checkpoint without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestWALStoreWALFsyncFailureIsSticky`, `TestWALStoreExtentFsyncFailureIsSticky`, `TestWALStoreCheckpointFsyncFailureIsSticky` (`core/storage/walstore_sticky_fsync_test.go`); `TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | +| `INV-WAL-APPEND-STICKY-001` | A WAL append whose write failed latches the store fault; writers already queued behind it are refused. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteAppendFailure`, `WALStore.Write` | `TestWALStoreWritersQueuedBehindAFailedAppendAreRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | +| `INV-WAL-SYNC-FRONTIER-001` | `Sync` never reports an uncovered write durable: it returns the global synced frontier, which is at least the caller's own write and is covered by a completed `fsync`. It may include later writes whose covering `fsync` completed before the caller resumed. | M1 write lifecycle: Appended → Synced | `core/storage/walstore.go` `WALStore.Sync` | `TestWALStore_SyncDoesNotClaimConcurrentWrite` (`core/storage/walstore_test.go`); `TestWALGenerationFirstCallerReturnOrdering` (`core/storage/walstore_sync_frontier_order_test.go`) | — | ACTIVE | +| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt` (`cmd/blockvolume/durable_startup_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE | +| `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE | | `INV-WAL-V3-ACTIVATION-001` | Public create produces an owned mapped v3/impl3 volume with the requested chunk geometry and C default/A option. Writable/readonly open validate A/B dependencies, reject actual legacy headers without mutation, and can select a valid fallback when A is damaged. Production provider capture/HEAD restore/status use those selectors. Legacy fixture constructors cannot be called by default production code or enter its transitive storage import closure. | M1 open/create/readonly | `walstore.go` public selectors; `walstore_v3.go` `refuseLegacyWALStore`, `ProbeWALStoreV3`; `provider.go` | `TestWALStoreProductionSelectorCreatesMappedV3`, `TestWALStoreProductionRefusesLegacyWithoutMutation`, `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy`, `TestWALStoreProductionCreateOptions`, `TestLegacyFixtureIsolation`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE | | `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE | | `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | -| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | +| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-RECORD-001` | An impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | | `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB | | `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire` | `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | @@ -298,17 +298,17 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Append-only retention preserves both slots and pending candidates. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | -| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | -| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | -| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | -| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | -| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | +| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | +| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | +| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | +| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | +| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | | `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB | | `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB | | `INV-WAL-V3-MIGRATE-001` | `sw-block migrate-v3` rewrites only the descriptor of a cleanly closed v2/impl1 volume whose WAL the exhaustive scan proves flushed; the scan and the geometry check run before any write, and a refusal leaves the volume and every sidecar byte-identical. It keeps the extent base (WALSize = old - 4096), writes an atomic operator backup, an all-UNKNOWN initial map (covered = the v2 checkpoint), the prepared slot B, slot A at phase 0 (the commit point), slot B at phase 0, and only then retires the v2 chunk bitmap; each step is durable before the next. A rerun decides from the slot bytes alone: before the commit it restarts with a full rescan; after it, it only finishes the rollover and the retirement; a prepared B with an invalid A refuses with `ErrMigrationIncomplete`, as v3 open does; it never reads or restores the backup. | offline tool | `cmd/sw-block/migrate.go`; `cmd/sw-block/internal/v2legacy`; `core/storage/migrate_v3.go` | `TestMigrateV3CleanVolume`, `TestMigrateV3RefusalsChangeNothing`, `TestMigrateV3CrashAfterEachStepIsResumable`, `TestMigrateV3OldBinaryAfterPreparation`, `TestMigrateV3OldWALOverwritesThePreparedSlot`, `TestMigrateV3NeverRestoresTheBackup` (`cmd/sw-block/migrate_test.go`); tagged `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | none (tool) | STUB | -| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | -| `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | -| `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE | +| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | +| `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | +| `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE | Notes: @@ -332,15 +332,15 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | -| `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that clears the lease is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | -| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | +| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | +| `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that clears the lease is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | +| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | Notes: @@ -352,16 +352,16 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | -| `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | -| `INV-REPL-INGRESS-SLOTS-001` | Replication listeners are open only while the assignment has replica slots. | M3 role → listener lifecycle | `cmd/blockvolume/replication_ingress.go` `roleLocked` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | ACTIVE | -| `INV-REPL-CATCHUP-REBUILD-001` | The engine chooses catch-up when the gap is still in the primary's WAL and rebuild when it is not. | M3 Degraded → CatchingUp \| NeedsRebuild | `core/engine/apply.go` `decide` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | ACTIVE | -| `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE | -| `INV-REPL-DURABILITY-MODE-001` | Under `sync_all` a replicated `Sync` fails if any replica barrier fails; under `sync_quorum` it fails unless a majority of nodes, the primary included, are durable. | M3 barrier evaluation | `core/replication/durability.go` `EvaluateBarrierAcks` | `TestDurabilityCoordinator_Quorum_RF3_OneReplicaFailed`, `TestDurabilityCoordinator_Quorum_RF3_BothReplicasFailed`, `TestDurabilityCoordinator_SyncAll_AnyFailure_Fails` (`core/replication/durability_test.go`) | — | ACTIVE | -| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`) | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive` | ACTIVE | -| `INV-ROLE-STALE-REPLAY-001` | A role call below the host's current desired epoch is refused and cannot clear a newer role-admission failure. | M3 role admission | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `TestG1_StaleReplayDoesNotClearANewerAdmissionFailure`, `TestG1_StaleSupportingReplayDoesNotClearTheLatch` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | -| `INV-ROLE-READINESS-BLOCK-001` | While local recovery blocks readiness, `applyFact` admits neither a primary nor a supporting role, and replays the stored fact once readiness clears. | M3 Unassigned → Primary \| Supporting (guard) | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter`, `TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter`, `TestHost_ApplyFact_Self_ReplaysAfterLocalReadinessClearsWithReplicationFirst` (`core/host/volume/apply_fact_test.go`) | — | ACTIVE | -| `INV-ROLE-SUPERSEDED-001` | A fact naming another replica as primary, with this replica not among its peers, never reaches this host's adapter or replication, and is recorded as the other line. | M3 Primary \| Supporting → Excluded | `core/host/volume/host.go` `applyFact`, `recordOtherLine` | `TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication` (`core/host/volume/apply_fact_test.go`); `TestHost_BuildReport_SupersededReplicaNotReadyForPrimary` (`core/host/volume/frontend_targets_test.go`) | — | ACTIVE | +| `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | +| `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | +| `INV-REPL-INGRESS-SLOTS-001` | Replication listeners are open only while the assignment has replica slots. | M3 role → listener lifecycle | `cmd/blockvolume/replication_ingress.go` `roleLocked` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | ACTIVE | +| `INV-REPL-CATCHUP-REBUILD-001` | The engine chooses catch-up when the gap is still in the primary's WAL and rebuild when it is not. | M3 Degraded → CatchingUp \| NeedsRebuild | `core/engine/apply.go` `decide` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | ACTIVE | +| `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE | +| `INV-REPL-DURABILITY-MODE-001` | Under `sync_all` a replicated `Sync` fails if any replica barrier fails; under `sync_quorum` it fails unless a majority of nodes, the primary included, are durable. | M3 barrier evaluation | `core/replication/durability.go` `EvaluateBarrierAcks` | `TestDurabilityCoordinator_Quorum_RF3_OneReplicaFailed`, `TestDurabilityCoordinator_Quorum_RF3_BothReplicasFailed`, `TestDurabilityCoordinator_SyncAll_AnyFailure_Fails` (`core/replication/durability_test.go`) | — | ACTIVE | +| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`) | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive` | ACTIVE | +| `INV-ROLE-STALE-REPLAY-001` | A role call below the host's current desired epoch is refused and cannot clear a newer role-admission failure. | M3 role admission | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `TestG1_StaleReplayDoesNotClearANewerAdmissionFailure`, `TestG1_StaleSupportingReplayDoesNotClearTheLatch` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | +| `INV-ROLE-READINESS-BLOCK-001` | While local recovery blocks readiness, `applyFact` admits neither a primary nor a supporting role, and replays the stored fact once readiness clears. | M3 Unassigned → Primary \| Supporting (guard) | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter`, `TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter`, `TestHost_ApplyFact_Self_ReplaysAfterLocalReadinessClearsWithReplicationFirst` (`core/host/volume/apply_fact_test.go`) | — | ACTIVE | +| `INV-ROLE-SUPERSEDED-001` | A fact naming another replica as primary, with this replica not among its peers, never reaches this host's adapter or replication, and is recorded as the other line. | M3 Primary \| Supporting → Excluded | `core/host/volume/host.go` `applyFact`, `recordOtherLine` | `TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication` (`core/host/volume/apply_fact_test.go`); `TestHost_BuildReport_SupersededReplicaNotReadyForPrimary` (`core/host/volume/frontend_targets_test.go`) | — | ACTIVE | Notes: @@ -372,15 +372,15 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-WS-HEAD-CAS-001` | Every HEAD publish is a conditional update on `{gen, epoch}`, so only one holder can publish each HEAD generation; a holder that sees a superseding HEAD fences itself. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | +| `INV-WS-HEAD-CAS-001` | Every HEAD publish is a conditional update on `{gen, epoch}`, so only one holder can publish each HEAD generation; a holder that sees a superseding HEAD fences itself. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | | `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | -| `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | -| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | -| `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | -| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | -| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | -| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `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`) | — | ACTIVE | +| `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | +| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | +| `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | +| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | +| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `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`) | — | ACTIVE | Notes: @@ -392,16 +392,16 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | -| `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | -| `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | -| `INV-CUT-STAGED-REUSE-001` | A chunk pre-copied outside the barrier is used only if no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window (legacy fixtures retain the full-copy barrier). | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | -| `INV-CUT-BITMAP-001` | The dirty bitmap never under-reports: it is durable before the checkpoint passes its WAL entries, and it is reset only after a successful CAS, keeping chunks dirtied after the cut. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/chunk_layer.go` `BeforeCheckpointAdvance`, `finishCut` | `TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle`, `TestChunkLayer_C11_RolloverKeepsPostCutDirt` (`core/storage/chunk_layer_c11_test.go`) | `CutCapture` `HeadImage` | ACTIVE | -| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE | -| `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut, an intent naming every new key is durable, and it is removed only after the CAS outcome is known. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | +| `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | +| `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | +| `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-STAGED-REUSE-001` | A chunk pre-copied outside the barrier is used only if no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window (legacy fixtures retain the full-copy barrier). | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-BITMAP-001` | The dirty bitmap never under-reports: it is durable before the checkpoint passes its WAL entries, and it is reset only after a successful CAS, keeping chunks dirtied after the cut. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/chunk_layer.go` `BeforeCheckpointAdvance`, `finishCut` | `TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle`, `TestChunkLayer_C11_RolloverKeepsPostCutDirt` (`core/storage/chunk_layer_c11_test.go`) | `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE | +| `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut, an intent naming every new key is durable, and it is removed only after the CAS outcome is known. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | | `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | -| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | +| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | Notes: @@ -411,14 +411,14 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | -| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | -| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | -| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | -| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | -| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | -| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | -| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | +| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | +| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | +| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | +| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | +| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | +| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | +| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | +| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | Notes: @@ -429,27 +429,27 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | -| `INV-PROMOTE-FRONTIER-001` | The RF=3 promotion gate promotes only a probed candidate that covers the required acknowledgement frontier, and blocks promotion without a fresh probe. With a known frontier the candidate's durable LSN must be at least the required LSN. With an unknown frontier under `sync_quorum` or `sync_all`, the highest-durable ready candidate is promoted only when at least P-K+1 distinct peers are probed ready and fresh in the same tick (K from `waitForSyncAcks`; RF=3: both peers under `sync_quorum`, one under `sync_all`); otherwise nothing is promoted. An unknown frontier is never read as zero; `best_effort` is unchanged. | M3 Supporting → Primary (RF=3 gate) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/host/master/promotion_probe.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe`, `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe`, `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused`, `TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | -| `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-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 | -| `INV-K8S-REATTACH-001` | A CSI re-stage after failover uses the fresh publish target, and the read model reports recovery by reattach only with CSI reattach observed and a verified reader. | K8s readiness model | `core/csi/node.go` `refreshPublishContext`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestManagedVolumeProjection_NodeLossReattachRecovered` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-MANAGED-VOLUME-READMODEL-001` | Volume explanations in the observation report and explain output are rendered from the `ManagedVolume` projection. | K8s readiness model | `core/ops/managed_volume_model.go` `ProjectManagedVolume` | `TestObservationExplain_IncludesManagedVolumeProjectionAndDryRunActions`, `TestObservationReportSummary_IncludesManagedVolumeStatus` (`core/ops/observation_report_test.go`); `TestProjectManagedVolumeFromEvidence_DualPrimaryInvalid` (`core/ops/managed_volume_evidence_test.go`) | — | ACTIVE | -| `INV-CONTROL-CONTEXT-001` | Cross-layer explanations replayed from a bundle are derived from recorded facts and events. Superseded in scope by `INV-MANAGED-VOLUME-READMODEL-001`; kept for continuity. | K8s readiness model | `core/ops/observation_bundle.go` `BuildObservationFromBundle` | `TestObservationBundle_RendersNodeLossRecoveryStory`, `TestObservationBundle_ManagedVolumeUsesPrimaryFailureArtifactHints` (`core/ops/observation_bundle_test.go`) | — | ACTIVE | -| `INV-K8S-ADAPTOR-FACTS-001` | PVC, pod, node and CSI conditions enter the read model as typed facts and map to distinct blocked reasons before any recovery status is derived. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestManagedVolumeProjection_PVCPendingBlocked`, `TestManagedVolumeProjection_WriterFailedMountBlocked`, `TestManagedVolumeProjection_CSINodeImagePullBlocked`, `TestManagedVolumeProjection_LoopbackCrossNodeBlocked` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-HOSTPATH-FACTS-001` | The read model keeps path facts separate from the recovery claim: missing multipath blocks the transparent claim, and an NVMe ANA seam alone does not infer transparent recovery. | K8s readiness model | `core/ops/managed_volume_model.go` `deriveManagedVolumeStates`, `hasTransparentHostPathEvidence` | `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim`, `TestManagedVolumeProjection_NVMeANASeamDoesNotInferTransparentRecovery` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-FENCE-SELF-ON-PROMOTE-001` | A primary at epoch e applies no inbound replication traffic (ship, recovery lane start, rebuild), and none below e; it still answers probes, and its epoch floor never goes down when it later supports another primary (fencing gap G2). | M3 Supporting → Primary | `core/transport/replica.go` `FenceAsPrimary`, `acceptMutationLineage`; `core/host/volume/host.go` `fenceSelfWithPeers` | `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`); `TestG2_PrimaryListenerRefusesMutationsButAnswersProbes`, `TestG2_FloorStaysWhenThePrimaryLaterSupportsAnother` (`core/transport/g2_self_fence_test.go`) | `ReplicationFailover` `AckedSurvive`, `NoStaleAck` | ACTIVE | -| `INV-FENCE-FLOOR-DURABLE-001` | A replica never accepts mutating traffic below the highest epoch it has acknowledged or taken a role at, across restarts, and accepts none before its assignment is known; a role call whose floor cannot be made durable is not adopted and keeps the frontend unhealthy (fencing gap G1). | M3 Unassigned → Primary \| Supporting | `core/transport/replica.go` `raiseFloor`, `admitMutation`, `AdmitAsReplica`; `core/host/volume/host.go` `latchRoleAdmission` | `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch`, `TestG1_ConcurrentRaisesNeverLowerTheRecord`, `TestG1_RoleCallsPersistBeforeReturning` (`core/transport/g1_durable_floor_test.go`); `TestG1_FailedRoleAdmissionStopsAPreviouslyHealthyFrontend` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | +| `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | +| `INV-PROMOTE-FRONTIER-001` | The RF=3 promotion gate promotes only a probed candidate that covers the required acknowledgement frontier, and blocks promotion without a fresh probe. With a known frontier the candidate's durable LSN must be at least the required LSN. With an unknown frontier under `sync_quorum` or `sync_all`, the highest-durable ready candidate is promoted only when at least P-K+1 distinct peers are probed ready and fresh in the same tick (K from `waitForSyncAcks`; RF=3: both peers under `sync_quorum`, one under `sync_all`); otherwise nothing is promoted. An unknown frontier is never read as zero; `best_effort` is unchanged. | M3 Supporting → Primary (RF=3 gate) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/host/master/promotion_probe.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe`, `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe`, `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused`, `TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | +| `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-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 | +| `INV-K8S-REATTACH-001` | A CSI re-stage after failover uses the fresh publish target, and the read model reports recovery by reattach only with CSI reattach observed and a verified reader. | K8s readiness model | `core/csi/node.go` `refreshPublishContext`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestManagedVolumeProjection_NodeLossReattachRecovered` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-MANAGED-VOLUME-READMODEL-001` | Volume explanations in the observation report and explain output are rendered from the `ManagedVolume` projection. | K8s readiness model | `core/ops/managed_volume_model.go` `ProjectManagedVolume` | `TestObservationExplain_IncludesManagedVolumeProjectionAndDryRunActions`, `TestObservationReportSummary_IncludesManagedVolumeStatus` (`core/ops/observation_report_test.go`); `TestProjectManagedVolumeFromEvidence_DualPrimaryInvalid` (`core/ops/managed_volume_evidence_test.go`) | — | ACTIVE | +| `INV-CONTROL-CONTEXT-001` | Cross-layer explanations replayed from a bundle are derived from recorded facts and events. Superseded in scope by `INV-MANAGED-VOLUME-READMODEL-001`; kept for continuity. | K8s readiness model | `core/ops/observation_bundle.go` `BuildObservationFromBundle` | `TestObservationBundle_RendersNodeLossRecoveryStory`, `TestObservationBundle_ManagedVolumeUsesPrimaryFailureArtifactHints` (`core/ops/observation_bundle_test.go`) | — | ACTIVE | +| `INV-K8S-ADAPTOR-FACTS-001` | PVC, pod, node and CSI conditions enter the read model as typed facts and map to distinct blocked reasons before any recovery status is derived. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestManagedVolumeProjection_PVCPendingBlocked`, `TestManagedVolumeProjection_WriterFailedMountBlocked`, `TestManagedVolumeProjection_CSINodeImagePullBlocked`, `TestManagedVolumeProjection_LoopbackCrossNodeBlocked` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-HOSTPATH-FACTS-001` | The read model keeps path facts separate from the recovery claim: missing multipath blocks the transparent claim, and an NVMe ANA seam alone does not infer transparent recovery. | K8s readiness model | `core/ops/managed_volume_model.go` `deriveManagedVolumeStates`, `hasTransparentHostPathEvidence` | `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim`, `TestManagedVolumeProjection_NVMeANASeamDoesNotInferTransparentRecovery` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-FENCE-SELF-ON-PROMOTE-001` | A primary at epoch e applies no inbound replication traffic (ship, recovery lane start, rebuild), and none below e; it still answers probes, and its epoch floor never goes down when it later supports another primary (fencing gap G2). | M3 Supporting → Primary | `core/transport/replica.go` `FenceAsPrimary`, `acceptMutationLineage`; `core/host/volume/host.go` `fenceSelfWithPeers` | `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`); `TestG2_PrimaryListenerRefusesMutationsButAnswersProbes`, `TestG2_FloorStaysWhenThePrimaryLaterSupportsAnother` (`core/transport/g2_self_fence_test.go`) | `ReplicationFailover` `AckedSurvive`, `NoStaleAck` | ACTIVE | +| `INV-FENCE-FLOOR-DURABLE-001` | A replica never accepts mutating traffic below the highest epoch it has acknowledged or taken a role at, across restarts, and accepts none before its assignment is known; a role call whose floor cannot be made durable is not adopted and keeps the frontend unhealthy (fencing gap G1). | M3 Unassigned → Primary \| Supporting | `core/transport/replica.go` `raiseFloor`, `admitMutation`, `AdmitAsReplica`; `core/host/volume/host.go` `latchRoleAdmission` | `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch`, `TestG1_ConcurrentRaisesNeverLowerTheRecord`, `TestG1_RoleCallsPersistBeforeReturning` (`core/transport/g1_durable_floor_test.go`); `TestG1_FailedRoleAdmissionStopsAPreviouslyHealthyFrontend` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | Notes: - `INV-AUTH-ONE-PRIMARY-001`: Narrowed. The lab evidence field `post_failure_primary_count=1` is not read by any Go test. `IntentBind` is checked per volume: the Publisher refuses a genesis `Bind` (`ErrBindAlreadyBound`) once any slot of the volume holds a present line, also after a restart, when only the current slot is reloaded; `decideVolume` also binds only when the volume has no line ([#183](https://github.com/seaweedfs/seaweed-block/issues/183)). - `INV-FENCE-STALE-PRIMARY-001`: Narrowed. A primary cut off from blockmaster that has not seen the newer line keeps admitting I/O, and under `best_effort` its local `fsync` still acknowledges (no primary lease on the Kubernetes path; see the Kubernetes known gaps). The lab counter `old_primary_stale_io_success_count=0` is lab evidence only. -- `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`. +- `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`. - `INV-K8S-NONLOOPBACK-001`: Rejection is opt-in: the chart default for `network.rejectLoopbackPublishTargets` is false; the generator sets it for multi-node values. - `INV-OBS-PRODUCT-EVENTS-001`: Each event type has a unit test; all four together in one node-loss run is lab evidence only. - `INV-HOSTPATH-TRANSPARENT-001`: Narrowed to the classifier. It does not compare the host path target with the promoted target, and only the missing-multipath case has a negative test. The mounted-failover run is lab evidence. @@ -467,7 +467,13 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | +| `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | + +### HEAD publication metadata cost + +| ID | Invariant | Transition | Enforced in | Regression test | Model | Status | +|---|---|---|---|---|---|---| +| `INV-WS-HEAD-ROOT-READ-001` | A HEAD CAS reads and validates only the root entry; immutable segment availability does not gate publication. Normal GetHead still resolves and verifies segments. | M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `getHeadRoot`, `CASHead` | `TestManifest_CASReadsOnlyRoot` | Cost/read-dependency property; no state or transition change to `CutPipeline` | ACTIVE | ## Part C. Change rules From 14282cb97587911ee063022f836185eda5b77e9c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:00:32 -0800 Subject: [PATCH 003/150] blockvolume: refuse replication on a walstore-chunk volume A chunk cut takes its LSN from the local WAL head, which no replica is guaranteed to hold, so a published HEAD could be ahead of every replica. The master's workspace RPCs enforce RF1; a direct start did not. - start: --durable-impl=walstore-chunk with --replication-ack sync-quorum or sync-all is refused at flag parse. - assignment: the replication factor arrives with the assignment, so the ingress role gate of a walstore-chunk volume refuses every role with replica slots (replica, primary with peers) without opening a socket; the host's existing role-admission latch keeps the role unadopted and not Healthy. A primary without peers (RF1) is unchanged. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/chunk_remote.go | 10 +++ .../cmd/blockvolume/chunk_rf1_guard_test.go | 69 +++++++++++++++++++ seaweed-block/cmd/blockvolume/main.go | 3 +- .../cmd/blockvolume/replication_ingress.go | 28 ++++++-- 4 files changed, 104 insertions(+), 6 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index b4f60cfa2b..48015840f1 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -53,6 +53,9 @@ func validateChunkFlags(f flags) error { if c.controlEndpoint && f.statusAddr == "" { return errors.New("--chunk-control-endpoint requires --status-addr") } + if f.replicationAck != "" && f.replicationAck != "best-effort" { + return fmt.Errorf("--durable-impl=walstore-chunk is single-replica: --replication-ack=%q needs replica peers (%s)", f.replicationAck, chunkRF1Reason) + } if f.durableRoot == "" { return errors.New("--durable-impl=walstore-chunk requires --durable-root") } @@ -74,6 +77,13 @@ func validateChunkFlags(f flags) error { return nil } +// chunkRF1Reason is why a walstore-chunk volume refuses replication, at start +// and on every assignment with replica slots: a chunk cut takes its LSN from the +// local WAL head, which no replica is guaranteed to hold, so a published HEAD +// could be ahead of every replica. The master's workspace RPCs enforce RF1; this +// is the same rule on the volume server, for a direct start. +const chunkRF1Reason = "chunk snapshots take the cut LSN from the local WAL, which replicas may not hold; walstore-chunk is RF1 only" + // chunkWiring is what --durable-impl=walstore-chunk dials once: the // provider's per-volume remotes, the catalog under the same base (VOLUME // entries, snapshots) and the client's closer. diff --git a/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go b/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go new file mode 100644 index 0000000000..60e1bcc825 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go @@ -0,0 +1,69 @@ +package main + +import ( + "net" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A walstore-chunk volume is RF1 only: a chunk cut takes its LSN from the local +// WAL head, which replicas may not hold. A direct start must refuse replication +// (the master's workspace RPCs already do). +func TestChunkVolumeRefusesReplicationAckAtStart(t *testing.T) { + base := []string{"--master", "127.0.0.1:1", "--server-id", "node-a", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:9100", "--ctrl-addr", "127.0.0.1:9101"} + chunk := append(append([]string{}, base...), "--durable-root", t.TempDir(), "--durable-impl", "walstore-chunk", "--chunk-filer", "127.0.0.1:18888") + for _, ack := range []string{"sync-quorum", "sync-all"} { + _, err := parseFlags(append(append([]string{}, chunk...), "--replication-ack", ack)) + if err == nil || !strings.Contains(err.Error(), "single-replica") || !strings.Contains(err.Error(), "RF1 only") { + t.Fatalf("walstore-chunk with --replication-ack=%s: %v", ack, err) + } + } + if _, err := parseFlags(append(append([]string{}, chunk...), "--replication-ack", "best-effort")); err != nil { + t.Fatalf("walstore-chunk best-effort refused: %v", err) + } + if _, err := parseFlags(append(append([]string{}, base...), "--durable-root", t.TempDir(), "--durable-impl", "walstore", "--replication-ack", "sync-quorum")); err != nil { + t.Fatalf("walstore sync-quorum refused: %v", err) + } +} + +// The replication factor arrives with the master's assignment, so the guard is +// also on the role gate: every role with replica slots is refused and no socket +// is opened; a primary role without peers (RF1) is admitted. +func TestChunkVolumeIngressRefusesReplicaSlots(t *testing.T) { + for _, impl := range []string{"walstore", "walstore-chunk"} { + t.Run(impl, func(t *testing.T) { + addr, _ := ingressPair(t) + r := newReplicationIngress(flags{dataAddr: addr, volumeID: "v1", durableImpl: impl, recoveryMode: "legacy"}, storage.NewBlockStore(4, 4096)) + defer r.Stop() + admitErr := r.AdmitAsReplica(1) + if impl == "walstore" { + if admitErr != nil || r.listener == nil { + t.Fatalf("walstore replica role: %v", admitErr) + } + return + } + if admitErr == nil || !strings.Contains(admitErr.Error(), "refuses a replica role") || !strings.Contains(admitErr.Error(), "RF1 only") { + t.Fatalf("replica role admitted: %v", admitErr) + } + if err := r.FenceAsPrimaryWithPeers(2, true); err == nil || !strings.Contains(err.Error(), "refuses a primary role with replica peers") { + t.Fatalf("primary with peers admitted: %v", err) + } + if err := r.FenceAsPrimary(3); err == nil { + t.Fatal("legacy primary fence (peers assumed) admitted") + } + if r.listener != nil { + t.Fatal("a replica listener was created") + } + if c, err := net.DialTimeout("tcp", addr, 500*time.Millisecond); err == nil { + c.Close() + t.Fatal("the replication address accepts connections") + } + if err := r.FenceAsPrimaryWithPeers(4, false); err != nil { + t.Fatalf("RF1 primary refused: %v", err) + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 96935591bd..5fa728be95 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -871,8 +871,7 @@ func run(f flags) int { // No replication socket exists until a master assignment includes // replica slots. The role gate starts/fences both lanes before admission. - replListen = &replicationIngress{addr: f.dataAddr, store: store, - volumeID: f.volumeID, floorPath: replicaFloorPath(f), dualLane: f.recoveryMode == "dual-lane"} + replListen = newReplicationIngress(f, store) if err := h.SetSelfFence(replListen); err != nil { fmt.Fprintln(os.Stderr, "blockvolume: replica listener role:", err) replListen.Stop() diff --git a/seaweed-block/cmd/blockvolume/replication_ingress.go b/seaweed-block/cmd/blockvolume/replication_ingress.go index 4117fbad45..eb22ed7ea5 100644 --- a/seaweed-block/cmd/blockvolume/replication_ingress.go +++ b/seaweed-block/cmd/blockvolume/replication_ingress.go @@ -19,10 +19,24 @@ type replicationIngress struct { addr, volumeID, floorPath string store storage.LogicalStorage dualLane bool - listener *transport.ReplicaListener - dual net.Listener - cancel context.CancelFunc - closed bool + // rf1Only, when set, refuses every role with replica slots with this reason + // (walstore-chunk). The host latches the error: no role is adopted, not Healthy. + rf1Only string + listener *transport.ReplicaListener + dual net.Listener + cancel context.CancelFunc + closed bool +} + +// newReplicationIngress is the volume's ingress from its flags; a walstore-chunk +// volume refuses every role with replica slots (chunkRF1Reason). +func newReplicationIngress(f flags, store storage.LogicalStorage) *replicationIngress { + r := &replicationIngress{addr: f.dataAddr, store: store, volumeID: f.volumeID, + floorPath: replicaFloorPath(f), dualLane: f.recoveryMode == "dual-lane"} + if f.durableImpl == "walstore-chunk" { + r.rf1Only = chunkRF1Reason + } + return r } func (r *replicationIngress) FenceAsPrimary(epoch uint64) error { @@ -43,6 +57,9 @@ func (r *replicationIngress) FenceAsPrimaryWithPeers(epoch uint64, hasPeers bool r.stopLocked(true) return nil } + if r.rf1Only != "" { + return fmt.Errorf("volume %s refuses a primary role with replica peers at epoch %d: %s", r.volumeID, epoch, r.rf1Only) + } return r.roleLocked(epoch, true) } func (r *replicationIngress) AdmitAsReplica(epoch uint64) error { @@ -51,6 +68,9 @@ func (r *replicationIngress) AdmitAsReplica(epoch uint64) error { if r.closed { return fmt.Errorf("replication ingress closed") } + if r.rf1Only != "" { + return fmt.Errorf("volume %s refuses a replica role at epoch %d: %s", r.volumeID, epoch, r.rf1Only) + } return r.roleLocked(epoch, false) } func (r *replicationIngress) roleLocked(epoch uint64, primary bool) error { From 300c3b097e802074f3ef09da0edab47cf55564db Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:01:58 -0800 Subject: [PATCH 004/150] docs: preserve existing invariant text and record root-only CAS cost --- seaweed-block/docs/design/invariants.md | 194 ++++++++++++------------ 1 file changed, 97 insertions(+), 97 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7d8f9772f2..5d8db88395 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -36,7 +36,7 @@ Each machine lists its states, the allowed transitions, the guard that must hold ### M1 walstore: open, recover, serve, fault -The local storage engine and the durable backend in front of it. Diagrams in the core design: the per-I/O gate in [§1.1](block-design.md#11-frontends-and-the-backend-contract), and the life of one write (appended, synced, in the extent, checkpointed, reusable) in [§1.2](block-design.md#12-walstore-wal-plus-extent). +The local storage engine and the durable backend in front of it. Diagrams in the core design: the per-I/O gate in [§1.1](block-design.md#11-frontends-and-the-backend-contract), and the life of one write (appended, synced, in the extent, checkpointed, reusable) in [§1.2](block-design.md#12-walstore-wal-plus-extent). ```mermaid stateDiagram-v2 @@ -53,7 +53,7 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | +| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | @@ -61,7 +61,7 @@ stateDiagram-v2 | Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse (C11 bitmap/superblock path remains legacy-fixture-only) | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001` | | Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `noteAppendFailure`, `syncFile` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | | FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | -| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | +| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. @@ -71,7 +71,7 @@ Recovery warnings such as `wal_hole_suspected` are recorded in Serving without c ### M2 Authority: assignment, epoch, lease -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). +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). **Assignment line, per volume.** @@ -88,8 +88,8 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | From | To | Event and guard | Enforced in | Protects | |---|---|---|---|---| -| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | -| Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | +| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | +| Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | @@ -99,7 +99,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a ### M3 Replica role and peer state -The role a blockvolume takes from each assignment, its replica listener's admission, and the primary's view of each replica. This is the replication engine of [core §1.6](block-design.md#16-replication-and-failover) (which has the peer-state diagram) as the Kubernetes line uses it; promotion is in [Kubernetes §6](kubernetes-block-design.md#6-authority-promotion) (diagram) and the failover sequence in [Kubernetes §4](kubernetes-block-design.md#4-replication-and-failover). +The role a blockvolume takes from each assignment, its replica listener's admission, and the primary's view of each replica. This is the replication engine of [core §1.6](block-design.md#16-replication-and-failover) (which has the peer-state diagram) as the Kubernetes line uses it; promotion is in [Kubernetes §6](kubernetes-block-design.md#6-authority-promotion) (diagram) and the failover sequence in [Kubernetes §4](kubernetes-block-design.md#4-replication-and-failover). ```mermaid stateDiagram-v2 @@ -123,7 +123,7 @@ stateDiagram-v2 | Unassigned, Primary | Supporting at e | the fact names another primary and lists this replica as a peer; the floor e is persisted first; the frontend stays gated | `core/host/volume/host.go` `applyFact`; `core/transport/replica.go` `AdmitAsReplica` | `INV-FENCE-FLOOR-DURABLE-001` | | Primary, Supporting | Excluded | the fact names another primary and does not list this replica; ingress is closed, the other line is recorded and the frontend is unhealthy | `core/host/volume/host.go` `applyFact`, `recordOtherLine`; `core/host/volume/projection_bridge.go` `projectionWithSupersede` | `INV-ROLE-SUPERSEDED-001`, `INV-FENCE-STALE-PRIMARY-001` | | any | role admission failed | the listener cannot be fenced or its floor cannot be persisted; the role is not adopted and the projection is not healthy | `core/host/volume/host.go` `latchRoleAdmission` | `INV-FENCE-FLOOR-DURABLE-001` | -| (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | +| (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | | Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | **Peer state, as the primary sees each replica** (type `ReplicaState` in `core/replication/peer.go`). A new peer starts `Healthy` (`NewReplicaPeer`). @@ -134,13 +134,13 @@ stateDiagram-v2 | `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001` | | `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | | any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | -| `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | +| `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.Invalidate`, called on a ship, barrier or fence error, goes through the same gate as `SetState` (`replicaStateTransitionAllowed`): `Healthy`, `Degraded` and `CatchingUp` move to `Degraded`; from `NeedsRebuild` the state is kept and the reason is still logged ([#182](https://github.com/seaweedfs/seaweed-block/issues/182)). A replicated `Sync` is judged per durability mode (`core/replication/durability.go` `EvaluateBarrierAcks`; `INV-REPL-DURABILITY-MODE-001`). ### M4 Workspace HEAD holder and takeover -One host at a time holds a workspace volume's HEAD in SeaweedFS. The sequence diagram of a clean and a forced move is in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves); blockmaster's side of the lease is in M2. +One host at a time holds a workspace volume's HEAD in SeaweedFS. The sequence diagram of a clean and a forced move is in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves); blockmaster's side of the lease is in M2. ```mermaid stateDiagram-v2 @@ -179,7 +179,7 @@ stateDiagram-v2 ### M5 The cut pipeline -A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. The steps are described in [agent workspace §5](agent-workspace-design.md#5-the-cut), and the figure in [§3](agent-workspace-design.md#3-remote-layout) shows them against the remote layout. All steps are in `core/storage/chunk_layer.go` `captureLocked` unless stated. +A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. The steps are described in [agent workspace §5](agent-workspace-design.md#5-the-cut), and the figure in [§3](agent-workspace-design.md#3-remote-layout) shows them against the remote layout. All steps are in `core/storage/chunk_layer.go` `captureLocked` unless stated. ```mermaid stateDiagram-v2 @@ -223,13 +223,13 @@ stateDiagram-v2 ### M6 Chunk lifecycle -HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete). +HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete). **HEAD states** (`active`, `detached`, `deleting`, `purging`, `deleted`, `aborted`). | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | +| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | | `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | | `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | @@ -237,14 +237,14 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | `deleting` | previous state | a snapshot name record exists: the delete is refused and reverted | `core/frontend/chunkstore/volume_delete.go` `snapshotsBlock`, `revertHeadDeleting` | `INV-VOLDEL-COMMIT-001` | | `deleting` | `purging` | commit point, bound to the same delete incarnation | `core/frontend/chunkstore/volume_delete.go` `commitHeadPurging` | `INV-VOLDEL-COMMIT-001` | | `purging` | `deleted` | chunks dropped and `VOLUME` marked deleted | `core/frontend/chunkstore/volume_delete.go` `finishHeadDeleted`, `markVolumeDeleted` | `INV-VOL-ID-NO-REUSE-001` | -| `deleting`, `purging`, `deleted` | — | no claim or cut moves HEAD; only the delete's own transitions | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-HEAD-DELETE-FROZEN-001` | -| — | `aborted` | a GC copy sweep settles a dead fork by an exclusive create of an aborted HEAD tombstone, so the fork can never publish | `core/frontend/chunkstore/catalog.go` `AbortFork`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies` | — | +| `deleting`, `purging`, `deleted` | — | no claim or cut moves HEAD; only the delete's own transitions | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-HEAD-DELETE-FROZEN-001` | +| — | `aborted` | a GC copy sweep settles a dead fork by an exclusive create of an aborted HEAD tombstone, so the fork can never publish | `core/frontend/chunkstore/catalog.go` `AbortFork`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies` | — | **Snapshots and forks.** | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | +| — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | | name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001` | @@ -253,10 +253,10 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | +| — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | | intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` | | intent live | expired | older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001` | -| — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | +| — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | | bound | tombstoned, needle deleted | unrooted in two complete marks at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001` | | tombstoned | (never rebound) | bindings are never removed | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | @@ -272,22 +272,22 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | +| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | | `INV-WAL-REPLAY-LWW-001` | Replay applies the highest LSN per LBA, independent of the physical scan order. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALStoreRecoverLastWriterWinsAcrossScanOrder` (`core/storage/walstore_recovery_lww_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | -| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the on-disk superblock has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_writer.go` `spaceUsed`, `tailPersisted`; `core/storage/walstore.go` `persistCheckpointReleasing` | `TestWALWriterReuseIsBoundedByTheDurableTail`, `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherSnapshotCutPreservesSyncedWrites` (`core/storage/flusher_snapshot_cut_test.go`); `TestWALStoreCheckpointSIGKILLCrashWindows` (`core/storage/walstore_checkpoint_crash_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the on-disk superblock has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_writer.go` `spaceUsed`, `tailPersisted`; `core/storage/walstore.go` `persistCheckpointReleasing` | `TestWALWriterReuseIsBoundedByTheDurableTail`, `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherSnapshotCutPreservesSyncedWrites` (`core/storage/flusher_snapshot_cut_test.go`); `TestWALStoreCheckpointSIGKILLCrashWindows` (`core/storage/walstore_checkpoint_crash_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-FRONTIER-GAP-001` | Synced entries above an intentional LSN gap (a rebuild's frontier jump) are kept by recovery. | M1 Recovering | `core/storage/recovery.go` `recoverWAL` | `TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump` (`core/storage/walstore_recovery_frontier_gap_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore.go` `persistCheckpointReleasing` | `TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle` (`core/storage/walstore_checkpoint_safety_test.go`) | — | ACTIVE | -| `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent or superblock), the open store refuses every later `Sync`, write and checkpoint without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestWALStoreWALFsyncFailureIsSticky`, `TestWALStoreExtentFsyncFailureIsSticky`, `TestWALStoreCheckpointFsyncFailureIsSticky` (`core/storage/walstore_sticky_fsync_test.go`); `TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | -| `INV-WAL-APPEND-STICKY-001` | A WAL append whose write failed latches the store fault; writers already queued behind it are refused. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteAppendFailure`, `WALStore.Write` | `TestWALStoreWritersQueuedBehindAFailedAppendAreRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | -| `INV-WAL-SYNC-FRONTIER-001` | `Sync` never reports an uncovered write durable: it returns the global synced frontier, which is at least the caller's own write and is covered by a completed `fsync`. It may include later writes whose covering `fsync` completed before the caller resumed. | M1 write lifecycle: Appended → Synced | `core/storage/walstore.go` `WALStore.Sync` | `TestWALStore_SyncDoesNotClaimConcurrentWrite` (`core/storage/walstore_test.go`); `TestWALGenerationFirstCallerReturnOrdering` (`core/storage/walstore_sync_frontier_order_test.go`) | — | ACTIVE | -| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt` (`cmd/blockvolume/durable_startup_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE | -| `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE | +| `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore.go` `persistCheckpointReleasing` | `TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle` (`core/storage/walstore_checkpoint_safety_test.go`) | — | ACTIVE | +| `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent or superblock), the open store refuses every later `Sync`, write and checkpoint without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestWALStoreWALFsyncFailureIsSticky`, `TestWALStoreExtentFsyncFailureIsSticky`, `TestWALStoreCheckpointFsyncFailureIsSticky` (`core/storage/walstore_sticky_fsync_test.go`); `TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | +| `INV-WAL-APPEND-STICKY-001` | A WAL append whose write failed latches the store fault; writers already queued behind it are refused. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteAppendFailure`, `WALStore.Write` | `TestWALStoreWritersQueuedBehindAFailedAppendAreRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | +| `INV-WAL-SYNC-FRONTIER-001` | `Sync` never reports an uncovered write durable: it returns the global synced frontier, which is at least the caller's own write and is covered by a completed `fsync`. It may include later writes whose covering `fsync` completed before the caller resumed. | M1 write lifecycle: Appended → Synced | `core/storage/walstore.go` `WALStore.Sync` | `TestWALStore_SyncDoesNotClaimConcurrentWrite` (`core/storage/walstore_test.go`); `TestWALGenerationFirstCallerReturnOrdering` (`core/storage/walstore_sync_frontier_order_test.go`) | — | ACTIVE | +| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt` (`cmd/blockvolume/durable_startup_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE | +| `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE | | `INV-WAL-V3-ACTIVATION-001` | Public create produces an owned mapped v3/impl3 volume with the requested chunk geometry and C default/A option. Writable/readonly open validate A/B dependencies, reject actual legacy headers without mutation, and can select a valid fallback when A is damaged. Production provider capture/HEAD restore/status use those selectors. Legacy fixture constructors cannot be called by default production code or enter its transitive storage import closure. | M1 open/create/readonly | `walstore.go` public selectors; `walstore_v3.go` `refuseLegacyWALStore`, `ProbeWALStoreV3`; `provider.go` | `TestWALStoreProductionSelectorCreatesMappedV3`, `TestWALStoreProductionRefusesLegacyWithoutMutation`, `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy`, `TestWALStoreProductionCreateOptions`, `TestLegacyFixtureIsolation`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE | | `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE | | `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | -| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | +| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-RECORD-001` | An impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | | `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB | | `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire` | `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | @@ -298,17 +298,17 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Append-only retention preserves both slots and pending candidates. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | -| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | -| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | -| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | -| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | -| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | +| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | +| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | +| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | +| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | +| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | | `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB | | `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB | | `INV-WAL-V3-MIGRATE-001` | `sw-block migrate-v3` rewrites only the descriptor of a cleanly closed v2/impl1 volume whose WAL the exhaustive scan proves flushed; the scan and the geometry check run before any write, and a refusal leaves the volume and every sidecar byte-identical. It keeps the extent base (WALSize = old - 4096), writes an atomic operator backup, an all-UNKNOWN initial map (covered = the v2 checkpoint), the prepared slot B, slot A at phase 0 (the commit point), slot B at phase 0, and only then retires the v2 chunk bitmap; each step is durable before the next. A rerun decides from the slot bytes alone: before the commit it restarts with a full rescan; after it, it only finishes the rollover and the retirement; a prepared B with an invalid A refuses with `ErrMigrationIncomplete`, as v3 open does; it never reads or restores the backup. | offline tool | `cmd/sw-block/migrate.go`; `cmd/sw-block/internal/v2legacy`; `core/storage/migrate_v3.go` | `TestMigrateV3CleanVolume`, `TestMigrateV3RefusalsChangeNothing`, `TestMigrateV3CrashAfterEachStepIsResumable`, `TestMigrateV3OldBinaryAfterPreparation`, `TestMigrateV3OldWALOverwritesThePreparedSlot`, `TestMigrateV3NeverRestoresTheBackup` (`cmd/sw-block/migrate_test.go`); tagged `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | none (tool) | STUB | -| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | -| `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | -| `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE | +| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | +| `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | +| `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE | Notes: @@ -332,15 +332,15 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | -| `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that clears the lease is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | -| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | +| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | +| `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that clears the lease is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | +| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | Notes: @@ -352,16 +352,16 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | -| `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | -| `INV-REPL-INGRESS-SLOTS-001` | Replication listeners are open only while the assignment has replica slots. | M3 role → listener lifecycle | `cmd/blockvolume/replication_ingress.go` `roleLocked` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | ACTIVE | -| `INV-REPL-CATCHUP-REBUILD-001` | The engine chooses catch-up when the gap is still in the primary's WAL and rebuild when it is not. | M3 Degraded → CatchingUp \| NeedsRebuild | `core/engine/apply.go` `decide` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | ACTIVE | -| `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE | -| `INV-REPL-DURABILITY-MODE-001` | Under `sync_all` a replicated `Sync` fails if any replica barrier fails; under `sync_quorum` it fails unless a majority of nodes, the primary included, are durable. | M3 barrier evaluation | `core/replication/durability.go` `EvaluateBarrierAcks` | `TestDurabilityCoordinator_Quorum_RF3_OneReplicaFailed`, `TestDurabilityCoordinator_Quorum_RF3_BothReplicasFailed`, `TestDurabilityCoordinator_SyncAll_AnyFailure_Fails` (`core/replication/durability_test.go`) | — | ACTIVE | -| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`) | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive` | ACTIVE | -| `INV-ROLE-STALE-REPLAY-001` | A role call below the host's current desired epoch is refused and cannot clear a newer role-admission failure. | M3 role admission | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `TestG1_StaleReplayDoesNotClearANewerAdmissionFailure`, `TestG1_StaleSupportingReplayDoesNotClearTheLatch` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | -| `INV-ROLE-READINESS-BLOCK-001` | While local recovery blocks readiness, `applyFact` admits neither a primary nor a supporting role, and replays the stored fact once readiness clears. | M3 Unassigned → Primary \| Supporting (guard) | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter`, `TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter`, `TestHost_ApplyFact_Self_ReplaysAfterLocalReadinessClearsWithReplicationFirst` (`core/host/volume/apply_fact_test.go`) | — | ACTIVE | -| `INV-ROLE-SUPERSEDED-001` | A fact naming another replica as primary, with this replica not among its peers, never reaches this host's adapter or replication, and is recorded as the other line. | M3 Primary \| Supporting → Excluded | `core/host/volume/host.go` `applyFact`, `recordOtherLine` | `TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication` (`core/host/volume/apply_fact_test.go`); `TestHost_BuildReport_SupersededReplicaNotReadyForPrimary` (`core/host/volume/frontend_targets_test.go`) | — | ACTIVE | +| `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | +| `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | +| `INV-REPL-INGRESS-SLOTS-001` | Replication listeners are open only while the assignment has replica slots. | M3 role → listener lifecycle | `cmd/blockvolume/replication_ingress.go` `roleLocked` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | ACTIVE | +| `INV-REPL-CATCHUP-REBUILD-001` | The engine chooses catch-up when the gap is still in the primary's WAL and rebuild when it is not. | M3 Degraded → CatchingUp \| NeedsRebuild | `core/engine/apply.go` `decide` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | ACTIVE | +| `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE | +| `INV-REPL-DURABILITY-MODE-001` | Under `sync_all` a replicated `Sync` fails if any replica barrier fails; under `sync_quorum` it fails unless a majority of nodes, the primary included, are durable. | M3 barrier evaluation | `core/replication/durability.go` `EvaluateBarrierAcks` | `TestDurabilityCoordinator_Quorum_RF3_OneReplicaFailed`, `TestDurabilityCoordinator_Quorum_RF3_BothReplicasFailed`, `TestDurabilityCoordinator_SyncAll_AnyFailure_Fails` (`core/replication/durability_test.go`) | — | ACTIVE | +| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`) | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive` | ACTIVE | +| `INV-ROLE-STALE-REPLAY-001` | A role call below the host's current desired epoch is refused and cannot clear a newer role-admission failure. | M3 role admission | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `TestG1_StaleReplayDoesNotClearANewerAdmissionFailure`, `TestG1_StaleSupportingReplayDoesNotClearTheLatch` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | +| `INV-ROLE-READINESS-BLOCK-001` | While local recovery blocks readiness, `applyFact` admits neither a primary nor a supporting role, and replays the stored fact once readiness clears. | M3 Unassigned → Primary \| Supporting (guard) | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter`, `TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter`, `TestHost_ApplyFact_Self_ReplaysAfterLocalReadinessClearsWithReplicationFirst` (`core/host/volume/apply_fact_test.go`) | — | ACTIVE | +| `INV-ROLE-SUPERSEDED-001` | A fact naming another replica as primary, with this replica not among its peers, never reaches this host's adapter or replication, and is recorded as the other line. | M3 Primary \| Supporting → Excluded | `core/host/volume/host.go` `applyFact`, `recordOtherLine` | `TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication` (`core/host/volume/apply_fact_test.go`); `TestHost_BuildReport_SupersededReplicaNotReadyForPrimary` (`core/host/volume/frontend_targets_test.go`) | — | ACTIVE | Notes: @@ -372,15 +372,15 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-WS-HEAD-CAS-001` | Every HEAD publish is a conditional update on `{gen, epoch}`, so only one holder can publish each HEAD generation; a holder that sees a superseding HEAD fences itself. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | +| `INV-WS-HEAD-CAS-001` | Every HEAD publish is a conditional update on `{gen, epoch}`, so only one holder can publish each HEAD generation; a holder that sees a superseding HEAD fences itself. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | | `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | -| `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | -| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | -| `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | -| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | -| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | -| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `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`) | — | ACTIVE | +| `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | +| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | +| `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | +| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | +| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `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`) | — | ACTIVE | Notes: @@ -392,16 +392,16 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | -| `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | -| `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | -| `INV-CUT-STAGED-REUSE-001` | A chunk pre-copied outside the barrier is used only if no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window (legacy fixtures retain the full-copy barrier). | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | -| `INV-CUT-BITMAP-001` | The dirty bitmap never under-reports: it is durable before the checkpoint passes its WAL entries, and it is reset only after a successful CAS, keeping chunks dirtied after the cut. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/chunk_layer.go` `BeforeCheckpointAdvance`, `finishCut` | `TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle`, `TestChunkLayer_C11_RolloverKeepsPostCutDirt` (`core/storage/chunk_layer_c11_test.go`) | `CutCapture` `HeadImage` | ACTIVE | -| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE | -| `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut, an intent naming every new key is durable, and it is removed only after the CAS outcome is known. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | +| `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | +| `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | +| `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-STAGED-REUSE-001` | A chunk pre-copied outside the barrier is used only if no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window (legacy fixtures retain the full-copy barrier). | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-BITMAP-001` | The dirty bitmap never under-reports: it is durable before the checkpoint passes its WAL entries, and it is reset only after a successful CAS, keeping chunks dirtied after the cut. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/chunk_layer.go` `BeforeCheckpointAdvance`, `finishCut` | `TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle`, `TestChunkLayer_C11_RolloverKeepsPostCutDirt` (`core/storage/chunk_layer_c11_test.go`) | `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE | +| `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut, an intent naming every new key is durable, and it is removed only after the CAS outcome is known. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | | `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | -| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | +| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | Notes: @@ -411,14 +411,14 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | -| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | -| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | -| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | -| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | -| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | -| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | -| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | +| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | +| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | +| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | +| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | +| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | +| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | +| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | +| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | Notes: @@ -429,27 +429,27 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | -| `INV-PROMOTE-FRONTIER-001` | The RF=3 promotion gate promotes only a probed candidate that covers the required acknowledgement frontier, and blocks promotion without a fresh probe. With a known frontier the candidate's durable LSN must be at least the required LSN. With an unknown frontier under `sync_quorum` or `sync_all`, the highest-durable ready candidate is promoted only when at least P-K+1 distinct peers are probed ready and fresh in the same tick (K from `waitForSyncAcks`; RF=3: both peers under `sync_quorum`, one under `sync_all`); otherwise nothing is promoted. An unknown frontier is never read as zero; `best_effort` is unchanged. | M3 Supporting → Primary (RF=3 gate) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/host/master/promotion_probe.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe`, `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe`, `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused`, `TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | -| `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-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 | -| `INV-K8S-REATTACH-001` | A CSI re-stage after failover uses the fresh publish target, and the read model reports recovery by reattach only with CSI reattach observed and a verified reader. | K8s readiness model | `core/csi/node.go` `refreshPublishContext`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestManagedVolumeProjection_NodeLossReattachRecovered` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-MANAGED-VOLUME-READMODEL-001` | Volume explanations in the observation report and explain output are rendered from the `ManagedVolume` projection. | K8s readiness model | `core/ops/managed_volume_model.go` `ProjectManagedVolume` | `TestObservationExplain_IncludesManagedVolumeProjectionAndDryRunActions`, `TestObservationReportSummary_IncludesManagedVolumeStatus` (`core/ops/observation_report_test.go`); `TestProjectManagedVolumeFromEvidence_DualPrimaryInvalid` (`core/ops/managed_volume_evidence_test.go`) | — | ACTIVE | -| `INV-CONTROL-CONTEXT-001` | Cross-layer explanations replayed from a bundle are derived from recorded facts and events. Superseded in scope by `INV-MANAGED-VOLUME-READMODEL-001`; kept for continuity. | K8s readiness model | `core/ops/observation_bundle.go` `BuildObservationFromBundle` | `TestObservationBundle_RendersNodeLossRecoveryStory`, `TestObservationBundle_ManagedVolumeUsesPrimaryFailureArtifactHints` (`core/ops/observation_bundle_test.go`) | — | ACTIVE | -| `INV-K8S-ADAPTOR-FACTS-001` | PVC, pod, node and CSI conditions enter the read model as typed facts and map to distinct blocked reasons before any recovery status is derived. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestManagedVolumeProjection_PVCPendingBlocked`, `TestManagedVolumeProjection_WriterFailedMountBlocked`, `TestManagedVolumeProjection_CSINodeImagePullBlocked`, `TestManagedVolumeProjection_LoopbackCrossNodeBlocked` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-HOSTPATH-FACTS-001` | The read model keeps path facts separate from the recovery claim: missing multipath blocks the transparent claim, and an NVMe ANA seam alone does not infer transparent recovery. | K8s readiness model | `core/ops/managed_volume_model.go` `deriveManagedVolumeStates`, `hasTransparentHostPathEvidence` | `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim`, `TestManagedVolumeProjection_NVMeANASeamDoesNotInferTransparentRecovery` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-FENCE-SELF-ON-PROMOTE-001` | A primary at epoch e applies no inbound replication traffic (ship, recovery lane start, rebuild), and none below e; it still answers probes, and its epoch floor never goes down when it later supports another primary (fencing gap G2). | M3 Supporting → Primary | `core/transport/replica.go` `FenceAsPrimary`, `acceptMutationLineage`; `core/host/volume/host.go` `fenceSelfWithPeers` | `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`); `TestG2_PrimaryListenerRefusesMutationsButAnswersProbes`, `TestG2_FloorStaysWhenThePrimaryLaterSupportsAnother` (`core/transport/g2_self_fence_test.go`) | `ReplicationFailover` `AckedSurvive`, `NoStaleAck` | ACTIVE | -| `INV-FENCE-FLOOR-DURABLE-001` | A replica never accepts mutating traffic below the highest epoch it has acknowledged or taken a role at, across restarts, and accepts none before its assignment is known; a role call whose floor cannot be made durable is not adopted and keeps the frontend unhealthy (fencing gap G1). | M3 Unassigned → Primary \| Supporting | `core/transport/replica.go` `raiseFloor`, `admitMutation`, `AdmitAsReplica`; `core/host/volume/host.go` `latchRoleAdmission` | `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch`, `TestG1_ConcurrentRaisesNeverLowerTheRecord`, `TestG1_RoleCallsPersistBeforeReturning` (`core/transport/g1_durable_floor_test.go`); `TestG1_FailedRoleAdmissionStopsAPreviouslyHealthyFrontend` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | +| `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | +| `INV-PROMOTE-FRONTIER-001` | The RF=3 promotion gate promotes only a probed candidate that covers the required acknowledgement frontier, and blocks promotion without a fresh probe. With a known frontier the candidate's durable LSN must be at least the required LSN. With an unknown frontier under `sync_quorum` or `sync_all`, the highest-durable ready candidate is promoted only when at least P-K+1 distinct peers are probed ready and fresh in the same tick (K from `waitForSyncAcks`; RF=3: both peers under `sync_quorum`, one under `sync_all`); otherwise nothing is promoted. An unknown frontier is never read as zero; `best_effort` is unchanged. | M3 Supporting → Primary (RF=3 gate) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/host/master/promotion_probe.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe`, `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe`, `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused`, `TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | +| `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-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 | +| `INV-K8S-REATTACH-001` | A CSI re-stage after failover uses the fresh publish target, and the read model reports recovery by reattach only with CSI reattach observed and a verified reader. | K8s readiness model | `core/csi/node.go` `refreshPublishContext`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestManagedVolumeProjection_NodeLossReattachRecovered` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-MANAGED-VOLUME-READMODEL-001` | Volume explanations in the observation report and explain output are rendered from the `ManagedVolume` projection. | K8s readiness model | `core/ops/managed_volume_model.go` `ProjectManagedVolume` | `TestObservationExplain_IncludesManagedVolumeProjectionAndDryRunActions`, `TestObservationReportSummary_IncludesManagedVolumeStatus` (`core/ops/observation_report_test.go`); `TestProjectManagedVolumeFromEvidence_DualPrimaryInvalid` (`core/ops/managed_volume_evidence_test.go`) | — | ACTIVE | +| `INV-CONTROL-CONTEXT-001` | Cross-layer explanations replayed from a bundle are derived from recorded facts and events. Superseded in scope by `INV-MANAGED-VOLUME-READMODEL-001`; kept for continuity. | K8s readiness model | `core/ops/observation_bundle.go` `BuildObservationFromBundle` | `TestObservationBundle_RendersNodeLossRecoveryStory`, `TestObservationBundle_ManagedVolumeUsesPrimaryFailureArtifactHints` (`core/ops/observation_bundle_test.go`) | — | ACTIVE | +| `INV-K8S-ADAPTOR-FACTS-001` | PVC, pod, node and CSI conditions enter the read model as typed facts and map to distinct blocked reasons before any recovery status is derived. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestManagedVolumeProjection_PVCPendingBlocked`, `TestManagedVolumeProjection_WriterFailedMountBlocked`, `TestManagedVolumeProjection_CSINodeImagePullBlocked`, `TestManagedVolumeProjection_LoopbackCrossNodeBlocked` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-HOSTPATH-FACTS-001` | The read model keeps path facts separate from the recovery claim: missing multipath blocks the transparent claim, and an NVMe ANA seam alone does not infer transparent recovery. | K8s readiness model | `core/ops/managed_volume_model.go` `deriveManagedVolumeStates`, `hasTransparentHostPathEvidence` | `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim`, `TestManagedVolumeProjection_NVMeANASeamDoesNotInferTransparentRecovery` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-FENCE-SELF-ON-PROMOTE-001` | A primary at epoch e applies no inbound replication traffic (ship, recovery lane start, rebuild), and none below e; it still answers probes, and its epoch floor never goes down when it later supports another primary (fencing gap G2). | M3 Supporting → Primary | `core/transport/replica.go` `FenceAsPrimary`, `acceptMutationLineage`; `core/host/volume/host.go` `fenceSelfWithPeers` | `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`); `TestG2_PrimaryListenerRefusesMutationsButAnswersProbes`, `TestG2_FloorStaysWhenThePrimaryLaterSupportsAnother` (`core/transport/g2_self_fence_test.go`) | `ReplicationFailover` `AckedSurvive`, `NoStaleAck` | ACTIVE | +| `INV-FENCE-FLOOR-DURABLE-001` | A replica never accepts mutating traffic below the highest epoch it has acknowledged or taken a role at, across restarts, and accepts none before its assignment is known; a role call whose floor cannot be made durable is not adopted and keeps the frontend unhealthy (fencing gap G1). | M3 Unassigned → Primary \| Supporting | `core/transport/replica.go` `raiseFloor`, `admitMutation`, `AdmitAsReplica`; `core/host/volume/host.go` `latchRoleAdmission` | `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch`, `TestG1_ConcurrentRaisesNeverLowerTheRecord`, `TestG1_RoleCallsPersistBeforeReturning` (`core/transport/g1_durable_floor_test.go`); `TestG1_FailedRoleAdmissionStopsAPreviouslyHealthyFrontend` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | Notes: - `INV-AUTH-ONE-PRIMARY-001`: Narrowed. The lab evidence field `post_failure_primary_count=1` is not read by any Go test. `IntentBind` is checked per volume: the Publisher refuses a genesis `Bind` (`ErrBindAlreadyBound`) once any slot of the volume holds a present line, also after a restart, when only the current slot is reloaded; `decideVolume` also binds only when the volume has no line ([#183](https://github.com/seaweedfs/seaweed-block/issues/183)). - `INV-FENCE-STALE-PRIMARY-001`: Narrowed. A primary cut off from blockmaster that has not seen the newer line keeps admitting I/O, and under `best_effort` its local `fsync` still acknowledges (no primary lease on the Kubernetes path; see the Kubernetes known gaps). The lab counter `old_primary_stale_io_success_count=0` is lab evidence only. -- `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`. +- `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`. - `INV-K8S-NONLOOPBACK-001`: Rejection is opt-in: the chart default for `network.rejectLoopbackPublishTargets` is false; the generator sets it for multi-node values. - `INV-OBS-PRODUCT-EVENTS-001`: Each event type has a unit test; all four together in one node-loss run is lab evidence only. - `INV-HOSTPATH-TRANSPARENT-001`: Narrowed to the classifier. It does not compare the host path target with the promoted target, and only the missing-multipath case has a negative test. The mounted-failover run is lab evidence. @@ -467,7 +467,7 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | +| `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | ### HEAD publication metadata cost From 90ecf57c28289653addaf3cf096a576e41e580af Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:17:28 -0800 Subject: [PATCH 005/150] blockvolume: install the RF1 rule in the host before any fact is applied Review fold (P2): SetReplicationVolume replays a retained RF2 fact before SetSelfFence installs the ingress gate; with no self fence the host could install the peer set, adopt and emit readiness. The rule now lives in the host config (RF1Only, from hostConfig at construction): every fact with replica slots, primary with peers or supporting replica, is refused before UpdateReplicaSet, adoption or the ready marker, and latched as a role admission failure; an RF1 fact clears it. The ingress gate stays as the second layer. Tests: the start schedule (blocked readiness, stored RF2 fact, replay with no self fence), supporting refusal, RF1 recovery, unset control; ingress refusal with dual-lane on both ports, classified by ingressPortReleased; hostConfig wiring. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/chunk_rf1_guard_test.go | 32 ++++--- seaweed-block/cmd/blockvolume/main.go | 32 ++++--- .../cmd/blockvolume/replication_ingress.go | 19 +++-- seaweed-block/core/host/volume/host.go | 30 +++++++ .../core/host/volume/rf1_only_test.go | 85 +++++++++++++++++++ 5 files changed, 166 insertions(+), 32 deletions(-) create mode 100644 seaweed-block/core/host/volume/rf1_only_test.go diff --git a/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go b/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go index 60e1bcc825..38c45269d5 100644 --- a/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go @@ -1,10 +1,8 @@ package main import ( - "net" "strings" "testing" - "time" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -29,19 +27,24 @@ func TestChunkVolumeRefusesReplicationAckAtStart(t *testing.T) { } } -// The replication factor arrives with the master's assignment, so the guard is -// also on the role gate: every role with replica slots is refused and no socket -// is opened; a primary role without peers (RF1) is admitted. +// The replication factor arrives with the master's assignment. The host refuses +// roles with replica slots (core/host/volume RF1Only, from hostConfig); the +// ingress gate refuses them again and opens neither inbound lane (legacy and +// dual-lane ports). A primary role without peers (RF1) is admitted. func TestChunkVolumeIngressRefusesReplicaSlots(t *testing.T) { for _, impl := range []string{"walstore", "walstore-chunk"} { t.Run(impl, func(t *testing.T) { - addr, _ := ingressPair(t) - r := newReplicationIngress(flags{dataAddr: addr, volumeID: "v1", durableImpl: impl, recoveryMode: "legacy"}, storage.NewBlockStore(4, 4096)) + addr, dual := ingressPair(t) + f := flags{dataAddr: addr, volumeID: "v1", durableImpl: impl, recoveryMode: "dual-lane"} + if got, want := hostConfig(f, nil).RF1Only, map[string]string{"walstore": "", "walstore-chunk": chunkRF1Reason}[impl]; got != want { + t.Fatalf("host config RF1Only = %q, want %q", got, want) + } + r := newReplicationIngress(f, storage.NewBlockStore(4, 4096)) defer r.Stop() admitErr := r.AdmitAsReplica(1) if impl == "walstore" { - if admitErr != nil || r.listener == nil { - t.Fatalf("walstore replica role: %v", admitErr) + if admitErr != nil || r.listener == nil || r.dual == nil { + t.Fatalf("walstore replica role (dual-lane): %v", admitErr) } return } @@ -54,12 +57,13 @@ func TestChunkVolumeIngressRefusesReplicaSlots(t *testing.T) { if err := r.FenceAsPrimary(3); err == nil { t.Fatal("legacy primary fence (peers assumed) admitted") } - if r.listener != nil { - t.Fatal("a replica listener was created") + if r.listener != nil || r.dual != nil { + t.Fatal("an inbound listener was created") } - if c, err := net.DialTimeout("tcp", addr, 500*time.Millisecond); err == nil { - c.Close() - t.Fatal("the replication address accepts connections") + for _, a := range []string{addr, dual} { + if err := ingressPortReleased(a); err != nil { + t.Fatal(err) + } } if err := r.FenceAsPrimaryWithPeers(4, false); err != nil { t.Fatalf("RF1 primary refused: %v", err) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 5fa728be95..3d809580f7 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -526,19 +526,7 @@ type nvmeReadyLine struct { func run(f flags) int { readyCh := make(chan adapter.AssignmentInfo, 16) - h, err := volume.New(volume.Config{ - MasterAddr: f.masterAddr, - ServerID: f.serverID, - VolumeID: f.volumeID, - ReplicaID: f.replicaID, - DataAddr: f.dataAddr, - CtrlAddr: f.ctrlAddr, - HeartbeatInterval: f.hbInterval, - RecoverTimeout: f.recoverTimeout, - ReadyMarker: readyCh, - EnableT1Readiness: f.enableT1Readiness, - WorkspaceLease: f.workspaceLease, - }) + h, err := volume.New(hostConfig(f, readyCh)) if err != nil { fmt.Fprintln(os.Stderr, "blockvolume:", err) return 1 @@ -1432,6 +1420,24 @@ func deriveDualLaneAddr(addr string) (string, error) { // replicaFloorPath is where the replica's epoch floor record lives (G1): // beside the volume's durable files, or "" for non-durable memback runs. +// hostConfig is the volume host's configuration from the flags. +func hostConfig(f flags, readyCh chan<- adapter.AssignmentInfo) volume.Config { + return volume.Config{ + MasterAddr: f.masterAddr, + ServerID: f.serverID, + VolumeID: f.volumeID, + ReplicaID: f.replicaID, + DataAddr: f.dataAddr, + CtrlAddr: f.ctrlAddr, + HeartbeatInterval: f.hbInterval, + RecoverTimeout: f.recoverTimeout, + ReadyMarker: readyCh, + EnableT1Readiness: f.enableT1Readiness, + WorkspaceLease: f.workspaceLease, + RF1Only: rf1Only(f), + } +} + func replicaFloorPath(f flags) string { if f.durableRoot == "" { return "" diff --git a/seaweed-block/cmd/blockvolume/replication_ingress.go b/seaweed-block/cmd/blockvolume/replication_ingress.go index eb22ed7ea5..89ab03da31 100644 --- a/seaweed-block/cmd/blockvolume/replication_ingress.go +++ b/seaweed-block/cmd/blockvolume/replication_ingress.go @@ -28,17 +28,26 @@ type replicationIngress struct { closed bool } -// newReplicationIngress is the volume's ingress from its flags; a walstore-chunk -// volume refuses every role with replica slots (chunkRF1Reason). +// newReplicationIngress is the volume's ingress from its flags; an RF1-only +// volume (walstore-chunk) refuses every role with replica slots. func newReplicationIngress(f flags, store storage.LogicalStorage) *replicationIngress { r := &replicationIngress{addr: f.dataAddr, store: store, volumeID: f.volumeID, floorPath: replicaFloorPath(f), dualLane: f.recoveryMode == "dual-lane"} - if f.durableImpl == "walstore-chunk" { - r.rf1Only = chunkRF1Reason - } + r.rf1Only = rf1Only(f) return r } +// rf1Only is the single-replica rule of this volume, "" when replication is +// allowed. The host refuses assignments with replica slots (installed at +// construction, before any fact is applied or replayed); the ingress gate +// refuses the same roles again. +func rf1Only(f flags) string { + if f.durableImpl == "walstore-chunk" { + return chunkRF1Reason + } + return "" +} + func (r *replicationIngress) FenceAsPrimary(epoch uint64) error { return r.FenceAsPrimaryWithPeers(epoch, true) } diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 1bea934d13..14e91de17f 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -66,6 +66,11 @@ type Config struct { // their documented non-healthy projection). EnableT1Readiness bool WorkspaceLease bool // Opt-in: require a workspace lease before I/O or capture. + // RF1Only, when set, is why this volume serves single-replica only + // (walstore-chunk): every assignment with replica slots, primary with + // peers or supporting replica, is refused before any peer set, role or + // readiness is installed, and latched like a failed role admission. + RF1Only string // ReplicationVolume, when non-nil, receives peer-set updates on // every self-replica AssignmentFact. The Host calls @@ -143,6 +148,7 @@ type Host struct { // even on a host that was healthy at its prior epoch; only a later // successful role call for the current role and epoch clears it. roleAdmissionFailed atomic.Value // string reason; "" = not failed + rf1Refused atomic.Value // string reason (Config.RF1Only); "" = the last fact was RF1 conn *grpc.ClientConn obsCli control.ObservationServiceClient @@ -428,6 +434,9 @@ func (h *Host) latchRoleAdmission(role selfRole, epoch uint64, err error) { // call on this host's replica listener failed, and why. The projection view // treats a failure as not Healthy. func (h *Host) RoleAdmissionFailure() (bool, string) { + if reason, _ := h.rf1Refused.Load().(string); reason != "" { + return true, reason + } reason, _ := h.roleAdmissionFailed.Load().(string) return reason != "", reason } @@ -780,6 +789,10 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { h.cfg.VolumeID, reason, info.ReplicaID, info.Epoch, info.EndpointVersion) return } + if h.cfg.RF1Only != "" { + h.refuseRF1("a supporting replica role", info.Epoch) + return + } if err := h.fenceSelf(selfRoleReplica, info.Epoch); err != nil { // G1: fail closed, as for the primary path; stream replay // redelivers the fact and a later success clears the latch. @@ -817,6 +830,15 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { return } + // An RF1-only volume refuses replica peers before anything is installed. + if h.cfg.RF1Only != "" { + if len(fact.Peers) > 0 { + h.refuseRF1(fmt.Sprintf("a primary role with %d replica peers", len(fact.Peers)), fact.Epoch) + return + } + h.rf1Refused.Store("") + } + // Step (2a): install replication peer set first. Decoded via // the separate host-only decodeReplicaTargets path (not through // AssignmentInfo), so the TestNoOtherAssignmentInfoConstruction @@ -866,6 +888,14 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { } } +// refuseRF1 latches the refusal of a role with replica slots on an RF1-only +// volume (Config.RF1Only): no peer set, role or readiness was installed. +func (h *Host) refuseRF1(what string, epoch uint64) { + reason := fmt.Sprintf("volume %s refuses %s at epoch %d: %s", h.cfg.VolumeID, what, epoch, h.cfg.RF1Only) + h.rf1Refused.Store(reason) + h.log.Printf("blockvolume: %s — NOT applying to adapter (fail-closed)", reason) +} + func (h *Host) emitSupportingReadyMarker(info adapter.AssignmentInfo) { if h.cfg.ReadyMarker == nil || info.Epoch == 0 { return diff --git a/seaweed-block/core/host/volume/rf1_only_test.go b/seaweed-block/core/host/volume/rf1_only_test.go new file mode 100644 index 0000000000..cba7617456 --- /dev/null +++ b/seaweed-block/core/host/volume/rf1_only_test.go @@ -0,0 +1,85 @@ +package volume + +import ( + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/adapter" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +func rf2PrimaryFact(epoch uint64) *control.AssignmentFact { + return &control.AssignmentFact{ + VolumeId: "vol1", ReplicaId: "r1", Epoch: epoch, EndpointVersion: 1, + DataAddr: "127.0.0.1:1000", CtrlAddr: "127.0.0.1:1001", PeerSetGeneration: epoch, + Peers: []*control.ReplicaDescriptor{{ReplicaId: "r2", Epoch: epoch, EndpointVersion: 1, DataAddr: "127.0.0.1:2000", CtrlAddr: "127.0.0.1:2001"}}, + } +} + +// The production start schedule of an RF1-only (walstore-chunk) volume: the +// host starts with local readiness blocked, a retained RF2 fact arrives and is +// stored, and installing the replication volume replays it with no self fence +// installed yet. The host must refuse it before any peer set, adoption or +// readiness marker, and latch the refusal; a later RF1 fact is adopted. +func TestRF1Only_RetainedReplicatedFactReplayedBeforeSelfFence(t *testing.T) { + rec := &orderingRecorder{} + h, a, r := newStubbedHost(t, "vol1", "r1", rec) + ready := make(chan adapter.AssignmentInfo, 4) + h.cfg.ReadyMarker, h.cfg.RF1Only = ready, "chunk snapshots need RF1" + rv := h.replication + h.replication = nil + h.BlockLocalReadiness("awaiting durable recovery") + + h.applyFact(rf2PrimaryFact(3)) // stored for replay + h.ClearLocalReadinessBlock() + h.replicationMu.Lock() + h.setReplicationLocked(rv) // what SetReplicationVolume does, then it replays + h.replicationMu.Unlock() + h.replayLocalReadinessFactIfReady() + + if h.selfFence != nil { + t.Fatal("fixture: a self fence is installed") + } + if r.callCount.Load() != 0 || a.callCount.Load() != 0 || len(ready) != 0 { + t.Fatalf("replayed RF2 fact installed something: peers=%d adopt=%d ready=%d %v", r.callCount.Load(), a.callCount.Load(), len(ready), rec.snapshot()) + } + failed, reason := h.RoleAdmissionFailure() + if !failed || !strings.Contains(reason, "refuses a primary role with 1 replica peers at epoch 3") || !strings.Contains(reason, "chunk snapshots need RF1") { + t.Fatalf("no refusal latch: %v %q", failed, reason) + } + + // A supporting-replica fact (another primary lists this replica) is refused too. + sup := rf2PrimaryFact(4) + sup.ReplicaId, sup.Peers[0].ReplicaId = "r2", "r1" + h.applyFact(sup) + if r.callCount.Load() != 0 || a.callCount.Load() != 0 || len(ready) != 0 { + t.Fatal("supporting replica admitted on an RF1-only volume") + } + if _, reason := h.RoleAdmissionFailure(); !strings.Contains(reason, "refuses a supporting replica role at epoch 4") { + t.Fatalf("supporting refusal not latched: %q", reason) + } + + // The master moves the volume to RF1: adopted, latch cleared, ready emitted. + rf1 := rf2PrimaryFact(5) + rf1.Peers = nil + h.applyFact(rf1) + if a.callCount.Load() != 1 || len(ready) != 1 { + t.Fatalf("RF1 primary not adopted: adopt=%d ready=%d", a.callCount.Load(), len(ready)) + } + if failed, reason := h.RoleAdmissionFailure(); failed { + t.Fatalf("latch not cleared by an RF1 fact: %q", reason) + } +} + +// Control: without the rule the same replayed RF2 fact installs its peer set +// and is adopted (today's behaviour for replicated volumes). +func TestRF1Only_UnsetKeepsReplicatedAdoption(t *testing.T) { + h, a, r := newStubbedHost(t, "vol1", "r1", &orderingRecorder{}) + h.applyFact(rf2PrimaryFact(3)) + if r.callCount.Load() != 1 || a.callCount.Load() != 1 { + t.Fatalf("replicated fact not applied: peers=%d adopt=%d", r.callCount.Load(), a.callCount.Load()) + } + if failed, _ := h.RoleAdmissionFailure(); failed { + t.Fatal("latched without the rule") + } +} From f7e0823fc3d3e24b9fba4386aca8173ac4d7b43d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:03:24 -0800 Subject: [PATCH 006/150] volume: bind the RF1 refusal to its epoch Review fold (P1): the refusal had no epoch, so RF1@2 -> RF2@3 refused -> a stale RF1@2 replay cleared it and reopened the old healthy view. The host now records the highest refused epoch; an RF1 fact below it is stale (not adopted, refusal kept), and the refusal is cleared only after the role fence of a current-or-newer RF1 fact succeeds, never by a failed attempt. Test with a real backend write schedule; ingress rows for legacy and dual-lane, and no listener after the RF1 primary role. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/chunk_rf1_guard_test.go | 14 +++-- seaweed-block/core/host/volume/host.go | 23 +++++-- .../core/host/volume/rf1_only_test.go | 63 +++++++++++++++++++ 3 files changed, 91 insertions(+), 9 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go b/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go index 38c45269d5..0d0fd71741 100644 --- a/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go @@ -32,10 +32,11 @@ func TestChunkVolumeRefusesReplicationAckAtStart(t *testing.T) { // ingress gate refuses them again and opens neither inbound lane (legacy and // dual-lane ports). A primary role without peers (RF1) is admitted. func TestChunkVolumeIngressRefusesReplicaSlots(t *testing.T) { - for _, impl := range []string{"walstore", "walstore-chunk"} { - t.Run(impl, func(t *testing.T) { + for _, row := range []struct{ impl, mode string }{{"walstore", "legacy"}, {"walstore", "dual-lane"}, {"walstore-chunk", "legacy"}, {"walstore-chunk", "dual-lane"}} { + impl, dualLane := row.impl, row.mode == "dual-lane" + t.Run(row.impl+"/"+row.mode, func(t *testing.T) { addr, dual := ingressPair(t) - f := flags{dataAddr: addr, volumeID: "v1", durableImpl: impl, recoveryMode: "dual-lane"} + f := flags{dataAddr: addr, volumeID: "v1", durableImpl: impl, recoveryMode: row.mode} if got, want := hostConfig(f, nil).RF1Only, map[string]string{"walstore": "", "walstore-chunk": chunkRF1Reason}[impl]; got != want { t.Fatalf("host config RF1Only = %q, want %q", got, want) } @@ -43,8 +44,8 @@ func TestChunkVolumeIngressRefusesReplicaSlots(t *testing.T) { defer r.Stop() admitErr := r.AdmitAsReplica(1) if impl == "walstore" { - if admitErr != nil || r.listener == nil || r.dual == nil { - t.Fatalf("walstore replica role (dual-lane): %v", admitErr) + if admitErr != nil || r.listener == nil || (r.dual != nil) != dualLane { + t.Fatalf("walstore replica role (%s): %v", row.mode, admitErr) } return } @@ -68,6 +69,9 @@ func TestChunkVolumeIngressRefusesReplicaSlots(t *testing.T) { if err := r.FenceAsPrimaryWithPeers(4, false); err != nil { t.Fatalf("RF1 primary refused: %v", err) } + if r.listener != nil || r.dual != nil { + t.Fatal("the RF1 primary role opened an inbound listener") + } }) } } diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 14e91de17f..1f1cddf935 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -147,8 +147,9 @@ type Host struct { // While set, the frontend projection is not Healthy, so writes refuse // even on a host that was healthy at its prior epoch; only a later // successful role call for the current role and epoch clears it. - roleAdmissionFailed atomic.Value // string reason; "" = not failed - rf1Refused atomic.Value // string reason (Config.RF1Only); "" = the last fact was RF1 + roleAdmissionFailed atomic.Value // string reason; "" = not failed + rf1Refused atomic.Value // string reason (Config.RF1Only); "" = not refused + rf1RefusedEpoch atomic.Uint64 // highest epoch refused under RF1Only; a lower fact is stale conn *grpc.ClientConn obsCli control.ObservationServiceClient @@ -830,13 +831,18 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { return } - // An RF1-only volume refuses replica peers before anything is installed. + // An RF1-only volume refuses replica peers before anything is installed, + // and a fact below a refused epoch is stale: it neither adopts nor clears. if h.cfg.RF1Only != "" { if len(fact.Peers) > 0 { h.refuseRF1(fmt.Sprintf("a primary role with %d replica peers", len(fact.Peers)), fact.Epoch) return } - h.rf1Refused.Store("") + if refused := h.rf1RefusedEpoch.Load(); fact.Epoch < refused { + h.log.Printf("blockvolume: volume %s stale RF1 assignment at epoch %d below refused epoch %d — NOT applying to adapter", + h.cfg.VolumeID, fact.Epoch, refused) + return + } } // Step (2a): install replication peer set first. Decoded via @@ -877,6 +883,9 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { h.cfg.VolumeID, info.Epoch, err) return } + if h.cfg.RF1Only != "" { + h.rf1Refused.Store("") // only a current-or-newer RF1 fact whose role was admitted clears the refusal + } h.adpt.OnAssignment(info) h.log.Printf("blockvolume: volume %s adopted as PRIMARY at %s@%d (EV=%d)", h.cfg.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion) @@ -892,6 +901,12 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { // volume (Config.RF1Only): no peer set, role or readiness was installed. func (h *Host) refuseRF1(what string, epoch uint64) { reason := fmt.Sprintf("volume %s refuses %s at epoch %d: %s", h.cfg.VolumeID, what, epoch, h.cfg.RF1Only) + for { + cur := h.rf1RefusedEpoch.Load() + if epoch <= cur || h.rf1RefusedEpoch.CompareAndSwap(cur, epoch) { + break + } + } h.rf1Refused.Store(reason) h.log.Printf("blockvolume: %s — NOT applying to adapter (fail-closed)", reason) } diff --git a/seaweed-block/core/host/volume/rf1_only_test.go b/seaweed-block/core/host/volume/rf1_only_test.go index cba7617456..509d083502 100644 --- a/seaweed-block/core/host/volume/rf1_only_test.go +++ b/seaweed-block/core/host/volume/rf1_only_test.go @@ -1,11 +1,17 @@ package volume import ( + "context" + "errors" "strings" "testing" "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/engine" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage/memorywal" ) func rf2PrimaryFact(epoch uint64) *control.AssignmentFact { @@ -83,3 +89,60 @@ func TestRF1Only_UnsetKeepsReplicatedAdoption(t *testing.T) { t.Fatal("latched without the rule") } } + +// A refusal is bound to its epoch: RF1@2 healthy and writing, RF2@3 refused +// (writes stop), then a stale RF1@2 replay must neither adopt nor clear the +// refusal (writes stay refused, no peers installed); only RF1 at the refused +// epoch or newer, once its role is admitted, clears it. +func TestRF1Only_StaleRF1FactDoesNotClearANewerRefusal(t *testing.T) { + h, a, r := newStubbedHost(t, "vol1", "r1", &orderingRecorder{}) + h.cfg.RF1Only = "chunk snapshots need RF1" + proj := &mutableProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 2, EndpointVersion: 1}} + h.view = NewAdapterProjectionView(proj, "vol1", "r1", h) + fencer := &switchFencer{} + if err := h.SetSelfFence(fencer); err != nil { + t.Fatal(err) + } + rf1 := func(epoch uint64) *control.AssignmentFact { f := rf2PrimaryFact(epoch); f.Peers = nil; return f } + h.applyFact(rf1(2)) + if a.callCount.Load() != 1 { + t.Fatal("fixture: RF1@2 not adopted") + } + store := memorywal.NewStore(8, 4096) + t.Cleanup(func() { _ = store.Close() }) + backend := durable.NewStorageBackend(store, h.view, frontend.Identity{VolumeID: "vol1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1}) + backend.SetOperational(true, "rf1 baseline") + ctx := context.Background() + if _, err := backend.Write(ctx, 0, []byte("epoch-2")); err != nil { + t.Fatalf("baseline write: %v", err) + } + + h.applyFact(rf2PrimaryFact(3)) + if _, err := backend.Write(ctx, 0, []byte("x")); !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("write after the RF2@3 refusal: %v", err) + } + h.applyFact(rf1(2)) // stale replay below the refused epoch + if failed, reason := h.RoleAdmissionFailure(); !failed || !strings.Contains(reason, "at epoch 3") { + t.Fatalf("stale RF1@2 cleared the RF2@3 refusal: %v %q", failed, reason) + } + if _, err := backend.Write(ctx, 0, []byte("x")); !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("write reopened by a stale RF1@2: %v", err) + } + if a.callCount.Load() != 1 || r.callCount.Load() != 1 { + t.Fatalf("stale RF1@2 adopted or RF2 peers installed: adopt=%d peerSets=%d", a.callCount.Load(), r.callCount.Load()) + } + if len(r.lastTargetIDs) != 0 { + t.Fatalf("forbidden peers installed: %v", r.lastTargetIDs) + } + + fencer.fail.Store(true) // RF1@3 whose role fence fails: a failed attempt does not clear the refusal + h.applyFact(rf1(3)) + if _, reason := h.RoleAdmissionFailure(); !strings.Contains(reason, "refuses a primary role") || a.callCount.Load() != 1 { + t.Fatalf("failed RF1@3 attempt cleared the refusal: %q adopt=%d", reason, a.callCount.Load()) + } + fencer.fail.Store(false) + h.applyFact(rf1(3)) + if failed, reason := h.RoleAdmissionFailure(); failed || a.callCount.Load() != 2 { + t.Fatalf("RF1@3 did not reconcile: %v %q adopt=%d", failed, reason, a.callCount.Load()) + } +} From dfffdd80887ead8c6e462d562837dddb3484679f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:12:13 -0800 Subject: [PATCH 007/150] test(storage): cut upload retry, ambiguous completion and cancellation --- .../core/storage/chunk_upload_retry_test.go | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_upload_retry_test.go diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go new file mode 100644 index 0000000000..d55ce37a22 --- /dev/null +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -0,0 +1,113 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "sync" + "testing" + "time" +) + +// Faults sit at the remote seam; all captures, intents, hashes and HEADs use +// the real layer and the write-once fake remote. +type retryUploadRemote struct { + *fakeChunkRemote + mu sync.Mutex + mode string + calls map[string]int +} + +func (r *retryUploadRemote) Put(ctx context.Context, key string, data []byte) error { + r.mu.Lock() + r.calls[key]++ + n, mode := r.calls[key], r.mode + r.mu.Unlock() + if mode == "down" || mode == "transient" && n == 1 { + return errFakeRemoteDown + } + if mode == "lost" && n == 1 { + if err := r.fakeChunkRemote.Put(ctx, key, data); err != nil { + return err + } + return errFakeRemoteDown // binding committed, response lost + } + if mode == "collision" { + bad := bytes.Repeat([]byte{0xff}, len(data)) + if err := r.fakeChunkRemote.Put(ctx, key, bad); err != nil { + return err + } + return errChunkKeyExists + } + return r.fakeChunkRemote.Put(ctx, key, data) +} + +func TestChunkCutRetriesOnlyTheFailedUpload(t *testing.T) { + for _, mode := range []string{"transient", "lost"} { + t.Run(mode, func(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &retryUploadRemote{fakeChunkRemote: f, mode: mode, calls: map[string]int{}} + layer := mustAttach(t, s, r, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 0, 0x41) + w.write(t, s, ctChunkBlocks, 0x42) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if len(f.installedHeads()) != 1 { + t.Fatal("cut did not publish exactly one HEAD") + } + assertEveryHeadIsPrefixImage(t, f, w) + r.mu.Lock() + defer r.mu.Unlock() + if len(r.calls) != 2 { + t.Fatalf("new key generated on retry: %v", r.calls) + } + for key, n := range r.calls { + if n != 2 { + t.Fatalf("key %s attempted %d times, want 2", key, n) + } + } + }) + } +} + +func TestChunkCutUploadCollisionNeverPublishes(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &retryUploadRemote{fakeChunkRemote: f, mode: "collision", calls: map[string]int{}} + layer := mustAttach(t, s, r, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 0, 0x41) + if _, err := layer.Cut(ctTimeout(t)); err == nil { + t.Fatal("published mismatching existing key") + } + if len(f.installedHeads()) != 0 { + t.Fatal("HEAD moved after collision") + } +} + +func TestChunkCutUploadRetryHonorsDeadlineAndRetainsDirt(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &retryUploadRemote{fakeChunkRemote: f, mode: "down", calls: map[string]int{}} + layer := mustAttach(t, s, r, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 0, 0x41) + ctx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond) + defer cancel() + if _, err := layer.Cut(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("deadline lost: %v", err) + } + if len(f.installedHeads()) != 0 { + t.Fatal("HEAD moved during outage") + } + r.mu.Lock() + r.mode = "ok" + r.mu.Unlock() + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + assertEveryHeadIsPrefixImage(t, f, w) +} From a9d24e425665eed1f542ef284db8e69843ebc655 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:14:03 -0800 Subject: [PATCH 008/150] storage: resolve lost upload replies before bounded single-object retries --- seaweed-block/core/storage/chunk_layer.go | 9 +++-- seaweed-block/core/storage/chunk_upload.go | 34 +++++++++++++++++++ .../core/storage/chunk_upload_retry_test.go | 8 +++-- 3 files changed, 47 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index d8d56fc664..ffee0274f9 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -800,6 +800,11 @@ type stagedChunk struct { const chunkStageRounds = 3 func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res chunkCutResult, err error) { + // Retries share one cut budget, shortened by the caller's own deadline. + // As with every remote operation, an implementation ignoring cancellation + // is still joined before buffers and intents are settled. + ctx, deadlineCancel := context.WithTimeout(ctx, 5*time.Minute) + defer deadlineCancel() done, err := l.register() if err != nil { return chunkCutResult{}, err @@ -1012,7 +1017,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error { u := uploads[i] - return l.remote.Put(ctx, u.key, u.c.data) + return l.putCaptured(ctx, u.key, u.c.data) }); err != nil { l.abortCut(all) l.dropIntents(ctx, intents) @@ -1662,7 +1667,7 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint intents = append(intents, id) if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error { u := uploads[i] - return l.remote.Put(ctx, u.key, u.data) + return l.putCaptured(ctx, u.key, u.data) }); err != nil { return nil, intents, fmt.Errorf("storage: capture stage upload: %w: %w", errChunkRemoteUnavailable, err) } diff --git a/seaweed-block/core/storage/chunk_upload.go b/seaweed-block/core/storage/chunk_upload.go index b1e79b7b2f..f03fc831f9 100644 --- a/seaweed-block/core/storage/chunk_upload.go +++ b/seaweed-block/core/storage/chunk_upload.go @@ -1,10 +1,44 @@ package storage import ( + "bytes" "context" "sync" + "time" ) +// putCaptured retries one immutable object, never a whole batch or HEAD CAS. +// A lost binding reply can turn the next attempt into KeyExists: only exact +// bytes read from that binding prove completion; a collision is terminal. +func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byte) error { + backoff := 100 * time.Millisecond + for { + if err := ctx.Err(); err != nil { + return err + } + err := l.remote.Put(ctx, key, data) + if err == nil { + return nil + } + // Resolve a possibly committed binding before replaying the Put. + got, readErr := l.remote.Get(ctx, key) + if readErr == nil { + if bytes.Equal(got, data) { + return nil + } + return errChunkKeyExists + } + timer := time.NewTimer(backoff) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + backoff = min(2*time.Second, 2*backoff) + } +} + // uploadBatch owns and joins all Put calls before its caller settles intents. // No storage/publication lock is acquired by workers. Cancellation stops new // admission; a remote ignoring cancellation remains joined, never declared done. diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go index d55ce37a22..cbee7db935 100644 --- a/seaweed-block/core/storage/chunk_upload_retry_test.go +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -65,8 +65,12 @@ func TestChunkCutRetriesOnlyTheFailedUpload(t *testing.T) { t.Fatalf("new key generated on retry: %v", r.calls) } for key, n := range r.calls { - if n != 2 { - t.Fatalf("key %s attempted %d times, want 2", key, n) + want := 2 + if mode == "lost" { + want = 1 + } + if n != want { + t.Fatalf("key %s attempted %d times, want %d", key, n, want) } } }) From 9859a0c1c57032f5b0f65cf65946e81bbf74c251 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:17:46 -0800 Subject: [PATCH 009/150] volume: RF1 admission state under one lock; a clear removes only what it can see Review fold (P1): the refused epoch and reason were separate atomics, so an allowed RF1@2 replay could pass the stale check, a stream RF2@3 latch the refusal, and the replay then clear that newer refusal. The epoch, reason and the highest admitted RF1 epoch are now one unit under rf1Mu (field access only). admitRF1 clears and adopts only if no newer refusal was latched; otherwise the fact is not adopted. P2: a refusal below an admitted RF1 epoch is stale and does not re-latch. Deterministic test with a hook between the stale check and the admit; stale RF2 test. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/volume/host.go | 65 +++++++++++--- .../core/host/volume/rf1_only_test.go | 85 +++++++++++++++++++ 2 files changed, 136 insertions(+), 14 deletions(-) diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 1f1cddf935..bd077186d4 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -147,9 +147,16 @@ type Host struct { // While set, the frontend projection is not Healthy, so writes refuse // even on a host that was healthy at its prior epoch; only a later // successful role call for the current role and epoch clears it. - roleAdmissionFailed atomic.Value // string reason; "" = not failed - rf1Refused atomic.Value // string reason (Config.RF1Only); "" = not refused - rf1RefusedEpoch atomic.Uint64 // highest epoch refused under RF1Only; a lower fact is stale + roleAdmissionFailed atomic.Value // string reason; "" = not failed + // RF1Only admission state, one unit under rf1Mu (field access only, no + // calls): the highest refused epoch with its reason ("" = cleared), and the + // highest epoch an RF1 fact was admitted at. A clear removes only the + // refusal it can still see as not newer than its own fact. + rf1Mu sync.Mutex + rf1Reason string + rf1Refused uint64 + rf1Admitted uint64 + rf1BeforeAdmit func() // test hook: between the stale check and the admit conn *grpc.ClientConn obsCli control.ObservationServiceClient @@ -435,8 +442,11 @@ func (h *Host) latchRoleAdmission(role selfRole, epoch uint64, err error) { // call on this host's replica listener failed, and why. The projection view // treats a failure as not Healthy. func (h *Host) RoleAdmissionFailure() (bool, string) { - if reason, _ := h.rf1Refused.Load().(string); reason != "" { - return true, reason + h.rf1Mu.Lock() + rf1 := h.rf1Reason + h.rf1Mu.Unlock() + if rf1 != "" { + return true, rf1 } reason, _ := h.roleAdmissionFailed.Load().(string) return reason != "", reason @@ -838,7 +848,10 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { h.refuseRF1(fmt.Sprintf("a primary role with %d replica peers", len(fact.Peers)), fact.Epoch) return } - if refused := h.rf1RefusedEpoch.Load(); fact.Epoch < refused { + h.rf1Mu.Lock() + refused := h.rf1Refused + h.rf1Mu.Unlock() + if fact.Epoch < refused { h.log.Printf("blockvolume: volume %s stale RF1 assignment at epoch %d below refused epoch %d — NOT applying to adapter", h.cfg.VolumeID, fact.Epoch, refused) return @@ -883,8 +896,10 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { h.cfg.VolumeID, info.Epoch, err) return } - if h.cfg.RF1Only != "" { - h.rf1Refused.Store("") // only a current-or-newer RF1 fact whose role was admitted clears the refusal + if h.cfg.RF1Only != "" && !h.admitRF1(fact.Epoch) { + h.log.Printf("blockvolume: volume %s RF1 assignment at epoch %d overtaken by a newer refusal — NOT applying to adapter", + h.cfg.VolumeID, fact.Epoch) + return } h.adpt.OnAssignment(info) h.log.Printf("blockvolume: volume %s adopted as PRIMARY at %s@%d (EV=%d)", @@ -901,16 +916,38 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { // volume (Config.RF1Only): no peer set, role or readiness was installed. func (h *Host) refuseRF1(what string, epoch uint64) { reason := fmt.Sprintf("volume %s refuses %s at epoch %d: %s", h.cfg.VolumeID, what, epoch, h.cfg.RF1Only) - for { - cur := h.rf1RefusedEpoch.Load() - if epoch <= cur || h.rf1RefusedEpoch.CompareAndSwap(cur, epoch) { - break - } + h.rf1Mu.Lock() + stale := epoch < h.rf1Admitted // older than an admitted RF1 fact: does not re-latch + if !stale && epoch >= h.rf1Refused { + h.rf1Refused, h.rf1Reason = epoch, reason + } + h.rf1Mu.Unlock() + if stale { + h.log.Printf("blockvolume: stale %s (admitted RF1 epoch is newer) — NOT applying to adapter", reason) + return } - h.rf1Refused.Store(reason) h.log.Printf("blockvolume: %s — NOT applying to adapter (fail-closed)", reason) } +// admitRF1 clears the RF1 refusal for an RF1 fact whose role was admitted, +// unless a refusal at a newer epoch was latched meanwhile (then it reports +// false and the fact must not be adopted). +func (h *Host) admitRF1(epoch uint64) bool { + if hook := h.rf1BeforeAdmit; hook != nil { + hook() + } + h.rf1Mu.Lock() + defer h.rf1Mu.Unlock() + if epoch < h.rf1Refused { + return false + } + h.rf1Reason = "" + if epoch > h.rf1Admitted { + h.rf1Admitted = epoch + } + return true +} + func (h *Host) emitSupportingReadyMarker(info adapter.AssignmentInfo) { if h.cfg.ReadyMarker == nil || info.Epoch == 0 { return diff --git a/seaweed-block/core/host/volume/rf1_only_test.go b/seaweed-block/core/host/volume/rf1_only_test.go index 509d083502..b8fa0dbaf9 100644 --- a/seaweed-block/core/host/volume/rf1_only_test.go +++ b/seaweed-block/core/host/volume/rf1_only_test.go @@ -146,3 +146,88 @@ func TestRF1Only_StaleRF1FactDoesNotClearANewerRefusal(t *testing.T) { t.Fatalf("RF1@3 did not reconcile: %v %q adopt=%d", failed, reason, a.callCount.Load()) } } + +func newRF1BackendHost(t *testing.T) (*Host, *stubAdapter, *stubReplication, *durable.StorageBackend) { + t.Helper() + h, a, r := newStubbedHost(t, "vol1", "r1", &orderingRecorder{}) + h.cfg.RF1Only = "chunk snapshots need RF1" + proj := &mutableProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 2, EndpointVersion: 1}} + h.view = NewAdapterProjectionView(proj, "vol1", "r1", h) + if err := h.SetSelfFence(&switchFencer{}); err != nil { + t.Fatal(err) + } + store := memorywal.NewStore(8, 4096) + t.Cleanup(func() { _ = store.Close() }) + backend := durable.NewStorageBackend(store, h.view, frontend.Identity{VolumeID: "vol1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1}) + backend.SetOperational(true, "rf1 baseline") + return h, a, r, backend +} + +func rf1Fact(epoch uint64) *control.AssignmentFact { + f := rf2PrimaryFact(epoch) + f.Peers = nil + return f +} + +// Concurrent schedule: an allowed RF1@2 replay passes the stale check, and +// before it admits, the stream latches an RF2@3 refusal. The replay must not +// clear that newer refusal nor adopt; writes stay refused. RF1@3 then admits. +func TestRF1Only_HeldRF1ReplayDoesNotClearANewerRefusal(t *testing.T) { + h, a, r, backend := newRF1BackendHost(t) + ctx := context.Background() + h.applyFact(rf1Fact(2)) + if _, err := backend.Write(ctx, 0, []byte("epoch-2")); err != nil || a.callCount.Load() != 1 { + t.Fatalf("baseline: adopt=%d write=%v", a.callCount.Load(), err) + } + fired := false + h.rf1BeforeAdmit = func() { + if !fired { + fired = true + h.applyFact(rf2PrimaryFact(3)) // the stream, between the replay's check and its admit + } + } + h.applyFact(rf1Fact(2)) // the held replay + h.rf1BeforeAdmit = nil + if !fired { + t.Fatal("fixture: the replay did not reach the admit point") + } + if failed, reason := h.RoleAdmissionFailure(); !failed || !strings.Contains(reason, "at epoch 3") { + t.Fatalf("held RF1@2 cleared the newer RF2@3 refusal: %v %q", failed, reason) + } + if a.callCount.Load() != 1 { + t.Fatalf("held RF1@2 adopted after the newer refusal: adopt=%d", a.callCount.Load()) + } + if _, err := backend.Write(ctx, 0, []byte("x")); !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("write after the newer refusal: %v", err) + } + if len(r.lastTargetIDs) != 0 { + t.Fatalf("forbidden peers installed: %v", r.lastTargetIDs) + } + h.applyFact(rf1Fact(3)) + if failed, reason := h.RoleAdmissionFailure(); failed || a.callCount.Load() != 2 { + t.Fatalf("current RF1@3 not admitted: %v %q adopt=%d", failed, reason, a.callCount.Load()) + } +} + +// A stale RF2 below an admitted RF1 epoch does not re-latch the refusal. +func TestRF1Only_StaleRF2AfterNewerRF1DoesNotRelatch(t *testing.T) { + h, a, _, backend := newRF1BackendHost(t) + ctx := context.Background() + h.applyFact(rf1Fact(2)) + h.applyFact(rf2PrimaryFact(3)) + h.applyFact(rf1Fact(4)) + if failed, reason := h.RoleAdmissionFailure(); failed || a.callCount.Load() != 2 { + t.Fatalf("RF1@4 not admitted: %v %q adopt=%d", failed, reason, a.callCount.Load()) + } + h.applyFact(rf2PrimaryFact(3)) // stale replay + if failed, reason := h.RoleAdmissionFailure(); failed { + t.Fatalf("stale RF2@3 re-latched after RF1@4: %q", reason) + } + if _, err := backend.Write(ctx, 0, []byte("x")); errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("stale RF2@3 stopped writes: %v", err) + } + h.applyFact(rf2PrimaryFact(4)) // same epoch, peers added: refused + if failed, _ := h.RoleAdmissionFailure(); !failed { + t.Fatal("RF2 at the admitted epoch not refused") + } +} From 92f172006a595a15f3bf7225430e4b083faa1a13 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:18:34 -0800 Subject: [PATCH 010/150] docs: record bounded cut-upload retry and unchanged publication guards --- seaweed-block/docs/design/agent-workspace-design.md | 1 + seaweed-block/docs/design/invariants.md | 10 +++++++++- seaweed-block/docs/spec/CutPipeline.tla | 5 +++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 48b9ca7a58..bef22a0ab8 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -126,6 +126,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto 5. **LSN guard:** if H is below HEAD's `RemoteLSN`, refuse (`lsn_behind`). 6. **Diff:** upload only chunks whose SHA-256 differs from HEAD; drop all-zero chunks from the map. 7. **Intent first:** write an intent naming every key, then upload in parallel (`UploadConcurrency`, `--chunk-upload-concurrency`, default 8, 1 to 64). + Failed chunk uploads retry the same immutable key and captured bytes with 100 ms exponential backoff capped at 2 s. Resolve a possibly committed binding by exact-byte read-back before replay; a mismatch refuses the cut. All retries share a five-minute cut execution budget, shortened by the caller deadline. Queued lock wait and a remote ignoring cancellation are not forcibly terminated: workers remain joined before buffers/intents settle. Failure preserves dirt. HEAD CAS is never blindly replayed by this upload retry. 8. **Manifest:** build segments; new segments are also covered by an intent before upload (`PrepareManifest`). 9. **Re-admit** right before the CAS; fence if a superseding holder owns HEAD (`supersededBy`). 10. **CAS** HEAD on `{gen, epoch}` with `RemoteLSN = H`. On success, drop the intents and settle unchanged owned-map versions, keeping post-cut dirt. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b032a37af0..e9dcfa760e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -194,6 +194,8 @@ stateDiagram-v2 Aborted --> Refused: drain owners, cleanup, merge candidates Copy --> Refused: H below HEAD RemoteLSN Closed --> Upload: drain and cleanup; intent durable first + Upload --> Upload: retry one immutable key after backoff + Upload --> Refused: shared deadline/cancel or mismatching binding Upload --> Manifest Manifest --> Readmit Readmit --> Fenced: superseding HEAD @@ -213,7 +215,7 @@ stateDiagram-v2 | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read into buffers; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | -| Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after a durable intent names them | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | +| Upload | upload changed chunks after a durable intent names their write-once keys; retry one key under the shared five-minute cut execution deadline (or shorter caller deadline); resolve ambiguous bindings by exact-byte read-back before replay | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | | Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | | No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001` | | Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-WS-HEAD-CAS-001` | @@ -469,6 +471,12 @@ Notes: |---|---|---|---|---|---|---| | `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | +### Cut upload retry + +| ID | Status | Invariant | Enforced in | Tests | Model | +|---|---|---|---|---|---| +| INV-CUT-UPLOAD-RETRY-001 | ACTIVE | A failed chunk upload retries the same key and captured bytes, keeps its intent, and cannot advance HEAD before completion; cancellation preserves dirt. | `chunk_upload.go` `putCaptured`; `chunk_layer.go` `captureLocked` | `TestChunkCutRetriesOnlyTheFailedUpload`, `TestChunkCutUploadCollisionNeverPublishes`, `TestChunkCutUploadRetryHonorsDeadlineAndRetainsDirt` | M5; retry stutters in abstract `CutPipeline`; timing and ambiguity are qualified by native tests. | + ## Part C. Change rules How a fix or a feature is calibrated against this model: diff --git a/seaweed-block/docs/spec/CutPipeline.tla b/seaweed-block/docs/spec/CutPipeline.tla index 40367a642d..166f466a8f 100644 --- a/seaweed-block/docs/spec/CutPipeline.tla +++ b/seaweed-block/docs/spec/CutPipeline.tla @@ -13,6 +13,11 @@ (* chunk is compared against HEAD; cuts are refused ("reconciling") *) (* until the compare finishes (chunk_layer.go:95); *) (* - a crash before the root CAS leaves only orphan uploads. *) +(* Per-object upload retries retain the same key/bytes and intent. Failed *) +(* attempts make no abstract state change (Spec permits stuttering); the *) +(* atomic Cut below still requires all objects before HEAD publication. *) +(* Backoff/deadline timing and ambiguous-reply byte checks are qualified *) +(* by native TestChunkCut*Upload* controls, not by this abstraction. *) (* Chunk content = the LSN of the write it holds. *) (***************************************************************************) EXTENDS Integers, FiniteSets, Sequences, TLC From b47b40fadf00f049d53403c2fc9f952543d93cb1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:20:47 -0800 Subject: [PATCH 011/150] storage: retain the remote cause when a retry budget ends --- seaweed-block/core/storage/chunk_upload.go | 7 +++++-- .../core/storage/chunk_upload_parallel_test.go | 13 ++++++++++--- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/storage/chunk_upload.go b/seaweed-block/core/storage/chunk_upload.go index f03fc831f9..7a623ac315 100644 --- a/seaweed-block/core/storage/chunk_upload.go +++ b/seaweed-block/core/storage/chunk_upload.go @@ -3,6 +3,7 @@ package storage import ( "bytes" "context" + "errors" "sync" "time" ) @@ -12,14 +13,16 @@ import ( // bytes read from that binding prove completion; a collision is terminal. func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byte) error { backoff := 100 * time.Millisecond + var lastErr error for { if err := ctx.Err(); err != nil { - return err + return errors.Join(lastErr, err) } err := l.remote.Put(ctx, key, data) if err == nil { return nil } + lastErr = err // Resolve a possibly committed binding before replaying the Put. got, readErr := l.remote.Get(ctx, key) if readErr == nil { @@ -32,7 +35,7 @@ func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byt select { case <-ctx.Done(): timer.Stop() - return ctx.Err() + return errors.Join(lastErr, ctx.Err()) case <-timer.C: } backoff = min(2*time.Second, 2*backoff) diff --git a/seaweed-block/core/storage/chunk_upload_parallel_test.go b/seaweed-block/core/storage/chunk_upload_parallel_test.go index c843ccee54..3cad929a6c 100644 --- a/seaweed-block/core/storage/chunk_upload_parallel_test.go +++ b/seaweed-block/core/storage/chunk_upload_parallel_test.go @@ -108,12 +108,16 @@ type unjoinedUploadRemote struct { } func (r *unjoinedUploadRemote) Put(ctx context.Context, key string, data []byte) error { - if r.calls.Add(1) == 1 { + switch r.calls.Add(1) { + case 1: <-r.second close(r.failed) return errFakeRemoteDown + case 2: + close(r.second) + default: + return errFakeRemoteDown } - close(r.second) <-r.release return r.fakeChunkRemote.Put(context.Background(), key, data) } @@ -128,10 +132,13 @@ func TestChunkUploads_FailureJoinsBeforeIntentCleanup(t *testing.T) { w := newWriteLog() w.write(t, s, 0, 0x21) w.write(t, s, ctChunkBlocks, 0x22) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() done := make(chan error, 1) - go func() { _, err := l.Cut(context.Background()); done <- err }() + go func() { _, err := l.Cut(ctx); done <- err }() select { case <-r.failed: + cancel() // retries are now allowed; terminate this cut explicitly case <-time.After(time.Second): close(r.release) <-done From 62813dc9a87dcc206f4a79bbfb34a0912c2ee9b6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:23:37 -0800 Subject: [PATCH 012/150] test(storage): exercise upload retries beyond the WAL with periodic flushes --- .../core/storage/chunk_upload_retry_test.go | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go index cbee7db935..a03441690c 100644 --- a/seaweed-block/core/storage/chunk_upload_retry_test.go +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "path/filepath" "sync" "testing" "time" @@ -115,3 +116,33 @@ func TestChunkCutUploadRetryHonorsDeadlineAndRetainsDirt(t *testing.T) { } assertEveryHeadIsPrefixImage(t, f, w) } + +func TestChunkCutRetrySustainedWritesPastWALWithFlush(t *testing.T) { + const walBytes = 64 * 1024 + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), ctNumBlocks, ctBlockSize, walBytes, WModeStrict, ctChunkBlocks) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { closeBounded(t, s) }) + f := newFakeChunkRemote() + r := &retryUploadRemote{fakeChunkRemote: f, mode: "transient", calls: map[string]int{}} + layer := mustAttach(t, s, r, ctConfig(1)) + w := newWriteLog() + for i := 0; i < 96; i++ { + w.write(t, s, uint32(i%ctNumBlocks), byte(i+1)) + if (i+1)%4 == 0 { + mustSyncFlush(t, s) + } + if (i+1)%16 == 0 { + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + } + } + assertEveryHeadIsPrefixImage(t, f, w) + if len(f.installedHeads()) != 6 { + t.Fatalf("published %d HEADs", len(f.installedHeads())) + } + t.Logf("payload=%d > WAL=%d; 24 periodic flushes; 6 cuts with transient upload faults", 96*ctBlockSize, walBytes) +} From 08b4e33384960c9300631129ab219621f96cd560 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:27:16 -0800 Subject: [PATCH 013/150] volume: RF1 tests write and read back at the current identity; parallel replay race Review fold (P2, tests only): the positive RF1@3 steps now write and read back through a backend at the epoch-3 identity (exact n, nil error); the stale-RF2 test requires a successful write. New two-worker test: the replay worker's RF1@2 parks in the peer-set update, the stream worker's RF2@3 is refused meanwhile, then the replay resumes; bounded by timeouts. Co-Authored-By: Claude Opus 5.5 --- .../core/host/volume/rf1_only_test.go | 251 +++++++++++------- 1 file changed, 159 insertions(+), 92 deletions(-) diff --git a/seaweed-block/core/host/volume/rf1_only_test.go b/seaweed-block/core/host/volume/rf1_only_test.go index b8fa0dbaf9..d4fb831e18 100644 --- a/seaweed-block/core/host/volume/rf1_only_test.go +++ b/seaweed-block/core/host/volume/rf1_only_test.go @@ -1,15 +1,20 @@ package volume import ( + "bytes" "context" "errors" + "fmt" "strings" + "sync/atomic" "testing" + "time" "github.com/seaweedfs/seaweed-block/core/adapter" "github.com/seaweedfs/seaweed-block/core/engine" "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/replication" control "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/core/storage/memorywal" ) @@ -95,6 +100,43 @@ func TestRF1Only_UnsetKeepsReplicatedAdoption(t *testing.T) { // refusal (writes stay refused, no peers installed); only RF1 at the refused // epoch or newer, once its role is admitted, clears it. func TestRF1Only_StaleRF1FactDoesNotClearANewerRefusal(t *testing.T) { + f := newRF1BackendHost(t) + f.h.applyFact(rf1Fact(2)) + if f.a.callCount.Load() != 1 { + t.Fatal("fixture: RF1@2 not adopted") + } + f.mustWrite(t, 2, 0xD2) + f.h.applyFact(rf2PrimaryFact(3)) + f.assertRefusedAt(t, 3) + f.h.applyFact(rf1Fact(2)) // stale replay below the refused epoch + f.assertRefusedAt(t, 3) + if f.a.callCount.Load() != 1 || f.r.callCount.Load() != 1 { + t.Fatalf("stale RF1@2 adopted or RF2 peers installed: adopt=%d peerSets=%d", f.a.callCount.Load(), f.r.callCount.Load()) + } + f.fencer.fail.Store(true) // RF1@3 whose role fence fails: a failed attempt does not clear the refusal + f.h.applyFact(rf1Fact(3)) + if _, reason := f.h.RoleAdmissionFailure(); !strings.Contains(reason, "refuses a primary role") || f.a.callCount.Load() != 1 { + t.Fatalf("failed RF1@3 attempt cleared the refusal: %q adopt=%d", reason, f.a.callCount.Load()) + } + f.fencer.fail.Store(false) + f.h.applyFact(rf1Fact(3)) + if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 { + t.Fatalf("RF1@3 did not reconcile: %v %q adopt=%d", failed, reason, f.a.callCount.Load()) + } + f.mustWrite(t, 3, 0xD3) +} + +type rf1Fixture struct { + fencer *switchFencer + h *Host + a *stubAdapter + r *stubReplication + proj *mutableProjector + store *memorywal.Store +} + +func newRF1BackendHost(t *testing.T) *rf1Fixture { + t.Helper() h, a, r := newStubbedHost(t, "vol1", "r1", &orderingRecorder{}) h.cfg.RF1Only = "chunk snapshots need RF1" proj := &mutableProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 2, EndpointVersion: 1}} @@ -103,64 +145,33 @@ func TestRF1Only_StaleRF1FactDoesNotClearANewerRefusal(t *testing.T) { if err := h.SetSelfFence(fencer); err != nil { t.Fatal(err) } - rf1 := func(epoch uint64) *control.AssignmentFact { f := rf2PrimaryFact(epoch); f.Peers = nil; return f } - h.applyFact(rf1(2)) - if a.callCount.Load() != 1 { - t.Fatal("fixture: RF1@2 not adopted") - } store := memorywal.NewStore(8, 4096) t.Cleanup(func() { _ = store.Close() }) - backend := durable.NewStorageBackend(store, h.view, frontend.Identity{VolumeID: "vol1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1}) - backend.SetOperational(true, "rf1 baseline") - ctx := context.Background() - if _, err := backend.Write(ctx, 0, []byte("epoch-2")); err != nil { - t.Fatalf("baseline write: %v", err) - } - - h.applyFact(rf2PrimaryFact(3)) - if _, err := backend.Write(ctx, 0, []byte("x")); !errors.Is(err, frontend.ErrStalePrimary) { - t.Fatalf("write after the RF2@3 refusal: %v", err) - } - h.applyFact(rf1(2)) // stale replay below the refused epoch - if failed, reason := h.RoleAdmissionFailure(); !failed || !strings.Contains(reason, "at epoch 3") { - t.Fatalf("stale RF1@2 cleared the RF2@3 refusal: %v %q", failed, reason) - } - if _, err := backend.Write(ctx, 0, []byte("x")); !errors.Is(err, frontend.ErrStalePrimary) { - t.Fatalf("write reopened by a stale RF1@2: %v", err) - } - if a.callCount.Load() != 1 || r.callCount.Load() != 1 { - t.Fatalf("stale RF1@2 adopted or RF2 peers installed: adopt=%d peerSets=%d", a.callCount.Load(), r.callCount.Load()) - } - if len(r.lastTargetIDs) != 0 { - t.Fatalf("forbidden peers installed: %v", r.lastTargetIDs) - } - - fencer.fail.Store(true) // RF1@3 whose role fence fails: a failed attempt does not clear the refusal - h.applyFact(rf1(3)) - if _, reason := h.RoleAdmissionFailure(); !strings.Contains(reason, "refuses a primary role") || a.callCount.Load() != 1 { - t.Fatalf("failed RF1@3 attempt cleared the refusal: %q adopt=%d", reason, a.callCount.Load()) - } - fencer.fail.Store(false) - h.applyFact(rf1(3)) - if failed, reason := h.RoleAdmissionFailure(); failed || a.callCount.Load() != 2 { - t.Fatalf("RF1@3 did not reconcile: %v %q adopt=%d", failed, reason, a.callCount.Load()) - } + return &rf1Fixture{fencer: fencer, h: h, a: a, r: r, proj: proj, store: store} } -func newRF1BackendHost(t *testing.T) (*Host, *stubAdapter, *stubReplication, *durable.StorageBackend) { +// backend is a frontend at this epoch's identity, with the engine projection +// at that epoch (only called while no applyFact runs). +func (f *rf1Fixture) backend(epoch uint64) *durable.StorageBackend { + f.proj.p = engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: epoch, EndpointVersion: 1} + b := durable.NewStorageBackend(f.store, f.h.view, frontend.Identity{VolumeID: "vol1", ReplicaID: "r1", Epoch: epoch, EndpointVersion: 1}) + b.SetOperational(true, "rf1 fixture") + return b +} + +// mustWrite writes one block at the epoch's identity and reads it back. +func (f *rf1Fixture) mustWrite(t *testing.T, epoch uint64, fill byte) { t.Helper() - h, a, r := newStubbedHost(t, "vol1", "r1", &orderingRecorder{}) - h.cfg.RF1Only = "chunk snapshots need RF1" - proj := &mutableProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 2, EndpointVersion: 1}} - h.view = NewAdapterProjectionView(proj, "vol1", "r1", h) - if err := h.SetSelfFence(&switchFencer{}); err != nil { - t.Fatal(err) + ctx := context.Background() + b := f.backend(epoch) + data := bytes.Repeat([]byte{fill}, 4096) + if n, err := b.Write(ctx, 0, data); n != len(data) || err != nil { + t.Fatalf("write at epoch %d: n=%d err=%v", epoch, n, err) + } + got := make([]byte, len(data)) + if n, err := b.Read(ctx, 0, got); n != len(got) || err != nil || !bytes.Equal(got, data) { + t.Fatalf("readback at epoch %d: n=%d err=%v equal=%v", epoch, n, err, bytes.Equal(got, data)) } - store := memorywal.NewStore(8, 4096) - t.Cleanup(func() { _ = store.Close() }) - backend := durable.NewStorageBackend(store, h.view, frontend.Identity{VolumeID: "vol1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1}) - backend.SetOperational(true, "rf1 baseline") - return h, a, r, backend } func rf1Fact(epoch uint64) *control.AssignmentFact { @@ -169,65 +180,121 @@ func rf1Fact(epoch uint64) *control.AssignmentFact { return f } -// Concurrent schedule: an allowed RF1@2 replay passes the stale check, and -// before it admits, the stream latches an RF2@3 refusal. The replay must not -// clear that newer refusal nor adopt; writes stay refused. RF1@3 then admits. -func TestRF1Only_HeldRF1ReplayDoesNotClearANewerRefusal(t *testing.T) { - h, a, r, backend := newRF1BackendHost(t) - ctx := context.Background() - h.applyFact(rf1Fact(2)) - if _, err := backend.Write(ctx, 0, []byte("epoch-2")); err != nil || a.callCount.Load() != 1 { - t.Fatalf("baseline: adopt=%d write=%v", a.callCount.Load(), err) +func (f *rf1Fixture) assertRefusedAt(t *testing.T, epoch uint64) { + t.Helper() + if failed, reason := f.h.RoleAdmissionFailure(); !failed || !strings.Contains(reason, fmt.Sprintf("at epoch %d", epoch)) { + t.Fatalf("want the refusal at epoch %d latched: %v %q", epoch, failed, reason) } + if _, err := f.backend(epoch-1).Write(context.Background(), 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("write at the old identity after the refusal: %v", err) + } + if len(f.r.lastTargetIDs) != 0 { + t.Fatalf("forbidden peers installed: %v", f.r.lastTargetIDs) + } +} + +// Serial interleaving: an allowed RF1@2 replay passes the stale check, and +// before it admits, the stream latches an RF2@3 refusal. The replay must not +// clear that newer refusal nor adopt. RF1@3 then admits and serves at epoch 3. +func TestRF1Only_HeldRF1ReplayDoesNotClearANewerRefusal(t *testing.T) { + f := newRF1BackendHost(t) + f.h.applyFact(rf1Fact(2)) + f.mustWrite(t, 2, 0xA2) fired := false - h.rf1BeforeAdmit = func() { + f.h.rf1BeforeAdmit = func() { if !fired { fired = true - h.applyFact(rf2PrimaryFact(3)) // the stream, between the replay's check and its admit + f.h.applyFact(rf2PrimaryFact(3)) } } - h.applyFact(rf1Fact(2)) // the held replay - h.rf1BeforeAdmit = nil - if !fired { - t.Fatal("fixture: the replay did not reach the admit point") + f.h.applyFact(rf1Fact(2)) + f.h.rf1BeforeAdmit = nil + if !fired || f.a.callCount.Load() != 1 { + t.Fatalf("fixture fired=%v; held RF1@2 adopted=%d", fired, f.a.callCount.Load()) } - if failed, reason := h.RoleAdmissionFailure(); !failed || !strings.Contains(reason, "at epoch 3") { - t.Fatalf("held RF1@2 cleared the newer RF2@3 refusal: %v %q", failed, reason) + f.assertRefusedAt(t, 3) + f.h.applyFact(rf1Fact(3)) + if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 || f.a.lastInfo.Epoch != 3 { + t.Fatalf("current RF1@3 not admitted: %v %q adopt=%d", failed, reason, f.a.callCount.Load()) } - if a.callCount.Load() != 1 { - t.Fatalf("held RF1@2 adopted after the newer refusal: adopt=%d", a.callCount.Load()) + f.mustWrite(t, 3, 0xA3) +} + +// holdingUpdater parks the first armed UpdateReplicaSet until released. +type holdingUpdater struct { + inner replicaSetUpdater + armed atomic.Bool + entered, release chan struct{} +} + +func (u *holdingUpdater) UpdateReplicaSet(gen uint64, targets []replication.ReplicaTarget) error { + if u.armed.CompareAndSwap(true, false) { + close(u.entered) + <-u.release } - if _, err := backend.Write(ctx, 0, []byte("x")); !errors.Is(err, frontend.ErrStalePrimary) { - t.Fatalf("write after the newer refusal: %v", err) + return u.inner.UpdateReplicaSet(gen, targets) +} + +// Two workers: the replay worker's RF1@2 passes the stale check and parks in +// the peer-set update; the stream worker's RF2@3 is refused meanwhile; the +// replay then resumes. Bounded by timeouts. +func TestRF1Only_ParallelHeldReplayAndNewerRefusal(t *testing.T) { + f := newRF1BackendHost(t) + f.h.applyFact(rf1Fact(2)) + f.mustWrite(t, 2, 0xB2) + u := &holdingUpdater{inner: f.r, entered: make(chan struct{}), release: make(chan struct{})} + u.armed.Store(true) + f.h.replicationMu.Lock() + f.h.setReplicationLocked(u) + f.h.replicationMu.Unlock() + + replay := make(chan struct{}) + go func() { defer close(replay); f.h.applyFact(rf1Fact(2)) }() + select { + case <-u.entered: + case <-time.After(5 * time.Second): + t.Fatal("replay worker did not reach the peer-set update") } - if len(r.lastTargetIDs) != 0 { - t.Fatalf("forbidden peers installed: %v", r.lastTargetIDs) + stream := make(chan struct{}) + go func() { defer close(stream); f.h.applyFact(rf2PrimaryFact(3)) }() + select { + case <-stream: + case <-time.After(5 * time.Second): + t.Fatal("stream worker blocked behind the parked replay") } - h.applyFact(rf1Fact(3)) - if failed, reason := h.RoleAdmissionFailure(); failed || a.callCount.Load() != 2 { - t.Fatalf("current RF1@3 not admitted: %v %q adopt=%d", failed, reason, a.callCount.Load()) + close(u.release) + select { + case <-replay: + case <-time.After(5 * time.Second): + t.Fatal("replay worker did not finish") } + if f.a.callCount.Load() != 1 { + t.Fatalf("parked RF1@2 adopted after the newer refusal: adopt=%d", f.a.callCount.Load()) + } + f.assertRefusedAt(t, 3) + f.h.applyFact(rf1Fact(3)) + if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 { + t.Fatalf("current RF1@3 not admitted: %v %q", failed, reason) + } + f.mustWrite(t, 3, 0xB3) } // A stale RF2 below an admitted RF1 epoch does not re-latch the refusal. func TestRF1Only_StaleRF2AfterNewerRF1DoesNotRelatch(t *testing.T) { - h, a, _, backend := newRF1BackendHost(t) - ctx := context.Background() - h.applyFact(rf1Fact(2)) - h.applyFact(rf2PrimaryFact(3)) - h.applyFact(rf1Fact(4)) - if failed, reason := h.RoleAdmissionFailure(); failed || a.callCount.Load() != 2 { - t.Fatalf("RF1@4 not admitted: %v %q adopt=%d", failed, reason, a.callCount.Load()) + f := newRF1BackendHost(t) + f.h.applyFact(rf1Fact(2)) + f.h.applyFact(rf2PrimaryFact(3)) + f.h.applyFact(rf1Fact(4)) + if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 { + t.Fatalf("RF1@4 not admitted: %v %q adopt=%d", failed, reason, f.a.callCount.Load()) } - h.applyFact(rf2PrimaryFact(3)) // stale replay - if failed, reason := h.RoleAdmissionFailure(); failed { + f.h.applyFact(rf2PrimaryFact(3)) // stale replay + if failed, reason := f.h.RoleAdmissionFailure(); failed { t.Fatalf("stale RF2@3 re-latched after RF1@4: %q", reason) } - if _, err := backend.Write(ctx, 0, []byte("x")); errors.Is(err, frontend.ErrStalePrimary) { - t.Fatalf("stale RF2@3 stopped writes: %v", err) - } - h.applyFact(rf2PrimaryFact(4)) // same epoch, peers added: refused - if failed, _ := h.RoleAdmissionFailure(); !failed { + f.mustWrite(t, 4, 0xC4) + f.h.applyFact(rf2PrimaryFact(4)) // same epoch, peers added: refused + if failed, _ := f.h.RoleAdmissionFailure(); !failed { t.Fatal("RF2 at the admitted epoch not refused") } } From b46c31ccea8dc2593e78b418f9fec40626fe6715 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:33:33 -0800 Subject: [PATCH 014/150] volume: parallel RF1 test releases and joins its workers on every exit path Review fold (P2 cleanup, test only): an idempotent release and bounded joins of the started workers are registered with t.Cleanup before any worker starts, so a Fatal while the replay is parked cannot leave it running past teardown. A join timeout is reported as an error. Co-Authored-By: Claude Opus 5.5 --- .../core/host/volume/rf1_only_test.go | 30 +++++++++++++++++-- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/host/volume/rf1_only_test.go b/seaweed-block/core/host/volume/rf1_only_test.go index d4fb831e18..fd9b0b3b16 100644 --- a/seaweed-block/core/host/volume/rf1_only_test.go +++ b/seaweed-block/core/host/volume/rf1_only_test.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "strings" + "sync" "sync/atomic" "testing" "time" @@ -248,21 +249,44 @@ func TestRF1Only_ParallelHeldReplayAndNewerRefusal(t *testing.T) { f.h.setReplicationLocked(u) f.h.replicationMu.Unlock() - replay := make(chan struct{}) + // Registered before any worker starts: every exit path (including a Fatal + // below) releases the parked replay and joins both workers, bounded. + var once sync.Once + release := func() { once.Do(func() { close(u.release) }) } + replay, stream := make(chan struct{}), make(chan struct{}) + replayStarted, streamStarted := false, false + t.Cleanup(func() { + release() + for _, w := range []struct { + started bool + done chan struct{} + name string + }{{replayStarted, replay, "replay"}, {streamStarted, stream, "stream"}} { + if !w.started { + continue + } + select { + case <-w.done: + case <-time.After(5 * time.Second): + t.Errorf("%s worker did not finish after release", w.name) + } + } + }) + replayStarted = true go func() { defer close(replay); f.h.applyFact(rf1Fact(2)) }() select { case <-u.entered: case <-time.After(5 * time.Second): t.Fatal("replay worker did not reach the peer-set update") } - stream := make(chan struct{}) + streamStarted = true go func() { defer close(stream); f.h.applyFact(rf2PrimaryFact(3)) }() select { case <-stream: case <-time.After(5 * time.Second): t.Fatal("stream worker blocked behind the parked replay") } - close(u.release) + release() select { case <-replay: case <-time.After(5 * time.Second): From b1bfbb1dbbacdfd500a6a48a87d019867bde00f7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:56:59 -0800 Subject: [PATCH 015/150] chore: keep public PR changes to implementation and tests --- seaweed-block/docs/design/invariants.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5d8db88395..b032a37af0 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -469,12 +469,6 @@ Notes: |---|---|---|---|---|---|---| | `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | -### HEAD publication metadata cost - -| ID | Invariant | Transition | Enforced in | Regression test | Model | Status | -|---|---|---|---|---|---|---| -| `INV-WS-HEAD-ROOT-READ-001` | A HEAD CAS reads and validates only the root entry; immutable segment availability does not gate publication. Normal GetHead still resolves and verifies segments. | M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `getHeadRoot`, `CASHead` | `TestManifest_CASReadsOnlyRoot` | Cost/read-dependency property; no state or transition change to `CutPipeline` | ACTIVE | - ## Part C. Change rules How a fix or a feature is calibrated against this model: From 19195503eb5d4b77cc9217bc8a90a11a024d16df Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:57:17 -0800 Subject: [PATCH 016/150] chore: keep public PR changes to implementation and tests --- seaweed-block/docs/design/agent-workspace-design.md | 1 - seaweed-block/docs/design/invariants.md | 10 +--------- seaweed-block/docs/spec/CutPipeline.tla | 5 ----- 3 files changed, 1 insertion(+), 15 deletions(-) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index bef22a0ab8..48b9ca7a58 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -126,7 +126,6 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto 5. **LSN guard:** if H is below HEAD's `RemoteLSN`, refuse (`lsn_behind`). 6. **Diff:** upload only chunks whose SHA-256 differs from HEAD; drop all-zero chunks from the map. 7. **Intent first:** write an intent naming every key, then upload in parallel (`UploadConcurrency`, `--chunk-upload-concurrency`, default 8, 1 to 64). - Failed chunk uploads retry the same immutable key and captured bytes with 100 ms exponential backoff capped at 2 s. Resolve a possibly committed binding by exact-byte read-back before replay; a mismatch refuses the cut. All retries share a five-minute cut execution budget, shortened by the caller deadline. Queued lock wait and a remote ignoring cancellation are not forcibly terminated: workers remain joined before buffers/intents settle. Failure preserves dirt. HEAD CAS is never blindly replayed by this upload retry. 8. **Manifest:** build segments; new segments are also covered by an intent before upload (`PrepareManifest`). 9. **Re-admit** right before the CAS; fence if a superseding holder owns HEAD (`supersededBy`). 10. **CAS** HEAD on `{gen, epoch}` with `RemoteLSN = H`. On success, drop the intents and settle unchanged owned-map versions, keeping post-cut dirt. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e9dcfa760e..b032a37af0 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -194,8 +194,6 @@ stateDiagram-v2 Aborted --> Refused: drain owners, cleanup, merge candidates Copy --> Refused: H below HEAD RemoteLSN Closed --> Upload: drain and cleanup; intent durable first - Upload --> Upload: retry one immutable key after backoff - Upload --> Refused: shared deadline/cancel or mismatching binding Upload --> Manifest Manifest --> Readmit Readmit --> Fenced: superseding HEAD @@ -215,7 +213,7 @@ stateDiagram-v2 | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read into buffers; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | -| Upload | upload changed chunks after a durable intent names their write-once keys; retry one key under the shared five-minute cut execution deadline (or shorter caller deadline); resolve ambiguous bindings by exact-byte read-back before replay | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | +| Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after a durable intent names them | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | | Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | | No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001` | | Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-WS-HEAD-CAS-001` | @@ -471,12 +469,6 @@ Notes: |---|---|---|---|---|---|---| | `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | -### Cut upload retry - -| ID | Status | Invariant | Enforced in | Tests | Model | -|---|---|---|---|---|---| -| INV-CUT-UPLOAD-RETRY-001 | ACTIVE | A failed chunk upload retries the same key and captured bytes, keeps its intent, and cannot advance HEAD before completion; cancellation preserves dirt. | `chunk_upload.go` `putCaptured`; `chunk_layer.go` `captureLocked` | `TestChunkCutRetriesOnlyTheFailedUpload`, `TestChunkCutUploadCollisionNeverPublishes`, `TestChunkCutUploadRetryHonorsDeadlineAndRetainsDirt` | M5; retry stutters in abstract `CutPipeline`; timing and ambiguity are qualified by native tests. | - ## Part C. Change rules How a fix or a feature is calibrated against this model: diff --git a/seaweed-block/docs/spec/CutPipeline.tla b/seaweed-block/docs/spec/CutPipeline.tla index 166f466a8f..40367a642d 100644 --- a/seaweed-block/docs/spec/CutPipeline.tla +++ b/seaweed-block/docs/spec/CutPipeline.tla @@ -13,11 +13,6 @@ (* chunk is compared against HEAD; cuts are refused ("reconciling") *) (* until the compare finishes (chunk_layer.go:95); *) (* - a crash before the root CAS leaves only orphan uploads. *) -(* Per-object upload retries retain the same key/bytes and intent. Failed *) -(* attempts make no abstract state change (Spec permits stuttering); the *) -(* atomic Cut below still requires all objects before HEAD publication. *) -(* Backoff/deadline timing and ambiguous-reply byte checks are qualified *) -(* by native TestChunkCut*Upload* controls, not by this abstraction. *) (* Chunk content = the LSN of the write it holds. *) (***************************************************************************) EXTENDS Integers, FiniteSets, Sequences, TLC From 3e6e0c9603c225b3bc77b3fdd50b01a8d4ab8ce7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:13:32 -0800 Subject: [PATCH 017/150] blockvolume: correct the --chunk-dirty-threshold help text and comment The flag help and the ChunkDirtyThreshold comment still described the cut as it was before copy-before-write: "bound on one cut's barrier copy" and "0 = unbounded". Since the chunk copy moved out of the barrier, the value is the number of candidate chunks above which a cut pre-copies (stages) chunks before its barrier, in rounds of that size, and 0 disables pre-copy (chunk_layer.go, stage: a bound <= 0 returns without staging). Text only. No behaviour change. Co-Authored-By: Claude Fable 5.2 --- seaweed-block/cmd/blockvolume/main.go | 2 +- seaweed-block/core/frontend/durable/provider.go | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 96935591bd..1b55ae9c5d 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -193,7 +193,7 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)") fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: automatic cut once this long has passed since the last successful cut; 0 (default) disables the timer, e.g. 15m as a host-loss safety net") fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)") - fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", defaultChunkDirtyThreshold, "walstore-chunk: bound on one cut's barrier copy, in chunks; never triggers a cut; 0 = unbounded") + fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", defaultChunkDirtyThreshold, "walstore-chunk: number of candidate chunks above which a cut pre-copies (stages) chunks before its barrier, in rounds of this size; copy-before-write copies the rest outside the barrier; never triggers a cut; 0 = no pre-copy") fs.BoolVar(&f.chunk.controlEndpoint, "chunk-control-endpoint", false, "walstore-chunk: expose the /chunk/* control routes (cut, snapshot, snapshots, snapshot/delete, detach) on the status HTTP listener; off by default; loopback-only like the listener") fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)") fs.UintVar(&f.durableBlockSize, "durable-blocksize", 4096, "block size in bytes on first create") diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 1b9f8e565f..8b3395f381 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -157,10 +157,12 @@ type ProviderConfig struct { // passed since the volume's last successful cut (of any kind). Zero // disables the timer. ChunkCaptureInterval time.Duration - // ChunkDirtyThreshold is the bound on one cut's barrier copy, in - // chunks. It never triggers a cut: the remote holds snapshots, and - // cuts are published only by CaptureVolume, MakeVolumeRemoteDurable - // (snapshot, detach) and the timer. Zero: unbounded. + // ChunkDirtyThreshold is the number of candidate chunks above which + // a cut pre-copies (stages) chunks before its barrier, in rounds of + // this size; copy-before-write copies the rest outside the barrier. + // It never triggers a cut: the remote holds snapshots, and cuts are + // published only by CaptureVolume, MakeVolumeRemoteDurable + // (snapshot, detach) and the timer. Zero: no pre-copy. ChunkDirtyThreshold int // ChunkUploadConcurrency bounds remote uploads; zero defaults to 8. ChunkUploadConcurrency int From 3579e6dd42b0a03b34c00d87d20668df4783d488 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:56:33 -0800 Subject: [PATCH 018/150] test: distinguish successful key from failed upload retry --- .../core/storage/chunk_upload_retry_test.go | 53 +++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go index a03441690c..b553613f6f 100644 --- a/seaweed-block/core/storage/chunk_upload_retry_test.go +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -14,14 +14,21 @@ import ( // the real layer and the write-once fake remote. type retryUploadRemote struct { *fakeChunkRemote - mu sync.Mutex - mode string - calls map[string]int + mu sync.Mutex + mode string + calls map[string]int + values map[string]byte } func (r *retryUploadRemote) Put(ctx context.Context, key string, data []byte) error { r.mu.Lock() r.calls[key]++ + if r.values == nil { + r.values = map[string]byte{} + } + if len(data) > 0 { + r.values[key] = data[0] + } n, mode := r.calls[key], r.mode r.mu.Unlock() if mode == "down" || mode == "transient" && n == 1 { @@ -43,6 +50,46 @@ func (r *retryUploadRemote) Put(ctx context.Context, key string, data []byte) er return r.fakeChunkRemote.Put(ctx, key, data) } +func TestChunkCutMixedSuccessDoesNotReplaySuccessfulKey(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &retryUploadRemote{fakeChunkRemote: f, mode: "mixed", calls: map[string]int{}} + l := mustAttach(t, s, r, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 0, 0x41) + w.write(t, s, ctChunkBlocks, 0x42) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + assertEveryHeadIsPrefixImage(t, f, w) + if len(f.installedHeads()) != 1 { + t.Fatal("must publish once") + } + r.mu.Lock() + defer r.mu.Unlock() + if len(r.calls) != 2 { + t.Fatalf("changed immutable keys: %v", r.calls) + } + seen := map[byte]bool{} + for key, n := range r.calls { + value := r.values[key] + want := 1 + if value == 0x42 { + want = 2 + } + if value != 0x41 && value != 0x42 { + t.Fatalf("unexpected payload %x", value) + } + if n != want { + t.Fatalf("payload %x attempted %d times, want %d", value, n, want) + } + seen[value] = true + } + if len(seen) != 2 { + t.Fatal("did not exercise success and retry") + } +} + func TestChunkCutRetriesOnlyTheFailedUpload(t *testing.T) { for _, mode := range []string{"transient", "lost"} { t.Run(mode, func(t *testing.T) { From 9536ab0dd2d34cf70e70e2b5fd28e8c660d18587 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:57:51 -0800 Subject: [PATCH 019/150] test: bound shared staged cut budget and ordinary write progress --- .../core/storage/chunk_upload_budget_test.go | 149 ++++++++++++++++++ .../core/storage/chunk_upload_retry_test.go | 2 +- 2 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/storage/chunk_upload_budget_test.go diff --git a/seaweed-block/core/storage/chunk_upload_budget_test.go b/seaweed-block/core/storage/chunk_upload_budget_test.go new file mode 100644 index 0000000000..db6e60ef26 --- /dev/null +++ b/seaweed-block/core/storage/chunk_upload_budget_test.go @@ -0,0 +1,149 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "sync" + "testing" + "time" +) + +type cutBudgetRemote struct { + *fakeChunkRemote + mu sync.Mutex + keys []string + deadlines []time.Time + held chan struct{} + once sync.Once + healthy bool +} + +func (r *cutBudgetRemote) Put(ctx context.Context, key string, data []byte) error { + r.mu.Lock() + if r.healthy { + r.mu.Unlock() + return r.fakeChunkRemote.Put(ctx, key, data) + } + r.keys = append(r.keys, key) + d, ok := ctx.Deadline() + if !ok { + d = time.Time{} + } + r.deadlines = append(r.deadlines, d) + n := len(r.keys) + r.mu.Unlock() + if n >= 3 { + r.once.Do(func() { close(r.held) }) + <-ctx.Done() + return ctx.Err() + } + return r.fakeChunkRemote.Put(ctx, key, data) +} + +func TestChunkCutDefaultBudgetSharedAcrossStagesAndWritesProgress(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &cutBudgetRemote{fakeChunkRemote: f, held: make(chan struct{})} + cfg := ctConfig(1) + cfg.FreshFromHead = true + cfg.BarrierBound = 1 + cfg.UploadConcurrency = 2 + l := mustAttach(t, s, r, cfg).(*chunkLayerImpl) + for i := 0; i < 3; i++ { + if _, err := s.Write(uint32(i*ctChunkBlocks), makeBlock(ctBlockSize, byte(0x41+i))); err != nil { + t.Fatal(err) + } + } + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + joined := make(chan struct{}) + t.Cleanup(func() { + cancel() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("cut worker not joined") + } + }) + start := time.Now() + go func() { defer close(joined); _, err := l.Cut(ctx); done <- err }() + select { + case <-r.held: + case <-time.After(5 * time.Second): + t.Fatal("did not reach staged then final upload") + } + r.mu.Lock() + deadlines := append([]time.Time(nil), r.deadlines...) + r.mu.Unlock() + if len(deadlines) != 3 { + t.Fatalf("want two staged and one final upload: %v", deadlines) + } + if deadlines[0].IsZero() || deadlines[0].Sub(start) > 4*time.Second { + t.Fatalf("default cut budget exceeds sub-5s target: %v", deadlines[0].Sub(start)) + } + for _, d := range deadlines { + if !d.Equal(deadlines[0]) { + t.Fatal("stage/worker received a reset budget") + } + } + writeDone := make(chan error, 1) + writeJoined := make(chan struct{}) + t.Cleanup(func() { + cancel() + select { + case <-writeJoined: + case <-time.After(5 * time.Second): + t.Error("ordinary write not joined") + } + }) + go func() { + defer close(writeJoined) + _, err := s.Write(3*ctChunkBlocks, makeBlock(ctBlockSize, 0x44)) + if err == nil { + _, err = s.Sync() + } + writeDone <- err + }() + select { + case err := <-writeDone: + if err != nil { + t.Fatal(err) + } + case err := <-done: + t.Fatalf("ordinary write waited for remote cut settlement: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("ordinary write blocked") + } + select { + case err := <-done: + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("lost default deadline: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("cooperative cut did not settle") + } + if time.Since(start) >= 5*time.Second { + t.Fatal("cut exceeded sub-5s target") + } + if len(f.installedHeads()) != 0 { + t.Fatal("outage published HEAD") + } + r.mu.Lock() + r.healthy = true + r.mu.Unlock() + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + heads := f.installedHeads() + if len(heads) != 1 { + t.Fatal("retry did not publish exactly once") + } + want := make([]byte, ctNumBlocks*ctBlockSize) + for i := 0; i < 4; i++ { + copy(want[i*ctChunkBlocks*ctBlockSize:], makeBlock(ctBlockSize, byte(0x41+i))) + } + if !bytes.Equal(f.imageOf(t, heads[0]), want) { + t.Fatal("shared-budget abort lost pending/concurrent bytes") + } +} diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go index b553613f6f..c243b2aee8 100644 --- a/seaweed-block/core/storage/chunk_upload_retry_test.go +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -31,7 +31,7 @@ func (r *retryUploadRemote) Put(ctx context.Context, key string, data []byte) er } n, mode := r.calls[key], r.mode r.mu.Unlock() - if mode == "down" || mode == "transient" && n == 1 { + if mode == "down" || mode == "transient" && n == 1 || mode == "mixed" && n == 1 && len(data) > 0 && data[0] == 0x42 { return errFakeRemoteDown } if mode == "lost" && n == 1 { From d67368a9899f71c73800bdec53edf75894db30ae Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:59:12 -0800 Subject: [PATCH 020/150] fix: shorten shared cut retry budget and bound test worker cleanup --- seaweed-block/core/storage/chunk_layer.go | 2 +- .../storage/chunk_upload_parallel_test.go | 51 ++++++++++++++----- 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index ffee0274f9..f9d8e20733 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -803,7 +803,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // Retries share one cut budget, shortened by the caller's own deadline. // As with every remote operation, an implementation ignoring cancellation // is still joined before buffers and intents are settled. - ctx, deadlineCancel := context.WithTimeout(ctx, 5*time.Minute) + ctx, deadlineCancel := context.WithTimeout(ctx, 2*time.Second) defer deadlineCancel() done, err := l.register() if err != nil { diff --git a/seaweed-block/core/storage/chunk_upload_parallel_test.go b/seaweed-block/core/storage/chunk_upload_parallel_test.go index 3cad929a6c..7bb842c9f2 100644 --- a/seaweed-block/core/storage/chunk_upload_parallel_test.go +++ b/seaweed-block/core/storage/chunk_upload_parallel_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "sync" "sync/atomic" "testing" "time" @@ -105,16 +106,22 @@ type unjoinedUploadRemote struct { second chan struct{} failed chan struct{} release chan struct{} + settled chan struct{} } func (r *unjoinedUploadRemote) Put(ctx context.Context, key string, data []byte) error { switch r.calls.Add(1) { case 1: - <-r.second + select { + case <-r.second: + case <-ctx.Done(): + return ctx.Err() + } close(r.failed) return errFakeRemoteDown case 2: close(r.second) + defer close(r.settled) default: return errFakeRemoteDown } @@ -124,7 +131,7 @@ func (r *unjoinedUploadRemote) Put(ctx context.Context, key string, data []byte) func TestChunkUploads_FailureJoinsBeforeIntentCleanup(t *testing.T) { s, _ := newChunkTestStore(t) f := newFakeChunkRemote() - r := &unjoinedUploadRemote{fakeChunkRemote: f, second: make(chan struct{}), failed: make(chan struct{}), release: make(chan struct{})} + r := &unjoinedUploadRemote{fakeChunkRemote: f, second: make(chan struct{}), failed: make(chan struct{}), release: make(chan struct{}), settled: make(chan struct{})} cfg := ctConfig(1) cfg.FreshFromHead = true cfg.UploadConcurrency = 2 @@ -133,31 +140,51 @@ func TestChunkUploads_FailureJoinsBeforeIntentCleanup(t *testing.T) { w.write(t, s, 0, 0x21) w.write(t, s, ctChunkBlocks, 0x22) ctx, cancel := context.WithCancel(context.Background()) - defer cancel() done := make(chan error, 1) - go func() { _, err := l.Cut(ctx); done <- err }() + joined := make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(r.release) }) } + t.Cleanup(func() { + cancel() + release() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("cut worker not joined") + } + select { + case <-r.second: + select { + case <-r.settled: + case <-time.After(5 * time.Second): + t.Error("owned upload not joined") + } + default: + } + }) + go func() { defer close(joined); _, err := l.Cut(ctx); done <- err }() select { case <-r.failed: cancel() // retries are now allowed; terminate this cut explicitly case <-time.After(time.Second): - close(r.release) - <-done t.Fatal("uploads did not overlap") } select { case err := <-done: - close(r.release) t.Fatalf("returned with owned upload still active: %v", err) case <-time.After(20 * time.Millisecond): } if len(liveIntents(t, f)) == 0 { - close(r.release) - <-done t.Fatal("intent removed before join") } - close(r.release) - if err := <-done; !errors.Is(err, errFakeRemoteDown) { - t.Fatalf("lost upload failure: %v", err) + release() + select { + case err := <-done: + if !errors.Is(err, errFakeRemoteDown) { + t.Fatalf("lost upload failure: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("cut completion not joined") } if f.stats().cas != 0 { t.Fatal("failed batch published") From 953d2795b846789245bda4c30047c3aaa9e65a87 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:01:02 -0800 Subject: [PATCH 021/150] test: qualify BASE waiting behind an interrupted upload --- .../storage/chunk_upload_base_budget_test.go | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_upload_base_budget_test.go diff --git a/seaweed-block/core/storage/chunk_upload_base_budget_test.go b/seaweed-block/core/storage/chunk_upload_base_budget_test.go new file mode 100644 index 0000000000..1e0d8ff462 --- /dev/null +++ b/seaweed-block/core/storage/chunk_upload_base_budget_test.go @@ -0,0 +1,82 @@ +package storage + +import ( + "context" + "errors" + "testing" + "time" +) + +func TestChunkUploadOutageSettlesBeforeQueuedBASE(t *testing.T) { + s, f, l := mappedBASELayerV3(t) + if _, err := s.Write(5, blk(0x31)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + entered, release := holdPuts(t, f) + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + cutDone := make(chan error, 1) + cutJoined := make(chan struct{}) + var baseJoined chan struct{} + t.Cleanup(func() { + cancel() + release() + select { + case <-cutJoined: + case <-time.After(5 * time.Second): + t.Error("cut not joined") + } + if baseJoined != nil { + select { + case <-baseJoined: + case <-time.After(5 * time.Second): + t.Error("BASE worker not joined") + } + } + }) + start := time.Now() + go func() { defer close(cutJoined); _, err := l.Cut(ctx); cutDone <- err }() + waitKey(t, entered, "cooperative cut upload") + attempted := make(chan struct{}) + l.testBaseTransitionBeforeLock = func() { close(attempted) } + baseJoined = make(chan struct{}) + type result struct { + h InstallHandle + err error + } + baseDone := make(chan result, 1) + go func() { defer close(baseJoined); h, err := s.BeginBaseInstall(7, idA); baseDone <- result{h, err} }() + select { + case <-attempted: + case <-time.After(5 * time.Second): + t.Fatal("BASE did not reach cut drain") + } + select { + case err := <-cutDone: + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("cut deadline: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("cooperative cut not settled") + } + var got result + select { + case got = <-baseDone: + case <-time.After(5 * time.Second): + t.Fatal("BASE did not proceed after cut settlement") + } + if got.err != nil { + t.Fatal(got.err) + } + if time.Since(start) >= 5*time.Second { + t.Fatal("single queued BASE exceeded sub-5s target") + } + if len(f.installedHeads()) != 0 { + t.Fatal("failed upload published HEAD") + } + if err := got.h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } +} From 42d30e06274d1de7c607874db927c0c9a8e52963 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:04:46 -0800 Subject: [PATCH 022/150] test: retire BASE begin hook before completion transition --- seaweed-block/core/storage/chunk_upload_base_budget_test.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/seaweed-block/core/storage/chunk_upload_base_budget_test.go b/seaweed-block/core/storage/chunk_upload_base_budget_test.go index 1e0d8ff462..f52f4d8ea1 100644 --- a/seaweed-block/core/storage/chunk_upload_base_budget_test.go +++ b/seaweed-block/core/storage/chunk_upload_base_budget_test.go @@ -76,6 +76,12 @@ func TestChunkUploadOutageSettlesBeforeQueuedBASE(t *testing.T) { if len(f.installedHeads()) != 0 { t.Fatal("failed upload published HEAD") } + select { + case <-baseJoined: + case <-time.After(5 * time.Second): + t.Fatal("BASE begin worker not joined") + } + l.testBaseTransitionBeforeLock = nil if err := got.h.MarkBaseComplete(); err != nil { t.Fatal(err) } From aea5f5d88bf1d849293c8a91045c8bbd2852096c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:15:38 -0800 Subject: [PATCH 023/150] test: observe mixed-arm counts before the generic overwrite oracle --- seaweed-block/core/storage/chunk_upload_retry_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go index c243b2aee8..f946ca0be0 100644 --- a/seaweed-block/core/storage/chunk_upload_retry_test.go +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -61,7 +61,6 @@ func TestChunkCutMixedSuccessDoesNotReplaySuccessfulKey(t *testing.T) { if _, err := l.Cut(ctTimeout(t)); err != nil { t.Fatal(err) } - assertEveryHeadIsPrefixImage(t, f, w) if len(f.installedHeads()) != 1 { t.Fatal("must publish once") } @@ -88,6 +87,7 @@ func TestChunkCutMixedSuccessDoesNotReplaySuccessfulKey(t *testing.T) { if len(seen) != 2 { t.Fatal("did not exercise success and retry") } + assertEveryHeadIsPrefixImage(t, f, w) } func TestChunkCutRetriesOnlyTheFailedUpload(t *testing.T) { From 6a2bd2a4e3e8ed5770dfbec1e655edc0d6d689c5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:29:37 -0800 Subject: [PATCH 024/150] test: refuse unknown published segment fields --- .../chunkstore/format_upgrade_test.go | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/format_upgrade_test.go diff --git a/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go b/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go new file mode 100644 index 0000000000..4a7dd08854 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go @@ -0,0 +1,38 @@ +package chunkstore + +import ( + "bytes" + "context" + "crypto/sha256" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestManifestFormatUpgradeRefusesUnknownSegmentField(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + r, h := publishSegmented(t, f, b) + ctx := context.Background() + if _, err := r.GetHead(ctx); err != nil { + t.Fatalf("valid legacy segment refused: %v", err) + } + ref := h.Segments[0] + body, err := r.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + // Keep the object hash valid: the refusal must come from the segment schema. + body = append(bytes.TrimSuffix(body, []byte("}")), []byte(",\"future_encoding\":\"unsupported\"}")...) + if err := r.Put(ctx, "format-upgrade-unknown-field", body); err != nil { + t.Fatal(err) + } + ref.Key = qualifyManifestKey(ref.Owner, "format-upgrade-unknown-field") + ref.SHA256 = sha256.Sum256(body) + h.Segments[0] = ref + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, h); err != nil { + t.Fatal(err) + } + if _, err := r.GetHead(ctx); err == nil { + t.Fatal("published segment with unknown field accepted") + } +} From 2e8954aae0c77f1fb0f779100e1d30a482cb193d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:30:03 -0800 Subject: [PATCH 025/150] fix: decode published segment fields strictly --- seaweed-block/core/frontend/chunkstore/manifest.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/seaweed-block/core/frontend/chunkstore/manifest.go b/seaweed-block/core/frontend/chunkstore/manifest.go index 9a4708655d..fa82cae3ce 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest.go +++ b/seaweed-block/core/frontend/chunkstore/manifest.go @@ -165,6 +165,11 @@ func (r *ChunkRemote) resolveManifest(ctx context.Context, h storage.ChunkHead) if err := decodeManifestJSON(body, &doc); err != nil { return h, err } + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&doc); err != nil { + return h, err + } if doc.Format != 1 || doc.Range != group || doc.ChunkBytes != h.ChunkBytes || doc.Owner != ref.Owner || len(doc.Chunks) != ref.Count { return h, errors.New("chunkstore: invalid segment contents") } From d9e5f7c9fa3894e78d5a832fbf55dacfc336cbde Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:42:23 -0800 Subject: [PATCH 026/150] fix: bound individual upload retries without timing out whole cuts --- seaweed-block/core/storage/chunk_layer.go | 5 -- seaweed-block/core/storage/chunk_upload.go | 7 +- .../core/storage/chunk_upload_budget_test.go | 11 +-- .../core/storage/chunk_upload_retry_test.go | 32 +++++++++ .../storage/chunk_upload_slow_cut_test.go | 68 +++++++++++++++++++ 5 files changed, 112 insertions(+), 11 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_upload_slow_cut_test.go diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index f9d8e20733..3f508fed75 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -800,11 +800,6 @@ type stagedChunk struct { const chunkStageRounds = 3 func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res chunkCutResult, err error) { - // Retries share one cut budget, shortened by the caller's own deadline. - // As with every remote operation, an implementation ignoring cancellation - // is still joined before buffers and intents are settled. - ctx, deadlineCancel := context.WithTimeout(ctx, 2*time.Second) - defer deadlineCancel() done, err := l.register() if err != nil { return chunkCutResult{}, err diff --git a/seaweed-block/core/storage/chunk_upload.go b/seaweed-block/core/storage/chunk_upload.go index 7a623ac315..ff71412b44 100644 --- a/seaweed-block/core/storage/chunk_upload.go +++ b/seaweed-block/core/storage/chunk_upload.go @@ -11,10 +11,12 @@ import ( // putCaptured retries one immutable object, never a whole batch or HEAD CAS. // A lost binding reply can turn the next attempt into KeyExists: only exact // bytes read from that binding prove completion; a collision is terminal. +// Bound attempts per object, without imposing a deadline on legitimate work +// across the whole cut. All attempts still obey the caller's context. func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byte) error { backoff := 100 * time.Millisecond var lastErr error - for { + for attempt := 1; ; attempt++ { if err := ctx.Err(); err != nil { return errors.Join(lastErr, err) } @@ -31,6 +33,9 @@ func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byt } return errChunkKeyExists } + if attempt == 3 { + return lastErr + } timer := time.NewTimer(backoff) select { case <-ctx.Done(): diff --git a/seaweed-block/core/storage/chunk_upload_budget_test.go b/seaweed-block/core/storage/chunk_upload_budget_test.go index db6e60ef26..836b7a9275 100644 --- a/seaweed-block/core/storage/chunk_upload_budget_test.go +++ b/seaweed-block/core/storage/chunk_upload_budget_test.go @@ -41,7 +41,7 @@ func (r *cutBudgetRemote) Put(ctx context.Context, key string, data []byte) erro return r.fakeChunkRemote.Put(ctx, key, data) } -func TestChunkCutDefaultBudgetSharedAcrossStagesAndWritesProgress(t *testing.T) { +func TestChunkCutCallerBudgetSharedAcrossStagesAndWritesProgress(t *testing.T) { s, _ := newChunkTestStore(t) f := newFakeChunkRemote() r := &cutBudgetRemote{fakeChunkRemote: f, held: make(chan struct{})} @@ -55,7 +55,7 @@ func TestChunkCutDefaultBudgetSharedAcrossStagesAndWritesProgress(t *testing.T) t.Fatal(err) } } - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) done := make(chan error, 1) joined := make(chan struct{}) t.Cleanup(func() { @@ -79,8 +79,9 @@ func TestChunkCutDefaultBudgetSharedAcrossStagesAndWritesProgress(t *testing.T) if len(deadlines) != 3 { t.Fatalf("want two staged and one final upload: %v", deadlines) } - if deadlines[0].IsZero() || deadlines[0].Sub(start) > 4*time.Second { - t.Fatalf("default cut budget exceeds sub-5s target: %v", deadlines[0].Sub(start)) + wantDeadline, _ := ctx.Deadline() + if !deadlines[0].Equal(wantDeadline) { + t.Fatalf("cut replaced caller's deadline: %v, want %v", deadlines[0], wantDeadline) } for _, d := range deadlines { if !d.Equal(deadlines[0]) { @@ -118,7 +119,7 @@ func TestChunkCutDefaultBudgetSharedAcrossStagesAndWritesProgress(t *testing.T) select { case err := <-done: if !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("lost default deadline: %v", err) + t.Fatalf("lost caller deadline: %v", err) } case <-time.After(5 * time.Second): t.Fatal("cooperative cut did not settle") diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go index f946ca0be0..d8d2419af6 100644 --- a/seaweed-block/core/storage/chunk_upload_retry_test.go +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -164,6 +164,38 @@ func TestChunkCutUploadRetryHonorsDeadlineAndRetainsDirt(t *testing.T) { assertEveryHeadIsPrefixImage(t, f, w) } +func TestChunkCutUploadAttemptBoundRetainsDirt(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &retryUploadRemote{fakeChunkRemote: f, mode: "down", calls: map[string]int{}} + layer := mustAttach(t, s, r, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 0, 0x51) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := layer.Cut(ctx); err == nil { + t.Fatal("persistent upload outage published") + } + r.mu.Lock() + if len(r.calls) != 1 { + t.Fatalf("retry changed object keys: %v", r.calls) + } + for _, n := range r.calls { + if n != 3 { + t.Errorf("single object attempted %d times, want bounded 3", n) + } + } + r.mode = "ok" + r.mu.Unlock() + if len(f.installedHeads()) != 0 { + t.Fatal("failed object published HEAD") + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + assertEveryHeadIsPrefixImage(t, f, w) +} + func TestChunkCutRetrySustainedWritesPastWALWithFlush(t *testing.T) { const walBytes = 64 * 1024 s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), ctNumBlocks, ctBlockSize, walBytes, WModeStrict, ctChunkBlocks) diff --git a/seaweed-block/core/storage/chunk_upload_slow_cut_test.go b/seaweed-block/core/storage/chunk_upload_slow_cut_test.go new file mode 100644 index 0000000000..7f2fd7e4be --- /dev/null +++ b/seaweed-block/core/storage/chunk_upload_slow_cut_test.go @@ -0,0 +1,68 @@ +package storage + +import ( + "bytes" + "context" + "testing" + "time" +) + +type slowSuccessfulUploadRemote struct{ *fakeChunkRemote } + +func (r *slowSuccessfulUploadRemote) Put(ctx context.Context, key string, data []byte) error { + timer := time.NewTimer(600 * time.Millisecond) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return r.fakeChunkRemote.Put(ctx, key, data) + } +} + +func TestChunkCutLegitimateUploadsExceedTwoSeconds(t *testing.T) { + for _, detach := range []bool{false, true} { + name := "cut" + if detach { + name = "detach" + } + t.Run(name, func(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &slowSuccessfulUploadRemote{f} + cfg := ctConfig(1) + cfg.UploadConcurrency = 1 + l := mustAttach(t, s, r, cfg).(*chunkLayerImpl) + want := make([]byte, ctNumBlocks*ctBlockSize) + for i := 0; i < 5; i++ { + data := makeBlock(ctBlockSize, byte(0x41+i)) + if _, err := s.Write(uint32(i*ctChunkBlocks), data); err != nil { + t.Fatal(err) + } + copy(want[i*ctChunkBlocks*ctBlockSize:], data) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + start := time.Now() + var err error + if detach { + _, err = l.Detach(ctx) + } else { + _, err = l.Cut(ctx) + } + if err != nil { + t.Fatalf("legitimate multi-object work canceled: %v", err) + } + if time.Since(start) <= 2*time.Second { + t.Fatal("fixture did not exceed the former whole-cut limit") + } + heads := f.installedHeads() + if len(heads) != 1 || !bytes.Equal(f.imageOf(t, heads[0]), want) { + t.Fatal("slow successful cut did not publish the exact image once") + } + if detach && heads[0].State != ChunkHeadDetached { + t.Fatal("slow detach did not install detached proof") + } + }) + } +} From 66c7dd78cd70872da2845ef74f3b27bd1f98110c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:58:53 -0800 Subject: [PATCH 027/150] feat: version segmented HEAD and stored-byte chunk references --- .../core/frontend/chunkstore/chunk_remote.go | 8 +- .../chunkstore/format_upgrade_test.go | 54 +++++++++ .../core/frontend/chunkstore/head_decode.go | 51 ++++++++- .../core/frontend/chunkstore/manifest.go | 31 ++++-- .../frontend/chunkstore/manifest_format.go | 105 ++++++++++++++++++ seaweed-block/core/storage/chunk_manifest.go | 10 +- seaweed-block/core/storage/chunk_seam.go | 8 +- 7 files changed, 243 insertions(+), 24 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/manifest_format.go diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index e204667cdc..d472f59e6a 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -339,6 +339,7 @@ func decodeIntent(p string, e *filerpb.Entry) (storage.ChunkIntent, error) { } type headDoc struct { + Levels int `json:"levels,omitempty"` Segments map[uint64]storage.ChunkSegment `json:"segments,omitempty"` ChunkBytes uint64 `json:"chunk_bytes,omitempty"` ChunkCount int `json:"chunk_count,omitempty"` @@ -457,7 +458,8 @@ func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) { if err := validateRoot(h); err != nil { return nil, err } - doc.Format = 2 + doc.Format = 3 + doc.Levels = 1 doc.Chunks = nil doc.Segments = h.Segments doc.ChunkBytes = h.ChunkBytes @@ -561,11 +563,11 @@ func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) { if err != nil || len(sum) != 32 || ref.Key == "" { return fail("chunk %d ref invalid", idx) } - cr := storage.ChunkRef{Key: ref.Key} + cr := storage.ChunkRef{Key: ref.Key, Encoding: "full", BirthLSN: doc.RemoteLSN} copy(cr.SHA256[:], sum) h.Chunks[idx] = cr } - if doc.Format == 2 { + if doc.Format == 2 || doc.Format == 3 { if len(doc.Chunks) != 0 { return fail("segmented root contains flat chunks") } diff --git a/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go b/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go index 4a7dd08854..4797adfd75 100644 --- a/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go +++ b/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go @@ -4,11 +4,65 @@ import ( "bytes" "context" "crypto/sha256" + "encoding/json" + "path" "testing" "github.com/seaweedfs/seaweed-block/core/storage" ) +func TestManifestFormatUpgradeWritesVersionedStoredByteReferences(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + r, h := publishSegmented(t, f, b) + ctx := context.Background() + entry, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName) + if err != nil { + t.Fatal(err) + } + var root struct { + Format int `json:"format"` + Levels int `json:"levels"` + Segments map[string]struct { + Format int `json:"seg_format"` + Max uint64 `json:"max_birth_lsn"` + } `json:"segments"` + } + if err := json.Unmarshal(entry.Content, &root); err != nil { + t.Fatal(err) + } + if root.Format != 3 || root.Levels != 1 || root.Segments["0"].Format != 2 || root.Segments["0"].Max != h.RemoteLSN { + t.Fatalf("missing format3/levels/segment2 metadata: %s", entry.Content) + } + body, err := r.Get(ctx, h.Segments[0].Key) + if err != nil { + t.Fatal(err) + } + var segment struct { + Format int `json:"format"` + Max uint64 `json:"max_birth_lsn"` + Chunks map[string]struct { + Encoding string `json:"enc"` + Birth uint64 `json:"birth_lsn"` + Hash string `json:"sha256"` + } `json:"chunks"` + } + if err := json.Unmarshal(body, &segment); err != nil { + t.Fatal(err) + } + if segment.Format != 2 || segment.Max != h.RemoteLSN || len(segment.Chunks) != 2 { + t.Fatalf("missing segment format/max: %s", body) + } + for _, ref := range segment.Chunks { + if ref.Encoding != "full" || ref.Birth != h.RemoteLSN || len(ref.Hash) != 64 { + t.Fatalf("invalid inherited chunk reference: %+v", ref) + } + } + resolved, err := r.GetHead(ctx) + if err != nil || len(resolved.Chunks) != 2 { + t.Fatalf("format3 roundtrip: %+v %v", resolved, err) + } +} + func TestManifestFormatUpgradeRefusesUnknownSegmentField(t *testing.T) { f, b, _, _, _ := gcFixture(t) r, h := publishSegmented(t, f, b) diff --git a/seaweed-block/core/frontend/chunkstore/head_decode.go b/seaweed-block/core/frontend/chunkstore/head_decode.go index fca0c37eff..699259088b 100644 --- a/seaweed-block/core/frontend/chunkstore/head_decode.go +++ b/seaweed-block/core/frontend/chunkstore/head_decode.go @@ -26,9 +26,30 @@ type flatHeadDoc struct { } type segmentedHeadDoc struct { headIdentityDoc - Segments map[uint64]storage.ChunkSegment `json:"segments"` - ChunkBytes uint64 `json:"chunk_bytes"` - ChunkCount int `json:"chunk_count"` + Segments map[uint64]legacySegmentRefDoc `json:"segments"` + ChunkBytes uint64 `json:"chunk_bytes"` + ChunkCount int `json:"chunk_count"` +} + +type legacySegmentRefDoc struct { + Key string `json:"key"` + SHA256 [32]byte `json:"sha256"` + Owner string `json:"owner"` + Count int `json:"count"` +} + +type segmentRefV3Doc struct { + legacySegmentRefDoc + MaxBirthLSN *uint64 `json:"max_birth_lsn"` + SegFormat int `json:"seg_format"` +} + +type levelHeadDoc struct { + headIdentityDoc + Levels int `json:"levels"` + Segments map[uint64]segmentRefV3Doc `json:"segments"` + ChunkBytes uint64 `json:"chunk_bytes"` + ChunkCount int `json:"chunk_count"` } func (d headIdentityDoc) document() headDoc { @@ -61,7 +82,29 @@ func decodeFormatHead(content []byte) (headDoc, error) { return headDoc{}, err } doc := segmented.headIdentityDoc.document() - doc.Segments, doc.ChunkBytes, doc.ChunkCount = segmented.Segments, segmented.ChunkBytes, segmented.ChunkCount + doc.Segments = make(map[uint64]storage.ChunkSegment, len(segmented.Segments)) + for group, ref := range segmented.Segments { + doc.Segments[group] = storage.ChunkSegment{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count, SegFormat: 1, MaxBirthLSN: doc.RemoteLSN} + } + doc.ChunkBytes, doc.ChunkCount = segmented.ChunkBytes, segmented.ChunkCount + return doc, nil + case 3: + var root levelHeadDoc + if err := decoder.Decode(&root); err != nil { + return headDoc{}, err + } + if root.Levels != 1 { + return headDoc{}, fmt.Errorf("chunkstore: unsupported levels %d", root.Levels) + } + doc := root.headIdentityDoc.document() + doc.Levels, doc.ChunkBytes, doc.ChunkCount = root.Levels, root.ChunkBytes, root.ChunkCount + doc.Segments = make(map[uint64]storage.ChunkSegment, len(root.Segments)) + for group, ref := range root.Segments { + if ref.MaxBirthLSN == nil || (ref.SegFormat != 1 && ref.SegFormat != 2) || *ref.MaxBirthLSN > root.RemoteLSN { + return headDoc{}, fmt.Errorf("chunkstore: invalid segment version/birth maximum") + } + doc.Segments[group] = storage.ChunkSegment{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count, SegFormat: ref.SegFormat, MaxBirthLSN: *ref.MaxBirthLSN} + } return doc, nil default: return headDoc{}, fmt.Errorf("chunkstore: unsupported HEAD format %d", discriminator.Format) diff --git a/seaweed-block/core/frontend/chunkstore/manifest.go b/seaweed-block/core/frontend/chunkstore/manifest.go index fa82cae3ce..ee525f2213 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest.go +++ b/seaweed-block/core/frontend/chunkstore/manifest.go @@ -48,6 +48,9 @@ func validateRoot(h storage.ChunkHead) error { } count := 0 for group, ref := range h.Segments { + if (ref.SegFormat != 1 && ref.SegFormat != 2) || ref.MaxBirthLSN > h.RemoteLSN { + return errors.New("chunkstore: invalid segment version/birth maximum") + } if CheckVolumeID(ref.Owner) != nil || storage.ValidChunkKey(ref.Key) != nil || ref.Count <= 0 || uint64(ref.Count) > manifestSegmentBytes/h.ChunkBytes || group > ^uint64(0)/(manifestSegmentBytes/h.ChunkBytes) { return errors.New("chunkstore: invalid segment reference") } @@ -76,6 +79,12 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch groups := map[uint64]map[uint64]storage.ChunkRef{} canonical := make(map[uint64]storage.ChunkRef, len(next.Chunks)) for idx, ref := range next.Chunks { + if ref.Encoding == "" { + ref.Encoding, ref.BirthLSN = "full", next.RemoteLSN + } + if ref.Encoding != "full" || ref.BirthLSN > next.RemoteLSN { + return next, nil, errors.New("chunkstore: invalid chunk encoding/birth") + } ref.Key = qualifyManifestKey(owner, ref.Key) canonical[idx] = ref group := idx / per @@ -94,6 +103,9 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch // segment group. Keep the same qualified-key comparison for segment reuse. baseGroups := map[uint64]map[uint64]storage.ChunkRef{} for idx, ref := range base.Chunks { + if ref.Encoding == "" { + ref.Encoding, ref.BirthLSN = "full", base.RemoteLSN + } group := idx / per if baseGroups[group] == nil { baseGroups[group] = map[uint64]storage.ChunkRef{} @@ -104,10 +116,14 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch for group, chunks := range groups { old := baseGroups[group] if previous, ok := base.Segments[group]; ok && base.ChunkBytes == chunkBytes && reflect.DeepEqual(chunks, old) { + // Legacy groups keep a conservative upper bound until rewritten. + if previous.SegFormat == 0 { + previous.SegFormat, previous.MaxBirthLSN = 1, base.RemoteLSN + } next.Segments[group] = previous continue } - body, err := json.Marshal(segmentDoc{1, group, chunkBytes, owner, chunks}) + body, maxBirth, err := encodeSegmentV2(group, chunkBytes, owner, chunks) if err != nil { return next, nil, err } @@ -119,7 +135,7 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch return next, nil, err } key := fmt.Sprintf("seg/%x", nonce) - next.Segments[group] = storage.ChunkSegment{Key: qualifyManifestKey(owner, key), SHA256: sha256.Sum256(body), Owner: owner, Count: len(chunks)} + next.Segments[group] = storage.ChunkSegment{Key: qualifyManifestKey(owner, key), SHA256: sha256.Sum256(body), Owner: owner, Count: len(chunks), SegFormat: 2, MaxBirthLSN: maxBirth} uploads = append(uploads, upload{key, body}) } if err := validateRoot(next); err != nil { @@ -161,16 +177,11 @@ func (r *ChunkRemote) resolveManifest(ctx context.Context, h storage.ChunkHead) if len(body) > maxManifestBytes || sha256.Sum256(body) != ref.SHA256 { return h, errors.New("chunkstore: segment hash/size mismatch") } - var doc segmentDoc - if err := decodeManifestJSON(body, &doc); err != nil { + doc, err := decodeSegment(body, ref, h.RemoteLSN) + if err != nil { return h, err } - decoder := json.NewDecoder(bytes.NewReader(body)) - decoder.DisallowUnknownFields() - if err := decoder.Decode(&doc); err != nil { - return h, err - } - if doc.Format != 1 || doc.Range != group || doc.ChunkBytes != h.ChunkBytes || doc.Owner != ref.Owner || len(doc.Chunks) != ref.Count { + if doc.Range != group || doc.ChunkBytes != h.ChunkBytes || doc.Owner != ref.Owner || len(doc.Chunks) != ref.Count { return h, errors.New("chunkstore: invalid segment contents") } for idx, cr := range doc.Chunks { diff --git a/seaweed-block/core/frontend/chunkstore/manifest_format.go b/seaweed-block/core/frontend/chunkstore/manifest_format.go new file mode 100644 index 0000000000..bd5f852035 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/manifest_format.go @@ -0,0 +1,105 @@ +package chunkstore + +import ( + "bytes" + "encoding/hex" + "encoding/json" + "errors" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type segmentChunkV2Doc struct { + Key string `json:"key"` + // SHA256 covers stored object bytes, before any encoding is decoded. + SHA256 string `json:"sha256"` + Encoding string `json:"enc"` + BirthLSN *uint64 `json:"birth_lsn"` +} + +type segmentV2Doc struct { + Format int `json:"format"` + Range uint64 `json:"range"` + ChunkBytes uint64 `json:"chunk_bytes"` + Owner string `json:"owner"` + MaxBirthLSN *uint64 `json:"max_birth_lsn"` + Chunks map[uint64]segmentChunkV2Doc `json:"chunks"` +} + +type legacyChunkRefDoc struct { + Key string + SHA256 [32]byte +} + +type legacySegmentDoc struct { + Format int `json:"format"` + Range uint64 `json:"range"` + ChunkBytes uint64 `json:"chunk_bytes"` + Owner string `json:"owner"` + Chunks map[uint64]legacyChunkRefDoc `json:"chunks"` +} + +func encodeSegmentV2(group, chunkBytes uint64, owner string, chunks map[uint64]storage.ChunkRef) ([]byte, uint64, error) { + doc := segmentV2Doc{Format: 2, Range: group, ChunkBytes: chunkBytes, Owner: owner, Chunks: map[uint64]segmentChunkV2Doc{}} + var maxBirth uint64 + for idx, ref := range chunks { + birth := ref.BirthLSN + doc.Chunks[idx] = segmentChunkV2Doc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:]), Encoding: ref.Encoding, BirthLSN: &birth} + maxBirth = max(maxBirth, birth) + } + doc.MaxBirthLSN = &maxBirth + body, err := json.Marshal(doc) + return body, maxBirth, err +} + +func decodeSegment(body []byte, ref storage.ChunkSegment, remoteLSN uint64) (segmentDoc, error) { + var discriminator struct { + Format int `json:"format"` + } + if err := decodeManifestJSON(body, &discriminator); err != nil { + return segmentDoc{}, err + } + if discriminator.Format != ref.SegFormat { + return segmentDoc{}, errors.New("chunkstore: segment format/reference mismatch") + } + d := json.NewDecoder(bytes.NewReader(body)) + d.DisallowUnknownFields() + result := segmentDoc{Chunks: map[uint64]storage.ChunkRef{}} + switch discriminator.Format { + case 1: + var doc legacySegmentDoc + if err := d.Decode(&doc); err != nil { + return result, err + } + result.Format, result.Range, result.ChunkBytes, result.Owner = doc.Format, doc.Range, doc.ChunkBytes, doc.Owner + for idx, cr := range doc.Chunks { + result.Chunks[idx] = storage.ChunkRef{Key: cr.Key, SHA256: cr.SHA256, Encoding: "full", BirthLSN: ref.MaxBirthLSN} + } + case 2: + var doc segmentV2Doc + if err := d.Decode(&doc); err != nil { + return result, err + } + if doc.MaxBirthLSN == nil || *doc.MaxBirthLSN != ref.MaxBirthLSN || *doc.MaxBirthLSN > remoteLSN { + return result, errors.New("chunkstore: segment birth maximum mismatch") + } + result.Format, result.Range, result.ChunkBytes, result.Owner = doc.Format, doc.Range, doc.ChunkBytes, doc.Owner + var maxBirth uint64 + for idx, cr := range doc.Chunks { + sum, err := hex.DecodeString(cr.SHA256) + if err != nil || len(sum) != 32 || cr.Encoding != "full" || cr.BirthLSN == nil || *cr.BirthLSN > remoteLSN { + return result, errors.New("chunkstore: invalid segment chunk encoding/hash/birth") + } + v := storage.ChunkRef{Key: cr.Key, Encoding: cr.Encoding, BirthLSN: *cr.BirthLSN} + copy(v.SHA256[:], sum) + result.Chunks[idx] = v + maxBirth = max(maxBirth, v.BirthLSN) + } + if maxBirth != *doc.MaxBirthLSN { + return result, errors.New("chunkstore: incorrect segment birth maximum") + } + default: + return result, errors.New("chunkstore: unsupported segment format") + } + return result, nil +} diff --git a/seaweed-block/core/storage/chunk_manifest.go b/seaweed-block/core/storage/chunk_manifest.go index 2125321931..28e4297cf8 100644 --- a/seaweed-block/core/storage/chunk_manifest.go +++ b/seaweed-block/core/storage/chunk_manifest.go @@ -5,10 +5,12 @@ import "context" // ChunkSegment names an immutable range manifest. Owner is the namespace in // which that manifest was encoded; forks preserve it without rewriting data. type ChunkSegment struct { - Key string `json:"key"` - SHA256 [32]byte `json:"sha256"` - Owner string `json:"owner"` - Count int `json:"count"` + Key string `json:"key"` + SHA256 [32]byte `json:"sha256"` + Owner string `json:"owner"` + Count int `json:"count"` + MaxBirthLSN uint64 `json:"max_birth_lsn"` + SegFormat int `json:"seg_format"` } // ChunkManifestBuilder prepares immutable segments before the existing root diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 0a469d1082..790456f6e7 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -151,10 +151,12 @@ type chunkBitmapStore interface { } // chunkRef names one published chunk: its immutable key and the SHA-256 of -// its ChunkBlocks*BlockSize bytes. +// its stored object bytes, verified before any encoding is decoded. type chunkRef struct { - Key string - SHA256 [32]byte + Key string + SHA256 [32]byte + Encoding string + BirthLSN uint64 } // chunkHeadVersion is the CAS guard of HEAD. From 9d0f99e8d5fdba02ab569c8c5ce79ff43a406e3d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:59:07 -0800 Subject: [PATCH 028/150] test: refuse expired writes before their WAL mutation --- .../core/storage/write_command_budget_test.go | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 seaweed-block/core/storage/write_command_budget_test.go diff --git a/seaweed-block/core/storage/write_command_budget_test.go b/seaweed-block/core/storage/write_command_budget_test.go new file mode 100644 index 0000000000..998b8e5ce4 --- /dev/null +++ b/seaweed-block/core/storage/write_command_budget_test.go @@ -0,0 +1,36 @@ +package storage + +import ( + "errors" + "testing" + "time" +) + +func TestWALStoreV3WriteBudgetIncludesPostAdmissionWait(t *testing.T) { + for _, batch := range []bool{false, true} { + t.Run(map[bool]string{false: "single", true: "batch"}[batch], func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.admissionTimeout = 40 * time.Millisecond + // Admission is healthy. A delayed admitted writer must not start a fresh + // budget after waiting to reach its mutation boundary. + s.testAfterAdmit = func() { time.Sleep(60 * time.Millisecond) } + before := s.NextLSN() + var err error + if batch { + _, err = s.WriteBatch(0, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.Write(0, blk(1)) + } + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatalf("expired command mutated: %v", err) + } + if s.NextLSN() != before || s.dm.len() != 0 { + t.Fatal("expired write changed WAL/dirty state") + } + s.testAfterAdmit = nil + if _, err := s.Write(0, blk(2)); err != nil { + t.Fatal(err) + } + }) + } +} From d49f308e92ffa61d91c2f9c767b0519ef2e4e0ba Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:02:04 -0800 Subject: [PATCH 029/150] test: align roundtrip and intent tracing with versioned segments --- .../core/frontend/chunkstore/chunk_remote_test.go | 3 +++ .../core/frontend/chunkstore/decode_fuzz_test.go | 2 +- seaweed-block/core/frontend/chunkstore/gc.go | 9 +++++++++ seaweed-block/core/frontend/chunkstore/manifest_test.go | 2 +- 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go index 7bee5cbf5b..896b271c03 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go @@ -55,6 +55,9 @@ func TestChunkRemote_HeadRoundTripAndCAS(t *testing.T) { t.Fatal(err) } want := head(1, "a", 42, map[uint64]storage.ChunkRef{3: ref("chunks/e1/c3/n-1", d)}) + legacy := want.Chunks[3] + legacy.Encoding, legacy.BirthLSN = "full", want.RemoteLSN + want.Chunks[3] = legacy gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, want) if err != nil || gen != 1 { t.Fatalf("first CAS = %d, %v; want gen 1", gen, err) diff --git a/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go b/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go index 5dce4f7ad3..86ec004bab 100644 --- a/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go +++ b/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go @@ -21,7 +21,7 @@ func fuzzHeadSeeds(tb testing.TB) [][]byte { {Gen: 3, Epoch: 4, Holder: "r2", RemoteLSN: 9, State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Holder: "r2", Epoch: 4, Gen: 3}, Chunks: map[uint64]storage.ChunkRef{}}, {Gen: 2, Epoch: 1, Holder: "r1", RemoteLSN: 3, ChunkBytes: 4 << 20, ManifestChunkCount: 2, - Segments: map[uint64]storage.ChunkSegment{0: {Key: "@v1/seg/00", SHA256: sum, Owner: "v1", Count: 2}}}, + Segments: map[uint64]storage.ChunkSegment{0: {Key: "@v1/seg/00", SHA256: sum, Owner: "v1", Count: 2, SegFormat: 2, MaxBirthLSN: 3}}}, } var out [][]byte for _, h := range heads { diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index 5d524d0c13..7e8bf522f5 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -230,6 +230,15 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e } if in.Segments != nil { h := storage.ChunkHead{Segments: in.Segments, ChunkBytes: in.ChunkBytes} + // Intents protect keys without carrying a published frontier. + // Validate segment maxima against the reference maxima here. + for group, ref := range h.Segments { + if ref.SegFormat == 0 { + ref.SegFormat = 1 + h.Segments[group] = ref + } + h.RemoteLSN = max(h.RemoteLSN, ref.MaxBirthLSN) + } for _, ref := range in.Segments { h.ManifestChunkCount += ref.Count } diff --git a/seaweed-block/core/frontend/chunkstore/manifest_test.go b/seaweed-block/core/frontend/chunkstore/manifest_test.go index eb53976606..fa0309f434 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest_test.go +++ b/seaweed-block/core/frontend/chunkstore/manifest_test.go @@ -54,7 +54,7 @@ func TestManifest_CapturePublishesSegmentRoot(t *testing.T) { if err = json.Unmarshal(e.Content, &doc); err != nil { t.Fatal(err) } - if doc.Format != 2 || len(doc.Chunks) != 0 || len(doc.Segments) != 1 { + if doc.Format != 3 || len(doc.Chunks) != 0 || len(doc.Segments) != 1 { t.Fatalf("cut did not publish a small segmented root: %s", e.Content) } h, err := r.GetHead(ctx) From 9b53a8a9e13282fd2b1f9c4991c9328a18314872 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:04:46 -0800 Subject: [PATCH 030/150] storage: preserve the write command deadline through admission --- .../core/frontend/durable/storage_adapter.go | 18 ++++- .../durable/write_command_budget_test.go | 80 +++++++++++++++++++ seaweed-block/core/frontend/nvme/io.go | 2 + seaweed-block/core/frontend/nvme/session.go | 3 + .../nvme/write_command_budget_test.go | 38 +++++++++ seaweed-block/core/frontend/write_budget.go | 21 +++++ seaweed-block/core/storage/logical_storage.go | 14 +++- seaweed-block/core/storage/wal_admission.go | 25 ++++++ seaweed-block/core/storage/walstore.go | 37 ++++++++- .../core/storage/write_command_budget.go | 39 +++++++++ .../core/storage/write_command_budget_test.go | 47 +++++++++++ 11 files changed, 319 insertions(+), 5 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/write_command_budget_test.go create mode 100644 seaweed-block/core/frontend/nvme/write_command_budget_test.go create mode 100644 seaweed-block/core/frontend/write_budget.go create mode 100644 seaweed-block/core/storage/write_command_budget.go diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 9f99490226..98a103b5ba 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -543,6 +543,8 @@ func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, // overlay the partial range, write the full block back. // Every write is gated. func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int, error) { + ctx, cancel := frontend.WithWriteBudget(ctx, time.Time{}) + defer cancel() iolatency.BackendEnter(ctx) defer iolatency.BackendExit(ctx) release, err := b.admit() @@ -755,7 +757,13 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte) return total, fmt.Errorf("%w: no write observer installed", ErrReplicationAckUnavailable) } - lsn, err := b.storage.Write(lba, block) + var lsn uint64 + var err error + if writer, ok := b.storage.(storage.ContextWriter); ok { + lsn, err = writer.WriteContext(ctx, lba, block) + } else { + lsn, err = b.storage.Write(lba, block) + } writeLock.Unlock() if err != nil { return total, fmt.Errorf("durable: write lba=%d: %w", lba, err) @@ -791,7 +799,13 @@ func (b *StorageBackend) writeFullBlockBatch(ctx context.Context, startLBA uint3 blocks[i] = p[i*bs : (i+1)*bs] } unlock := b.lockLBARange(startLBA, blockCount) - lsns, err := batcher.WriteBatch(startLBA, blocks) + var lsns []uint64 + var err error + if writer, ok := batcher.(storage.ContextWriteBatcher); ok { + lsns, err = writer.WriteBatchContext(ctx, startLBA, blocks) + } else { + lsns, err = batcher.WriteBatch(startLBA, blocks) + } unlock() if len(lsns) > 0 { b.profile.recordBackendStorageWrite(len(lsns), true) diff --git a/seaweed-block/core/frontend/durable/write_command_budget_test.go b/seaweed-block/core/frontend/durable/write_command_budget_test.go new file mode 100644 index 0000000000..c927b8c440 --- /dev/null +++ b/seaweed-block/core/frontend/durable/write_command_budget_test.go @@ -0,0 +1,80 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type deadlineStorage struct { + storage.LogicalStorage + deadlines []time.Time + legacyCalls int +} + +func (s *deadlineStorage) Write(lba uint32, p []byte) (uint64, error) { + s.legacyCalls++ + return s.LogicalStorage.Write(lba, p) +} +func (s *deadlineStorage) WriteBatch(lba uint32, blocks [][]byte) ([]uint64, error) { + s.legacyCalls++ + return nil, errors.New("contextless batch called") +} +func (s *deadlineStorage) WriteContext(ctx context.Context, lba uint32, p []byte) (uint64, error) { + deadline, _ := ctx.Deadline() + s.deadlines = append(s.deadlines, deadline) + return s.LogicalStorage.Write(lba, p) +} +func (s *deadlineStorage) WriteBatchContext(ctx context.Context, lba uint32, blocks [][]byte) ([]uint64, error) { + deadline, _ := ctx.Deadline() + s.deadlines = append(s.deadlines, deadline) + var lsns []uint64 + for i, p := range blocks { + lsn, err := s.LogicalStorage.Write(lba+uint32(i), p) + if err != nil { + return lsns, err + } + lsns = append(lsns, lsn) + } + return lsns, nil +} +func TestStorageBackendWriteKeepsOneDeadlineAcrossBatches(t *testing.T) { + _, view, base := newTestBackend(t, logicalStorageFactories()[0], 160, 4096) + wrapped := &deadlineStorage{LogicalStorage: base} + b := durable.NewStorageBackend(wrapped, view, frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}) + b.SetOperational(true, "test") + want := time.Now().Add(2 * time.Second) + ctx, cancel := context.WithDeadline(context.Background(), want) + defer cancel() + if n, err := b.Write(ctx, 0, make([]byte, 130*4096)); err != nil || n != 130*4096 { + t.Fatalf("write %d %v", n, err) + } + if _, err := b.Write(ctx, 130*4096, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + if wrapped.legacyCalls != 0 || len(wrapped.deadlines) != 4 { + t.Fatalf("dispatch legacy=%d deadlines=%v", wrapped.legacyCalls, wrapped.deadlines) + } + for _, got := range wrapped.deadlines { + if !got.Equal(want) { + t.Fatalf("deadline reset %v want%v", got, want) + } + } +} +func TestStorageBackendExpiredWriteDoesNotAppend(t *testing.T) { + b, _, s := newTestBackend(t, logicalStorageFactories()[0], 16, 4096) + before := s.NextLSN() + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + for _, size := range []int{4096, 8192} { + n, err := b.Write(ctx, 0, make([]byte, size)) + if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || s.NextLSN() != before { + t.Fatalf("expired write n=%d err=%v next=%d", n, err, s.NextLSN()) + } + } +} diff --git a/seaweed-block/core/frontend/nvme/io.go b/seaweed-block/core/frontend/nvme/io.go index 4615b3d08a..6f4c88ef18 100644 --- a/seaweed-block/core/frontend/nvme/io.go +++ b/seaweed-block/core/frontend/nvme/io.go @@ -263,6 +263,8 @@ func (h *IOHandler) read(ctx context.Context, cmd IOCommand) IOResult { } func (h *IOHandler) write(ctx context.Context, cmd IOCommand) IOResult { + ctx, cancel := frontend.WithWriteBudget(ctx, time.Time{}) + defer cancel() if cmd.NLB == 0 { return IOResult{SCT: SCTGeneric, SC: SCInvalidField, Reason: "NLB=0"} } diff --git a/seaweed-block/core/frontend/nvme/session.go b/seaweed-block/core/frontend/nvme/session.go index fef22cfca6..61806e72f5 100644 --- a/seaweed-block/core/frontend/nvme/session.go +++ b/seaweed-block/core/frontend/nvme/session.go @@ -63,6 +63,7 @@ import ( "context" "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/frontend" "io" "net" "sync" @@ -588,6 +589,8 @@ func (s *Session) handleRead(ctx context.Context, req *Request) { } func (s *Session) handleWrite(ctx context.Context, req *Request) { + ctx, cancel := frontend.WithWriteBudget(ctx, req.dispatchReadyAt) + defer cancel() s.recordWriteCommand() s.recordWriteDispatchWait(time.Since(req.dispatchReadyAt)) handlerStart := time.Now() diff --git a/seaweed-block/core/frontend/nvme/write_command_budget_test.go b/seaweed-block/core/frontend/nvme/write_command_budget_test.go new file mode 100644 index 0000000000..f965551d29 --- /dev/null +++ b/seaweed-block/core/frontend/nvme/write_command_budget_test.go @@ -0,0 +1,38 @@ +package nvme + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" +) + +type expiredDispatchBackend struct { + frontend.Backend + deadline time.Time + calls int +} + +func (b *expiredDispatchBackend) Write(ctx context.Context, _ int64, _ []byte) (int, error) { + b.calls++ + b.deadline, _ = ctx.Deadline() + if ctx.Err() == context.DeadlineExceeded { + return 0, frontend.ErrBackendBusy + } + return 512, nil +} +func TestSessionWriteBudgetIncludesDispatchQueue(t *testing.T) { + b := &expiredDispatchBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"})} + s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), respCh: make(chan *response, 1), done: make(chan struct{})} + arrived := time.Now().Add(-5 * time.Second) + req := &Request{payload: make([]byte, 512), dispatchReadyAt: arrived} + req.capsule.OpCode = ioWrite + req.capsule.NSID = 1 + s.handleWrite(context.Background(), req) + resp := <-s.respCh + if b.calls != 1 || !b.deadline.Equal(arrived.Add(frontend.WriteCommandBudget)) || resp.resp.Status != MakeStatusField(SCTGeneric, SCNamespaceNotReady, false) { + t.Fatalf("deadline=%v status=%#x calls=%d", b.deadline, resp.resp.Status, b.calls) + } +} diff --git a/seaweed-block/core/frontend/write_budget.go b/seaweed-block/core/frontend/write_budget.go new file mode 100644 index 0000000000..2958ea549f --- /dev/null +++ b/seaweed-block/core/frontend/write_budget.go @@ -0,0 +1,21 @@ +package frontend + +import ( + "context" + "time" +) + +const WriteCommandBudget = 4 * time.Second + +// WithWriteBudget preserves an earlier caller deadline, including time spent +// queued before dispatch. A zero arrival denotes a direct backend call. +func WithWriteBudget(ctx context.Context, arrival time.Time) (context.Context, context.CancelFunc) { + if arrival.IsZero() { + arrival = time.Now() + } + deadline := arrival.Add(WriteCommandBudget) + if prior, ok := ctx.Deadline(); ok && !deadline.Before(prior) { + return ctx, func() {} + } + return context.WithDeadline(ctx, deadline) +} diff --git a/seaweed-block/core/storage/logical_storage.go b/seaweed-block/core/storage/logical_storage.go index 4fdc11cf1d..bf0cf6df6a 100644 --- a/seaweed-block/core/storage/logical_storage.go +++ b/seaweed-block/core/storage/logical_storage.go @@ -1,6 +1,9 @@ package storage -import "fmt" +import ( + "context" + "fmt" +) // LogicalStorage is the V3 persistence-seam contract. It separates the // "what data exists, what frontier is durable" question (storage) from @@ -302,3 +305,12 @@ func (h *legacyInstallHandle) MarkBaseComplete() error { type WriteBatcher interface { WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error) } + +// ContextWriter and ContextWriteBatcher preserve one caller deadline across +// storage admission. Implementations must not abandon already-started I/O. +type ContextWriter interface { + WriteContext(context.Context, uint32, []byte) (uint64, error) +} +type ContextWriteBatcher interface { + WriteBatchContext(context.Context, uint32, [][]byte) ([]uint64, error) +} diff --git a/seaweed-block/core/storage/wal_admission.go b/seaweed-block/core/storage/wal_admission.go index 8302bdc5fd..1f6e13fb3a 100644 --- a/seaweed-block/core/storage/wal_admission.go +++ b/seaweed-block/core/storage/wal_admission.go @@ -1,6 +1,7 @@ package storage import ( + "context" "errors" "fmt" "sync/atomic" @@ -96,6 +97,13 @@ func (a *walAdmission) HardMark() float64 { return a.hardMark } // expires. Returns errWALFull on timeout, errVolumeClosed if the // store closes during the wait. func (a *walAdmission) Acquire(timeout time.Duration) error { + return a.acquireContext(context.Background(), timeout) +} + +func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration) error { + if err := ctx.Err(); err != nil { + return admissionContextError(err) + } deadline := time.NewTimer(timeout) defer deadline.Stop() @@ -117,6 +125,11 @@ func (a *walAdmission) Acquire(timeout time.Duration) error { } a.notifyFn() select { + case <-ctx.Done(): + if err := a.terminalFault(); err != nil { + return err + } + return admissionContextError(ctx.Err()) case <-deadline.C: a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds()) if err := a.terminalFault(); err != nil { @@ -157,6 +170,11 @@ func (a *walAdmission) Acquire(timeout time.Duration) error { select { case a.sem <- struct{}{}: return nil + case <-ctx.Done(): + if err := a.terminalFault(); err != nil { + return err + } + return admissionContextError(ctx.Err()) case <-deadline.C: if err := a.terminalFault(); err != nil { return err @@ -184,3 +202,10 @@ func (a *walAdmission) terminalFault() error { } return nil } + +func admissionContextError(err error) error { + if errors.Is(err, context.DeadlineExceeded) { + return ErrWALPressureTimeout + } + return err +} diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 21c2c6ca13..ac725f505e 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -1,6 +1,7 @@ package storage import ( + "context" "errors" "fmt" "os" @@ -753,6 +754,11 @@ func (s *WALStore) Recover() (frontier uint64, err error) { // covers this LSN). Reads after this Write see the new bytes // immediately. func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { + return s.WriteContext(context.Background(), lba, data) +} + +func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (uint64, error) { + deadline := s.writeAdmissionDeadline(ctx) s.captureMu.RLock() defer s.captureMu.RUnlock() if err := s.stickyIOFault(); err != nil { @@ -773,8 +779,15 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { s.lifecycleMu.RLock() defer s.lifecycleMu.RUnlock() + if err := s.writeBudgetError(ctx, deadline); err != nil { + return 0, err + } if s.admission != nil { - if err := s.admission.Acquire(s.admissionTimeout); err != nil { + wait := s.admissionTimeout + if !deadline.IsZero() { + wait = time.Until(deadline) + } + if err := s.admission.acquireContext(ctx, wait); err != nil { return 0, fmt.Errorf("storage: WAL admission: %w", err) } defer s.admission.Release() @@ -796,6 +809,10 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { s.mu.Unlock() return 0, err } + if err := s.writeBudgetError(ctx, deadline); err != nil { + s.mu.Unlock() + return 0, err + } lsn := s.nextLSN entry := &walEntry{ @@ -840,6 +857,11 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { } func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error) { + return s.WriteBatchContext(context.Background(), startLBA, blocks) +} + +func (s *WALStore) WriteBatchContext(ctx context.Context, startLBA uint32, blocks [][]byte) ([]uint64, error) { + deadline := s.writeAdmissionDeadline(ctx) s.captureMu.RLock() defer s.captureMu.RUnlock() if err := s.stickyIOFault(); err != nil { @@ -862,8 +884,15 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error s.lifecycleMu.RLock() defer s.lifecycleMu.RUnlock() + if err := s.writeBudgetError(ctx, deadline); err != nil { + return nil, err + } if s.admission != nil { - if err := s.admission.Acquire(s.admissionTimeout); err != nil { + wait := s.admissionTimeout + if !deadline.IsZero() { + wait = time.Until(deadline) + } + if err := s.admission.acquireContext(ctx, wait); err != nil { return nil, fmt.Errorf("storage: WAL admission: %w", err) } defer s.admission.Release() @@ -883,6 +912,10 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error s.mu.Unlock() return nil, err } + if err := s.writeBudgetError(ctx, deadline); err != nil { + s.mu.Unlock() + return nil, err + } firstLSN := s.nextLSN if s.v3 != nil { lsns, err := s.writeBatchV3Locked(startLBA, blocks, firstLSN) diff --git a/seaweed-block/core/storage/write_command_budget.go b/seaweed-block/core/storage/write_command_budget.go new file mode 100644 index 0000000000..316303e3dd --- /dev/null +++ b/seaweed-block/core/storage/write_command_budget.go @@ -0,0 +1,39 @@ +package storage + +import ( + "context" + "time" +) + +// Compute once, before capture/COW/lifecycle admission. Keep append/completion +// headroom instead of spending the entire command budget in WAL admission. +// This is cooperative: it cannot interrupt a mutex or physical I/O in progress. +func (s *WALStore) writeAdmissionDeadline(ctx context.Context) time.Time { + now := time.Now() + deadline, hasDeadline := ctx.Deadline() + if s.v3 != nil { + local := now.Add(s.admissionTimeout) + if !hasDeadline || local.Before(deadline) { + deadline = local + } + reserve := min(time.Second, max(time.Duration(0), deadline.Sub(now)/4)) + return deadline.Add(-reserve) + } + if hasDeadline { + return deadline + } + return time.Time{} // preserve legacy admission policy +} + +func (s *WALStore) writeBudgetError(ctx context.Context, deadline time.Time) error { + if err := s.stickyIOFault(); err != nil { + return err + } + if ctx.Err() == context.Canceled { + return context.Canceled + } + if !deadline.IsZero() && !time.Now().Before(deadline) { + return ErrWALPressureTimeout + } + return nil +} diff --git a/seaweed-block/core/storage/write_command_budget_test.go b/seaweed-block/core/storage/write_command_budget_test.go index 998b8e5ce4..ca9a88d4cb 100644 --- a/seaweed-block/core/storage/write_command_budget_test.go +++ b/seaweed-block/core/storage/write_command_budget_test.go @@ -1,7 +1,9 @@ package storage import ( + "context" "errors" + "fmt" "testing" "time" ) @@ -34,3 +36,48 @@ func TestWALStoreV3WriteBudgetIncludesPostAdmissionWait(t *testing.T) { }) } } + +func TestWALStoreV3WriteContextDeadlineIncludesCaptureWait(t *testing.T) { + for _, batch := range []bool{false, true} { + t.Run(fmt.Sprint(batch), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + s.captureMu.Lock() + done := make(chan error, 1) + go func() { + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 0, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.WriteContext(ctx, 0, blk(1)) + } + done <- err + }() + <-ctx.Done() + s.captureMu.Unlock() + select { + case err := <-done: + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatal(err) + } + case <-time.After(time.Second): + t.Fatal("writer did not join") + } + if s.NextLSN() != 1 || s.dm.len() != 0 { + t.Fatal("expired capture waiter mutated") + } + }) + } +} + +func TestWALStoreV3WriteBudgetKeepsTerminalFault(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + injected := errors.New("terminal fsync fault") + s.latchV3(injected) + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + if _, err := s.WriteContext(ctx, 0, blk(1)); !errors.Is(err, injected) { + t.Fatalf("fault hidden by deadline: %v", err) + } +} From fd214025987ee93c705974cbaf322b0ccbf4401b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:06:15 -0800 Subject: [PATCH 031/150] test: retain retryable pressure completion and command latency checks --- .../durable/provider_chunk_noflush_test.go | 73 ++++++++++++++++--- seaweed-block/core/storage/wal_admission.go | 4 + .../walstore_noflush_pressure_v3_test.go | 44 ++++++++++- seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 110 insertions(+), 13 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go b/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go index 674102985b..fd9fd059cf 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go @@ -4,7 +4,9 @@ import ( "bytes" "context" "encoding/binary" + "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" "github.com/seaweedfs/seaweed-block/core/recovery" @@ -15,6 +17,19 @@ import ( "time" ) +// Preserve the typed backend cause alongside the actual NVMe handler result. +// This test submits writes synchronously, so lastError has one caller. +type noFlushBackend struct { + frontend.Backend + lastError error +} + +func (b *noFlushBackend) Write(ctx context.Context, offset int64, data []byte) (int, error) { + n, err := b.Backend.Write(ctx, offset, data) + b.lastError = err + return n, err +} + // Public provider + actual NVMe handler, file-backed v3 with the default // 64 MiB WAL. No injected I/O failures, private selector, or flusher control. func TestWALStoreChunkV3_NoClientFlushBurst(t *testing.T) { @@ -63,8 +78,10 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) { } syncsBefore := ws.WALSyncCount() var durations []time.Duration + busyCount := 0 t.Logf("before HEAD gen=%d remoteLSN=%d cp=%d next=%d retention=%d", before.Gen, before.RemoteLSN, ws.CheckpointLSN(), ws.NextLSN(), ws.RecoveryRetentionLSNs()) - h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: be, BlockSize: 4096, VolumeSize: 1 << 30}) + recorded := &noFlushBackend{Backend: be} + h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: recorded, BlockSize: 4096, VolumeSize: 1 << 30}) data := make([]byte, transfer) start := time.Now() for off := 0; off < total; off += transfer { @@ -73,14 +90,50 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) { binary.LittleEndian.PutUint64(data[i:i+8], uint64(off+i)) } } - writeStart := time.Now() - r := h.Handle(ctx, nvme.IOCommand{Opcode: 0x01, NSID: 1, SLBA: uint64(off / 4096), NLB: transfer / 4096, Data: data}) - durations = append(durations, time.Since(writeStart)) - if r.AsError() != nil { - dump := make([]byte, 2<<20) - n := runtime.Stack(dump, true) - t.Logf("TIMEOUT STACKS\n%s", dump[:n]) - t.Fatalf("NO FLUSH write bytes=%d elapsed=%v result=%+v cp=%d next=%d", off, time.Since(start), r, ws.CheckpointLSN(), ws.NextLSN()) + retryDeadline := time.Now().Add(30 * time.Second) + cpBefore := ws.CheckpointLSN() + retried := false + for { + writeStart := time.Now() + r := h.Handle(ctx, nvme.IOCommand{Opcode: 0x01, NSID: 1, SLBA: uint64(off / 4096), NLB: transfer / 4096, Data: data}) + elapsed := time.Since(writeStart) + durations = append(durations, elapsed) + if elapsed >= 5*time.Second || time.Since(start) >= 2*time.Minute || time.Now().After(retryDeadline) { + dump := make([]byte, 2<<20) + n := runtime.Stack(dump, true) + t.Logf("TIMEOUT STACKS\n%s", dump[:n]) + t.Fatalf("NO FLUSH exceeded wait bound bytes=%d attempt=%v total=%v busy=%d result=%+v cp=%d next=%d", off, elapsed, time.Since(start), busyCount, r, ws.CheckpointLSN(), ws.NextLSN()) + } + if r.AsError() == nil { + if retried { + t.Logf("NO FLUSH resumed bytes=%d cp=%d->%d next=%d syncs=%d busy=%d", off, cpBefore, ws.CheckpointLSN(), ws.NextLSN(), ws.WALSyncCount(), busyCount) + } + break + } + if !errors.Is(recorded.lastError, frontend.ErrBackendBusy) || r.SCT != nvme.SCTGeneric || r.SC != nvme.SCNamespaceNotReady { + t.Fatalf("NO FLUSH non-retryable write bytes=%d result=%+v cause=%v", off, r, recorded.lastError) + } + busyCount++ + retried = true + t.Logf("NO FLUSH retry bytes=%d busy=%d attempt=%v cp=%d next=%d syncs=%d", off, busyCount, elapsed, ws.CheckpointLSN(), ws.NextLSN(), ws.WALSyncCount()) + if busyCount == 1 { + passiveStart := time.Now() + cpAtBusy := ws.CheckpointLSN() + target := ws.NextLSN() - 1 + cpObserved := cpAtBusy + // Getters only: no Write, Sync, NotifyUrgent or Close may + // drive progress before the first retry. + for cpAtBusy < target && cpObserved <= cpAtBusy && time.Since(passiveStart) < 10*time.Second { + time.Sleep(25 * time.Millisecond) + cpObserved = ws.CheckpointLSN() + } + t.Logf("NO FLUSH passive bytes=%d wait=%v cpBefore=%d cpAtBusy=%d cpObserved=%d target=%d", off, time.Since(passiveStart), cpBefore, cpAtBusy, cpObserved, target) + if time.Since(passiveStart) >= 10*time.Second || (cpAtBusy < target && cpObserved <= cpAtBusy) { + t.Fatalf("NO FLUSH passive checkpoint did not advance without another write: bytes=%d cp=%d busy=%d", off, cpObserved, busyCount) + } + } + // Retry the identical command; no caller Flush drives reclamation. + time.Sleep(25 * time.Millisecond) } if (off+transfer)%(16*1024*1024) == 0 { t.Logf("NO FLUSH progress bytes=%d elapsed=%v cp=%d next=%d", off+transfer, time.Since(start), ws.CheckpointLSN(), ws.NextLSN()) @@ -109,7 +162,7 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) { if mode == storage.WModeStrict { fsyncs *= 2 } - t.Logf("COST mode=%d bytes=%d pressureBatches=%d internalFsyncsPerGiB=%.2f writeP99=%v max=%v", mode, total, batches, float64(fsyncs)/(float64(total)/(1<<30)), durations[(len(durations)-1)*99/100], durations[len(durations)-1]) + t.Logf("COST mode=%d bytes=%d busy=%d pressureBatches=%d internalFsyncsPerGiB=%.2f attemptP99=%v maxAttempt=%v", mode, total, busyCount, batches, float64(fsyncs)/(float64(total)/(1<<30)), durations[(len(durations)-1)*99/100], durations[len(durations)-1]) after, err := remote.GetHead(ctx) if err != nil { t.Fatal(err) diff --git a/seaweed-block/core/storage/wal_admission.go b/seaweed-block/core/storage/wal_admission.go index 1f6e13fb3a..913d3bd91f 100644 --- a/seaweed-block/core/storage/wal_admission.go +++ b/seaweed-block/core/storage/wal_admission.go @@ -102,6 +102,9 @@ func (a *walAdmission) Acquire(timeout time.Duration) error { func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration) error { if err := ctx.Err(); err != nil { + if fault := a.terminalFault(); fault != nil { + return fault + } return admissionContextError(err) } deadline := time.NewTimer(timeout) @@ -126,6 +129,7 @@ func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration a.notifyFn() select { case <-ctx.Done(): + a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds()) if err := a.terminalFault(); err != nil { return err } diff --git a/seaweed-block/core/storage/walstore_noflush_pressure_v3_test.go b/seaweed-block/core/storage/walstore_noflush_pressure_v3_test.go index ae079f7e96..b525470054 100644 --- a/seaweed-block/core/storage/walstore_noflush_pressure_v3_test.go +++ b/seaweed-block/core/storage/walstore_noflush_pressure_v3_test.go @@ -29,9 +29,48 @@ func TestWALStoreV3NoClientSyncSixRings(t *testing.T) { if s.admissionTimeout >= 5*time.Second { t.Fatalf("budget=%v", s.admissionTimeout) } + start := time.Now() + busyCount := 0 + var maxAttempt time.Duration for i := uint32(0); i < count; i++ { - if _, err := s.Write(i, blk(byte(i+1))); err != nil { - t.Fatalf("no-client-Sync write %d/%d: %v", i, count, err) + retryDeadline := time.Now().Add(30 * time.Second) + cpBefore, wackBefore := s.CheckpointLSN(), s.v3.wack.Load() + retried := false + for { + attemptStart := time.Now() + _, err := s.Write(i, blk(byte(i+1))) + elapsed := time.Since(attemptStart) + maxAttempt = max(maxAttempt, elapsed) + if elapsed >= 5*time.Second || time.Since(start) >= 2*time.Minute || time.Now().After(retryDeadline) { + t.Fatalf("no-client-Sync exceeded wait bound write=%d/%d attempt=%v total=%v busy=%d err=%v", i, count, elapsed, time.Since(start), busyCount, err) + } + if err == nil { + if retried { + t.Logf("no-client-Sync resumed write=%d cp=%d->%d wack=%d->%d busy=%d", i, cpBefore, s.CheckpointLSN(), wackBefore, s.v3.wack.Load(), busyCount) + } + break + } + if !errors.Is(err, ErrWALPressureTimeout) || s.stickyIOFault() != nil { + t.Fatalf("no-client-Sync non-retryable write %d/%d: %v", i, count, err) + } + busyCount++ + retried = true + t.Logf("no-client-Sync busy write=%d cp=%d wack=%d busy=%d attempt=%v", i, s.CheckpointLSN(), s.v3.wack.Load(), busyCount, elapsed) + if busyCount == 1 { + passiveStart := time.Now() + cpAtBusy, wackAtBusy := s.CheckpointLSN(), s.v3.wack.Load() + target := s.v3.appended.Load() + cpObserved, wackObserved := cpAtBusy, wackAtBusy + for cpAtBusy < target && cpObserved <= cpAtBusy && time.Since(passiveStart) < 10*time.Second { + time.Sleep(25 * time.Millisecond) + cpObserved, wackObserved = s.CheckpointLSN(), s.v3.wack.Load() + } + t.Logf("no-client-Sync passive write=%d wait=%v cpBefore=%d cpAtBusy=%d cpObserved=%d target=%d wack=%d->%d", i, time.Since(passiveStart), cpBefore, cpAtBusy, cpObserved, target, wackAtBusy, wackObserved) + if time.Since(passiveStart) >= 10*time.Second || (cpAtBusy < target && cpObserved <= cpAtBusy) || wackObserved < cpObserved { + t.Fatalf("no-client-Sync passive checkpoint did not advance without another write: cp=%d wack=%d busy=%d", cpObserved, wackObserved, busyCount) + } + } + time.Sleep(25 * time.Millisecond) } } for i := uint32(0); i < count; i++ { @@ -40,6 +79,7 @@ func TestWALStoreV3NoClientSyncSixRings(t *testing.T) { t.Fatalf("readback %d: %v", i, err) } } + t.Logf("no-client-Sync mode=%d writes=%d busy=%d elapsed=%v maxAttempt=%v", mode, count, busyCount, time.Since(start), maxAttempt) }) } } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6ee4916e12..5f90ff18a2 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -279,7 +279,7 @@ snapshot lifetime; local persistence does not bypass it. checkpoint, both-slot floor and dirty-reference retirement; I4, with healthy local progress and no guest Sync, the reuse floor advances. Enforced by `syncWALBatchV3Internal`, `persistOwnedMapCheckpointV3` and the existing reclaim - publisher. Tests: `TestWALStoreV3NoClientSyncSixRings`, + publisher. Tests: `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestSessionWriteBudgetIncludesDispatchQueue`, `TestWALStoreV3NoClientSyncSixRings`, `TestWALStoreV3PressureSyncFaultDoesNotPublishFrontiers`, `TestWALStoreV3PressureSyncSkipsInstalling`, `TestWALStoreV3PressureProgressWithPendingCutOrClose` and From 8d542549a3d20f0ab49eb10b6eff1350810d6638 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:10:42 -0800 Subject: [PATCH 032/150] fix: reserve flat HEAD writes for chunk-free roots --- .../core/frontend/chunkstore/catalog_test.go | 9 +++++ .../core/frontend/chunkstore/chunk_remote.go | 3 ++ .../frontend/chunkstore/chunk_remote_test.go | 12 ++++++- .../frontend/chunkstore/decode_fuzz_test.go | 10 ++++++ .../chunkstore/format_upgrade_test.go | 33 +++++++++++++++++++ .../chunkstore/legacy_head_fixture_test.go | 25 ++++++++++++++ 6 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/frontend/chunkstore/legacy_head_fixture_test.go diff --git a/seaweed-block/core/frontend/chunkstore/catalog_test.go b/seaweed-block/core/frontend/chunkstore/catalog_test.go index 5e666b46a6..6bdff5c17e 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_test.go @@ -41,11 +41,20 @@ func publishSource(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string, chunks if err != nil { t.Fatal(err) } + h, intents, err := r.PrepareManifest(ctx, cur, h, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks)) + if err != nil { + t.Fatal(err) + } gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h) if err != nil { t.Fatal(err) } h.Gen = gen + for _, id := range intents { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } return h } diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index d472f59e6a..7f2118d4d9 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -446,6 +446,9 @@ func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) { doc.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen} } if h.Segments == nil { + if len(h.Chunks) != 0 { + return nil, errors.New("chunkstore: data HEAD requires a segmented manifest and geometry") + } doc.Chunks = make(map[uint64]refDoc, len(h.Chunks)) for idx, ref := range h.Chunks { if ref.Key == "" { diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go index 896b271c03..70a1f172ff 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go @@ -58,10 +58,19 @@ func TestChunkRemote_HeadRoundTripAndCAS(t *testing.T) { legacy := want.Chunks[3] legacy.Encoding, legacy.BirthLSN = "full", want.RemoteLSN want.Chunks[3] = legacy + want, intents, err := r.PrepareManifest(ctx, storage.ChunkHead{}, want, 4096) + if err != nil { + t.Fatal(err) + } gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, want) if err != nil || gen != 1 { t.Fatalf("first CAS = %d, %v; want gen 1", gen, err) } + for _, id := range intents { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } got, err := r.GetHead(ctx) if err != nil { t.Fatal(err) @@ -231,7 +240,8 @@ func TestChunkRemote_UntrustedHeadIsAnError(t *testing.T) { f := newFakeFiler() r := newTestRemote(t, f, newFakeBlobs()) h := head(1, "a", 1, map[uint64]storage.ChunkRef{0: ref("k", []byte("x"))}) - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, h); err != nil { + h.Gen = 1 + if err := f.CreateEntry(ctx, testRoot, legacyHeadFixture(t, h), true); err != nil { t.Fatal(err) } f.mu.Lock() diff --git a/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go b/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go index 86ec004bab..ea28bc0c35 100644 --- a/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go +++ b/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go @@ -25,6 +25,10 @@ func fuzzHeadSeeds(tb testing.TB) [][]byte { } var out [][]byte for _, h := range heads { + if h.Segments == nil && len(h.Chunks) > 0 { + out = append(out, legacyHeadFixture(tb, h).Content) + continue + } e, err := headEntry(h) if err != nil { tb.Fatalf("seed %+v: %v", h, err) @@ -90,6 +94,12 @@ func FuzzDecodeHeadDocument(f *testing.F) { return } e, err := headEntry(h) + if h.Segments == nil && len(h.Chunks) > 0 { + if err == nil { + t.Fatal("read-only legacy data was writable as flat HEAD") + } + return + } if err != nil { if gap := knownHeadEncodeGap(h); gap != "" { return diff --git a/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go b/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go index 4797adfd75..f758d1f4d0 100644 --- a/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go +++ b/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go @@ -11,6 +11,39 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) +func TestManifestFormatUpgradeFlatWriterNeverStoresData(t *testing.T) { + dataHead := storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "h1", RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{0: {Key: "k"}}} + if _, err := headEntry(dataHead); err == nil { + t.Fatal("flat writer accepted chunk-bearing HEAD without a manifest") + } + f, b, _, _, _ := gcFixture(t) + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + cur, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if _, err := r.CASHead(context.Background(), storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, dataHead); err == nil { + t.Fatal("direct CAS accepted geometry-free data") + } + after, err := r.GetHead(context.Background()) + if err != nil || after.Gen != cur.Gen { + t.Fatal("refused flat CAS changed HEAD") + } + empty, err := headEntry(storage.ChunkHead{Gen: 1, State: storage.ChunkHeadActive}) + if err != nil { + t.Fatal(err) + } + var shape struct { + Format int `json:"format"` + } + if err := json.Unmarshal(empty.Content, &shape); err != nil || shape.Format != 1 { + t.Fatal("empty flat root must remain writable") + } +} + func TestManifestFormatUpgradeWritesVersionedStoredByteReferences(t *testing.T) { f, b, _, _, _ := gcFixture(t) r, h := publishSegmented(t, f, b) diff --git a/seaweed-block/core/frontend/chunkstore/legacy_head_fixture_test.go b/seaweed-block/core/frontend/chunkstore/legacy_head_fixture_test.go new file mode 100644 index 0000000000..5df831bae3 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/legacy_head_fixture_test.go @@ -0,0 +1,25 @@ +package chunkstore + +import ( + "encoding/hex" + "encoding/json" + "strconv" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Only old-reader fixtures bypass the production format-1 data-write refusal. +func legacyHeadFixture(t testing.TB, h storage.ChunkHead) *filerpb.Entry { + t.Helper() + doc := headDoc{Format: 1, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: h.State, Chunks: map[uint64]refDoc{}} + for idx, ref := range h.Chunks { + doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} + } + body, err := json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + return &filerpb.Entry{Name: headName, Content: body, Extended: map[string][]byte{extKind: []byte(kindChunkHead), extGen: []byte(strconv.FormatUint(h.Gen, 10)), extEpoch: []byte(strconv.FormatUint(h.Epoch, 10)), extHolder: []byte(h.Holder)}} +} From 209d626b15d163fcc1a02749b7058928279cd30c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:11:20 -0800 Subject: [PATCH 033/150] nvme: include capsule receipt and queued time in the write deadline --- seaweed-block/core/frontend/nvme/session.go | 11 ++++++++--- .../core/frontend/nvme/write_command_budget_test.go | 2 +- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/frontend/nvme/session.go b/seaweed-block/core/frontend/nvme/session.go index 61806e72f5..950b7a0124 100644 --- a/seaweed-block/core/frontend/nvme/session.go +++ b/seaweed-block/core/frontend/nvme/session.go @@ -81,7 +81,8 @@ type Request struct { capsule CapsuleCommand payload []byte // inline/R2T-collected data for Write resp CapsuleResponse - c2hData []byte // non-nil for Read/Identify responses + c2hData []byte // non-nil for Read/Identify responses + receivedAt time.Time // capsule arrival, including queued/R2T time dispatchReadyAt time.Time } @@ -267,7 +268,7 @@ func (s *Session) parseCapsule() (*Request, error) { return nil, err } } - req := &Request{capsule: capsule, payload: payload} + req := &Request{capsule: capsule, payload: payload, receivedAt: start} req.resp.CID = capsule.CID if s.qid > 0 && capsule.OpCode == ioWrite { s.recordWriteCapsuleReceiveParse(time.Since(start)) @@ -589,7 +590,11 @@ func (s *Session) handleRead(ctx context.Context, req *Request) { } func (s *Session) handleWrite(ctx context.Context, req *Request) { - ctx, cancel := frontend.WithWriteBudget(ctx, req.dispatchReadyAt) + arrival := req.receivedAt + if arrival.IsZero() { + arrival = req.dispatchReadyAt + } + ctx, cancel := frontend.WithWriteBudget(ctx, arrival) defer cancel() s.recordWriteCommand() s.recordWriteDispatchWait(time.Since(req.dispatchReadyAt)) diff --git a/seaweed-block/core/frontend/nvme/write_command_budget_test.go b/seaweed-block/core/frontend/nvme/write_command_budget_test.go index f965551d29..18b6fe303c 100644 --- a/seaweed-block/core/frontend/nvme/write_command_budget_test.go +++ b/seaweed-block/core/frontend/nvme/write_command_budget_test.go @@ -27,7 +27,7 @@ func TestSessionWriteBudgetIncludesDispatchQueue(t *testing.T) { b := &expiredDispatchBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"})} s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), respCh: make(chan *response, 1), done: make(chan struct{})} arrived := time.Now().Add(-5 * time.Second) - req := &Request{payload: make([]byte, 512), dispatchReadyAt: arrived} + req := &Request{payload: make([]byte, 512), receivedAt: arrived, dispatchReadyAt: time.Now()} req.capsule.OpCode = ioWrite req.capsule.NSID = 1 s.handleWrite(context.Background(), req) From 2617ed456c09f401b00206bd06ccac75cacde205 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:12:46 -0800 Subject: [PATCH 034/150] storage: bound write admission lock waits without detached lockers --- seaweed-block/core/storage/walstore.go | 24 +++++++++++---- .../core/storage/write_command_budget.go | 30 +++++++++++++++++++ .../core/storage/write_command_budget_test.go | 26 ++++++++++++++-- 3 files changed, 72 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index ac725f505e..c99ab8bb6e 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -759,7 +759,9 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (uint64, error) { deadline := s.writeAdmissionDeadline(ctx) - s.captureMu.RLock() + if err := s.acquireWriteLock(ctx, deadline, s.captureMu.TryRLock, s.captureMu.RLock); err != nil { + return 0, err + } defer s.captureMu.RUnlock() if err := s.stickyIOFault(); err != nil { return 0, err @@ -776,7 +778,9 @@ func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (u // admission Acquire may block up to admissionTimeout — under // hard pressure it spins waiting for the flusher to drain. s.beforeChunkMutation(uint64(lba), 1) - s.lifecycleMu.RLock() + if err := s.acquireWriteLock(ctx, deadline, s.lifecycleMu.TryRLock, s.lifecycleMu.RLock); err != nil { + return 0, err + } defer s.lifecycleMu.RUnlock() if err := s.writeBudgetError(ctx, deadline); err != nil { @@ -797,7 +801,9 @@ func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (u } commitLockStart := time.Now() - s.mu.Lock() + if err := s.acquireWriteLock(ctx, deadline, s.mu.TryLock, s.mu.Lock); err != nil { + return 0, err + } s.instr.recordWriteCommitLockWait(time.Since(commitLockStart)) if s.closed { s.mu.Unlock() @@ -862,7 +868,9 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error func (s *WALStore) WriteBatchContext(ctx context.Context, startLBA uint32, blocks [][]byte) ([]uint64, error) { deadline := s.writeAdmissionDeadline(ctx) - s.captureMu.RLock() + if err := s.acquireWriteLock(ctx, deadline, s.captureMu.TryRLock, s.captureMu.RLock); err != nil { + return nil, err + } defer s.captureMu.RUnlock() if err := s.stickyIOFault(); err != nil { return nil, err @@ -881,7 +889,9 @@ func (s *WALStore) WriteBatchContext(ctx context.Context, startLBA uint32, block } s.beforeChunkMutation(uint64(startLBA), uint64(len(blocks))) - s.lifecycleMu.RLock() + if err := s.acquireWriteLock(ctx, deadline, s.lifecycleMu.TryRLock, s.lifecycleMu.RLock); err != nil { + return nil, err + } defer s.lifecycleMu.RUnlock() if err := s.writeBudgetError(ctx, deadline); err != nil { @@ -902,7 +912,9 @@ func (s *WALStore) WriteBatchContext(ctx context.Context, startLBA uint32, block } commitLockStart := time.Now() - s.mu.Lock() + if err := s.acquireWriteLock(ctx, deadline, s.mu.TryLock, s.mu.Lock); err != nil { + return nil, err + } s.instr.recordWriteCommitLockWait(time.Since(commitLockStart)) if s.closed { s.mu.Unlock() diff --git a/seaweed-block/core/storage/write_command_budget.go b/seaweed-block/core/storage/write_command_budget.go index 316303e3dd..a21c22233c 100644 --- a/seaweed-block/core/storage/write_command_budget.go +++ b/seaweed-block/core/storage/write_command_budget.go @@ -37,3 +37,33 @@ func (s *WALStore) writeBudgetError(ctx context.Context, deadline time.Time) err } return nil } + +// A parked command owns no new physical I/O. Stop waiting for admission locks +// on expiry without a helper goroutine that could acquire them after return. +func (s *WALStore) acquireWriteLock(ctx context.Context, deadline time.Time, try func() bool, lock func()) error { + if deadline.IsZero() && ctx.Done() == nil { + lock() + return nil + } + if err := s.writeBudgetError(ctx, deadline); err != nil { + return err + } + if try() { + return nil + } + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for { + if err := s.writeBudgetError(ctx, deadline); err != nil { + return err + } + if try() { + return nil + } + select { + case <-ctx.Done(): + return s.writeBudgetError(ctx, deadline) + case <-tick.C: + } + } +} diff --git a/seaweed-block/core/storage/write_command_budget_test.go b/seaweed-block/core/storage/write_command_budget_test.go index ca9a88d4cb..606c1528fe 100644 --- a/seaweed-block/core/storage/write_command_budget_test.go +++ b/seaweed-block/core/storage/write_command_budget_test.go @@ -54,8 +54,7 @@ func TestWALStoreV3WriteContextDeadlineIncludesCaptureWait(t *testing.T) { } done <- err }() - <-ctx.Done() - s.captureMu.Unlock() + defer s.captureMu.Unlock() select { case err := <-done: if !errors.Is(err, ErrWALPressureTimeout) { @@ -81,3 +80,26 @@ func TestWALStoreV3WriteBudgetKeepsTerminalFault(t *testing.T) { t.Fatalf("fault hidden by deadline: %v", err) } } + +func TestWALStoreV3WriteBudgetBoundsAppendLockWait(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + s.mu.Lock() + done := make(chan error, 1) + go func() { _, err := s.WriteContext(ctx, 0, blk(1)); done <- err }() + select { + case err := <-done: + if !errors.Is(err, ErrWALPressureTimeout) { + s.mu.Unlock() + t.Fatal(err) + } + case <-time.After(time.Second): + s.mu.Unlock() + t.Fatal("expired writer still waits for append lock") + } + s.mu.Unlock() + if s.NextLSN() != 1 || s.dm.len() != 0 { + t.Fatal("expired append waiter mutated") + } +} From 1b5f06291a6affae63ed89cf59ec0a3d8752e031 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:13:47 -0800 Subject: [PATCH 035/150] test: publish segmented data in catalog and fork controls --- .../frontend/chunkstore/catalog_settle_test.go | 12 ++++++++++-- .../core/frontend/chunkstore/catalog_test.go | 15 +++++++++------ .../core/frontend/chunkstore/gc_copy_test.go | 2 +- .../core/frontend/chunkstore/retention_test.go | 9 +++++++++ 4 files changed, 29 insertions(+), 9 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go index 7d7290c26f..44b67dffaa 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go @@ -28,8 +28,7 @@ func intentsOf(t *testing.T, f *fakeFiler, vol string) []storage.ChunkIntent { func sortedKeysOf(h storage.ChunkHead, qualify string) []string { var out []string - for _, ref := range h.Chunks { - k := ref.Key + for _, k := range headKeys(h) { if qualify != "" && !strings.HasPrefix(k, "@") { k = "@" + qualify + "/" + k } @@ -196,11 +195,20 @@ func TestFork_IncompleteRetryBoundToOriginalImage(t *testing.T) { next.Chunks[k] = v } next.Chunks[5] = storage.ChunkRef{Key: "chunks/e1/c5/new", SHA256: sha256Of(chunkBytes(0x55))} + next, ids, err := r1.PrepareManifest(ctx, h, next, h.ChunkBytes) + if err != nil { + t.Fatal(err) + } gen, err := r1.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: 1}, next) if err != nil { t.Fatal(err) } next.Gen = gen + for _, id := range ids { + if err := r1.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-new"}, next); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/chunkstore/catalog_test.go b/seaweed-block/core/frontend/chunkstore/catalog_test.go index 6bdff5c17e..a81b2a262f 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_test.go @@ -89,7 +89,10 @@ func chunkBytes(fill byte) []byte { func catalogFixture(t *testing.T) (*fakeFiler, *fakeBlobs, *Catalog, storage.ChunkHead) { t.Helper() f, b := newFakeFiler(), newFakeBlobs() - c := newCat(t, f) + c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) + if err != nil { + t.Fatal(err) + } if _, err := c.EnsureVolume(context.Background(), "v1", catGeo); err != nil { t.Fatal(err) } @@ -242,7 +245,7 @@ func TestCatalog_DeleteMarksThenIdempotent(t *testing.T) { } func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) { - f, _, c, h := catalogFixture(t) + f, b, c, h := catalogFixture(t) ctx := context.Background() if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { t.Fatal(err) @@ -268,7 +271,7 @@ func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) { if got, _ := f.ListEntries(ctx, catBase+"/v2/intents", "", "", 0); len(got) != 0 { t.Fatalf("fork left %d intents", len(got)) } - r2, _ := NewChunkRemote(f, newFakeBlobs(), catBase+"/v2") + r2, _ := NewChunkRemote(f, b, catBase+"/v2") head, err := r2.GetHead(ctx) if err != nil { t.Fatal(err) @@ -278,7 +281,7 @@ func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) { } for idx, ref := range head.Chunks { src := h.Chunks[idx] - if ref.Key != "@v1/"+src.Key || ref.SHA256 != src.SHA256 { + if ref.Key != qualifyManifestKey("v1", src.Key) || ref.SHA256 != src.SHA256 { t.Fatalf("chunk %d ref %+v, want @v1/%s with the same hash", idx, ref, src.Key) } } @@ -319,7 +322,7 @@ func TestFork_ForkOfForkKeepsOriginalOwner(t *testing.T) { r3, _ := NewChunkRemote(f, b, catBase+"/v3") h3, _ := r3.GetHead(ctx) for idx, ref := range h3.Chunks { - if ref.Key != "@v1/"+h.Chunks[idx].Key { + if ref.Key != qualifyManifestKey("v1", h.Chunks[idx].Key) { t.Fatalf("second-level fork chunk %d names %q, want the original owner @v1/%s", idx, ref.Key, h.Chunks[idx].Key) } if got, err := r3.Get(ctx, ref.Key); err != nil || sha256.Sum256(got) != ref.SHA256 { @@ -657,7 +660,7 @@ func TestCatalog_EnsureVolumeCreatesTheInitialHead(t *testing.T) { if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil { t.Fatal(err) } - if kept, _, _ := c.ReadHead(ctx, "v2"); kept.Gen != pub.Gen || len(kept.Chunks) != 1 { + if kept, _, _ := c.ReadHead(ctx, "v2"); kept.Gen != pub.Gen || manifestCount(kept) != 1 || kept.Segments[0] != pub.Segments[0] { t.Fatalf("an existing HEAD was replaced by the initial one: %+v, published %+v", kept, pub) } diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go index 3a296d2d37..00789d6bf4 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go @@ -164,7 +164,7 @@ func TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace(t *testing.T) { t.Fatalf("first unrooted mark: %+v %v", result, e) } *now = now.Add(time.Hour) - if result, e := g.Run(ctx); e != nil || result.Reclaimed != 1 { + if result, e := g.Run(ctx); e != nil || result.Reclaimed != 2 { t.Fatalf("deleted attempt retained chunks forever: %+v %v", result, e) } if _, e := f.LookupEntry(ctx, path.Dir(oldPath), path.Base(oldPath)); e != nil { diff --git a/seaweed-block/core/frontend/chunkstore/retention_test.go b/seaweed-block/core/frontend/chunkstore/retention_test.go index 79e8eed28b..17c5991523 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_test.go @@ -338,11 +338,20 @@ func publishTagged(t *testing.T, f *fakeFiler, b *fakeBlobs, vol, tag string, ch if err != nil { t.Fatal(err) } + h, ids, err := r.PrepareManifest(ctx, cur, h, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks)) + if err != nil { + t.Fatal(err) + } gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h) if err != nil { t.Fatal(err) } h.Gen = gen + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } return h } From d6a757b121aee2d5f48e6147877a7cde16d124f2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:20:38 -0800 Subject: [PATCH 036/150] test: retry bounded pressure after releasing the catch-up pin --- .../durable/provider_chunk_noflush_test.go | 30 ++++++++++++++++--- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go b/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go index fd9fd059cf..1e3e2a9734 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go @@ -208,7 +208,8 @@ func TestWALStoreChunkV3NoFlushWithActiveRF2CatchupPin(t *testing.T) { t.Fatal(err) } ws.SetRecycleFloorSource(c) - h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: be, BlockSize: 4096, VolumeSize: 1 << 30}) + recorded := &noFlushBackend{Backend: be} + h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: recorded, BlockSize: 4096, VolumeSize: 1 << 30}) data := bytes.Repeat([]byte{0x5a}, 128*1024) var stalled bool for off := 0; off < 80*1024*1024; off += len(data) { @@ -236,8 +237,29 @@ func TestWALStoreChunkV3NoFlushWithActiveRF2CatchupPin(t *testing.T) { t.Fatalf("retained catch-up records=%d err=%v", count, err) } c.EndSession("r2") - r := h.Handle(ctx, nvme.IOCommand{Opcode: 1, NSID: 1, SLBA: 20000, NLB: 32, Data: data}) - if err := r.AsError(); err != nil { - t.Fatalf("no-Flush progress after catch-up release: %v", err) + retryDeadline := time.Now().Add(30 * time.Second) + busy := 0 + for { + start := time.Now() + r := h.Handle(ctx, nvme.IOCommand{Opcode: 1, NSID: 1, SLBA: 20000, NLB: 32, Data: data}) + if time.Since(start) >= 5*time.Second || time.Now().After(retryDeadline) { + t.Fatalf("released pin exceeded bound: attempt=%v busy=%d result=%+v", time.Since(start), busy, r) + } + if r.AsError() == nil { + break + } + if !errors.Is(recorded.lastError, frontend.ErrBackendBusy) || r.SCT != nvme.SCTGeneric || r.SC != nvme.SCNamespaceNotReady { + t.Fatalf("non-retryable released-pin write: %+v cause=%v", r, recorded.lastError) + } + busy++ + time.Sleep(25 * time.Millisecond) } + got := make([]byte, len(data)) + if n, err := be.Read(ctx, 20000*4096, got); err != nil || n != len(got) || !bytes.Equal(got, data) { + t.Fatalf("released-pin readback n=%d err=%v", n, err) + } + if ws.CheckpointLSN() == 0 { + t.Fatal("released pin did not permit checkpoint progress") + } + t.Logf("released pin completed: busy=%d checkpoint=%d", busy, ws.CheckpointLSN()) } From f92e6da17126602d8ad44f80ae0c81549c6963bf Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:22:55 -0800 Subject: [PATCH 037/150] test: add format refusal goldens and pending birth frontier regression --- .../chunkstore/format_refusal_test.go | 100 ++++++++++++++++++ .../core/storage/chunk_birth_test.go | 45 ++++++++ 2 files changed, 145 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/format_refusal_test.go create mode 100644 seaweed-block/core/storage/chunk_birth_test.go diff --git a/seaweed-block/core/frontend/chunkstore/format_refusal_test.go b/seaweed-block/core/frontend/chunkstore/format_refusal_test.go new file mode 100644 index 0000000000..e328dc1fd5 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_refusal_test.go @@ -0,0 +1,100 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "encoding/json" + "path" + "testing" +) + +func TestManifestFormatUpgradeRejectsUnsupportedOrInconsistentObjects(t *testing.T) { + type mutation func(map[string]any) + for _, tc := range []struct { + name string + segment bool + change mutation + }{ + {"levels", false, func(v map[string]any) { v["levels"] = 2 }}, + {"missing-levels", false, func(v map[string]any) { delete(v, "levels") }}, + {"head-version", false, func(v map[string]any) { v["format"] = 4 }}, + {"head-unknown", false, func(v map[string]any) { v["future"] = true }}, + {"segment-version-ref", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["seg_format"] = 3 }}, + {"root-max", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["max_birth_lsn"] = 41 }}, + {"root-max-future", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["max_birth_lsn"] = 43 }}, + {"segment-version", true, func(v map[string]any) { v["format"] = 3 }}, + {"segment-unknown", true, func(v map[string]any) { v["future"] = true }}, + {"segment-max", true, func(v map[string]any) { v["max_birth_lsn"] = 41 }}, + {"segment-max-missing", true, func(v map[string]any) { delete(v, "max_birth_lsn") }}, + {"encoding", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["enc"] = "zstd" }}, + {"birth-future", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["birth_lsn"] = 43 }}, + {"birth-missing", true, func(v map[string]any) { delete(v["chunks"].(map[string]any)["0"].(map[string]any), "birth_lsn") }}, + {"hash-shape", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["sha256"] = "bad" }}, + } { + t.Run(tc.name, func(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + r, h := publishSegmented(t, f, b) + ctx := context.Background() + e, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName) + if err != nil { + t.Fatal(err) + } + var root map[string]any + if err := json.Unmarshal(e.Content, &root); err != nil { + t.Fatal(err) + } + if tc.segment { + body, err := r.Get(ctx, h.Segments[0].Key) + if err != nil { + t.Fatal(err) + } + var object map[string]any + if err := json.Unmarshal(body, &object); err != nil { + t.Fatal(err) + } + tc.change(object) + body, err = json.Marshal(object) + if err != nil { + t.Fatal(err) + } + if err := r.Put(ctx, "malformed-segment", body); err != nil { + t.Fatal(err) + } + ref := root["segments"].(map[string]any)["0"].(map[string]any) + ref["key"] = qualifyManifestKey("v1", "malformed-segment") + ref["sha256"] = sha256.Sum256(body) + } else { + tc.change(root) + } + e.Content, err = json.Marshal(root) + if err != nil { + t.Fatal(err) + } + if err := f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { + t.Fatal(err) + } + if _, err := r.GetHead(ctx); err == nil { + t.Fatal("invalid persisted schema accepted") + } + }) + } +} + +func TestManifestFormatUpgradeReadsLegacyRootGoldens(t *testing.T) { + for _, body := range []string{ + `{"format":1,"gen":1,"epoch":1,"holder":"old","remote_lsn":7,"chunks":{"0":{"key":"old","sha256":"0000000000000000000000000000000000000000000000000000000000000000"}}}`, + `{"format":2,"gen":1,"epoch":1,"holder":"old","remote_lsn":7,"chunk_bytes":4096,"chunk_count":1,"segments":{"0":{"key":"@v1/old","sha256":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"owner":"v1","count":1}}}`, + } { + h, err := DecodeHeadDocument("legacy", []byte(body)) + if err != nil { + t.Fatal(err) + } + if h.Segments == nil { + if h.Chunks[0].Encoding != "full" || h.Chunks[0].BirthLSN != 7 { + t.Fatal("legacy flat frontier not inherited") + } + } else if h.Segments[0].SegFormat != 1 || h.Segments[0].MaxBirthLSN != 7 { + t.Fatal("legacy segment maximum not inherited") + } + } +} diff --git a/seaweed-block/core/storage/chunk_birth_test.go b/seaweed-block/core/storage/chunk_birth_test.go new file mode 100644 index 0000000000..8d5aebee36 --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_test.go @@ -0,0 +1,45 @@ +package storage + +import "testing" + +func TestChunkBirthTracksNewestLocalWriteAtCut(t *testing.T) { + for _, bound := range []int{0, 1} { + t.Run(string(rune('0'+bound)), func(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.FreshFromHead = true + cfg.BarrierBound = bound + l := mustAttach(t, s, f, cfg) + x, err := s.Write(0, makeBlock(ctBlockSize, 0x41)) + if err != nil { + t.Fatal(err) + } + if _, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42)); err != nil { + t.Fatal(err) + } + y, err := s.Write(ctChunkBlocks+1, makeBlock(ctBlockSize, 0x43)) + if err != nil { + t.Fatal(err) + } + first, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if first.Head.Chunks[0].BirthLSN != x || first.Head.Chunks[1].BirthLSN != y || first.Head.Chunks[0].Encoding != "full" || first.Head.RemoteLSN != y { + t.Fatalf("births did not preserve distinct local write frontiers: %+v, want %d/%d", first.Head, x, y) + } + z, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x44)) + if err != nil { + t.Fatal(err) + } + second, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if second.Head.Chunks[0] != first.Head.Chunks[0] || second.Head.Chunks[1].BirthLSN != z { + t.Fatal("rewrite changed a cold chunk birth or failed to advance the changed version") + } + }) + } +} From e5391bea5431471cf8c5fc729b2d75ecc6a35231 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:23:44 -0800 Subject: [PATCH 038/150] feat: capture chunk births under the candidate barrier --- .../core/frontend/chunkstore/catalog_test.go | 2 +- .../frontend/chunkstore/retention_test.go | 6 +++--- seaweed-block/core/storage/chunk_birth.go | 18 ++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 19 ++++++++++++------- 4 files changed, 34 insertions(+), 11 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_birth.go diff --git a/seaweed-block/core/frontend/chunkstore/catalog_test.go b/seaweed-block/core/frontend/chunkstore/catalog_test.go index a81b2a262f..33ade710d3 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_test.go @@ -285,7 +285,7 @@ func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) { t.Fatalf("chunk %d ref %+v, want @v1/%s with the same hash", idx, ref, src.Key) } } - if res.HeadGen != 1 || res.HeadEpoch != 0 || res.QualifiedRefs != 2 || res.SourceGen != h.Gen || res.RemoteLSN != 42 || res.Replayed { + if res.HeadGen != 1 || res.HeadEpoch != 0 || res.QualifiedRefs != 1 || res.ChunkCount != 2 || res.SourceGen != h.Gen || res.RemoteLSN != 42 || res.Replayed { t.Fatalf("result %+v", res) } v, ok, err := c.ReadVolume(ctx, "v2") diff --git a/seaweed-block/core/frontend/chunkstore/retention_test.go b/seaweed-block/core/frontend/chunkstore/retention_test.go index 17c5991523..765aee8490 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_test.go @@ -372,7 +372,7 @@ func TestCatalog_UsageFromManifests(t *testing.T) { if u.LiveChunks != 2 || u.LiveBytes != 2*full || len(u.Snapshots) != 1 || u.Snapshots[0].ExclusiveBytes != 0 { t.Fatalf("shared chunks: %+v", u) } - if u.StoredBindings != 2 || u.StoredBytes != 2*full || u.StoredUpperBound { + if u.StoredBindings != 2+u.ManifestBindings || u.ManifestBindings != 1 || u.StoredBytes != 2*full+u.ManifestBytes || u.StoredUpperBound { t.Fatalf("stored: %+v; want 2 bindings, exact", u) } @@ -386,7 +386,7 @@ func TestCatalog_UsageFromManifests(t *testing.T) { // both of s1's chunks are now exclusive: the new HEAD uses e2 keys t.Fatalf("after HEAD moved: s1 exclusive %d, want %d", u.Snapshots[0].ExclusiveBytes, 2*full) } - if u.StoredBindings != 4 || u.StoredBytes != 4*full || u.StoredUpperBound { + if u.StoredBindings != 4+u.ManifestBindings || u.ManifestBindings != 2 || u.StoredBytes != 4*full+u.ManifestBytes || u.StoredUpperBound { t.Fatalf("stored after HEAD moved: %+v; want 4 bindings, exact", u) } @@ -399,7 +399,7 @@ func TestCatalog_UsageFromManifests(t *testing.T) { if err != nil { t.Fatal(err) } - if len(u.Snapshots) != 0 || u.StoredBindings != 4 || !u.StoredUpperBound { + if len(u.Snapshots) != 0 || u.StoredBindings != 4+u.ManifestBindings || !u.StoredUpperBound { t.Fatalf("after delete: %+v; want no snapshots, 4 bindings, upper bound", u) } } diff --git a/seaweed-block/core/storage/chunk_birth.go b/seaweed-block/core/storage/chunk_birth.go new file mode 100644 index 0000000000..6c580c43ca --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth.go @@ -0,0 +1,18 @@ +package storage + +// The caller holds captureMu exclusive, with no layer state lock held. +// An owned-map max is the newest local write in that chunk; base fills do +// not advance it. Other engines use the cut frontier as an upper bound. +func (l *chunkLayerImpl) captureBirths(candidates map[uint64]bool, frontier uint64) map[uint64]uint64 { + out := make(map[uint64]uint64, len(candidates)) + l.s.mu.RLock() + defer l.s.mu.RUnlock() + for idx := range candidates { + birth := frontier + if l.usesOwnedMapV3() && l.s.v3.mapEntries[idx].LSN != 0 { + birth = l.s.v3.mapEntries[idx].LSN + } + out[idx] = birth + } + return out +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index d8d56fc664..e9b03fa840 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -780,11 +780,12 @@ func (l *chunkLayerImpl) MakeRemoteDurable(ctx context.Context, t uint64) error } type capturedChunk struct { - idx uint64 - data []byte - sum [32]byte - zero bool - key string // staged: already uploaded under this key (data is nil) + idx uint64 + data []byte + sum [32]byte + zero bool + key string // staged: already uploaded under this key (data is nil) + birth uint64 } // stagedChunk is a chunk pre-copied outside the barrier at chunk version @@ -907,6 +908,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.cutLSN = h baseHead := copyHead(l.head) l.stMu.Unlock() + // Candidates, mutation versions and births belong to the same barrier. + // Do not sample the owned map after COW writers are admitted again. + births := l.captureBirths(candidates, h) st.CandidateChunks = len(candidates) var copyErr error @@ -974,6 +978,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } var uploads []upload for _, c := range captured { + c.birth = births[c.idx] ref, had := baseHead.Chunks[c.idx] switch { case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum: @@ -986,7 +991,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch continue } if c.key != "" { // staged: uploaded before the barrier - next.Chunks[c.idx] = chunkRef{Key: c.key, SHA256: c.sum} + next.Chunks[c.idx] = chunkRef{Key: c.key, SHA256: c.sum, Encoding: "full", BirthLSN: c.birth} newKeys[c.idx] = c.key changed = append(changed, c.idx) st.StagedChunksUsed++ @@ -1019,7 +1024,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w: %w", errChunkRemoteUnavailable, err) } for _, u := range uploads { - next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum} + next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum, Encoding: "full", BirthLSN: u.c.birth} newKeys[u.c.idx] = u.key changed = append(changed, u.c.idx) st.UploadedChunks++ From cd6e957eaa1521190700afa9b9c4a79ca9c8ebee Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:24:33 -0800 Subject: [PATCH 039/150] storage: apply write deadlines to admission pressure snapshots --- seaweed-block/core/storage/wal_admission.go | 31 ++++++++++++--- seaweed-block/core/storage/walstore.go | 4 +- .../core/storage/write_command_budget.go | 38 +++++++++++++++++++ 3 files changed, 65 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/storage/wal_admission.go b/seaweed-block/core/storage/wal_admission.go index 913d3bd91f..26be803ba1 100644 --- a/seaweed-block/core/storage/wal_admission.go +++ b/seaweed-block/core/storage/wal_admission.go @@ -97,10 +97,14 @@ func (a *walAdmission) HardMark() float64 { return a.hardMark } // expires. Returns errWALFull on timeout, errVolumeClosed if the // store closes during the wait. func (a *walAdmission) Acquire(timeout time.Duration) error { - return a.acquireContext(context.Background(), timeout) + return a.acquireContext(context.Background(), timeout, nil) } -func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration) error { +func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration, sample func() (float64, error)) error { + contextual := sample != nil + if sample == nil { + sample = func() (float64, error) { return a.walUsed(), nil } + } if err := ctx.Err(); err != nil { if fault := a.terminalFault(); fault != nil { return fault @@ -110,19 +114,29 @@ func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration deadline := time.NewTimer(timeout) defer deadline.Stop() - pressure := a.walUsed() + pressure, err := sample() + if err != nil { + return err + } // Hard watermark: wait for flusher to drain before competing // for the semaphore. if pressure >= a.hardMark { a.notifyFn() hardStart := time.Now() - for a.walUsed() >= a.hardMark { + for { + pressure, err = sample() + if err != nil { + return err + } + if pressure < a.hardMark { + break + } if err := a.terminalFault(); err != nil { a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds()) return err } - if a.closedFn() { + if !contextual && a.closedFn() { a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds()) return errVolumeClosed } @@ -185,10 +199,15 @@ func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration } return ErrWALPressureTimeout case <-closeTick.C: + if contextual { + if _, err := sample(); err != nil { + return err + } + } if err := a.terminalFault(); err != nil { return err } - if a.closedFn() { + if !contextual && a.closedFn() { return errVolumeClosed } } diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index c99ab8bb6e..208da4f639 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -791,7 +791,7 @@ func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (u if !deadline.IsZero() { wait = time.Until(deadline) } - if err := s.admission.acquireContext(ctx, wait); err != nil { + if err := s.admission.acquireContext(ctx, wait, s.writePressureSample(ctx, deadline)); err != nil { return 0, fmt.Errorf("storage: WAL admission: %w", err) } defer s.admission.Release() @@ -902,7 +902,7 @@ func (s *WALStore) WriteBatchContext(ctx context.Context, startLBA uint32, block if !deadline.IsZero() { wait = time.Until(deadline) } - if err := s.admission.acquireContext(ctx, wait); err != nil { + if err := s.admission.acquireContext(ctx, wait, s.writePressureSample(ctx, deadline)); err != nil { return nil, fmt.Errorf("storage: WAL admission: %w", err) } defer s.admission.Release() diff --git a/seaweed-block/core/storage/write_command_budget.go b/seaweed-block/core/storage/write_command_budget.go index a21c22233c..32a77c3b88 100644 --- a/seaweed-block/core/storage/write_command_budget.go +++ b/seaweed-block/core/storage/write_command_budget.go @@ -67,3 +67,41 @@ func (s *WALStore) acquireWriteLock(ctx context.Context, deadline time.Time, try } } } + +// The legacy controller's callbacks take blocking locks. A v3 guest write +// samples the same descriptor/floor/writer tuple with its command deadline; +// failure to acquire a lock refuses admission, never grants capacity or reuse. +func (s *WALStore) writePressureSample(ctx context.Context, deadline time.Time) func() (float64, error) { + if s.v3 == nil { + return nil + } + return func() (float64, error) { + if err := s.acquireWriteLock(ctx, deadline, s.mu.TryRLock, s.mu.RLock); err != nil { + return 0, err + } + defer s.mu.RUnlock() + if s.closed { + return 0, errVolumeClosed + } + v := s.v3 + w := v.w + if w == nil { + return 0, nil + } // append still refuses the missing binding + p := v.pub + if err := s.acquireWriteLock(ctx, deadline, p.descMu.TryLock, p.descMu.Lock); err != nil { + return 0, err + } + floor, valid := p.reuseFloorLocked() + d := p.cur + p.descMu.Unlock() // preserve snapshot ordering: no descriptor -> writer edge + if err := s.acquireWriteLock(ctx, deadline, w.mu.TryLock, w.mu.Lock); err != nil { + return 0, err + } + defer w.mu.Unlock() + if !valid || d.WALSize == 0 || d.Nonce != w.nonce || w.head < floor || w.head-floor > d.WALSize { + return 0, nil + } + return float64(w.head-floor) / float64(d.WALSize), nil + } +} From d89865366cc53e9f754b99a3fb8406217adb1738 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:26:07 -0800 Subject: [PATCH 040/150] test: observe terminal faults at the actual semaphore wait --- .../core/storage/wal_admission_fault_v3_test.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/storage/wal_admission_fault_v3_test.go b/seaweed-block/core/storage/wal_admission_fault_v3_test.go index 2f1aaf023a..fe85a7181e 100644 --- a/seaweed-block/core/storage/wal_admission_fault_v3_test.go +++ b/seaweed-block/core/storage/wal_admission_fault_v3_test.go @@ -85,12 +85,13 @@ func TestWALStoreV3AdmissionReturnsFaultWhileWaitingForWriterSlot(t *testing.T) var once sync.Once release := func() { once.Do(func() { close(resume) }) } t.Cleanup(release) - sample := s.admission.walUsed - s.admission.walUsed = func() float64 { - used := sample() // its store/descriptor/writer locks have all released - close(entered) + var sampled sync.Once + // Observe the real semaphore wait's terminal check. Pressure sampling now + // uses the command-aware callback instead of the legacy float callback. + s.admission.faultFn = func() error { + sampled.Do(func() { close(entered) }) <-resume - return used + return s.stickyIOFault() } done := make(chan error, 1) go func() { _, err := s.Write(0, blk(1)); done <- err }() From ac02bbc2ac4d7af381b68d3982b65e0e30e5f2cd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:26:52 -0800 Subject: [PATCH 041/150] fix: retain inherited BASE birth frontiers including zero --- seaweed-block/core/storage/base_install_v3.go | 10 +- seaweed-block/core/storage/chunk_birth.go | 2 +- .../core/storage/chunk_birth_test.go | 95 ++++++++++++++++++- 3 files changed, 104 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/storage/base_install_v3.go b/seaweed-block/core/storage/base_install_v3.go index 9b3ef91ecb..1139ea937c 100644 --- a/seaweed-block/core/storage/base_install_v3.go +++ b/seaweed-block/core/storage/base_install_v3.go @@ -633,7 +633,15 @@ func (s *WALStore) markMapUnknownV3(lba uint64) { if v.ownedMap == nil { return } - v.mapEntries[lba/v.ownedMap.chunkBlocks].Unknown = true + e := &v.mapEntries[lba/v.ownedMap.chunkBlocks] + e.Unknown = true + // A BASE byte has no WAL record: inherit its image frontier, not an + // unrelated later write. Keep UNKNOWN conservative as before. + birth := s.nextLSN - 1 + if d := v.pub.current(); d.BaseState == BaseInstalling { + birth = d.BaseLSN + } + e.LSN = max(e.LSN, birth) } // InstalledBaseLSN reports a completed local BASE obligation, not a normal diff --git a/seaweed-block/core/storage/chunk_birth.go b/seaweed-block/core/storage/chunk_birth.go index 6c580c43ca..85b3f7c273 100644 --- a/seaweed-block/core/storage/chunk_birth.go +++ b/seaweed-block/core/storage/chunk_birth.go @@ -9,7 +9,7 @@ func (l *chunkLayerImpl) captureBirths(candidates map[uint64]bool, frontier uint defer l.s.mu.RUnlock() for idx := range candidates { birth := frontier - if l.usesOwnedMapV3() && l.s.v3.mapEntries[idx].LSN != 0 { + if l.usesOwnedMapV3() { birth = l.s.v3.mapEntries[idx].LSN } out[idx] = birth diff --git a/seaweed-block/core/storage/chunk_birth_test.go b/seaweed-block/core/storage/chunk_birth_test.go index 8d5aebee36..36986ab9dd 100644 --- a/seaweed-block/core/storage/chunk_birth_test.go +++ b/seaweed-block/core/storage/chunk_birth_test.go @@ -1,6 +1,99 @@ package storage -import "testing" +import ( + "bytes" + "context" + "sync" + "testing" + "time" +) + +func TestChunkBirthBASEUsesInheritedFrontierIncludingZero(t *testing.T) { + for _, frontier := range []uint64{0, 7} { + t.Run(string(rune('0'+frontier)), func(t *testing.T) { + s, _, l := mappedBASELayerV3(t) + h, err := s.BeginBaseInstall(frontier, idA) + if err != nil { + t.Fatal(err) + } + if err := h.WriteBase(5, blk(0x55)); err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + newest, err := s.Write(0, blk(0x41)) + if err != nil { + t.Fatal(err) + } + cut, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if cut.Head.Chunks[1].BirthLSN != frontier || cut.Head.Chunks[0].BirthLSN != newest { + t.Fatalf("BASE birth drifted with unrelated WAL writes: %+v, inherited %d", cut.Head, frontier) + } + }) + } +} + +func TestChunkBirthCOWDoesNotObservePostBarrierWrite(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.FreshFromHead = true + cfg.BarrierBound = 0 + cfg.UploadConcurrency = 1 + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + if _, err := s.Write(0, makeBlock(ctBlockSize, 0x41)); err != nil { + t.Fatal(err) + } + before, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42)) + if err != nil { + t.Fatal(err) + } + entered, release := make(chan struct{}), make(chan struct{}) + var once, releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + l.testCOWRead = func(idx uint64, _ bool) { + if idx == 0 { + once.Do(func() { close(entered) }) + <-release + } + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + done := make(chan error, 1) + joined := make(chan struct{}) + t.Cleanup(func() { + cancel() + unblock() + select { + case <-joined: + case <-time.After(ctLocalBound): + t.Error("birth COW worker not joined") + } + }) + go func() { defer close(joined); _, err := l.Cut(ctx); done <- err }() + cowWaitSignal(t, entered, "copy after the birth barrier") + after, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x43)) + if err != nil { + t.Fatal(err) + } + unblock() + if err := waitErr(t, done, "birth COW cut"); err != nil { + t.Fatal(err) + } + cowWaitSignal(t, joined, "birth COW join") + first := f.installedHeads()[0] + if first.Chunks[1].BirthLSN != before || !bytes.Equal(f.imageOf(t, first)[ctChunkBlocks*ctBlockSize:(ctChunkBlocks+1)*ctBlockSize], makeBlock(ctBlockSize, 0x42)) { + t.Fatal("post-barrier write changed the saved image or its birth") + } + l.testCOWRead = nil + second, err := l.Cut(ctTimeout(t)) + if err != nil || second.Head.Chunks[1].BirthLSN != after { + t.Fatalf("next version lost post-barrier birth: %+v %v", second, err) + } +} func TestChunkBirthTracksNewestLocalWriteAtCut(t *testing.T) { for _, bound := range []int{0, 1} { From af633299e57ca5004468e397a5b8728097c355fd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:27:16 -0800 Subject: [PATCH 042/150] test: bound every v3 pressure-snapshot lock by the write deadline --- .../core/storage/write_command_budget_test.go | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/seaweed-block/core/storage/write_command_budget_test.go b/seaweed-block/core/storage/write_command_budget_test.go index 606c1528fe..77f65864f1 100644 --- a/seaweed-block/core/storage/write_command_budget_test.go +++ b/seaweed-block/core/storage/write_command_budget_test.go @@ -103,3 +103,63 @@ func TestWALStoreV3WriteBudgetBoundsAppendLockWait(t *testing.T) { t.Fatal("expired append waiter mutated") } } + +func TestWALStoreV3WriteBudgetBoundsPressureLocks(t *testing.T) { + for _, name := range []string{"descriptor", "writer"} { + t.Run(name, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + var unlock func() + if name == "descriptor" { + s.v3.pub.descMu.Lock() + unlock = s.v3.pub.descMu.Unlock + } else { + s.v3.w.mu.Lock() + unlock = s.v3.w.mu.Unlock + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + done := make(chan error, 1) + go func() { _, err := s.WriteContext(ctx, 0, blk(1)); done <- err }() + select { + case err := <-done: + if !errors.Is(err, ErrWALPressureTimeout) { + unlock() + t.Fatal(err) + } + case <-time.After(time.Second): + unlock() + t.Fatal("pressure snapshot did not respect command deadline") + } + unlock() + if s.NextLSN() != 1 || s.dm.len() != 0 { + t.Fatal("timed-out pressure sample granted a write") + } + }) + } +} + +func TestWALStoreV3WritePressureSampleMatchesOccupancy(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + check := func() { + t.Helper() + got, err := s.writePressureSample(context.Background(), time.Now().Add(time.Second))() + if err != nil || got != s.walUsedFraction() { + t.Fatalf("sample=%v err=%v normal=%v", got, err, s.walUsedFraction()) + } + } + check() + for lba := uint32(0); lba < 8; lba++ { + if _, err := s.Write(lba, blk(byte(lba))); err != nil { + t.Fatal(err) + } + } + check() + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + check() + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + check() +} From 5c835e21af63fb12abe8921f41971f9f114cc3ae Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:32:42 -0800 Subject: [PATCH 043/150] test: preserve legacy segments and version snapshot metadata --- .../chunkstore/format_refusal_test.go | 5 + .../frontend/chunkstore/format_reuse_test.go | 185 ++++++++++++++++++ .../storage/chunk_birth_migration_test.go | 97 +++++++++ 3 files changed, 287 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/format_reuse_test.go create mode 100644 seaweed-block/core/storage/chunk_birth_migration_test.go diff --git a/seaweed-block/core/frontend/chunkstore/format_refusal_test.go b/seaweed-block/core/frontend/chunkstore/format_refusal_test.go index e328dc1fd5..1fc6471d0a 100644 --- a/seaweed-block/core/frontend/chunkstore/format_refusal_test.go +++ b/seaweed-block/core/frontend/chunkstore/format_refusal_test.go @@ -26,6 +26,11 @@ func TestManifestFormatUpgradeRejectsUnsupportedOrInconsistentObjects(t *testing {"segment-unknown", true, func(v map[string]any) { v["future"] = true }}, {"segment-max", true, func(v map[string]any) { v["max_birth_lsn"] = 41 }}, {"segment-max-missing", true, func(v map[string]any) { delete(v, "max_birth_lsn") }}, + {"computed-max", true, func(v map[string]any) { + for _, entry := range v["chunks"].(map[string]any) { + entry.(map[string]any)["birth_lsn"] = 41 + } + }}, {"encoding", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["enc"] = "zstd" }}, {"birth-future", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["birth_lsn"] = 43 }}, {"birth-missing", true, func(v map[string]any) { delete(v["chunks"].(map[string]any)["0"].(map[string]any), "birth_lsn") }}, diff --git a/seaweed-block/core/frontend/chunkstore/format_reuse_test.go b/seaweed-block/core/frontend/chunkstore/format_reuse_test.go new file mode 100644 index 0000000000..7b738b075d --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_reuse_test.go @@ -0,0 +1,185 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "path" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func legacySegmentedFixture(t *testing.T) (*ChunkRemote, *fakeBlobs, storage.ChunkHead) { + t.Helper() + f, b, _, _, _ := gcFixture(t) + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + doc := segmentedHeadDoc{headIdentityDoc: headIdentityDoc{Format: 2, Gen: 1, Epoch: 1, Holder: "old", RemoteLSN: 42}, Segments: map[uint64]legacySegmentRefDoc{}, ChunkBytes: 4096, ChunkCount: 2} + for group := uint64(0); group < 2; group++ { + key := fmt.Sprintf("legacy-data-%d", group) + data := []byte{byte(0x41 + group)} + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + idx := group * (manifestSegmentBytes / 4096) + segment := legacySegmentDoc{Format: 1, Range: group, ChunkBytes: 4096, Owner: "v1", Chunks: map[uint64]legacyChunkRefDoc{idx: {Key: qualifyManifestKey("v1", key), SHA256: sha256.Sum256(data)}}} + body, err := json.Marshal(segment) + if err != nil { + t.Fatal(err) + } + segmentKey := fmt.Sprintf("legacy-segment-%d", group) + if err := r.Put(ctx, segmentKey, body); err != nil { + t.Fatal(err) + } + doc.Segments[group] = legacySegmentRefDoc{Key: qualifyManifestKey("v1", segmentKey), SHA256: sha256.Sum256(body), Owner: "v1", Count: 1} + } + e := legacyHeadFixture(t, storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "old", RemoteLSN: 42}) + e.Content, err = json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + if err := f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { + t.Fatal(err) + } + h, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + return r, b.fakeBlobs, h +} + +func TestManifestFormatUpgradeReusesColdSegmentsWithoutUploads(t *testing.T) { + r, b, base := legacySegmentedFixture(t) + ctx := context.Background() + before, _, _ := b.counts() + unchanged, ids, err := r.PrepareManifest(ctx, base, base, base.ChunkBytes) + if err != nil { + t.Fatal(err) + } + after, _, _ := b.counts() + if before != after || len(ids) != 0 || unchanged.Segments[0] != base.Segments[0] || unchanged.Segments[1] != base.Segments[1] { + t.Fatal("zero changed groups uploaded a segment or intent") + } + next := base + next.RemoteLSN = 43 + next.Chunks = map[uint64]storage.ChunkRef{} + for idx, ref := range base.Chunks { + next.Chunks[idx] = ref + } + data := []byte{0x53} + if err := r.Put(ctx, "changed-data", data); err != nil { + t.Fatal(err) + } + idx := manifestSegmentBytes / base.ChunkBytes + next.Chunks[idx] = storage.ChunkRef{Key: qualifyManifestKey("v1", "changed-data"), SHA256: sha256.Sum256(data), Encoding: "full", BirthLSN: 43} + before, _, _ = b.counts() + updated, ids, err := r.PrepareManifest(ctx, base, next, base.ChunkBytes) + if err != nil { + t.Fatal(err) + } + after, _, _ = b.counts() + if after-before != 1 || len(ids) != 1 || updated.Segments[0] != base.Segments[0] || updated.Segments[1].SegFormat != 2 || updated.Segments[1].MaxBirthLSN != 43 { + t.Fatal("one changed group rewrote cold segments or lost the new format") + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, updated); err != nil { + t.Fatal(err) + } + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + h, err := r.GetHead(ctx) + if err != nil || h.Segments[0].SegFormat != 1 || h.Chunks[0].BirthLSN != 42 || h.Chunks[idx].BirthLSN != 43 { + t.Fatalf("mixed legacy/new image did not resolve: %+v %v", h, err) + } + got, err := r.Get(ctx, h.Chunks[idx].Key) + if err != nil || len(got) != 1 || got[0] != 0x53 { + t.Fatal("mixed root changed bytes") + } +} + +func TestManifestFormatUpgradeAllowsInheritedZeroBirth(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + base, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + data := []byte{0x57} + if err := r.Put(ctx, "zero-birth", data); err != nil { + t.Fatal(err) + } + next := storage.ChunkHead{Epoch: 1, Holder: "base", Chunks: map[uint64]storage.ChunkRef{0: {Key: "zero-birth", SHA256: sha256.Sum256(data), Encoding: "full", BirthLSN: 0}}} + next, ids, err := r.PrepareManifest(ctx, base, next, 4096) + if err != nil { + t.Fatal(err) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, next); err != nil { + t.Fatal(err) + } + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + h, err := r.GetHead(ctx) + if err != nil || h.Chunks[0].BirthLSN != 0 || h.Segments[0].MaxBirthLSN != 0 { + t.Fatalf("fresh base zero birth refused: %+v %v", h, err) + } +} + +func TestManifestFormatUpgradeSnapshotAndForkPreserveMetadata(t *testing.T) { + f, b, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "format3", RequestID: "format3"}, h); err != nil { + t.Fatal(err) + } + snapshotPath := snapPath(t, f, "v1", "format3") + e, err := f.LookupEntry(ctx, path.Dir(snapshotPath), path.Base(snapshotPath)) + if err != nil { + t.Fatal(err) + } + var snapshot struct { + Head struct { + Format int `json:"format"` + Levels int `json:"levels"` + } `json:"head"` + } + if err := json.Unmarshal(e.Content, &snapshot); err != nil || snapshot.Head.Format != 3 || snapshot.Head.Levels != 1 { + t.Fatalf("data snapshot embedded flat HEAD: %s %v", e.Content, err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "format3", Target: "v2", RequestID: "format3-fork"}); err != nil { + t.Fatal(err) + } + r, err := NewChunkRemote(f, b, path.Join(catBase, "v2")) + if err != nil { + t.Fatal(err) + } + fork, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if fork.RemoteLSN != h.RemoteLSN || len(fork.Chunks) != len(h.Chunks) { + t.Fatal("fork lost inherited frontier or chunk count") + } + for idx, ref := range h.Chunks { + if fork.Chunks[idx] != ref { + t.Fatal("fork changed owner, encoding, birth or stored-byte hash") + } + } + for group, ref := range h.Segments { + if fork.Segments[group] != ref { + t.Fatal("fork changed segment version or maximum") + } + } +} diff --git a/seaweed-block/core/storage/chunk_birth_migration_test.go b/seaweed-block/core/storage/chunk_birth_migration_test.go new file mode 100644 index 0000000000..7888f79fcb --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_migration_test.go @@ -0,0 +1,97 @@ +package storage + +import ( + "bytes" + "os" + "testing" +) + +func TestChunkBirthMigrationCarriesImageFrontier(t *testing.T) { + s, path := newChunkTestStore(t) + d := s.v3.pub.current() + mapPath := s.v3.ownedMap.fd.Name() + if err := s.Close(); err != nil { + t.Fatal(err) + } + src := MigrationSourceV3{UUID: d.UUID, VolumeSize: d.VolumeSize, ExtentSize: d.ExtentSize, BlockSize: d.BlockSize, OldWALOffset: 4096, OldWALSize: d.WALSize + 4096, CreatedAt: d.CreatedAt, CheckpointLSN: 7, ChunkBlocks: ctChunkBlocks} + plan, err := PrepareMigrationV3(mapPath, src) + if err != nil { + t.Fatal(err) + } + fd, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { fd.Close() }) + // Actual offline migration's map and slot encoder, on a small flushed + // image. No legacy engine or fabricated in-memory owned-map entries. + for _, part := range []struct { + offset int64 + data []byte + }{{MigrationSlotBOffset, plan.PreparedB}, {MigrationSlotAOffset, plan.CommittedA}, {MigrationSlotBOffset, plan.RolloverB}} { + if _, err := fd.WriteAt(part.data, part.offset); err != nil { + t.Fatal(err) + } + if err := fd.Sync(); err != nil { + t.Fatal(err) + } + } + want := makeBlock(ctBlockSize, 0x57) + if _, err := fd.WriteAt(want, int64(d.WALOffset+d.WALSize)); err != nil { + t.Fatal(err) + } + if err := fd.Sync(); err != nil { + t.Fatal(err) + } + if err := fd.Close(); err != nil { + t.Fatal(err) + } + r, err := OpenWALStoreWithOptions(path, WALStoreOptions{ChunkBlocks: ctChunkBlocks}) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { closeBounded(t, r) }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + l := mustAttach(t, r, f, ctConfig(1)) + newest, err := r.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x41)) + if err != nil { + t.Fatal(err) + } + cut, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if cut.Head.Chunks[0].BirthLSN != 7 || cut.Head.Chunks[1].BirthLSN != newest { + t.Fatalf("migrated image birth lost: %+v", cut.Head) + } + if !bytes.Equal(f.imageOf(t, cut.Head)[:ctBlockSize], want) { + t.Fatal("migration cut changed inherited bytes") + } +} + +func TestChunkBirthSeededFrontierAnchorsDirectImage(t *testing.T) { + s, _ := newChunkTestStore(t) + if err := s.SeedChunkFrontier(7); err != nil { + t.Fatal(err) + } + if err := s.WriteExtentDirect(5, makeBlock(ctBlockSize, 0x57)); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + l := mustAttach(t, s, f, ctConfig(1)) + newest, err := s.Write(0, makeBlock(ctBlockSize, 0x41)) + if err != nil { + t.Fatal(err) + } + cut, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if cut.Head.Chunks[1].BirthLSN != 7 || cut.Head.Chunks[0].BirthLSN != newest { + t.Fatalf("seeded image birth lost: %+v", cut.Head) + } +} From 507a8d2051afbfa6eb5f0e4a172032d80310791a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:33:46 -0800 Subject: [PATCH 044/150] docs: bind write-deadline regressions to the admission invariant --- seaweed-block/docs/design/invariants.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5f90ff18a2..3925894a27 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -279,7 +279,7 @@ snapshot lifetime; local persistence does not bypass it. checkpoint, both-slot floor and dirty-reference retirement; I4, with healthy local progress and no guest Sync, the reuse floor advances. Enforced by `syncWALBatchV3Internal`, `persistOwnedMapCheckpointV3` and the existing reclaim - publisher. Tests: `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestSessionWriteBudgetIncludesDispatchQueue`, `TestWALStoreV3NoClientSyncSixRings`, + publisher. Tests: `TestWALStoreV3NoClientSyncSixRings`, `TestWALStoreV3PressureSyncFaultDoesNotPublishFrontiers`, `TestWALStoreV3PressureSyncSkipsInstalling`, `TestWALStoreV3PressureProgressWithPendingCutOrClose` and @@ -287,9 +287,11 @@ snapshot lifetime; local persistence does not bypass it. `AllWritten`/`NoStuckWaiter` in `REC_safe`/`REC_safe_big`; the no-internal-sync mutant violates liveness. Prior authored LIGHT receipts are referenced in `docs/spec/README.md`; this change does not claim a new TLC execution. -- The v3 pressure admission budget is four seconds of cooperative waiting. It - cannot preempt a blocking occupancy/closed callback, lock acquisition or - physical file I/O. An unresolved pin or local stall returns +- A v3 write carries one four-second command deadline through dispatch, + adapter batches, store admission locks and occupancy snapshots. Admission + reserves append headroom and expiry before append refuses without mutation. + Already-started physical I/O, COW/observer callbacks and higher-layer waits + are not preempted. An unresolved pin or local stall returns `ErrWALPressureTimeout`, preserved as `frontend.ErrBackendBusy`; NVMe returns Generic/Namespace Not Ready (SC0x82), DNR=0. Sticky faults retain their original non-retryable mapping. This is a local pressure outcome, not a whole-I/O @@ -330,7 +332,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-RECORD-001` | An impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | | `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB | -| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire` | `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | +| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. One earliest command deadline spans adapter batches and bounded store admission locks/snapshots; expiry before append preserves the WAL/nextLSN/dirty state. Already-started I/O is joined. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire`; `write_command_budget.go`; `StorageBackend.Write`; NVMe `handleWrite` | `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestSessionWriteBudgetIncludesDispatchQueue`, `TestWALStoreV3WriteBudgetBoundsAppendLockWait`, `TestWALStoreV3WriteBudgetBoundsPressureLocks`, `TestWALStoreV3WritePressureSampleMatchesOccupancy`, `TestStorageBackendExpiredWriteDoesNotAppend`; `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | | `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint releases only complete validated record ends covered by the checkpoint and outside the retention window; an installing BASE retains its install suffix. Physical recovery rebuilds the volatile boundary index only from the trusted kept scan, without restoring a disconnect cursor. Tail/head/map/checkpoint/W publish together, followed by metadata-only rollover; both slot tails still pin reuse. Failure grants no reuse and retains exact dirty retry identity. Checkpoint publication excludes writer admission through both-slot rollover and dirty-reference retirement. Idle, unchanged-checkpoint and admission settle pending rollover; catch-up revalidates tail/checkpoint before delivering its buffered scan. | M1 checkpoint / existing two-slot retirement | `wal_io_v3.go` `reclaimThroughV3`, `rememberReclaimScanV3`; `walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `descriptor_v3.go` `rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse`, `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint`, tagged `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB | | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | From 28c61803c85ead2cf8c82f05065d39ab6402e620 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:34:22 -0800 Subject: [PATCH 045/150] fix: inherit migration checkpoint births without changing unknown coverage --- .../frontend/chunkstore/retention_test.go | 22 +++++++++++++++---- .../storage/chunk_birth_migration_test.go | 12 +++++----- .../core/storage/chunk_fake_remote_test.go | 2 +- seaweed-block/core/storage/migrate_v3.go | 4 +++- 4 files changed, 29 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/retention_test.go b/seaweed-block/core/frontend/chunkstore/retention_test.go index 765aee8490..10109d3916 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_test.go @@ -362,6 +362,19 @@ func TestCatalog_UsageFromManifests(t *testing.T) { f, b, c, h := catalogFixture(t) // HEAD: chunks 0 and 3 ctx := context.Background() full := uint64(catGeo.ChunkBlocks) * uint64(catGeo.BlockSize) + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + manifestBytes := func(head storage.ChunkHead) uint64 { + var total uint64 + for _, ref := range head.Segments { + body, err := r.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + total += uint64(len(body)) + } + return total + } + expectedManifestBytes := manifestBytes(h) if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { t.Fatal(err) } @@ -372,12 +385,13 @@ func TestCatalog_UsageFromManifests(t *testing.T) { if u.LiveChunks != 2 || u.LiveBytes != 2*full || len(u.Snapshots) != 1 || u.Snapshots[0].ExclusiveBytes != 0 { t.Fatalf("shared chunks: %+v", u) } - if u.StoredBindings != 2+u.ManifestBindings || u.ManifestBindings != 1 || u.StoredBytes != 2*full+u.ManifestBytes || u.StoredUpperBound { + if u.StoredBindings != 3 || u.ManifestBindings != 1 || expectedManifestBytes == 0 || u.ManifestBytes != expectedManifestBytes || u.StoredBytes != 2*full+expectedManifestBytes || u.StoredUpperBound { t.Fatalf("stored: %+v; want 2 bindings, exact", u) } // HEAD moves on: chunk 0 is rewritten, so s1 alone holds the old one. - publishTagged(t, f, b, "v1", "e2", map[uint64][]byte{0: chunkBytes(0x20), 3: chunkBytes(0x13)}) + newHead := publishTagged(t, f, b, "v1", "e2", map[uint64][]byte{0: chunkBytes(0x20), 3: chunkBytes(0x13)}) + expectedManifestBytes += manifestBytes(newHead) u, err = c.Usage(ctx, "v1") if err != nil { t.Fatal(err) @@ -386,7 +400,7 @@ func TestCatalog_UsageFromManifests(t *testing.T) { // both of s1's chunks are now exclusive: the new HEAD uses e2 keys t.Fatalf("after HEAD moved: s1 exclusive %d, want %d", u.Snapshots[0].ExclusiveBytes, 2*full) } - if u.StoredBindings != 4+u.ManifestBindings || u.ManifestBindings != 2 || u.StoredBytes != 4*full+u.ManifestBytes || u.StoredUpperBound { + if u.StoredBindings != 6 || u.ManifestBindings != 2 || u.ManifestBytes != expectedManifestBytes || u.StoredBytes != 4*full+expectedManifestBytes || u.StoredUpperBound { t.Fatalf("stored after HEAD moved: %+v; want 4 bindings, exact", u) } @@ -399,7 +413,7 @@ func TestCatalog_UsageFromManifests(t *testing.T) { if err != nil { t.Fatal(err) } - if len(u.Snapshots) != 0 || u.StoredBindings != 4+u.ManifestBindings || !u.StoredUpperBound { + if len(u.Snapshots) != 0 || u.StoredBindings != 6 || !u.StoredUpperBound { t.Fatalf("after delete: %+v; want no snapshots, 4 bindings, upper bound", u) } } diff --git a/seaweed-block/core/storage/chunk_birth_migration_test.go b/seaweed-block/core/storage/chunk_birth_migration_test.go index 7888f79fcb..987c7bab07 100644 --- a/seaweed-block/core/storage/chunk_birth_migration_test.go +++ b/seaweed-block/core/storage/chunk_birth_migration_test.go @@ -73,16 +73,18 @@ func TestChunkBirthMigrationCarriesImageFrontier(t *testing.T) { } } -func TestChunkBirthSeededFrontierAnchorsDirectImage(t *testing.T) { +func TestChunkBirthSeededFrontierPreservesInheritedImage(t *testing.T) { s, _ := newChunkTestStore(t) if err := s.SeedChunkFrontier(7); err != nil { t.Fatal(err) } - if err := s.WriteExtentDirect(5, makeBlock(ctBlockSize, 0x57)); err != nil { - t.Fatal(err) - } f := newFakeChunkRemote() - l := mustAttach(t, s, f, ctConfig(1)) + image := make([]byte, ctNumBlocks*ctBlockSize) + copy(image[ctChunkBlocks*ctBlockSize:], makeBlock(ctBlockSize, 0x57)) + f.seedHead(t, image, 7, 1) + cfg := ctConfig(2) + cfg.FreshFromHead = true + l := mustAttach(t, s, f, cfg) newest, err := s.Write(0, makeBlock(ctBlockSize, 0x41)) if err != nil { t.Fatal(err) diff --git a/seaweed-block/core/storage/chunk_fake_remote_test.go b/seaweed-block/core/storage/chunk_fake_remote_test.go index f3eef79172..ea6d6da91f 100644 --- a/seaweed-block/core/storage/chunk_fake_remote_test.go +++ b/seaweed-block/core/storage/chunk_fake_remote_test.go @@ -386,7 +386,7 @@ func (f *fakeChunkRemote) seedHead(t *testing.T, image []byte, remoteLSN, epoch key := fmt.Sprintf("seed/%d", idx) f.objs[key] = append([]byte(nil), c...) f.everStored[key] = true - head.Chunks[uint64(idx)] = chunkRef{Key: key, SHA256: sha256.Sum256(c)} + head.Chunks[uint64(idx)] = chunkRef{Key: key, SHA256: sha256.Sum256(c), Encoding: "full", BirthLSN: remoteLSN} } f.installLocked(head) } diff --git a/seaweed-block/core/storage/migrate_v3.go b/seaweed-block/core/storage/migrate_v3.go index 16ebb3964d..89c12c0e6b 100644 --- a/seaweed-block/core/storage/migrate_v3.go +++ b/seaweed-block/core/storage/migrate_v3.go @@ -107,7 +107,8 @@ func ValidateMigrationV3(src MigrationSourceV3) error { // PrepareMigrationV3 runs DESIGN 10.1 step 3 and builds the slot images of // steps 4 to 6. It (re)creates the initial map sidecar at mapPath durably: -// generation 1, every chunk UNKNOWN with maxWriteLSN 0, coveredCheckpoint = +// generation 1, every chunk UNKNOWN with its inherited checkpoint frontier, +// coveredCheckpoint = // the v2 checkpoint (a fully flushed WAL is not remote-clean). The slots // carry a fresh random nonce and the map fields of that root. It writes // nothing to the store file. @@ -141,6 +142,7 @@ func PrepareMigrationV3(mapPath string, src MigrationSourceV3) (MigrationPlanV3, entries := make([]chunkLSNEntryV3, int(shape.chunks)) for i := range entries { entries[i].Unknown = true + entries[i].LSN = src.CheckpointLSN } c, err := m.Prepare(1, src.CheckpointLSN, entries, nil) if err = errors.Join(err, m.Close()); err != nil { From ba3db132b00739da81e9585718f9f74f447451bc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:37:45 -0800 Subject: [PATCH 046/150] test: sustain format3 publication beyond WAL capacity and restore exact bytes --- .../chunkstore/format_sustained_test.go | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/format_sustained_test.go diff --git a/seaweed-block/core/frontend/chunkstore/format_sustained_test.go b/seaweed-block/core/frontend/chunkstore/format_sustained_test.go new file mode 100644 index 0000000000..3d514e261b --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_sustained_test.go @@ -0,0 +1,113 @@ +package chunkstore + +import ( + "bytes" + "context" + "encoding/json" + "path" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestManifestFormatUpgradeSustainedWritesPastWALWithPeriodicFlush(t *testing.T) { + const blocks, blockSize, chunkBlocks = 1024, 4096, 64 + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + f, b := newFakeFiler(), newFakeBlobs() + r, err := NewChunkRemote(f, b, path.Join(catBase, "sustained")) + if err != nil { + t.Fatal(err) + } + s, err := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "source"), blocks, blockSize, storage.WALStoreOptions{ChunkBlocks: chunkBlocks, WMode: storage.WModeStrict}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { s.Close() }) + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: 1, Holder: "source", FreshFromHead: true, BarrierBound: 2, UploadConcurrency: 2}) + if err != nil { + t.Fatal(err) + } + walBytes := s.WALCapacityBytes() + if walBytes == 0 || walBytes > 128<<20 { + t.Fatalf("smoke WAL capacity outside bounded fixture: %d", walBytes) + } + batchBytes := uint64(blocks * blockSize) + rounds := int(walBytes/batchBytes) + 1 + var payload, last uint64 + var finalByte byte + for round := 0; round < rounds; round++ { + finalByte = byte(round%251 + 1) + data := bytes.Repeat([]byte{finalByte}, blocks*blockSize) + batch := make([][]byte, blocks) + for i := range batch { + batch[i] = data[i*blockSize : (i+1)*blockSize] + } + if _, err := s.WriteBatch(0, batch); err != nil { + t.Fatal(err) + } + last, err = s.Sync() + if err != nil { + t.Fatal(err) + } + payload += batchBytes + // Use the production periodic flusher, not a second checkpoint path. + for s.CheckpointLSN() < last { + select { + case <-ctx.Done(): + t.Fatalf("periodic Flush did not cover batch %d: %v", round, ctx.Err()) + case <-time.After(10 * time.Millisecond): + } + } + if (round+1)%4 == 0 || round+1 == rounds { + if _, err := l.Cut(ctx); err != nil { + t.Fatal(err) + } + } + } + if payload <= walBytes || s.FlushCount() == 0 { + t.Fatal("sustained fixture did not exceed WAL with periodic Flush") + } + h, err := r.GetHead(ctx) + if err != nil || h.RemoteLSN != last { + t.Fatalf("final frontier: %+v %v", h, err) + } + e, err := f.LookupEntry(ctx, path.Join(catBase, "sustained"), headName) + if err != nil { + t.Fatal(err) + } + var shape struct { + Format int `json:"format"` + Levels int `json:"levels"` + } + if err := json.Unmarshal(e.Content, &shape); err != nil || shape.Format != 3 || shape.Levels != 1 { + t.Fatal("sustained cut did not publish format3") + } + fresh, err := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "fresh"), blocks, blockSize, storage.WALStoreOptions{ChunkBlocks: chunkBlocks, WMode: storage.WModeStrict}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { fresh.Close() }) + if _, err := fresh.Recover(); err != nil { + t.Fatal(err) + } + if err := fresh.SeedChunkFrontier(last); err != nil { + t.Fatal(err) + } + if _, err := storage.AttachChunkLayer(fresh, r, storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: 2, Holder: "fresh", FreshFromHead: true}); err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{finalByte}, blockSize) + for lba := uint32(0); lba < blocks; lba++ { + got, err := fresh.Read(lba) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("fresh read block%d: %v", lba, err) + } + } + t.Logf("payload=%d > WAL=%d, checkpoint drains=%d, FlushCount=%d; full fresh lazy read exact", payload, walBytes, rounds, s.FlushCount()) +} From a8eab7b3613b2ba4dc4f96b2ab8ddd205e0cfff0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:45:07 -0800 Subject: [PATCH 047/150] test: prepare versioned manifests for catalog caller fixtures --- .../sw-block/chunk_manifest_fixture_test.go | 60 +++++++++++++++++++ .../cmd/sw-block/chunk_retain_partial_test.go | 6 +- .../cmd/sw-block/chunk_retain_test.go | 3 +- seaweed-block/cmd/sw-block/chunk_show_test.go | 3 +- seaweed-block/cmd/sw-block/chunk_test.go | 9 +++ .../core/frontend/chunkstore/chunk_remote.go | 8 +-- .../host/volume/chunk_control_adapter_test.go | 37 +++++++++++- 7 files changed, 114 insertions(+), 12 deletions(-) create mode 100644 seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go diff --git a/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go new file mode 100644 index 0000000000..e9e52d078c --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go @@ -0,0 +1,60 @@ +package main + +import ( + "context" + "fmt" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type manifestFixtureFiler struct { + chunkstore.Filer + mu sync.Mutex + blobs map[string][]byte +} + +func newManifestFixtureFiler(f chunkstore.Filer) *manifestFixtureFiler { + return &manifestFixtureFiler{Filer: f, blobs: map[string][]byte{}} +} + +func (f *manifestFixtureFiler) Put(_ context.Context, b []byte) (string, error) { + f.mu.Lock() + defer f.mu.Unlock() + id := fmt.Sprintf("fixture-%d", len(f.blobs)) + f.blobs[id] = append([]byte(nil), b...) + return id, nil +} + +func (f *manifestFixtureFiler) Get(_ context.Context, id string) ([]byte, error) { + f.mu.Lock() + defer f.mu.Unlock() + b, ok := f.blobs[id] + if !ok { + return nil, chunkstore.ErrNotFound + } + return append([]byte(nil), b...), nil +} + +func prepareFixtureHead(t *testing.T, f *manifestFixtureFiler, h storage.ChunkHead) storage.ChunkHead { + t.Helper() + ctx := context.Background() + r, err := chunkstore.NewChunkRemote(f, f, defaultChunkPathCLI+"/v1") + if err != nil { + t.Fatal(err) + } + h, intents, err := r.PrepareManifest(ctx, storage.ChunkHead{}, h, 8*4096) + if err != nil { + t.Fatal(err) + } + // These fixtures hand the completed cut directly to the catalog; the + // snapshot/fork operations establish their own reachability intents. + for _, id := range intents { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + return h +} diff --git a/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go b/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go index 705e2ca9d5..b40b03134e 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go +++ b/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go @@ -41,10 +41,11 @@ func (f *failingFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.E func TestOpsChunk_RetainReportsPartialProgress(t *testing.T) { ctx := context.Background() ff := &failingFiler{MemFiler: chunkstore.NewMemFiler()} + fm := newManifestFixtureFiler(ff) prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return ff, func() error { return nil }, nil } + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return fm, func() error { return nil }, nil } t.Cleanup(func() { dialChunkFiler = prev }) - cat, err := chunkstore.NewCatalog(ff, defaultChunkPathCLI) + cat, err := chunkstore.NewCatalog(fm, defaultChunkPathCLI) if err != nil { t.Fatal(err) } @@ -54,6 +55,7 @@ func TestOpsChunk_RetainReportsPartialProgress(t *testing.T) { base := time.Now().Add(-48 * time.Hour) head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + head = prepareFixtureHead(t, fm, head) for i := 0; i < 4; i++ { at := base.Add(time.Duration(i) * time.Minute) cat.SetClock(func() time.Time { return at }) diff --git a/seaweed-block/cmd/sw-block/chunk_retain_test.go b/seaweed-block/cmd/sw-block/chunk_retain_test.go index 3623088e6c..0dd4633cfd 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain_test.go +++ b/seaweed-block/cmd/sw-block/chunk_retain_test.go @@ -44,7 +44,7 @@ func TestOpsChunk_SnapshotPinAndExpires(t *testing.T) { // dry-run, apply, and see the accounting follow. func TestOpsChunk_UsageAndRetain(t *testing.T) { ctx := context.Background() - mem := chunkstore.NewMemFiler() + mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) prev := dialChunkFiler dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } t.Cleanup(func() { dialChunkFiler = prev }) @@ -59,6 +59,7 @@ func TestOpsChunk_UsageAndRetain(t *testing.T) { cat.SetClock(func() time.Time { return old }) head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + head = prepareFixtureHead(t, mem, head) for i := 0; i < 5; i++ { if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: fmt.Sprintf("s%d", i), RequestID: fmt.Sprintf("r%d", i), Class: chunkstore.SnapshotClassSemantic}, head); err != nil { t.Fatal(err) diff --git a/seaweed-block/cmd/sw-block/chunk_show_test.go b/seaweed-block/cmd/sw-block/chunk_show_test.go index 22b3eaa32a..6a36ac02a5 100644 --- a/seaweed-block/cmd/sw-block/chunk_show_test.go +++ b/seaweed-block/cmd/sw-block/chunk_show_test.go @@ -13,7 +13,7 @@ import ( // either is null when it does not exist (B9 W2 appendix). func TestOpsChunk_Show(t *testing.T) { ctx := context.Background() - mem := chunkstore.NewMemFiler() + mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) prev := dialChunkFiler dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } t.Cleanup(func() { dialChunkFiler = prev }) @@ -27,6 +27,7 @@ func TestOpsChunk_Show(t *testing.T) { } head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + head = prepareFixtureHead(t, mem, head) if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, head); err != nil { t.Fatal(err) } diff --git a/seaweed-block/cmd/sw-block/chunk_test.go b/seaweed-block/cmd/sw-block/chunk_test.go index 9b96c7f623..39347d09fa 100644 --- a/seaweed-block/cmd/sw-block/chunk_test.go +++ b/seaweed-block/cmd/sw-block/chunk_test.go @@ -157,6 +157,15 @@ func TestOpsChunk_FilerCommands(t *testing.T) { } head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "r1", RemoteLSN: 42, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + manifestMem := newManifestFixtureFiler(mem) + cat, err = chunkstore.NewCatalog(manifestMem, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return manifestMem, func() error { return nil }, nil + } + head = prepareFixtureHead(t, manifestMem, head) if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, head); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 7f2118d4d9..aff708783b 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -449,13 +449,7 @@ func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) { if len(h.Chunks) != 0 { return nil, errors.New("chunkstore: data HEAD requires a segmented manifest and geometry") } - doc.Chunks = make(map[uint64]refDoc, len(h.Chunks)) - for idx, ref := range h.Chunks { - if ref.Key == "" { - return nil, fmt.Errorf("chunkstore: HEAD chunk %d has no key", idx) - } - doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} - } + doc.Chunks = map[uint64]refDoc{} } if h.Segments != nil { if err := validateRoot(h); err != nil { diff --git a/seaweed-block/core/host/volume/chunk_control_adapter_test.go b/seaweed-block/core/host/volume/chunk_control_adapter_test.go index cac46d325a..c84cfb7877 100644 --- a/seaweed-block/core/host/volume/chunk_control_adapter_test.go +++ b/seaweed-block/core/host/volume/chunk_control_adapter_test.go @@ -3,7 +3,9 @@ package volume import ( "context" "encoding/json" + "fmt" "reflect" + "sync" "testing" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" @@ -19,6 +21,30 @@ type fakeChunkProvider struct { lastMin uint64 } +type adapterManifestFiler struct { + chunkstore.Filer + mu sync.Mutex + blobs map[string][]byte +} + +func (f *adapterManifestFiler) Put(_ context.Context, b []byte) (string, error) { + f.mu.Lock() + defer f.mu.Unlock() + id := fmt.Sprintf("fixture-%d", len(f.blobs)) + f.blobs[id] = append([]byte(nil), b...) + return id, nil +} + +func (f *adapterManifestFiler) Get(_ context.Context, id string) ([]byte, error) { + f.mu.Lock() + defer f.mu.Unlock() + b, ok := f.blobs[id] + if !ok { + return nil, chunkstore.ErrNotFound + } + return append([]byte(nil), b...), nil +} + func (f *fakeChunkProvider) CutVolume(_ context.Context, _ string, minLSN uint64) (storage.ChunkCutResult, error) { f.cuts++ f.lastMin = minLSN @@ -36,8 +62,17 @@ func adapterFixture(t *testing.T) (*fakeChunkProvider, ChunkControl) { t.Helper() head := storage.ChunkHead{Gen: 3, Epoch: 2, Holder: "r1", RemoteLSN: 9, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e2/c0/k1"}, 5: {Key: "chunks/e2/c5/k2"}}} + f := &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}} + r, err := chunkstore.NewChunkRemote(f, f, "/swblock/chunks/v1") + if err != nil { + t.Fatal(err) + } + head, _, err = r.PrepareManifest(context.Background(), storage.ChunkHead{}, head, 8*4096) + if err != nil { + t.Fatal(err) + } fp := &fakeChunkProvider{cut: storage.ChunkCutResult{H: 9, Head: head}} - cat, err := chunkstore.NewCatalog(chunkstore.NewMemFiler(), "/swblock/chunks") + cat, err := chunkstore.NewCatalog(f, "/swblock/chunks") if err != nil { t.Fatal(err) } From bf50377c469c7196904425543afcebec2129852f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:47:07 -0800 Subject: [PATCH 048/150] fix: report segmented counts and cover versioned segment fuzzing --- seaweed-block/core/frontend/chunkstore/api.go | 2 +- .../frontend/chunkstore/segment_fuzz_test.go | 53 +++++++++++++++++++ .../core/storage/chunk_birth_test.go | 27 ++++++++++ 3 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/frontend/chunkstore/segment_fuzz_test.go diff --git a/seaweed-block/core/frontend/chunkstore/api.go b/seaweed-block/core/frontend/chunkstore/api.go index 469ca3295f..eae7dd0fd8 100644 --- a/seaweed-block/core/frontend/chunkstore/api.go +++ b/seaweed-block/core/frontend/chunkstore/api.go @@ -94,7 +94,7 @@ func NewVolumeShowBody(vol string, v *VolumeInfo, h *storage.ChunkHead) VolumeSh if state == "" { state = storage.ChunkHeadActive } - body.Head = &HeadShow{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: state, ChunkCount: len(h.Chunks)} + body.Head = &HeadShow{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: state, ChunkCount: manifestCount(*h)} if d := h.DetachedBy; d != nil { body.Head.DetachedBy = &DetachedByShow{Holder: d.Holder, Epoch: d.Epoch, Gen: d.Gen} } diff --git a/seaweed-block/core/frontend/chunkstore/segment_fuzz_test.go b/seaweed-block/core/frontend/chunkstore/segment_fuzz_test.go new file mode 100644 index 0000000000..a70a44babb --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/segment_fuzz_test.go @@ -0,0 +1,53 @@ +package chunkstore + +import ( + "crypto/sha256" + "encoding/json" + "reflect" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func FuzzDecodeVersionedSegment(f *testing.F) { + sum := sha256.Sum256([]byte("stored bytes")) + refs := map[uint64]storage.ChunkRef{0: {Key: "@v1/k", SHA256: sum, Encoding: "full", BirthLSN: 7}} + body, _, err := encodeSegmentV2(0, 4096, "v1", refs) + if err != nil { + f.Fatal(err) + } + f.Add(body, uint8(2)) + legacy, err := json.Marshal(legacySegmentDoc{Format: 1, Range: 0, ChunkBytes: 4096, Owner: "v1", Chunks: map[uint64]legacyChunkRefDoc{0: {Key: "@v1/k", SHA256: sum}}}) + if err != nil { + f.Fatal(err) + } + f.Add(legacy, uint8(1)) + f.Add([]byte(`{"format":2,"format":1}`), uint8(2)) + f.Add([]byte(`{"format":3}`), uint8(3)) + f.Fuzz(func(t *testing.T, body []byte, version uint8) { + ref := storage.ChunkSegment{SegFormat: int(version), MaxBirthLSN: 7} + got, err := decodeSegment(body, ref, 7) + if err != nil { + return + } + if got.Format != 1 && got.Format != 2 { + t.Fatalf("accepted format %d", got.Format) + } + for _, cr := range got.Chunks { + if cr.Encoding != "full" || cr.BirthLSN > 7 { + t.Fatalf("accepted unsupported chunk metadata: %+v", cr) + } + } + if got.Format == 2 { + encoded, maxBirth, err := encodeSegmentV2(got.Range, got.ChunkBytes, got.Owner, got.Chunks) + if err != nil { + t.Fatal(err) + } + ref.MaxBirthLSN = maxBirth + again, err := decodeSegment(encoded, ref, 7) + if err != nil || !reflect.DeepEqual(got, again) { + t.Fatalf("round trip: %+v / %+v: %v", got, again, err) + } + } + }) +} diff --git a/seaweed-block/core/storage/chunk_birth_test.go b/seaweed-block/core/storage/chunk_birth_test.go index 36986ab9dd..ba9b4259e5 100644 --- a/seaweed-block/core/storage/chunk_birth_test.go +++ b/seaweed-block/core/storage/chunk_birth_test.go @@ -8,6 +8,33 @@ import ( "time" ) +func TestChunkBirthLegacyEngineUsesCutFrontierUpperBound(t *testing.T) { + s, _ := newLegacyChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + l := mustAttach(t, s, f, cfg) + if _, err := s.Write(0, makeBlock(ctBlockSize, 0x41)); err != nil { + t.Fatal(err) + } + last, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42)) + if err != nil { + t.Fatal(err) + } + cut, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + for _, idx := range []uint64{0, 1} { + if cr := cut.Head.Chunks[idx]; cr.Encoding != "full" || cr.BirthLSN != last { + t.Fatalf("legacy chunk %d metadata %+v, want frontier %d", idx, cr, last) + } + } + want := make([]byte, ctNumBlocks*ctBlockSize) + copy(want, makeBlock(ctBlockSize, 0x41)) + copy(want[ctChunkBlocks*ctBlockSize:], makeBlock(ctBlockSize, 0x42)) + assertImage(t, "legacy inherited image", f.imageOf(t, cut.Head), want) +} + func TestChunkBirthBASEUsesInheritedFrontierIncludingZero(t *testing.T) { for _, frontier := range []uint64{0, 7} { t.Run(string(rune('0'+frontier)), func(t *testing.T) { From 7869ee9642b1f51bd1da43f6c26044237b6f4544 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:53:45 -0800 Subject: [PATCH 049/150] test: retain cold birth metadata through zero-chunk deletion --- seaweed-block/core/storage/chunk_birth_test.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/seaweed-block/core/storage/chunk_birth_test.go b/seaweed-block/core/storage/chunk_birth_test.go index ba9b4259e5..677fc36266 100644 --- a/seaweed-block/core/storage/chunk_birth_test.go +++ b/seaweed-block/core/storage/chunk_birth_test.go @@ -160,6 +160,18 @@ func TestChunkBirthTracksNewestLocalWriteAtCut(t *testing.T) { if second.Head.Chunks[0] != first.Head.Chunks[0] || second.Head.Chunks[1].BirthLSN != z { t.Fatal("rewrite changed a cold chunk birth or failed to advance the changed version") } + for _, lba := range []uint64{ctChunkBlocks, ctChunkBlocks + 1} { + if _, err := s.Write(lba, makeBlock(ctBlockSize, 0)); err != nil { + t.Fatal(err) + } + } + third, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if _, exists := third.Head.Chunks[1]; exists || third.Head.Chunks[0] != first.Head.Chunks[0] { + t.Fatal("zero-chunk deletion retained a reference or changed the cold birth") + } }) } } From 9ba9444f377c7535cfbb978e280ac406d34ee4ec Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:53:57 -0800 Subject: [PATCH 050/150] test: use the storage block address type in deletion control --- seaweed-block/core/storage/chunk_birth_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_birth_test.go b/seaweed-block/core/storage/chunk_birth_test.go index 677fc36266..c442156f43 100644 --- a/seaweed-block/core/storage/chunk_birth_test.go +++ b/seaweed-block/core/storage/chunk_birth_test.go @@ -160,7 +160,7 @@ func TestChunkBirthTracksNewestLocalWriteAtCut(t *testing.T) { if second.Head.Chunks[0] != first.Head.Chunks[0] || second.Head.Chunks[1].BirthLSN != z { t.Fatal("rewrite changed a cold chunk birth or failed to advance the changed version") } - for _, lba := range []uint64{ctChunkBlocks, ctChunkBlocks + 1} { + for _, lba := range []uint32{ctChunkBlocks, ctChunkBlocks + 1} { if _, err := s.Write(lba, makeBlock(ctBlockSize, 0)); err != nil { t.Fatal(err) } From b8f9903545a08a8558994ce379b7a41c12728d70 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:55:09 -0800 Subject: [PATCH 051/150] test: keep write and FUA deadline expiry retryable on the wire --- .../nvme/write_command_budget_test.go | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/seaweed-block/core/frontend/nvme/write_command_budget_test.go b/seaweed-block/core/frontend/nvme/write_command_budget_test.go index 18b6fe303c..273c74a622 100644 --- a/seaweed-block/core/frontend/nvme/write_command_budget_test.go +++ b/seaweed-block/core/frontend/nvme/write_command_budget_test.go @@ -2,6 +2,8 @@ package nvme import ( "context" + "errors" + "fmt" "testing" "time" @@ -36,3 +38,53 @@ func TestSessionWriteBudgetIncludesDispatchQueue(t *testing.T) { t.Fatalf("deadline=%v status=%#x calls=%d", b.deadline, resp.resp.Status, b.calls) } } + +// An already-issued write is joined even if its deadline passes. A subsequent +// FUA wait may return deadline exceeded, but must not turn transient expiry +// into a permanent device error. Physical failures still win. +type joinedBudgetBackend struct { + frontend.Backend + fua, physical bool +} + +func (b *joinedBudgetBackend) result(ctx context.Context) error { + if b.physical { + return errors.New("physical fsync failure") + } + return ctx.Err() +} +func (b *joinedBudgetBackend) Write(ctx context.Context, _ int64, p []byte) (int, error) { + <-ctx.Done() + if b.fua { + return len(p), nil + } + return 0, b.result(ctx) +} +func (b *joinedBudgetBackend) Sync(ctx context.Context) error { return b.result(ctx) } +func TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA(t *testing.T) { + for _, fua := range []bool{false, true} { + for _, physical := range []bool{false, true} { + t.Run(fmt.Sprintf("fua=%t/physical=%t", fua, physical), func(t *testing.T) { + b := &joinedBudgetBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), fua: fua, physical: physical} + s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), respCh: make(chan *response, 1), done: make(chan struct{})} + ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) + defer cancel() + req := &Request{payload: make([]byte, 512)} + req.capsule.OpCode = ioWrite + req.capsule.NSID = 1 + if fua { + req.capsule.D12 |= 1 << 30 + } + s.handleWrite(ctx, req) + got := (<-s.respCh).resp.Status + want := MakeStatusField(SCTGeneric, SCNamespaceNotReady, false) + if physical { + want = MakeStatusField(SCTGeneric, SCInternalError, true) + } + if got != want { + t.Fatalf("completion=%#x want%#x", got, want) + } + }) + } + } +} From 8e546f7fe301a04d14ffe312df0f1d9f9e55bf57 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:57:10 -0800 Subject: [PATCH 052/150] nvme: retry pure command deadline expiry without masking physical faults --- seaweed-block/core/frontend/nvme/io.go | 34 +++++++++++++++++-- .../nvme/write_command_budget_test.go | 4 +-- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/frontend/nvme/io.go b/seaweed-block/core/frontend/nvme/io.go index 6f4c88ef18..f32075350f 100644 --- a/seaweed-block/core/frontend/nvme/io.go +++ b/seaweed-block/core/frontend/nvme/io.go @@ -283,19 +283,49 @@ func (h *IOHandler) write(ctx context.Context, cmd IOCommand) IOResult { start := time.Now() n, err := h.backend.Write(ctx, int64(cmd.SLBA)*int64(h.blockSize), cmd.Data[:expectedBytes]) if err != nil { - return mapBackendError(err, "write") + return mapWriteBudgetError(ctx, err, "write") } if rec, ok := h.backend.(targetWriteRecorder); ok { rec.RecordTargetWrite(n, time.Since(start)) } if cmd.FUA { if err := h.backend.Sync(ctx); err != nil { - return mapBackendError(err, "FUA sync") + return mapWriteBudgetError(ctx, err, "FUA sync") } } return IOResult{SCT: SCTGeneric, SC: SCSuccess} } +// Only a pure command-deadline cause is transient. A joined physical error +// must retain its terminal mapping even when the command deadline also passed. +func mapWriteBudgetError(ctx context.Context, err error, op string) IOResult { + if ctx.Err() == context.DeadlineExceeded && onlyDeadlineCause(err) { + err = fmt.Errorf("%w: %w", frontend.ErrBackendBusy, err) + } + return mapBackendError(err, op) +} +func onlyDeadlineCause(err error) bool { + if err == context.DeadlineExceeded { + return true + } + if err == nil { + return false + } + if joined, ok := err.(interface{ Unwrap() []error }); ok { + causes := joined.Unwrap() + if len(causes) == 0 { + return false + } + for _, cause := range causes { + if !onlyDeadlineCause(cause) { + return false + } + } + return true + } + return onlyDeadlineCause(errors.Unwrap(err)) +} + // mapBackendError translates frontend errors into NVMe CQE // status tuples. ErrStalePrimary → ANA Transition; // ErrBackendClosed → ANA Inaccessible; anything else → Internal diff --git a/seaweed-block/core/frontend/nvme/write_command_budget_test.go b/seaweed-block/core/frontend/nvme/write_command_budget_test.go index 273c74a622..71910cc639 100644 --- a/seaweed-block/core/frontend/nvme/write_command_budget_test.go +++ b/seaweed-block/core/frontend/nvme/write_command_budget_test.go @@ -49,9 +49,9 @@ type joinedBudgetBackend struct { func (b *joinedBudgetBackend) result(ctx context.Context) error { if b.physical { - return errors.New("physical fsync failure") + return errors.Join(errors.New("physical fsync failure"), ctx.Err()) } - return ctx.Err() + return fmt.Errorf("durability wait: %w", ctx.Err()) } func (b *joinedBudgetBackend) Write(ctx context.Context, _ int64, p []byte) (int, error) { <-ctx.Done() From e723a2a4fbf1d9d833ecce1a85856ac9fcafae38 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:59:57 -0800 Subject: [PATCH 053/150] nvme: identify command expiry separately from capacity pressure --- seaweed-block/core/frontend/nvme/io.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/nvme/io.go b/seaweed-block/core/frontend/nvme/io.go index f32075350f..cf34a05550 100644 --- a/seaweed-block/core/frontend/nvme/io.go +++ b/seaweed-block/core/frontend/nvme/io.go @@ -300,7 +300,7 @@ func (h *IOHandler) write(ctx context.Context, cmd IOCommand) IOResult { // must retain its terminal mapping even when the command deadline also passed. func mapWriteBudgetError(ctx context.Context, err error, op string) IOResult { if ctx.Err() == context.DeadlineExceeded && onlyDeadlineCause(err) { - err = fmt.Errorf("%w: %w", frontend.ErrBackendBusy, err) + return IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, retryable: true, Reason: "command deadline on " + op + ": " + err.Error()} } return mapBackendError(err, op) } From 26557e3946bc94e04740b5dd93156acd0379eb26 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:03:51 -0800 Subject: [PATCH 054/150] authority: a forced move records the upper bound of its lost range A forced move abandons the old holder's writes after the HEAD frontier it keeps (already recorded as RemoteLSN). The record now also carries LostUntilNS: the forced barrier (lease horizon or restart deadline, whichever is later, plus skew), the latest master time at which any of those writes can have been acknowledged. It is journaled with the record; clean moves leave it unset and keep their encoding. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/workspace.go | 16 ++- .../authority/workspace_lost_range_test.go | 107 ++++++++++++++++++ 2 files changed, 121 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/authority/workspace_lost_range_test.go diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 514520b38c..d28bfc7a5d 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -34,6 +34,12 @@ type WorkspaceMoveRecord struct { TargetDataAddr, TargetCtrlAddr string OldEpoch, NewEpoch, HeadGen, RemoteLSN uint64 Issued bool + // LostUntilNS, set only for Kind "forced", records the abandoned range: + // the old holder's writes after RemoteLSN (the HEAD frontier the move + // keeps) are lost, and none of them was acknowledged later than this + // master time (the forced barrier: the lease horizon plus skew). The + // lease carries no write frontier, so the upper bound is a time. + LostUntilNS int64 `json:",omitempty"` } type WorkspaceState struct { @@ -280,12 +286,18 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra if !ok || line.info.Epoch != q.ExpectedEpoch || line.info.ReplicaID != q.ExpectedReplicaID || s == nil || s.Lease == nil { return nil, 0, fmt.Errorf("workspace move: missing or changed authority/lease") } + var lostUntil int64 if q.Kind == "forced" { now := p.workspaceNow() skew := p.workspaceSkew(s.Lease) - if now.Before(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew)) || now.Before(p.leaseDeadlineLocked(q.VolumeID).Add(skew)) { + barrier := time.Unix(0, s.Lease.ExpiresAtNS).Add(skew) + if d := p.leaseDeadlineLocked(q.VolumeID).Add(skew); d.After(barrier) { + barrier = d + } + if now.Before(barrier) { return nil, 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") } + lostUntil = barrier.UnixNano() } // A restart may resume the identical durable reservation; it never grants // a different request the reserved epoch. @@ -318,7 +330,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra return nil, 0, fmt.Errorf("workspace epoch exhausted") } r := WorkspaceMoveRecord{RequestID: q.RequestID, VolumeID: q.VolumeID, OldHost: q.ExpectedHost, NewHost: q.TargetHost, OldReplicaID: q.ExpectedReplicaID, NewReplicaID: q.TargetReplicaID, Kind: q.Kind, - OldEpoch: q.ExpectedEpoch, NewEpoch: max + 1, HeadGen: h.Gen, RemoteLSN: h.RemoteLSN, TargetDataAddr: q.TargetDataAddr, TargetCtrlAddr: q.TargetCtrlAddr} + OldEpoch: q.ExpectedEpoch, NewEpoch: max + 1, HeadGen: h.Gen, RemoteLSN: h.RemoteLSN, TargetDataAddr: q.TargetDataAddr, TargetCtrlAddr: q.TargetCtrlAddr, LostUntilNS: lostUntil} s.Moves = append(s.Moves, r) if err := p.persistWorkspaceLocked(q.VolumeID, s); err != nil { return nil, 0, err diff --git a/seaweed-block/core/authority/workspace_lost_range_test.go b/seaweed-block/core/authority/workspace_lost_range_test.go new file mode 100644 index 0000000000..dafd2685b9 --- /dev/null +++ b/seaweed-block/core/authority/workspace_lost_range_test.go @@ -0,0 +1,107 @@ +package authority + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" +) + +// A forced move records the abandoned range: the kept HEAD frontier +// (RemoteLSN) and the forced barrier (lease horizon plus skew) as the +// latest master time an old-holder write can have been acknowledged. The +// record is journaled: a reload returns the same bound. +// +// After a restart the conservative restart deadline, not the lease horizon, +// is the later term of the barrier. +func TestWorkspaceForcedMoveRecordsTheLostRange(t *testing.T) { + for _, restart := range []bool{false, true} { + t.Run(map[bool]string{false: "running", true: "after restart"}[restart], func(t *testing.T) { forcedLostRange(t, restart) }) + } +} + +func forcedLostRange(t *testing.T, restart bool) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + clock := func() time.Time { return now } + p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, clock)) + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "old", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "old", 1); err != nil { + t.Fatal(err) + } + if restart { + now = now.Add(time.Second) + p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, clock)) + } + lease := p.WorkspaceState("v").Lease + if restart && !p.leaseDeadlineLockedForTest("v").After(time.Unix(0, lease.ExpiresAtNS)) { + t.Fatal("fixture: the restart deadline is not the later barrier term") + } + barrier := time.Unix(0, lease.ExpiresAtNS) + if d := p.leaseDeadlineLockedForTest("v"); d.After(barrier) { + barrier = d + } + barrier = barrier.Add(p.workspaceSkew(lease)) + req := WorkspaceMoveRequest{RequestID: "f", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, + TargetReplicaID: "old", TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} + head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42} + now = barrier.Add(-time.Nanosecond) + if _, err := p.MoveWorkspace(ctx, req, head); err == nil { + t.Fatal("forced move admitted before its barrier") + } + now = barrier.Add(5 * time.Second) // the bound is the barrier, not the time of the move + r, err := p.MoveWorkspace(ctx, req, head) + if err != nil { + t.Fatal(err) + } + if r.Kind != "forced" || r.RemoteLSN != 42 || r.LostUntilNS != barrier.UnixNano() { + t.Fatalf("forced record RemoteLSN=%d LostUntilNS=%d; want 42 and the barrier %d", r.RemoteLSN, r.LostUntilNS, barrier.UnixNano()) + } + reloaded := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, clock)).WorkspaceState("v") + if reloaded == nil || len(reloaded.Moves) != 1 || reloaded.Moves[0].LostUntilNS != barrier.UnixNano() || reloaded.Moves[0].RemoteLSN != 42 { + t.Fatalf("reloaded record lost the range: %+v", reloaded) + } +} + +// A clean move abandons nothing: its record has no lost-range bound, and +// its persisted encoding is unchanged (no LostUntilNS key). +func TestWorkspaceCleanMoveRecordsNoLostRange(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + p := NewPublisher(nil, WithStore(disk)) + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "old", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "old", 1); err != nil { + t.Fatal(err) + } + if err := p.BeginWorkspaceRevocation(ctx, "v", "old", 1); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "old", 1); err != nil { + t.Fatal(err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7}); err != nil { + t.Fatal(err) + } + req := WorkspaceMoveRequest{RequestID: "c", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, + TargetReplicaID: "old", TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"} + r, err := p.MoveWorkspace(ctx, req, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42, Detached: true}) + if err != nil { + t.Fatal(err) + } + if r.LostUntilNS != 0 { + t.Fatalf("clean record LostUntilNS=%d; want none", r.LostUntilNS) + } + raw, err := json.Marshal(NewPublisher(nil, WithStore(disk)).WorkspaceState("v").Moves[0]) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(raw), "LostUntilNS") { + t.Fatalf("clean record encoding changed: %s", raw) + } +} From 1fd87df5191cf71a4ab5e1c56bc2ca63e8f51a76 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:05:20 -0800 Subject: [PATCH 055/150] docs: bind deadline and physical-fault status to FUA regression coverage --- 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 3925894a27..8e23e36e26 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -348,7 +348,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB | | `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB | | `INV-WAL-V3-MIGRATE-001` | `sw-block migrate-v3` rewrites only the descriptor of a cleanly closed v2/impl1 volume whose WAL the exhaustive scan proves flushed; the scan and the geometry check run before any write, and a refusal leaves the volume and every sidecar byte-identical. It keeps the extent base (WALSize = old - 4096), writes an atomic operator backup, an all-UNKNOWN initial map (covered = the v2 checkpoint), the prepared slot B, slot A at phase 0 (the commit point), slot B at phase 0, and only then retires the v2 chunk bitmap; each step is durable before the next. A rerun decides from the slot bytes alone: before the commit it restarts with a full rescan; after it, it only finishes the rollover and the retirement; a prepared B with an invalid A refuses with `ErrMigrationIncomplete`, as v3 open does; it never reads or restores the backup. | offline tool | `cmd/sw-block/migrate.go`; `cmd/sw-block/internal/v2legacy`; `core/storage/migrate_v3.go` | `TestMigrateV3CleanVolume`, `TestMigrateV3RefusalsChangeNothing`, `TestMigrateV3CrashAfterEachStepIsResumable`, `TestMigrateV3OldBinaryAfterPreparation`, `TestMigrateV3OldWALOverwritesThePreparedSlot`, `TestMigrateV3NeverRestoresTheBackup` (`cmd/sw-block/migrate_test.go`); tagged `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | none (tool) | STUB | -| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | +| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA` (expiry and joined physical-fault wire status); `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | | `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | | `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE | From 042a20165118eaf8afb2b264bd18644990a0066a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:35:29 -0800 Subject: [PATCH 056/150] fix(storage): bound the v3 owned-map file by reusing unreferenced extents New map pages and roots go into 4 KiB extents that no live root references, lowest first, instead of always being appended. Live roots are the roots named by the two descriptor slots and every prepared candidate not yet published or superseded. After each publication the publisher reports both slots; an extent is released only once neither slot's root references it. New pages and the root are fsynced before a publication names them. The free tail is truncated when the file exceeds 4x the live bytes. The on-disk format is unchanged. WALStore.ChunkMapStatsV3 reports the file bytes, live bytes and truncations. Fixes #236. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/base_install_v3.go | 1 + .../core/storage/chunk_lsn_map_v3.go | 69 +++- .../core/storage/chunk_map_extents_v3.go | 220 ++++++++++ .../core/storage/chunk_map_extents_v3_test.go | 391 ++++++++++++++++++ .../core/storage/chunk_map_publication_v3.go | 21 +- .../core/storage/chunkmap_bounded_v3_test.go | 41 ++ seaweed-block/core/storage/descriptor_v3.go | 7 + .../storage/walstore_map_checkpoint_v3.go | 2 + seaweed-block/docs/design/invariants.md | 4 +- 9 files changed, 742 insertions(+), 14 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_map_extents_v3.go create mode 100644 seaweed-block/core/storage/chunk_map_extents_v3_test.go create mode 100644 seaweed-block/core/storage/chunkmap_bounded_v3_test.go diff --git a/seaweed-block/core/storage/base_install_v3.go b/seaweed-block/core/storage/base_install_v3.go index 9b3ef91ecb..1985eca5e7 100644 --- a/seaweed-block/core/storage/base_install_v3.go +++ b/seaweed-block/core/storage/base_install_v3.go @@ -517,6 +517,7 @@ func (s *WALStore) markBaseCompleteV3(id [16]byte) error { v.syncMu.Lock() defer v.syncMu.Unlock() if !v.flushLifetimeValidV3(gen) { + prepared.abandonV3() return ErrMapCoverageStale // a recovery or reset ran meanwhile } installed := func(n *descriptorV3) error { diff --git a/seaweed-block/core/storage/chunk_lsn_map_v3.go b/seaweed-block/core/storage/chunk_lsn_map_v3.go index 5c3cd936c2..98b8def104 100644 --- a/seaweed-block/core/storage/chunk_lsn_map_v3.go +++ b/seaweed-block/core/storage/chunk_lsn_map_v3.go @@ -1,7 +1,9 @@ package storage -// Dark impl-3 COW map, DESIGN r15 9.2-9.5. All bytes are append-only; -// neither fallback slots nor pending candidates can lose a dependency. +// Impl-3 COW map. Pages and roots are immutable once written; their extents +// are reused only after no live root references them +// (chunk_map_extents_v3.go), so neither slot root nor a pending candidate can +// lose a dependency. import ( "bytes" "crypto/sha256" @@ -242,6 +244,14 @@ type chunkLSNMapV3 struct { syncFile func() error syncDirectory func() error latchPersistence func(error) + // liveMu guards live (chunk_map_extents_v3.go); never held across I/O. + liveMu sync.Mutex + live chunkMapLiveV3 +} + +func (m *chunkLSNMapV3) initLiveV3() { + m.live.roots = map[mapRootKeyV3]mapRootExtentsV3{} + m.live.inflight = map[mapRootKeyV3]bool{} } func createChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3, error) { @@ -256,6 +266,7 @@ func createChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3 return nil, e } m := &chunkLSNMapV3{fd: f, identity: d, chunkBlocks: cb} + m.initLiveV3() m.syncFile = f.Sync m.syncDirectory = func() error { return syncDir(filepath.Dir(path)) } if e = m.syncFile(); e == nil { @@ -281,6 +292,13 @@ func openChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3, return nil, nil, e } m := &chunkLSNMapV3{fd: f, identity: d, chunkBlocks: cb, lastGeneration: d.MapGeneration} + m.initLiveV3() + if s, e := mapShapeForV3(d, cb); e == nil { + m.registerRootV3(d.MapGeneration, d.MapRootLocator, s.aligned, refs) + } + if info, e := f.Stat(); e == nil && info.Size() > 0 { + m.live.fileBytes.Store(uint64(info.Size())) + } m.syncFile = f.Sync m.syncDirectory = func() error { return syncDir(filepath.Dir(path)) } c := &chunkMapCandidateV3{owner: m, generation: d.MapGeneration, covered: d.MapCoveredCheckpoint, rootOffset: d.MapRootLocator, hash: d.MapRootHash, refs: refs, entries: es} @@ -291,7 +309,9 @@ func openChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3, // It returns a pinned tuple, never a descriptor publication or reuse authority. // Preflight and Stat errors do not latch. Once the append transaction starts, // an error latches and refuses subsequent persistence I/O until reopen. -// No pages are reclaimed in this append-only implementation. +// New pages and the root go into extents no live root references +// (chunk_map_extents_v3.go); the candidate stays live until a publication +// names it or supersedes it. func (m *chunkLSNMapV3) Prepare(g, C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (out *chunkMapCandidateV3, err error) { m.mu.Lock() defer m.mu.Unlock() @@ -300,7 +320,8 @@ func (m *chunkLSNMapV3) Prepare(g, C uint64, entries []chunkLSNEntryV3, prior *c // Generation reservation and persistence share the existing sidecar mutex. // Concurrent preparers cannot select the same generation; no new lock or -// scheduler is introduced, and aborted candidates remain immutable orphans. +// scheduler is introduced. A candidate known never to reach a slot is +// released (abandonCandidateV3); an uncertain one stays pinned until reopen. func (m *chunkLSNMapV3) prepareNextV3(C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (*chunkMapCandidateV3, error) { m.mu.Lock() defer m.mu.Unlock() @@ -342,11 +363,14 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, if info.Size() < 0 { return nil, ErrMapInvalid } - off := uint64(info.Size()) - if off > math.MaxInt64-4095 { + fileBytes := uint64(info.Size()) + if fileBytes > math.MaxInt64-4095 { return nil, ErrCounterExhausted } - off = (off + 4095) &^ uint64(4095) + // The live set: every page and root extent a live root references. + // Roots are only added here (under m.mu); the publisher's report only + // removes them, so this snapshot is a superset for the whole prepare. + used, liveBytes := usedPagesV3(m.liveSnapshotV3()) defer func() { if err != nil { m.failed = err @@ -355,11 +379,28 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, } } }() + // Bounded file: truncate the free tail once the file exceeds 4 x the + // live bytes. Nothing at or below the highest live page is touched, so + // a root the fallback slot names stays readable. + if liveBytes > 0 && fileBytes > 4*liveBytes { + keep := (used[len(used)-1] + 1) * 4096 + if keep < fileBytes { + if e := m.fd.Truncate(int64(keep)); e != nil { + return nil, e + } + if e := m.syncFile(); e != nil { + return nil, e + } + fileBytes = keep + m.live.truncations.Add(1) + } + } + alloc := newExtentAllocatorV3(used, fileBytes) write := func(b []byte) (uint64, error) { - if uint64(len(b)) > math.MaxInt64-off { + at := alloc.alloc(uint64(len(b)+4095) / 4096) + if uint64(len(b)) > math.MaxInt64-at { return 0, ErrCounterExhausted } - at := off n, e := m.fd.WriteAt(b, int64(at)) if e == nil && n != len(b) { e = io.ErrShortWrite @@ -367,7 +408,6 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, if e != nil { return 0, e } - off += uint64(len(b)) return at, nil } refs := make([]mapPageRefV3, s.pages) @@ -416,6 +456,15 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, } m.lastGeneration = g out = &chunkMapCandidateV3{owner: m, generation: g, covered: C, rootOffset: at, hash: mapDigestV3(mapRootDomainV3, root[:s.raw-32]), refs: refs, entries: append([]chunkLSNEntryV3(nil), entries...)} + // The candidate is live (in flight) until a publication names it or + // supersedes it. + x := rootExtentsV3(at, s.aligned, refs) + m.liveMu.Lock() + k := mapRootKeyV3{at, g} + m.live.roots[k] = x + m.live.inflight[k] = true + m.liveMu.Unlock() + m.live.fileBytes.Store(max(alloc.end*4096, fileBytes)) return out, nil } func (m *chunkLSNMapV3) Close() error { diff --git a/seaweed-block/core/storage/chunk_map_extents_v3.go b/seaweed-block/core/storage/chunk_map_extents_v3.go new file mode 100644 index 0000000000..ab8513cb3e --- /dev/null +++ b/seaweed-block/core/storage/chunk_map_extents_v3.go @@ -0,0 +1,220 @@ +package storage + +import ( + "sort" + "sync/atomic" +) + +// The owned-map file reuses space. A candidate's new pages and root go into +// 4 KiB extents that no live root references, and the file's free tail is +// truncated once the file exceeds 4x the live bytes. +// +// Live roots are the roots the two descriptor slots name and every prepared +// candidate not yet published or superseded (an uncertain candidate stays +// live, because a failed publication latches the publisher). An extent is +// released only after a publication leaves neither slot naming it. New +// pages and the root are fsynced before a publication names them, so a +// crash leaves every slot-named root intact. Roots and pages are addressed +// by offset and SHA-256, so the on-disk format is unchanged. +// +// Map pages are read by offset only at open, before any candidate exists; +// other openers take the same exclusive volume lock. +// +// Lock order: WALStore.mu -> descMu -> liveMu (the publisher's report and +// the definite-abandon path run under descMu), and chunkLSNMapV3.mu -> +// liveMu (a prepare snapshots and registers under it). liveMu is held only +// for map and slice bookkeeping, never across I/O, sorting or allocation, +// and nothing holding liveMu takes another lock. + +type mapRootKeyV3 struct{ off, gen uint64 } + +type mapRootExtentsV3 struct { + rootOff, rootLen uint64 // bytes, 4 KiB aligned + pages []uint64 // page offsets (every page the root references) +} + +// chunkMapLiveV3 is the live set of one owned map. +type chunkMapLiveV3 struct { + roots map[mapRootKeyV3]mapRootExtentsV3 + inflight map[mapRootKeyV3]bool + truncations atomic.Uint64 + fileBytes atomic.Uint64 // set at open, after each prepare and truncation +} + +// ChunkMapStats reports the owned map file's size, the bytes its live roots +// reference, and how many times its free tail was truncated. +type ChunkMapStats struct { + FileBytes, LiveBytes, Truncations uint64 +} + +// registerRootV3 records a slot-named root read at open. Caller holds no lock +// other than possibly m.mu. +func (m *chunkLSNMapV3) registerRootV3(gen, rootOff, rootLen uint64, refs []mapPageRefV3) { + m.liveMu.Lock() + defer m.liveMu.Unlock() + m.live.roots[mapRootKeyV3{rootOff, gen}] = rootExtentsV3(rootOff, rootLen, refs) +} + +func rootExtentsV3(rootOff, rootLen uint64, refs []mapPageRefV3) mapRootExtentsV3 { + x := mapRootExtentsV3{rootOff: rootOff, rootLen: rootLen, pages: make([]uint64, len(refs))} + for i, r := range refs { + x.pages[i] = r.Offset + } + return x +} + +// slotsPublishedV3 is the publisher's report after a successful publication +// (under descMu). Roots named by neither slot are released, and so is every +// in-flight candidate the new current generation supersedes (it can never +// be published: a publication needs a strictly higher generation). +func (m *chunkLSNMapV3) slotsPublishedV3(cur, other descriptorV3, otherValid bool) { + m.liveMu.Lock() + defer m.liveMu.Unlock() + keep := map[mapRootKeyV3]bool{{cur.MapRootLocator, cur.MapGeneration}: true} + if otherValid { + keep[mapRootKeyV3{other.MapRootLocator, other.MapGeneration}] = true + } + for k := range m.live.roots { + if keep[k] { + delete(m.live.inflight, k) + continue + } + if m.live.inflight[k] && k.gen > cur.MapGeneration { + continue // a newer candidate, still publishable + } + delete(m.live.roots, k) + delete(m.live.inflight, k) + } +} + +// abandonCandidateV3 releases a prepared candidate that is known never to +// have reached a descriptor slot: its publication was refused before any +// slot I/O (a stale proof, a validation refusal, a latched fault), or its +// caller gave up before publishing. A candidate whose publication I/O +// started stays pinned (uncertain) until reopen. +func (m *chunkLSNMapV3) abandonCandidateV3(c *chunkMapCandidateV3) { + m.liveMu.Lock() + defer m.liveMu.Unlock() + k := mapRootKeyV3{c.rootOffset, c.generation} + if m.live.inflight[k] { + delete(m.live.inflight, k) + delete(m.live.roots, k) + } +} + +// abandonV3 is the definite-abandon path for a prepared publication. +func (p *preparedMapPublicationV3) abandonV3() { + if p != nil && p.candidate != nil && p.candidate.owner != nil { + p.candidate.owner.abandonCandidateV3(p.candidate) + } +} + +// liveSnapshotV3 copies the live roots' extents under liveMu. +func (m *chunkLSNMapV3) liveSnapshotV3() []mapRootExtentsV3 { + m.liveMu.Lock() + defer m.liveMu.Unlock() + out := make([]mapRootExtentsV3, 0, len(m.live.roots)) + for _, x := range m.live.roots { + out = append(out, x) + } + return out +} + +// usedPagesV3 returns the sorted, distinct 4 KiB page indexes a live-set +// snapshot references, and the live byte count. It needs no lock. +func usedPagesV3(roots []mapRootExtentsV3) ([]uint64, uint64) { + set := map[uint64]bool{} + for _, x := range roots { + for p := x.rootOff / 4096; p < (x.rootOff+x.rootLen)/4096; p++ { + set[p] = true + } + for _, off := range x.pages { + set[off/4096] = true + } + } + used := make([]uint64, 0, len(set)) + for p := range set { + used = append(used, p) + } + sort.Slice(used, func(i, j int) bool { return used[i] < used[j] }) + return used, uint64(len(used)) * 4096 +} + +// extentAllocatorV3 hands out free 4 KiB-aligned runs, lowest first, given +// the pages in use; it grows the file only when no free run fits. +type extentAllocatorV3 struct { + used map[uint64]bool + end uint64 // page index just past the file's last page + next uint64 // scan start: pages below it were found used or allocated +} + +func newExtentAllocatorV3(used []uint64, fileBytes uint64) *extentAllocatorV3 { + a := &extentAllocatorV3{used: make(map[uint64]bool, len(used)), end: (fileBytes + 4095) / 4096} + for _, p := range used { + a.used[p] = true + } + return a +} + +// alloc reserves n contiguous pages and returns the byte offset. +func (a *extentAllocatorV3) alloc(n uint64) uint64 { + run, start := uint64(0), uint64(0) + for p := a.next; p < a.end; p++ { + if a.used[p] { + run = 0 + if p == a.next { + a.next++ + } + continue + } + if run == 0 { + start = p + } + run++ + if run == n { + for q := start; q < start+n; q++ { + a.used[q] = true + } + if start == a.next { + a.next = start + n + } + return start * 4096 + } + } + if run > 0 && start+run == a.end { // a free run at the end grows in place + for q := start; q < a.end; q++ { + a.used[q] = true + } + need := n - run + for q := a.end; q < a.end+need; q++ { + a.used[q] = true + } + a.end += need + return start * 4096 + } + off := a.end * 4096 + for q := a.end; q < a.end+n; q++ { + a.used[q] = true + } + a.end += n + return off +} + +// Stats reports the map file's size, live bytes and truncations. The live +// bytes are computed on demand from a snapshot. +func (m *chunkLSNMapV3) Stats() ChunkMapStats { + _, live := usedPagesV3(m.liveSnapshotV3()) + return ChunkMapStats{FileBytes: m.live.fileBytes.Load(), LiveBytes: live, Truncations: m.live.truncations.Load()} +} + +// ChunkMapStatsV3 reports the owned map file's bounded-growth counters, or +// the zero value when the store has no owned map. Close clears the map +// under lifecycleMu, so the read holds it shared. +func (s *WALStore) ChunkMapStatsV3() ChunkMapStats { + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + if s.v3 == nil || s.v3.ownedMap == nil { + return ChunkMapStats{} + } + return s.v3.ownedMap.Stats() +} diff --git a/seaweed-block/core/storage/chunk_map_extents_v3_test.go b/seaweed-block/core/storage/chunk_map_extents_v3_test.go new file mode 100644 index 0000000000..589cb07605 --- /dev/null +++ b/seaweed-block/core/storage/chunk_map_extents_v3_test.go @@ -0,0 +1,391 @@ +package storage + +import ( + "os" + "path/filepath" + "testing" +) + +// Extent reuse in the owned-map file. +// Map-level schedules on a one-page map (mapDescriptorV3: one chunk), with +// the publisher's slot report driven directly so each schedule is exact. + +func extentsMapV3(t *testing.T) (*chunkLSNMapV3, descriptorV3, string) { + t.Helper() + d := mapDescriptorV3(t) + path := filepath.Join(t.TempDir(), "map") + m, err := createChunkLSNMapV3(path, d, 1) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.Close() }) + return m, d, path +} + +func prepV3(t *testing.T, m *chunkLSNMapV3, g uint64, prior *chunkMapCandidateV3) *chunkMapCandidateV3 { + t.Helper() + c, err := m.Prepare(g, 7, []chunkLSNEntryV3{{LSN: 100 + g}}, prior) + if err != nil { + t.Fatalf("prepare gen %d: %v", g, err) + } + return c +} + +func readsV3(t *testing.T, m *chunkLSNMapV3, d descriptorV3, c *chunkMapCandidateV3, what string) { + t.Helper() + es, _, err := readChunkLSNMapV3(m.fd, c.descriptor(d), m.chunkBlocks) + if err != nil { + t.Fatalf("%s (gen %d at %d) unreadable: %v", what, c.generation, c.rootOffset, err) + } + if es[0].LSN != 100+c.generation { + t.Fatalf("%s (gen %d) reads LSN %d", what, c.generation, es[0].LSN) + } +} + +func publishV3(m *chunkLSNMapV3, d descriptorV3, cur, other *chunkMapCandidateV3) { + m.slotsPublishedV3(cur.descriptor(d), other.descriptor(d), true) +} + +func mapFileSizeV3(t *testing.T, path string) int64 { + t.Helper() + fi, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + return fi.Size() +} + +// Every publication leaves the previous generation in the fallback slot. Its +// root and page must stay readable after every later candidate, and the file +// stays within 8 one-page maps. Mutants: a live set without the fallback +// slot (a later candidate overwrites the fallback's extents) and an +// append-only allocator (the file grows by a page and a root per candidate). +func TestChunkMapExtentsV3FallbackRootIsNeverReused(t *testing.T) { + m, d, path := extentsMapV3(t) + prev := prepV3(t, m, 1, nil) + publishV3(m, d, prev, prev) + for g := uint64(2); g <= 60; g++ { + c := prepV3(t, m, g, prev) + publishV3(m, d, c, prev) + readsV3(t, m, d, c, "current") + readsV3(t, m, d, prev, "fallback") + prev = c + } + if size := mapFileSizeV3(t, path); size > 8*2*4096 { + t.Fatalf("map file %d B after 60 generations, bound %d B", size, 8*2*4096) + } +} + +// A candidate prepared after another one that is not yet published (two +// preparers) is newer than the generation the first publication makes +// current, so it stays live and the next candidate must not reuse its +// extents. Mutant: releasing every unpublished candidate at a publication +// overwrites it. +func TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused(t *testing.T) { + m, d, _ := extentsMapV3(t) + c1 := prepV3(t, m, 1, nil) + publishV3(m, d, c1, c1) + c2 := prepV3(t, m, 2, c1) + c3 := prepV3(t, m, 3, c1) // a second preparer, not yet published + publishV3(m, d, c2, c1) + c4 := prepV3(t, m, 4, c2) + readsV3(t, m, d, c3, "in-flight gen 3") + readsV3(t, m, d, c4, "gen 4") + readsV3(t, m, d, c1, "fallback") +} + +// A crash after a candidate was written into reused extents but before any +// publication named it: the reopen of the selected slot and its fallback +// reads both intact, because a candidate only ever takes extents no slot +// names. +func TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent(t *testing.T) { + m, d, path := extentsMapV3(t) + prev := prepV3(t, m, 1, nil) + publishV3(m, d, prev, prev) + var cur *chunkMapCandidateV3 + for g := uint64(2); g <= 10; g++ { + cur = prepV3(t, m, g, prev) + publishV3(m, d, cur, prev) + prev, cur = cur, prev + } + cur, prev = prev, cur // cur = gen 10, prev = gen 9 + orphan := prepV3(t, m, 11, cur) + if orphan.rootOffset+4096 >= uint64(mapFileSizeV3(t, path)) { + t.Fatalf("setup: gen 11's root at %d did not reuse a freed extent", orphan.rootOffset) + } + if err := m.Close(); err != nil { + t.Fatal(err) + } + r, rc, err := openChunkLSNMapV3(path, cur.descriptor(d), 1) + if err != nil { + t.Fatalf("reopen of the selected slot after the crash: %v", err) + } + defer r.Close() + if rc.entries[0].LSN != 100+cur.generation { + t.Fatalf("selected slot reads LSN %d", rc.entries[0].LSN) + } + if _, _, err := readChunkLSNMapV3(r.fd, prev.descriptor(d), 1); err != nil { + t.Fatalf("fallback after the crash: %v", err) + } +} + +// Truncation while the fallback slot's root lies at the file's tail: a burst +// of unpublished candidates raises the high-water mark; the fallback then is +// the highest of them and the current one lands low. The next candidate +// must not truncate below the fallback; once a later publication releases +// it, the free tail is truncated. Mutant: truncating above the lowest live +// page cuts the fallback's root away. +func TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail(t *testing.T) { + m, d, path := extentsMapV3(t) + c := prepV3(t, m, 1, nil) + publishV3(m, d, c, c) + var burst []*chunkMapCandidateV3 + for g := uint64(2); g <= 21; g++ { + burst = append(burst, prepV3(t, m, g, c)) // unpublished: the file grows + } + top := burst[len(burst)-1] // gen 21, the highest extents + publishV3(m, d, top, c) // releases gens 2..20 + low := prepV3(t, m, 22, top) + if low.rootOffset > top.rootOffset { + t.Fatalf("setup: gen 22 at %d did not land below gen 21 at %d", low.rootOffset, top.rootOffset) + } + publishV3(m, d, low, top) // fallback = gen 21 at the tail + next := prepV3(t, m, 23, low) + readsV3(t, m, d, top, "fallback at the tail") + publishV3(m, d, next, low) // releases gen 21 + before := mapFileSizeV3(t, path) + last := prepV3(t, m, 24, next) + readsV3(t, m, d, last, "gen 24") + readsV3(t, m, d, next, "gen 23") + if after := mapFileSizeV3(t, path); after >= before || m.Stats().Truncations == 0 { + t.Fatalf("free tail not truncated: %d B -> %d B, truncations %d", before, after, m.Stats().Truncations) + } +} + +// Repeated publications refused before any slot I/O (a stale proof) release +// their candidates at once, so the file and the live set stay bounded. +// Mutant: no definite-abandon path keeps every rejected candidate pinned +// until a later successful publication and the file grows by a root each. +func TestChunkMapExtentsV3RejectedPublicationsStayBounded(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + cp := s.v3.pub.current().CheckpointLSN + for i := 0; i < 300; i++ { + prepared, err := s.prepareOwnedMapCheckpointV3(cp) + if err != nil { + t.Fatalf("prepare %d: %v", i, err) + } + if err := s.v3.pub.invalidateMapProofV3(); err != nil { + t.Fatal(err) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err == nil { + t.Fatal("a stale-proof publication succeeded") + } + } + st := s.ChunkMapStatsV3() + fi, err := os.Stat(path + ".chunkmap") + if err != nil { + t.Fatal(err) + } + if fi.Size() > 8*2*4096 || st.LiveBytes > 4*2*4096 { + t.Fatalf("after 300 rejected publications: file %d B, live %d B", fi.Size(), st.LiveBytes) + } +} + +// damageNewestSlotV3 corrupts the slot with the higher generation so the +// next open selects the fallback slot. +func damageNewestSlotV3(t *testing.T, path string) { + t.Helper() + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + defer f.Close() + var gens [2]uint64 + offs := [2]int64{slotAOffsetV3, slotBOffsetV3} + for i, off := range offs { + b := make([]byte, slotSizeV3) + if _, err := f.ReadAt(b, off); err != nil { + t.Fatal(err) + } + if d, err := decodeSlotV3(b, nil); err == nil { + gens[i] = d.SlotGen + } + } + off := offs[0] + if gens[1] > gens[0] { + off = offs[1] + } + if _, err := f.WriteAt([]byte{0xFF, 0xFF, 0xFF, 0xFF}, off+64); err != nil { + t.Fatal(err) + } + if err := f.Sync(); err != nil { + t.Fatal(err) + } +} + +// A real two-slot reopen registers BOTH slot roots read from disk, so a +// candidate prepared before the open's first publication (which would +// re-report both slots) cannot take the fallback root's extents. The +// candidates are prepared right after the open, none is published, and the +// store crashes; with the newest slot damaged, the reopen selects the +// fallback slot and its map must validate. Mutant: an open that does not +// register the fallback slot's root lets the candidates overwrite it. +func TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot(t *testing.T) { + path := filepath.Join(t.TempDir(), "mapped") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, v3TestWAL, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 10; i++ { + writeSynced(t, s, i, i) + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + } + // One more map publication without the checkpoint's rollover, so the two + // slots name different map roots at the crash. + writeSynced(t, s, 12, 12) + prepared, err := s.prepareOwnedMapCheckpointV3(s.v3.pub.current().CheckpointLSN) + if err != nil { + t.Fatal(err) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + cp := r.v3.pub.current().CheckpointLSN + r.v3.pub.descMu.Lock() + cur, other, otherValid := r.v3.pub.cur, r.v3.pub.other, r.v3.pub.otherValid + r.v3.pub.descMu.Unlock() + if !otherValid || cur.MapGeneration == other.MapGeneration { + t.Fatalf("setup: slots name map generations %d and %d (fallback valid %v)", cur.MapGeneration, other.MapGeneration, otherValid) + } + for i := 0; i < 20; i++ { // unpublished candidates fill every free extent + if _, err := r.prepareOwnedMapCheckpointV3(cp); err != nil { + t.Fatal(err) + } + } + crashRecoveryHardeningStore(t, r) + damageNewestSlotV3(t, path) + q, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatalf("reopen from the fallback slot: %v", err) + } + q.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { crashRecoveryHardeningStore(t, q) }) + if _, err := q.Recover(); err != nil { + t.Fatalf("recover from the fallback slot: %v", err) + } +} + +// A failed fsync after a tail truncation latches the map, and the slot +// roots stay readable: the truncation only ever removes extents above the +// highest live page. +func TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots(t *testing.T) { + m, d, path := extentsMapV3(t) + c := prepV3(t, m, 1, nil) + publishV3(m, d, c, c) + var top *chunkMapCandidateV3 + for g := uint64(2); g <= 21; g++ { + top = prepV3(t, m, g, c) + } + publishV3(m, d, top, c) + low := prepV3(t, m, 22, top) + publishV3(m, d, low, top) + next := prepV3(t, m, 23, low) + publishV3(m, d, next, low) // gen 21 released: the tail is free + m.syncFile = func() error { return os.ErrInvalid } + if _, err := m.Prepare(24, 7, []chunkLSNEntryV3{{LSN: 124}}, next); err == nil { + t.Fatal("prepare across a failed truncation fsync succeeded") + } + if err := m.Close(); err != nil { + t.Fatal(err) + } + r, rc, err := openChunkLSNMapV3(path, next.descriptor(d), 1) + if err != nil { + t.Fatalf("reopen after the truncation fault: %v", err) + } + defer r.Close() + if rc.entries[0].LSN != 100+next.generation { + t.Fatalf("selected root reads LSN %d", rc.entries[0].LSN) + } + if _, _, err := readChunkLSNMapV3(r.fd, low.descriptor(d), 1); err != nil { + t.Fatalf("fallback after the truncation fault: %v", err) + } +} + +// A publication whose slot I/O failed leaves an uncertain candidate: the +// publisher latches and the candidate stays pinned until reopen. A later +// admitted prepare must not reuse its extents, and both the uncertain +// candidate and the slot roots stay readable. Mutant: abandoning the +// uncertain candidate like a refused one lets the later prepare overwrite it. +func TestChunkMapExtentsV3UncertainCandidateStaysPinned(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + cp := s.v3.pub.current().CheckpointLSN + prepared, err := s.prepareOwnedMapCheckpointV3(cp) + if err != nil { + t.Fatal(err) + } + s.v3.testBeforeSlotWrite = func() error { return os.ErrInvalid } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err == nil { + t.Fatal("a publication with a failed slot write succeeded") + } + s.v3.testBeforeSlotWrite = nil + m := s.v3.ownedMap + unc := prepared.candidate + for i := 0; i < 5; i++ { // admitted prepares after the failure + if _, err := m.prepareNextV3(cp, append([]chunkLSNEntryV3(nil), s.v3.mapEntries...), unc); err != nil { + t.Fatalf("admitted prepare %d: %v", i, err) + } + } + d := s.v3.pub.current() + if _, _, err := readChunkLSNMapV3(m.fd, unc.descriptor(d), m.chunkBlocks); err != nil { + t.Fatalf("uncertain candidate overwritten: %v", err) + } + if _, _, err := readChunkLSNMapV3(m.fd, d, m.chunkBlocks); err != nil { + t.Fatalf("selected slot root overwritten: %v", err) + } +} + +// ChunkMapStatsV3 is correct right after a reopen: the file size and the +// live bytes of the two slot roots read from disk, not zero. +func TestChunkMapExtentsV3StatsAfterReopen(t *testing.T) { + path := filepath.Join(t.TempDir(), "mapped") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, v3TestWAL, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 5; i++ { + writeSynced(t, s, i, i) + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + } + crashRecoveryHardeningStore(t, s) + fi, err := os.Stat(path + ".chunkmap") + if err != nil { + t.Fatal(err) + } + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + st := r.ChunkMapStatsV3() + if st.FileBytes != uint64(fi.Size()) || st.LiveBytes == 0 || st.LiveBytes > st.FileBytes { + t.Fatalf("stats after reopen: %+v, file %d B", st, fi.Size()) + } +} diff --git a/seaweed-block/core/storage/chunk_map_publication_v3.go b/seaweed-block/core/storage/chunk_map_publication_v3.go index c6496a298c..b667906314 100644 --- a/seaweed-block/core/storage/chunk_map_publication_v3.go +++ b/seaweed-block/core/storage/chunk_map_publication_v3.go @@ -137,7 +137,7 @@ func (p *descriptorPublisherV3) publishMapV3(storeMu sync.Locker, snap func(), p if prepared == nil || prepared.candidate == nil { return descriptorV3{}, ErrMapCoverageStale } - return p.publishWithMapV3(storeMu, snap, func(d *descriptorV3) error { + d, err := p.publishWithMapV3(storeMu, snap, func(d *descriptorV3) error { if mutate != nil { if e := mutate(d); e != nil { return e @@ -146,6 +146,18 @@ func (p *descriptorPublisherV3) publishMapV3(storeMu sync.Locker, snap func(), p *d = prepared.candidate.descriptor(*d) return nil }, prepared) + if err != nil { + // Definite abandon: unless the slot I/O started (the candidate is + // the uncertain one, pinned until reopen), no slot can name it. + c := prepared.candidate + p.descMu.Lock() + unc := p.uncertain + if unc == nil || unc.MapRootLocator != c.rootOffset || unc.MapGeneration != c.generation { + prepared.abandonV3() + } + p.descMu.Unlock() + } + return d, err } // invalidateMapProofV3 is called under WALStore.mu at a lifecycle boundary. @@ -187,7 +199,12 @@ func openDescriptorMapV3(path string, selected descriptorV3, fallback *descripto if fallback.UUID != selected.UUID || fallback.MapLineage != selected.MapLineage || !sameGeometryV3(*fallback, selected) { err = ErrMapInvalid } else { - _, _, err = readChunkLSNMapV3(m.fd, *fallback, cb) + var refs []mapPageRefV3 + if _, refs, err = readChunkLSNMapV3(m.fd, *fallback, cb); err == nil { + if sh, e := mapShapeForV3(*fallback, cb); e == nil { + m.registerRootV3(fallback.MapGeneration, fallback.MapRootLocator, sh.aligned, refs) + } + } } if err != nil { _ = m.Close() diff --git a/seaweed-block/core/storage/chunkmap_bounded_v3_test.go b/seaweed-block/core/storage/chunkmap_bounded_v3_test.go new file mode 100644 index 0000000000..99c3107f63 --- /dev/null +++ b/seaweed-block/core/storage/chunkmap_bounded_v3_test.go @@ -0,0 +1,41 @@ +package storage + +import ( + "os" + "testing" +) + +// The v3 owned-map file must stay bounded under steady writes. Each cycle +// writes, syncs and checkpoints, so every cycle publishes a new map +// generation with a changed page. After 300 checkpoints the file must not +// exceed a small multiple of one full map (pages + root, each 4 KiB +// aligned): the live map of the two descriptor slots plus one in-flight +// candidate, with slack. +func TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + shape, err := mapShapeForV3(s.v3.pub.current(), s.v3.ownedMap.chunkBlocks) + if err != nil { + t.Fatal(err) + } + rootBytes := (120 + 40*shape.pages + 4095) &^ 4095 + fullMap := int64(shape.pages*4096 + rootBytes) + bound := 8 * fullMap + const cycles = 300 + for i := 0; i < cycles; i++ { + writeSynced(t, s, uint32(i%64), uint32(i%64)) + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + } + gen := s.v3.pub.current().MapGeneration + if gen < cycles { + t.Fatalf("setup: %d map generations after %d checkpoint cycles", gen, cycles) + } + fi, err := os.Stat(path + ".chunkmap") + if err != nil { + t.Fatal(err) + } + if fi.Size() > bound { + t.Fatalf("chunkmap is %d B after %d generations; bound %d B (8 x one full map of %d B)", fi.Size(), gen, bound, fullMap) + } +} diff --git a/seaweed-block/core/storage/descriptor_v3.go b/seaweed-block/core/storage/descriptor_v3.go index ec5f3ea477..64c83d0795 100644 --- a/seaweed-block/core/storage/descriptor_v3.go +++ b/seaweed-block/core/storage/descriptor_v3.go @@ -266,6 +266,13 @@ func (p *descriptorPublisherV3) publishLockedCoreV3(mutate func(next *descriptor if prepared != nil { p.mapCurrent = prepared.candidate } + // Report the slot tuples to the owned map (descMu -> liveMu): roots + // neither slot names any more, and superseded candidates, are released. + // A publication before the map is bound reports nothing; that only + // delays a release until the next report. + if p.mapCurrent != nil && p.mapCurrent.owner != nil { + p.mapCurrent.owner.slotsPublishedV3(p.cur, p.other, p.otherValid) + } return next, nil } diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index 568eefa2fe..6449d469a0 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -116,6 +116,7 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) // The candidate proof alone is insufficient: it was prepared after extent // I/O and could belong to a newer Recover lifetime than those bytes. if !v.flushLifetimeValidV3(recoveryGen) { + prepared.abandonV3() return descriptorV3{}, ErrMapCoverageStale } wack := v.wack.Load() @@ -123,6 +124,7 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) wack = max(wack, cp) } if wack < cp { + prepared.abandonV3() return descriptorV3{}, ErrMapCoverageStale } s.mu.RLock() diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6ee4916e12..977d752fa1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -337,7 +337,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | | `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | -| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Append-only retention preserves both slots and pending candidates. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | +| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | | `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | | `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | @@ -357,7 +357,7 @@ Notes: - `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. Writes invalidate proofs before append and update per-chunk max LSN under store.mu, while Recover rebuilds that volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. -- `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. No sidecar page reclamation is implemented, so fallback or uncertain generations remain pinned conservatively. +- `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. Sidecar extents are reused only after neither slot nor a pending or uncertain candidate references them; see `chunk_map_extents_v3.go` and its tests. - `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only. - `INV-FE-FLUSH-SYNC-001`: NVMe/TCP also asserts failed-Sync status and reason logging through the actual session dispatch, and success produces no failure log. From 3ffface62abe3f55a1b9db09834b6834ae74e1a7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:40:53 -0800 Subject: [PATCH 057/150] fix(storage): keep map candidates pinned exactly while a slot may name them A candidate prepared successfully and then refused because its proof went stale during the prepare's I/O was left in flight until reopen; both preparation paths now release it before returning ErrMapCoverageStale. A publication whose slot write and fsync succeeded but which a fault latched meanwhile refuses at its success boundary may still be named by the slot on disk. It is now recorded as uncertain, so its candidate stays pinned until reopen instead of being released for reuse. The map's file-size counter now follows every write and truncation. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_lsn_map_v3.go | 4 + .../core/storage/chunk_map_extents_v3_test.go | 122 +++++++++++++++++- .../core/storage/chunk_map_publication_v3.go | 1 + seaweed-block/core/storage/descriptor_v3.go | 6 +- .../storage/walstore_map_checkpoint_v3.go | 1 + 5 files changed, 129 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/storage/chunk_lsn_map_v3.go b/seaweed-block/core/storage/chunk_lsn_map_v3.go index 98b8def104..59b7ce6cde 100644 --- a/seaweed-block/core/storage/chunk_lsn_map_v3.go +++ b/seaweed-block/core/storage/chunk_lsn_map_v3.go @@ -392,6 +392,7 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, return nil, e } fileBytes = keep + m.live.fileBytes.Store(keep) m.live.truncations.Add(1) } } @@ -402,6 +403,9 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, return 0, ErrCounterExhausted } n, e := m.fd.WriteAt(b, int64(at)) + if end := at + uint64(n); end > m.live.fileBytes.Load() { + m.live.fileBytes.Store(end) // also on a failed or short write + } if e == nil && n != len(b) { e = io.ErrShortWrite } diff --git a/seaweed-block/core/storage/chunk_map_extents_v3_test.go b/seaweed-block/core/storage/chunk_map_extents_v3_test.go index 589cb07605..6236402157 100644 --- a/seaweed-block/core/storage/chunk_map_extents_v3_test.go +++ b/seaweed-block/core/storage/chunk_map_extents_v3_test.go @@ -288,9 +288,10 @@ func TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot(t *testing.T) { } } -// A failed fsync after a tail truncation latches the map, and the slot -// roots stay readable: the truncation only ever removes extents above the -// highest live page. +// A failed fsync of the tail truncation itself (the first fsync of the +// prepare) latches the map: the prepare and every later one fail. The slot +// roots stay readable, because the truncation only removes extents above +// the highest live page. func TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots(t *testing.T) { m, d, path := extentsMapV3(t) c := prepV3(t, m, 1, nil) @@ -304,10 +305,24 @@ func TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots(t *testing.T) { publishV3(m, d, low, top) next := prepV3(t, m, 23, low) publishV3(m, d, next, low) // gen 21 released: the tail is free - m.syncFile = func() error { return os.ErrInvalid } + before := mapFileSizeV3(t, path) + orig, calls := m.syncFile, 0 + m.syncFile = func() error { + calls++ + if calls == 1 { + return os.ErrInvalid // the truncation's fsync + } + return orig() + } if _, err := m.Prepare(24, 7, []chunkLSNEntryV3{{LSN: 124}}, next); err == nil { t.Fatal("prepare across a failed truncation fsync succeeded") } + if calls != 1 || mapFileSizeV3(t, path) >= before { + t.Fatalf("setup: %d fsyncs, file %d B -> %d B; want the truncation's fsync to fail", calls, before, mapFileSizeV3(t, path)) + } + if _, err := m.Prepare(25, 7, []chunkLSNEntryV3{{LSN: 125}}, next); err == nil || calls != 1 { + t.Fatalf("the map did not latch: err %v, fsyncs %d", err, calls) + } if err := m.Close(); err != nil { t.Fatal(err) } @@ -389,3 +404,102 @@ func TestChunkMapExtentsV3StatsAfterReopen(t *testing.T) { t.Fatalf("stats after reopen: %+v, file %d B", st, fi.Size()) } } + +// A candidate that is prepared successfully but whose proof went stale +// during its file I/O (a guest write changed the map meanwhile) is +// refused before publication and must be released at once, so a steady +// stream of such refusals keeps the file bounded. Both preparation paths +// are covered: the checkpoint's and prepareMapPublicationV3. Mutant: not +// abandoning after the proof check pins every refused candidate. +func TestChunkMapExtentsV3ProofStalePreparesStayBounded(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + m := s.v3.ownedMap + orig := m.syncFile + m.syncFile = func() error { // the proof goes stale during the prepare's I/O + if err := s.v3.mapProof.mutatedV3(); err != nil { + return err + } + return orig() + } + cp := s.v3.pub.current().CheckpointLSN + for i := 0; i < 150; i++ { + if _, err := s.prepareOwnedMapCheckpointV3(cp); err != ErrMapCoverageStale { + t.Fatalf("checkpoint prepare %d: err = %v, want ErrMapCoverageStale", i, err) + } + } + g := s.v3.pub.current().MapGeneration + for i := 0; i < 150; i++ { + g += 1000 + entries := append([]chunkLSNEntryV3(nil), s.v3.mapEntries...) + if _, err := prepareMapPublicationV3(m, s.v3.mapProof, g, cp, entries, nil); err != ErrMapCoverageStale { + t.Fatalf("publication prepare %d: err = %v, want ErrMapCoverageStale", i, err) + } + } + m.syncFile = orig + fi, err := os.Stat(path + ".chunkmap") + if err != nil { + t.Fatal(err) + } + if st := s.ChunkMapStatsV3(); fi.Size() > 8*2*4096 || st.LiveBytes > 4*2*4096 { + t.Fatalf("after 300 proof-stale prepares: file %d B, live %d B", fi.Size(), st.LiveBytes) + } +} + +// A publication whose slot write and fsync both happened, but which a fault +// latched meanwhile refuses at its success boundary, may be named by the +// slot on disk. Its candidate stays pinned: an already admitted preparer +// does not reuse its extents, and after a crash the reopen selects that +// slot and its map validates. Mutant: treating that refusal like one before +// slot I/O abandons the candidate and the preparer overwrites it. +func TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned(t *testing.T) { + path := filepath.Join(t.TempDir(), "mapped") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, v3TestWAL, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 4; i++ { + writeSynced(t, s, i, i) + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + } + writeSynced(t, s, 9, 9) + cp := s.v3.pub.current().CheckpointLSN + prepared, err := s.prepareOwnedMapCheckpointV3(cp) + if err != nil { + t.Fatal(err) + } + orig := s.v3.pub.io.fsync + s.v3.pub.io.fsync = func() error { // the slot reaches disk, then a fault latches + err := orig() + s.latchV3(os.ErrInvalid) + return err + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err == nil { + t.Fatal("a publication refused at its success boundary returned no error") + } + s.v3.pub.io.fsync = orig + m := s.v3.ownedMap + for i := 0; i < 10; i++ { // an already admitted preparer keeps going + entries := append([]chunkLSNEntryV3(nil), s.v3.mapEntries...) + entries[0].LSN += uint64(i + 1) + if _, err := m.prepareNextV3(cp, entries, prepared.candidate); err != nil { + t.Fatalf("admitted prepare %d: %v", i, err) + } + } + crashRecoveryHardeningStore(t, s) + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatalf("reopen of the durable slot: %v", err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + if g := r.v3.pub.current().MapGeneration; g != prepared.candidate.generation { + t.Fatalf("reopen selected map generation %d, want the durable one %d", g, prepared.candidate.generation) + } +} diff --git a/seaweed-block/core/storage/chunk_map_publication_v3.go b/seaweed-block/core/storage/chunk_map_publication_v3.go index b667906314..8869949475 100644 --- a/seaweed-block/core/storage/chunk_map_publication_v3.go +++ b/seaweed-block/core/storage/chunk_map_publication_v3.go @@ -65,6 +65,7 @@ func prepareMapPublicationV3(m *chunkLSNMapV3, d *mapProofEpochV3, g, C uint64, return nil, e } if !proof.validV3(d) { + m.abandonCandidateV3(c) // prepared but never publishable return nil, ErrMapCoverageStale } return &preparedMapPublicationV3{candidate: c, proof: proof}, nil diff --git a/seaweed-block/core/storage/descriptor_v3.go b/seaweed-block/core/storage/descriptor_v3.go index 64c83d0795..1300ef199a 100644 --- a/seaweed-block/core/storage/descriptor_v3.go +++ b/seaweed-block/core/storage/descriptor_v3.go @@ -257,8 +257,12 @@ func (p *descriptorPublisherV3) publishLockedCoreV3(mutate func(next *descriptor return descriptorV3{}, err // refused before any I/O (a latched fault) } // Success boundary: a fault latched by another path while this - // publication was in flight still refuses it (#172). + // publication was in flight still refuses it (#172). The slot write and + // its fsync did happen, so the slot on disk may name this generation: + // its dependencies stay pinned as an uncertain candidate until reopen. if err := p.io.sticky(); err != nil { + uncertain := next + p.uncertain = &uncertain return descriptorV3{}, err } p.other, p.otherValid = p.cur, true diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index 6449d469a0..029d0ba210 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -44,6 +44,7 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati return nil, err } if !proof.validV3(domain) { + v.ownedMap.abandonCandidateV3(c) // prepared but never publishable return nil, ErrMapCoverageStale } return &preparedMapPublicationV3{candidate: c, proof: proof}, nil From bfd07d85cbbd037b14014cb7e61afa2d20d0f377 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:17:55 -0800 Subject: [PATCH 058/150] docs(invariants): list the owned-map extent-reuse regressions 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 977d752fa1..43a8867335 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -337,7 +337,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | | `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | -| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | +| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | | `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | | `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | From adf9b9e2a7432074ba7f91c603f0765f95af1c02 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:31:21 -0800 Subject: [PATCH 059/150] fix(storage): count a truncated map file before its fsync Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_lsn_map_v3.go | 6 +++--- seaweed-block/core/storage/chunk_map_extents_v3.go | 3 ++- seaweed-block/core/storage/chunk_map_extents_v3_test.go | 3 +++ 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/storage/chunk_lsn_map_v3.go b/seaweed-block/core/storage/chunk_lsn_map_v3.go index 59b7ce6cde..caac02dcb7 100644 --- a/seaweed-block/core/storage/chunk_lsn_map_v3.go +++ b/seaweed-block/core/storage/chunk_lsn_map_v3.go @@ -388,12 +388,12 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, if e := m.fd.Truncate(int64(keep)); e != nil { return nil, e } + fileBytes = keep + m.live.fileBytes.Store(keep) // the file is shorter even if the fsync fails + m.live.truncations.Add(1) if e := m.syncFile(); e != nil { return nil, e } - fileBytes = keep - m.live.fileBytes.Store(keep) - m.live.truncations.Add(1) } } alloc := newExtentAllocatorV3(used, fileBytes) diff --git a/seaweed-block/core/storage/chunk_map_extents_v3.go b/seaweed-block/core/storage/chunk_map_extents_v3.go index ab8513cb3e..85fe268188 100644 --- a/seaweed-block/core/storage/chunk_map_extents_v3.go +++ b/seaweed-block/core/storage/chunk_map_extents_v3.go @@ -23,7 +23,8 @@ import ( // Lock order: WALStore.mu -> descMu -> liveMu (the publisher's report and // the definite-abandon path run under descMu), and chunkLSNMapV3.mu -> // liveMu (a prepare snapshots and registers under it). liveMu is held only -// for map and slice bookkeeping, never across I/O, sorting or allocation, +// for map and slice bookkeeping (it may allocate a slice or a map entry), +// never across I/O, sorting or extent allocation, // and nothing holding liveMu takes another lock. type mapRootKeyV3 struct{ off, gen uint64 } diff --git a/seaweed-block/core/storage/chunk_map_extents_v3_test.go b/seaweed-block/core/storage/chunk_map_extents_v3_test.go index 6236402157..72cf43e1af 100644 --- a/seaweed-block/core/storage/chunk_map_extents_v3_test.go +++ b/seaweed-block/core/storage/chunk_map_extents_v3_test.go @@ -320,6 +320,9 @@ func TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots(t *testing.T) { if calls != 1 || mapFileSizeV3(t, path) >= before { t.Fatalf("setup: %d fsyncs, file %d B -> %d B; want the truncation's fsync to fail", calls, before, mapFileSizeV3(t, path)) } + if got, want := m.Stats().FileBytes, uint64(mapFileSizeV3(t, path)); got != want { + t.Fatalf("stats after a truncation whose fsync failed: file bytes %d, file is %d B", got, want) + } if _, err := m.Prepare(25, 7, []chunkLSNEntryV3{{LSN: 125}}, next); err == nil || calls != 1 { t.Fatalf("the map did not latch: err %v, fsyncs %d", err, calls) } From fcea950acd2d420d453cbf8b035ecf55f915be50 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:20:53 -0800 Subject: [PATCH 060/150] test: preserve retryable expiry through required observer error wrappers --- .../durable/write_command_budget_test.go | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/seaweed-block/core/frontend/durable/write_command_budget_test.go b/seaweed-block/core/frontend/durable/write_command_budget_test.go index c927b8c440..2f41b94c62 100644 --- a/seaweed-block/core/frontend/durable/write_command_budget_test.go +++ b/seaweed-block/core/frontend/durable/write_command_budget_test.go @@ -3,6 +3,7 @@ package durable_test import ( "context" "errors" + "fmt" "testing" "time" @@ -78,3 +79,65 @@ func TestStorageBackendExpiredWriteDoesNotAppend(t *testing.T) { } } } + +type deadlineAckStore struct{ storage.LogicalStorage } + +func (s *deadlineAckStore) WriteContext(ctx context.Context, lba uint32, p []byte) (uint64, error) { + <-ctx.Done() + return s.LogicalStorage.Write(lba, p) +} +func (s *deadlineAckStore) WriteBatch(lba uint32, blocks [][]byte) ([]uint64, error) { + var lsns []uint64 + for i, p := range blocks { + lsn, err := s.LogicalStorage.Write(lba+uint32(i), p) + if err != nil { + return lsns, err + } + lsns = append(lsns, lsn) + } + return lsns, nil +} +func (s *deadlineAckStore) WriteBatchContext(ctx context.Context, lba uint32, blocks [][]byte) ([]uint64, error) { + <-ctx.Done() + return s.WriteBatch(lba, blocks) +} +func TestStorageBackendRequiredObserverDeadlineStaysRetryable(t *testing.T) { + for _, batch := range []bool{false, true} { + for _, physical := range []bool{false, true} { + t.Run(fmt.Sprintf("batch=%t/physical=%t", batch, physical), func(t *testing.T) { + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} + s := &deadlineAckStore{storage.NewBlockStore(8, 4096)} + b := durable.NewStorageBackend(s, newStubView(healthyProj(id)), id) + b.SetOperational(true, "test") + injected := errors.New("physical observer failure") + outcome := func(ctx context.Context) error { + if physical { + return errors.Join(injected, ctx.Err()) + } + return fmt.Errorf("ack wait: %w", ctx.Err()) + } + b.SetWriteObserver(batchWriteObserverFunc{writeObserverFunc: writeObserverFunc{observe: func(ctx context.Context, _ uint32, _ uint64, _ []byte) error { return outcome(ctx) }}, observeBatch: func(ctx context.Context, _ uint32, _ []uint64, _ [][]byte) error { return outcome(ctx) }}) + b.SetWriteAckPolicy(durable.WriteAckRequireObserverAck) + ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) + defer cancel() + size := 4096 + if batch { + size *= 2 + } + n, err := b.Write(ctx, 0, make([]byte, size)) + if n != size || !errors.Is(err, durable.ErrReplicationAckUnavailable) { + t.Fatalf("committed error n=%d err=%v", n, err) + } + if physical { + if !errors.Is(err, injected) || errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("physical fault masked: %v", err) + } + } else { + if !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("observer deadline lost retryability: %v", err) + } + } + }) + } + } +} From fedb6c0f37363cee36e022a3b662a3661e611e01 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:22:02 -0800 Subject: [PATCH 061/150] durable: retain retryability when classifying observer deadline failures --- .../core/frontend/durable/storage_adapter.go | 14 ++++++++-- seaweed-block/core/frontend/nvme/io.go | 23 +-------------- seaweed-block/core/frontend/write_budget.go | 28 +++++++++++++++++++ 3 files changed, 41 insertions(+), 24 deletions(-) diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 98a103b5ba..3762626fc4 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -816,7 +816,7 @@ func (b *StorageBackend) writeFullBlockBatch(ctx context.Context, startLBA uint3 log.Printf("durable: replication batch fan-out failed lba=%d blocks=%d: %v", startLBA, len(lsns), obsErr) if policy == WriteAckRequireObserverAck { - return len(lsns) * bs, fmt.Errorf("%w: %w", ErrReplicationAckUnavailable, obsErr) + return len(lsns) * bs, replicationWriteError(ctx, obsErr) } } } else { @@ -868,12 +868,22 @@ func (b *StorageBackend) observeWrite(ctx context.Context, lba uint32, lsn uint6 log.Printf("durable: replication fan-out failed lba=%d lsn=%d: %v", lba, lsn, werr) if policy == WriteAckRequireObserverAck { - return fmt.Errorf("%w: %w", ErrReplicationAckUnavailable, werr) + return replicationWriteError(ctx, werr) } } return nil } +// Classify the observer cause before adding the acknowledgement sentinel; +// otherwise that sentinel would obscure a pure caller deadline at the target. +func replicationWriteError(ctx context.Context, err error) error { + wrapped := fmt.Errorf("%w: %w", ErrReplicationAckUnavailable, err) + if frontend.IsWriteDeadline(ctx, err) { + return fmt.Errorf("%w: %w", frontend.ErrBackendBusy, wrapped) + } + return wrapped +} + // Compile-time check that StorageBackend satisfies frontend.Backend. // Catches interface drift at build time rather than runtime. var _ frontend.Backend = (*StorageBackend)(nil) diff --git a/seaweed-block/core/frontend/nvme/io.go b/seaweed-block/core/frontend/nvme/io.go index cf34a05550..8505b0627e 100644 --- a/seaweed-block/core/frontend/nvme/io.go +++ b/seaweed-block/core/frontend/nvme/io.go @@ -299,32 +299,11 @@ func (h *IOHandler) write(ctx context.Context, cmd IOCommand) IOResult { // Only a pure command-deadline cause is transient. A joined physical error // must retain its terminal mapping even when the command deadline also passed. func mapWriteBudgetError(ctx context.Context, err error, op string) IOResult { - if ctx.Err() == context.DeadlineExceeded && onlyDeadlineCause(err) { + if frontend.IsWriteDeadline(ctx, err) { return IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, retryable: true, Reason: "command deadline on " + op + ": " + err.Error()} } return mapBackendError(err, op) } -func onlyDeadlineCause(err error) bool { - if err == context.DeadlineExceeded { - return true - } - if err == nil { - return false - } - if joined, ok := err.(interface{ Unwrap() []error }); ok { - causes := joined.Unwrap() - if len(causes) == 0 { - return false - } - for _, cause := range causes { - if !onlyDeadlineCause(cause) { - return false - } - } - return true - } - return onlyDeadlineCause(errors.Unwrap(err)) -} // mapBackendError translates frontend errors into NVMe CQE // status tuples. ErrStalePrimary → ANA Transition; diff --git a/seaweed-block/core/frontend/write_budget.go b/seaweed-block/core/frontend/write_budget.go index 2958ea549f..f2c447f5b4 100644 --- a/seaweed-block/core/frontend/write_budget.go +++ b/seaweed-block/core/frontend/write_budget.go @@ -2,6 +2,7 @@ package frontend import ( "context" + "errors" "time" ) @@ -19,3 +20,30 @@ func WithWriteBudget(ctx context.Context, arrival time.Time) (context.Context, c } return context.WithDeadline(ctx, deadline) } + +// IsWriteDeadline recognizes only an expired caller's pure deadline cause. +// Joined physical/unknown errors retain their terminal classification. +func IsWriteDeadline(ctx context.Context, err error) bool { + return ctx.Err() == context.DeadlineExceeded && deadlineCausesOnly(err) +} +func deadlineCausesOnly(err error) bool { + if err == context.DeadlineExceeded { + return true + } + if err == nil { + return false + } + if joined, ok := err.(interface{ Unwrap() []error }); ok { + causes := joined.Unwrap() + if len(causes) == 0 { + return false + } + for _, cause := range causes { + if !deadlineCausesOnly(cause) { + return false + } + } + return true + } + return deadlineCausesOnly(errors.Unwrap(err)) +} From 28f983bb4c1c7aaa093b9e78a74ccf471c68bb89 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:25:50 -0800 Subject: [PATCH 062/150] storage, sw-block: prove locally that no process holds a volume ProbeVolumeUnheld takes and releases the exclusive, nonblocking advisory lock that every v3 owner holds while its store is open; the kernel drops it when the owner process exits. nil means no process on this host holds the volume; ErrVolumeHeld means one does; anything else is unknown (a non-v3 file is refused: its owner would not take the lock). `sw-block ops volume-unheld --path P` exits 0 only when unheld (1 held, 2 unknown). The proof is per host and for local filesystems only; host cleanup must also check that the owner process is gone. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/main.go | 5 +- seaweed-block/cmd/sw-block/volume_unheld.go | 50 ++++++ .../cmd/sw-block/volume_unheld_test.go | 56 +++++++ seaweed-block/core/storage/volume_unheld.go | 44 ++++++ .../core/storage/volume_unheld_test.go | 147 ++++++++++++++++++ 5 files changed, 301 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/cmd/sw-block/volume_unheld.go create mode 100644 seaweed-block/cmd/sw-block/volume_unheld_test.go create mode 100644 seaweed-block/core/storage/volume_unheld.go create mode 100644 seaweed-block/core/storage/volume_unheld_test.go diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index a0015447bb..249ead1fac 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -86,7 +86,7 @@ func run(args []string, stdout, stderr io.Writer) int { return ops.VolumeStatusExitInvalid } if len(args) < 2 { - fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk") + fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk|volume-unheld") usage(stderr) return ops.VolumeStatusExitInvalid } @@ -129,6 +129,8 @@ func run(args []string, stdout, stderr io.Writer) int { return runOpsFrontendPublicationExecutor(args[2:], stdout, stderr) case "chunk": return runOpsChunk(args[2:], stdout, stderr) + case "volume-unheld": + return runOpsVolumeUnheld(args[2:], stdout, stderr) default: fmt.Fprintf(stderr, "sw-block: unknown ops subcommand %q\n", args[1]) usage(stderr) @@ -2296,6 +2298,7 @@ func usage(w io.Writer) { fmt.Fprintln(w, " sw-block ops chunk fork --chunk-filer [--chunk-path /swblock/chunks] --source --snapshot --target [--request-id ] [--label k=v]...") fmt.Fprintln(w, " sw-block ops chunk show --volume --chunk-filer [--chunk-path /swblock/chunks]") fmt.Fprintln(w, " sw-block ops chunk gc --chunk-filer --master [--chunk-path /swblock/chunks] [--apply] [--grace 1h] [--intent-ttl 1h] [--timeout 1m]") + fmt.Fprintln(w, " sw-block ops volume-unheld --path (exit 0: no process on this host holds it; local filesystems only)") } func emptyCLI(value string) string { diff --git a/seaweed-block/cmd/sw-block/volume_unheld.go b/seaweed-block/cmd/sw-block/volume_unheld.go new file mode 100644 index 0000000000..8d72c84b1f --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_unheld.go @@ -0,0 +1,50 @@ +package main + +import ( + "errors" + "flag" + "fmt" + "io" + + "github.com/seaweedfs/seaweed-block/core/ops" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const volumeUnheldUsage = `usage: sw-block ops volume-unheld --path + +Exit 0 only when no process on THIS host holds the v3 volume file's lock +(the lock every v3 owner holds while its store is open; the kernel releases +it when the owner process exits). Exit 1: held. Exit 2: unknown (missing +file, not a v3 volume, lock error) or bad usage. + +This proof is per host and for local filesystems only. It says nothing about +another host, and nothing on a network or shared mount. It does not prove the +owner process is dead: host cleanup must require BOTH this command's exit 0 +AND the host tooling's own check that the recorded owner process is gone. +` + +// runOpsVolumeUnheld is `sw-block ops volume-unheld`. +func runOpsVolumeUnheld(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops volume-unheld", flag.ContinueOnError) + fs.SetOutput(stderr) + fs.Usage = func() { fmt.Fprint(stderr, volumeUnheldUsage) } + path := fs.String("path", "", "the volume file") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if *path == "" || fs.NArg() != 0 { + fmt.Fprint(stderr, volumeUnheldUsage) + return ops.VolumeStatusExitInvalid + } + switch err := storage.ProbeVolumeUnheld(*path); { + case err == nil: + fmt.Fprintf(stdout, "unheld: no process on this host holds %s (local proof only; also check the owner process is gone)\n", *path) + return ops.VolumeStatusExitOK + case errors.Is(err, storage.ErrVolumeHeld): + fmt.Fprintf(stdout, "held: a live process on this host holds %s\n", *path) + return ops.VolumeStatusExitUnhealthy + default: + fmt.Fprintf(stderr, "unknown: %v\n", err) + return ops.VolumeStatusExitInvalid + } +} diff --git a/seaweed-block/cmd/sw-block/volume_unheld_test.go b/seaweed-block/cmd/sw-block/volume_unheld_test.go new file mode 100644 index 0000000000..bedae3cef7 --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_unheld_test.go @@ -0,0 +1,56 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// `sw-block ops volume-unheld` exits 0 only for an unheld v3 volume: 1 while +// a store holds it, 2 for unknown (missing, not v3) and bad usage. The +// usage states the per-host, local-only limit and the second check. +func TestOpsVolumeUnheldExitCodes(t *testing.T) { + path := filepath.Join(t.TempDir(), "v.bin") + s, err := storage.CreateWALStore(path, 64, 4096) + if err != nil { + t.Fatal(err) + } + junk := filepath.Join(t.TempDir(), "junk.bin") + if err := os.WriteFile(junk, make([]byte, 64<<10), 0o644); err != nil { + t.Fatal(err) + } + runIt := func(args ...string) (int, string, string) { + var out, errOut bytes.Buffer + code := run(append([]string{"ops", "volume-unheld"}, args...), &out, &errOut) + return code, out.String(), errOut.String() + } + if code, out, _ := runIt("--path", path); code != 1 || !strings.HasPrefix(out, "held:") { + t.Fatalf("open store: exit %d %q; want 1 held", code, out) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + if code, out, _ := runIt("--path", path); code != 0 || !strings.HasPrefix(out, "unheld:") { + t.Fatalf("closed store: exit %d %q; want 0 unheld", code, out) + } + for name, args := range map[string][]string{ + "missing": {"--path", filepath.Join(t.TempDir(), "missing.bin")}, + "not v3": {"--path", junk}, + "no path": nil, + "extra arg": {"--path", path, "x"}, + } { + if code, out, _ := runIt(args...); code != 2 || strings.HasPrefix(out, "unheld") { + t.Fatalf("%s: exit %d %q; want 2", name, code, out) + } + } + _, _, usage := runIt() + for _, want := range []string{"per host", "local filesystems only", "network or shared mount", "BOTH"} { + if !strings.Contains(usage, want) { + t.Fatalf("usage lacks %q:\n%s", want, usage) + } + } +} diff --git a/seaweed-block/core/storage/volume_unheld.go b/seaweed-block/core/storage/volume_unheld.go new file mode 100644 index 0000000000..c42e74b58e --- /dev/null +++ b/seaweed-block/core/storage/volume_unheld.go @@ -0,0 +1,44 @@ +package storage + +import ( + "errors" + "fmt" + "os" +) + +// ErrVolumeHeld: a live process on this host holds the volume file's lock. +var ErrVolumeHeld = errors.New("storage: volume held by a live owner on this host") + +// ProbeVolumeUnheld reports whether no process on THIS host holds the v3 +// volume file at path. It takes and releases the exclusive, nonblocking +// advisory lock that every v3 owner holds for as long as its store is open; +// the kernel releases that lock when the owner's process exits. +// +// nil: unheld. ErrVolumeHeld: held. Any other error: unknown (missing file, +// not a v3 volume, the lock call failed); treat it as not proven. +// +// The proof is per host and for local filesystems only: it says nothing +// about a process on another host, and nothing on a network or shared mount, +// where advisory lock semantics vary. It is not proof the owner process is +// dead; host cleanup must check that separately. The probe holds the lock +// only for an instant, but an owner opening the volume in that instant is +// refused with ErrWALStoreLocked: probe only when the owner is believed gone. +func ProbeVolumeUnheld(path string) error { + // Only a v3 owner takes the lock; for any other file a free lock proves + // nothing. + if err := ProbeWALStoreV3(path); err != nil { + return fmt.Errorf("storage: %s is not a v3 volume, unheld cannot be proven: %w", path, err) + } + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() // closing releases the probe's lock + switch err := LockWALStoreFile(f); { + case errors.Is(err, ErrWALStoreLocked): + return ErrVolumeHeld + case err != nil: + return err + } + return nil +} diff --git a/seaweed-block/core/storage/volume_unheld_test.go b/seaweed-block/core/storage/volume_unheld_test.go new file mode 100644 index 0000000000..97fcee13aa --- /dev/null +++ b/seaweed-block/core/storage/volume_unheld_test.go @@ -0,0 +1,147 @@ +package storage + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +func createClosedV3Volume(t *testing.T) string { + t.Helper() + path := filepath.Join(t.TempDir(), "v.bin") + s, err := CreateWALStore(path, 64, 4096) + if err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + return path +} + +// A closed v3 volume is unheld, and the probe leaves it openable (it +// released its own lock). +func TestProbeVolumeUnheldClosedVolume(t *testing.T) { + path := createClosedV3Volume(t) + if err := ProbeVolumeUnheld(path); err != nil { + t.Fatalf("closed volume: %v; want unheld", err) + } + s, err := OpenWALStore(path) + if err != nil { + t.Fatalf("open after the probe: %v", err) + } + _ = s.Close() +} + +// An open store holds the volume: the probe says held (also from another +// descriptor in the same process), and unheld once the store is closed. +func TestProbeVolumeUnheldOpenStoreIsHeld(t *testing.T) { + path := createClosedV3Volume(t) + s, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + if err := ProbeVolumeUnheld(path); !errors.Is(err, ErrVolumeHeld) { + _ = s.Close() + t.Fatalf("open store: %v; want ErrVolumeHeld", err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + if err := ProbeVolumeUnheld(path); err != nil { + t.Fatalf("after close: %v; want unheld", err) + } +} + +// Unknown is neither unheld nor held: a missing file and a file that is not +// a v3 volume (its owner would not take the lock). +func TestProbeVolumeUnheldUnknown(t *testing.T) { + missing := filepath.Join(t.TempDir(), "missing.bin") + junk := filepath.Join(t.TempDir(), "junk.bin") + if err := os.WriteFile(junk, make([]byte, 64<<10), 0o644); err != nil { + t.Fatal(err) + } + for name, path := range map[string]string{"missing": missing, "not v3": junk} { + if err := ProbeVolumeUnheld(path); err == nil || errors.Is(err, ErrVolumeHeld) { + t.Fatalf("%s: %v; want an unknown (non-nil, not held) result", name, err) + } + } +} + +const unheldHelperEnv = "SWBLOCK_UNHELD_HELPER_PATH" + +// TestProbeVolumeUnheldHelper is the holder process of the test below: it +// opens the store, says so, and waits to be killed. +func TestProbeVolumeUnheldHelper(t *testing.T) { + path := os.Getenv(unheldHelperEnv) + if path == "" { + t.Skip("helper process only") + } + s, err := OpenWALStore(path) + if err != nil { + os.Stdout.WriteString("OPEN-FAILED " + err.Error() + "\n") + os.Exit(3) + } + defer s.Close() + os.Stdout.WriteString("HOLDING\n") + time.Sleep(time.Minute) + os.Exit(4) +} + +// The property cleanup relies on: a volume held by another process is held, +// and becomes unheld when that process dies without closing it (the kernel +// releases the lock). +func TestProbeVolumeUnheldHolderProcessDies(t *testing.T) { + path := createClosedV3Volume(t) + cmd := exec.Command(os.Args[0], "-test.run=^TestProbeVolumeUnheldHelper$", "-test.count=1") + cmd.Env = append(os.Environ(), unheldHelperEnv+"="+path) + out, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + exited := make(chan struct{}) + t.Cleanup(func() { // kill and reap the holder, bounded + _ = cmd.Process.Kill() + select { + case <-exited: + case <-time.After(10 * time.Second): + t.Error("holder process not reaped") + } + }) + ready := make(chan string, 1) + go func() { + buf := make([]byte, 256) + n, _ := out.Read(buf) + ready <- string(buf[:n]) + }() + select { + case line := <-ready: + if !strings.Contains(line, "HOLDING") { + t.Fatalf("holder: %q", line) + } + case <-time.After(30 * time.Second): + t.Fatal("holder never opened the volume") + } + if err := ProbeVolumeUnheld(path); !errors.Is(err, ErrVolumeHeld) { + t.Fatalf("held by a live process: %v; want ErrVolumeHeld", err) + } + go func() { _ = cmd.Wait(); close(exited) }() + if err := cmd.Process.Kill(); err != nil { + t.Fatal(err) + } + select { + case <-exited: + case <-time.After(10 * time.Second): + t.Fatal("holder did not exit after kill") + } + if err := ProbeVolumeUnheld(path); err != nil { + t.Fatalf("after the holder died: %v; want unheld", err) + } +} From 2d6d97112ad675f7a4c80b67e0b65acf97d851c8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:27:05 -0800 Subject: [PATCH 063/150] docs: record observer deadline classification and I/O ownership coverage --- 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 8e23e36e26..0d394ff0f2 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -332,7 +332,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-RECORD-001` | An impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | | `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB | -| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. One earliest command deadline spans adapter batches and bounded store admission locks/snapshots; expiry before append preserves the WAL/nextLSN/dirty state. Already-started I/O is joined. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire`; `write_command_budget.go`; `StorageBackend.Write`; NVMe `handleWrite` | `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestSessionWriteBudgetIncludesDispatchQueue`, `TestWALStoreV3WriteBudgetBoundsAppendLockWait`, `TestWALStoreV3WriteBudgetBoundsPressureLocks`, `TestWALStoreV3WritePressureSampleMatchesOccupancy`, `TestStorageBackendExpiredWriteDoesNotAppend`; `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | +| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. One earliest command deadline spans adapter batches and bounded store admission locks/snapshots; expiry before append preserves the WAL/nextLSN/dirty state. Issued WAL I/O retains its existing lifecycle ownership. Pure caller expiry stays retryable through required-observer classification and NVMe; a provided physical cause remains terminal. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire`; `write_command_budget.go`; `StorageBackend.Write`; NVMe `handleWrite` | `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestSessionWriteBudgetIncludesDispatchQueue`, `TestWALStoreV3WriteBudgetBoundsAppendLockWait`, `TestWALStoreV3WriteBudgetBoundsPressureLocks`, `TestWALStoreV3WritePressureSampleMatchesOccupancy`, `TestStorageBackendExpiredWriteDoesNotAppend`, `TestStorageBackendRequiredObserverDeadlineStaysRetryable`; `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | | `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint releases only complete validated record ends covered by the checkpoint and outside the retention window; an installing BASE retains its install suffix. Physical recovery rebuilds the volatile boundary index only from the trusted kept scan, without restoring a disconnect cursor. Tail/head/map/checkpoint/W publish together, followed by metadata-only rollover; both slot tails still pin reuse. Failure grants no reuse and retains exact dirty retry identity. Checkpoint publication excludes writer admission through both-slot rollover and dirty-reference retirement. Idle, unchanged-checkpoint and admission settle pending rollover; catch-up revalidates tail/checkpoint before delivering its buffered scan. | M1 checkpoint / existing two-slot retirement | `wal_io_v3.go` `reclaimThroughV3`, `rememberReclaimScanV3`; `walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `descriptor_v3.go` `rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse`, `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint`, tagged `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB | | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | From 97d9746a8c9dd5965e42da59c91f42aad9f318b7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:29:58 -0800 Subject: [PATCH 064/150] authority: keep the lost range beside the move record, not in it Fold of the #255 review: a field in the record changed its checksummed body, so a binary that predates it skipped the whole record and reloaded the volume unbound. The record body is now unchanged. The forced move's lost range (kept HEAD frontier, forced barrier) goes to a per-volume side file that authority loaders never read, written atomically before the move record; an entry without a matching issued move is ignored. A failed range write refuses the move. The admission keeps its two original predicates; the audit bound is computed separately. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/authority.go | 10 + seaweed-block/core/authority/workspace.go | 28 +-- .../core/authority/workspace_lost_range.go | 194 ++++++++++++++++++ .../authority/workspace_lost_range_test.go | 176 +++++++++++----- 4 files changed, 342 insertions(+), 66 deletions(-) create mode 100644 seaweed-block/core/authority/workspace_lost_range.go diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 7cf968bcd9..321165423b 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -158,6 +158,7 @@ type Publisher struct { // Workspace state is serialized with assignment minting under mu. Remote // HEAD reads and subscriber delivery never run under this lock. workspace map[string]*WorkspaceState + lostRanges map[string][]WorkspaceLostRange // forced moves' abandoned ranges (side files) workspaceUncertain map[string]bool workspaceNow func() time.Time workspaceTTL time.Duration @@ -234,6 +235,7 @@ func NewPublisher(dir Directive, opts ...PublisherOption) *Publisher { subs: make(map[subKey][]*subscription), writeSeqByVolume: map[string]uint64{}, workspace: map[string]*WorkspaceState{}, + lostRanges: map[string][]WorkspaceLostRange{}, workspaceUncertain: map[string]bool{}, workspaceNow: time.Now, workspaceTTL: 30 * time.Second, @@ -283,6 +285,14 @@ func (p *Publisher) reloadFromStore() { } } p.loadErrs = append(p.loadErrs, skips...) + if ls, ok := p.store.(WorkspaceLostRangeStore); ok { + ranges, lskips, lerr := ls.LoadWorkspaceLostRanges() + if lerr != nil { + panic(fmt.Sprintf("authority: lost range load failure: %v", lerr)) + } + p.lostRanges = ranges + p.loadErrs = append(p.loadErrs, lskips...) + } for _, rec := range records { p.refreshLeaseViewLocked(rec.VolumeID) if rec.Workspace != nil { diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index d28bfc7a5d..ce4342dcb7 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -34,12 +34,6 @@ type WorkspaceMoveRecord struct { TargetDataAddr, TargetCtrlAddr string OldEpoch, NewEpoch, HeadGen, RemoteLSN uint64 Issued bool - // LostUntilNS, set only for Kind "forced", records the abandoned range: - // the old holder's writes after RemoteLSN (the HEAD frontier the move - // keeps) are lost, and none of them was acknowledged later than this - // master time (the forced barrier: the lease horizon plus skew). The - // lease carries no write frontier, so the upper bound is a time. - LostUntilNS int64 `json:",omitempty"` } type WorkspaceState struct { @@ -290,14 +284,16 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra if q.Kind == "forced" { now := p.workspaceNow() skew := p.workspaceSkew(s.Lease) - barrier := time.Unix(0, s.Lease.ExpiresAtNS).Add(skew) - if d := p.leaseDeadlineLocked(q.VolumeID).Add(skew); d.After(barrier) { - barrier = d - } - if now.Before(barrier) { + deadline := p.leaseDeadlineLocked(q.VolumeID) + if now.Before(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) { return nil, 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") } - lostUntil = barrier.UnixNano() + // The audit bound only, in wall time: the admission above keeps both + // predicates (the deadline's monotonic reading included). + lostUntil = time.Unix(0, s.Lease.ExpiresAtNS).Add(skew).UnixNano() + if d := deadline.Add(skew).UnixNano(); d > lostUntil { + lostUntil = d + } } // A restart may resume the identical durable reservation; it never grants // a different request the reserved epoch. @@ -330,7 +326,13 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra return nil, 0, fmt.Errorf("workspace epoch exhausted") } r := WorkspaceMoveRecord{RequestID: q.RequestID, VolumeID: q.VolumeID, OldHost: q.ExpectedHost, NewHost: q.TargetHost, OldReplicaID: q.ExpectedReplicaID, NewReplicaID: q.TargetReplicaID, Kind: q.Kind, - OldEpoch: q.ExpectedEpoch, NewEpoch: max + 1, HeadGen: h.Gen, RemoteLSN: h.RemoteLSN, TargetDataAddr: q.TargetDataAddr, TargetCtrlAddr: q.TargetCtrlAddr, LostUntilNS: lostUntil} + OldEpoch: q.ExpectedEpoch, NewEpoch: max + 1, HeadGen: h.Gen, RemoteLSN: h.RemoteLSN, TargetDataAddr: q.TargetDataAddr, TargetCtrlAddr: q.TargetCtrlAddr} + if q.Kind == "forced" { + lost := WorkspaceLostRange{RequestID: r.RequestID, NewEpoch: r.NewEpoch, OldReplicaID: r.OldReplicaID, OldEpoch: r.OldEpoch, LostAfterLSN: r.RemoteLSN, LostUntilNS: lostUntil} + if err := p.recordLostRangeLocked(q.VolumeID, lost); err != nil { + return nil, 0, err + } + } s.Moves = append(s.Moves, r) if err := p.persistWorkspaceLocked(q.VolumeID, s); err != nil { return nil, 0, err diff --git a/seaweed-block/core/authority/workspace_lost_range.go b/seaweed-block/core/authority/workspace_lost_range.go new file mode 100644 index 0000000000..dab767f3fd --- /dev/null +++ b/seaweed-block/core/authority/workspace_lost_range.go @@ -0,0 +1,194 @@ +package authority + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" +) + +// WorkspaceLostRange records what a forced move abandoned: the old holder's +// writes after LostAfterLSN (the HEAD frontier the move keeps) are lost, and +// none of them was acknowledged later than LostUntilNS (master time: the +// forced barrier, the lease horizon or restart deadline plus skew). The +// lease carries no write frontier, so the upper bound is a time. +type WorkspaceLostRange struct { + RequestID string + NewEpoch uint64 + OldReplicaID string + OldEpoch uint64 + LostAfterLSN uint64 + LostUntilNS int64 +} + +// WorkspaceLostRangeStore is an optional AuthorityStore capability. The +// ranges live beside the authority record, never in it, so the record body +// and its checksum stay readable by binaries that predate them (those load +// only *.v3auth.json). A store without it records no lost range. +type WorkspaceLostRangeStore interface { + PutWorkspaceLostRanges(volumeID string, ranges []WorkspaceLostRange) error + LoadWorkspaceLostRanges() (map[string][]WorkspaceLostRange, []error, error) +} + +// lostRangeFileExtension does not end in storeFileExtension: authority +// loaders, old and new, never read these files. +const lostRangeFileExtension = ".lostrange.json" + +type lostRangeEnvelope struct { + Version int `json:"v"` + VolumeID string `json:"volume"` + Ranges []WorkspaceLostRange `json:"ranges"` + Checksum string `json:"checksum"` +} + +func lostRangeChecksum(volumeID string, ranges []WorkspaceLostRange) string { + body, err := json.Marshal(struct { + VolumeID string + Ranges []WorkspaceLostRange + }{volumeID, ranges}) + if err != nil { + return "" + } + sum := sha256.Sum256(body) + return hex.EncodeToString(sum[:]) +} + +// PutWorkspaceLostRanges replaces volumeID's lost ranges atomically (temp +// file, fsync, rename, directory fsync). +func (s *FileAuthorityStore) PutWorkspaceLostRanges(volumeID string, ranges []WorkspaceLostRange) error { + if volumeID == "" { + return fmt.Errorf("authority_store: lost range with empty VolumeID") + } + payload, err := json.Marshal(lostRangeEnvelope{Version: 1, VolumeID: volumeID, Ranges: ranges, Checksum: lostRangeChecksum(volumeID, ranges)}) + if err != nil { + return fmt.Errorf("authority_store: encode lost range: %w", err) + } + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return fmt.Errorf("authority_store: lost range Put on closed store") + } + final := filepath.Join(s.dir, encodeVolumeIDForFilename(volumeID)+lostRangeFileExtension) + temp := final + tempSuffix + f, err := os.OpenFile(temp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) + if err != nil { + return fmt.Errorf("authority_store: open lost range temp: %w", err) + } + _, werr := f.Write(payload) + if werr == nil { + werr = f.Sync() + } + if cerr := f.Close(); werr == nil { + werr = cerr + } + if werr != nil { + _ = os.Remove(temp) + return fmt.Errorf("authority_store: write lost range temp: %w", werr) + } + if err := renameWithRetry(temp, final); err != nil { + _ = os.Remove(temp) + return fmt.Errorf("authority_store: rename lost range: %w", err) + } + d, err := os.Open(s.dir) + if err != nil { + return fmt.Errorf("authority_store: lost range directory open: %w", err) + } + serr := d.Sync() + if cerr := d.Close(); serr == nil { + serr = cerr + } + if serr != nil { + return fmt.Errorf("authority_store: lost range directory fsync: %w", serr) + } + return nil +} + +// LoadWorkspaceLostRanges returns every volume's lost ranges. A file that +// fails its checks is skipped with an error (these are records of loss, not +// authority); only an unreadable directory fails the load. +func (s *FileAuthorityStore) LoadWorkspaceLostRanges() (map[string][]WorkspaceLostRange, []error, error) { + s.mu.Lock() + defer s.mu.Unlock() + entries, err := os.ReadDir(s.dir) + if err != nil { + return nil, nil, fmt.Errorf("authority_store: readdir: %w", err) + } + out := map[string][]WorkspaceLostRange{} + var skips []error + for _, e := range entries { + name := e.Name() + if e.IsDir() || !strings.HasSuffix(name, lostRangeFileExtension) { + continue + } + raw, err := os.ReadFile(filepath.Join(s.dir, name)) + if err != nil { + skips = append(skips, fmt.Errorf("%s: read: %w", name, err)) + continue + } + var env lostRangeEnvelope + switch { + case json.Unmarshal(raw, &env) != nil: + err = errors.New("decode") + case env.Version != 1: + err = fmt.Errorf("version %d unsupported", env.Version) + case env.Checksum != lostRangeChecksum(env.VolumeID, env.Ranges): + err = errors.New("checksum mismatch") + case encodeVolumeIDForFilename(env.VolumeID)+lostRangeFileExtension != name: + err = fmt.Errorf("filename does not match VolumeID %q", env.VolumeID) + } + if err != nil { + skips = append(skips, fmt.Errorf("%s: %w: lost range %v", name, ErrCorruptRecord, err)) + continue + } + out[env.VolumeID] = env.Ranges + } + return out, skips, nil +} + +// recordLostRangeLocked durably records r for volume before the move record +// that issues it is written; a store without the capability records nothing. +// An entry whose move never issues is an orphan, ignored on read. Called +// under p.mu. +func (p *Publisher) recordLostRangeLocked(volume string, r WorkspaceLostRange) error { + ls, ok := p.store.(WorkspaceLostRangeStore) + if !ok { + return nil + } + next := make([]WorkspaceLostRange, 0, len(p.lostRanges[volume])+1) + for _, e := range p.lostRanges[volume] { + if e.RequestID != r.RequestID || e.NewEpoch != r.NewEpoch { + next = append(next, e) + } + } + next = append(next, r) + if err := ls.PutWorkspaceLostRanges(volume, next); err != nil { + return fmt.Errorf("workspace forced move: record lost range: %w", err) + } + p.lostRanges[volume] = next + return nil +} + +// WorkspaceLostRanges returns the lost ranges of volume's issued forced +// moves (an entry with no matching issued move is ignored). +func (p *Publisher) WorkspaceLostRanges(volume string) []WorkspaceLostRange { + p.mu.Lock() + defer p.mu.Unlock() + s := p.workspace[volume] + if s == nil { + return nil + } + var out []WorkspaceLostRange + for _, e := range p.lostRanges[volume] { + for _, m := range s.Moves { + if m.Issued && m.Kind == "forced" && m.RequestID == e.RequestID && m.NewEpoch == e.NewEpoch { + out = append(out, e) + break + } + } + } + return out +} diff --git a/seaweed-block/core/authority/workspace_lost_range_test.go b/seaweed-block/core/authority/workspace_lost_range_test.go index dafd2685b9..096f6f5141 100644 --- a/seaweed-block/core/authority/workspace_lost_range_test.go +++ b/seaweed-block/core/authority/workspace_lost_range_test.go @@ -3,30 +3,21 @@ package authority import ( "context" "encoding/json" + "errors" + "os" + "path/filepath" "strings" "testing" "time" ) -// A forced move records the abandoned range: the kept HEAD frontier -// (RemoteLSN) and the forced barrier (lease horizon plus skew) as the -// latest master time an old-holder write can have been acknowledged. The -// record is journaled: a reload returns the same bound. -// -// After a restart the conservative restart deadline, not the lease horizon, -// is the later term of the barrier. -func TestWorkspaceForcedMoveRecordsTheLostRange(t *testing.T) { - for _, restart := range []bool{false, true} { - t.Run(map[bool]string{false: "running", true: "after restart"}[restart], func(t *testing.T) { forcedLostRange(t, restart) }) - } -} - -func forcedLostRange(t *testing.T, restart bool) { +func forcedLostRangeFixture(t *testing.T, store AuthorityStore, restart bool) (p *Publisher, now *time.Time, barrier time.Time) { + t.Helper() ctx := context.Background() - disk, _ := newTempStore(t) - now := time.Unix(1000, 0) - clock := func() time.Time { return now } - p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, clock)) + at := time.Unix(1000, 0) + now = &at + clock := func() time.Time { return *now } + p = NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(time.Second, clock)) if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "old", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { t.Fatal(err) } @@ -34,44 +25,69 @@ func forcedLostRange(t *testing.T, restart bool) { t.Fatal(err) } if restart { - now = now.Add(time.Second) - p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, clock)) + *now = now.Add(time.Second) + p = NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(time.Second, clock)) } lease := p.WorkspaceState("v").Lease if restart && !p.leaseDeadlineLockedForTest("v").After(time.Unix(0, lease.ExpiresAtNS)) { t.Fatal("fixture: the restart deadline is not the later barrier term") } - barrier := time.Unix(0, lease.ExpiresAtNS) + barrier = time.Unix(0, lease.ExpiresAtNS) if d := p.leaseDeadlineLockedForTest("v"); d.After(barrier) { barrier = d } - barrier = barrier.Add(p.workspaceSkew(lease)) - req := WorkspaceMoveRequest{RequestID: "f", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, - TargetReplicaID: "old", TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} - head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42} - now = barrier.Add(-time.Nanosecond) - if _, err := p.MoveWorkspace(ctx, req, head); err == nil { - t.Fatal("forced move admitted before its barrier") - } - now = barrier.Add(5 * time.Second) // the bound is the barrier, not the time of the move - r, err := p.MoveWorkspace(ctx, req, head) - if err != nil { - t.Fatal(err) - } - if r.Kind != "forced" || r.RemoteLSN != 42 || r.LostUntilNS != barrier.UnixNano() { - t.Fatalf("forced record RemoteLSN=%d LostUntilNS=%d; want 42 and the barrier %d", r.RemoteLSN, r.LostUntilNS, barrier.UnixNano()) - } - reloaded := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, clock)).WorkspaceState("v") - if reloaded == nil || len(reloaded.Moves) != 1 || reloaded.Moves[0].LostUntilNS != barrier.UnixNano() || reloaded.Moves[0].RemoteLSN != 42 { - t.Fatalf("reloaded record lost the range: %+v", reloaded) + return p, now, barrier.Add(p.workspaceSkew(lease)) +} + +var forcedLostRangeReq = WorkspaceMoveRequest{RequestID: "f", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, + TargetReplicaID: "old", TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} +var forcedLostRangeHead = WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42} + +// A forced move records the abandoned range beside its record: the kept HEAD +// frontier and the forced barrier (lease horizon, or after a restart the +// later restart deadline, plus skew) as the latest master time an old-holder +// write can have been acknowledged. A reload returns it; the move record's +// own encoding is unchanged, so older binaries still verify and load it. +func TestWorkspaceForcedMoveRecordsTheLostRange(t *testing.T) { + for _, restart := range []bool{false, true} { + t.Run(map[bool]string{false: "running", true: "after restart"}[restart], func(t *testing.T) { + disk, _ := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, restart) + *now = barrier.Add(-time.Nanosecond) + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err == nil { + t.Fatal("forced move admitted before its barrier") + } + if got := p.WorkspaceLostRanges("v"); len(got) != 0 { + t.Fatalf("a refused move recorded a lost range: %+v", got) + } + *now = barrier.Add(5 * time.Second) // the bound is the barrier, not the time of the move + r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead) + if err != nil { + t.Fatal(err) + } + want := WorkspaceLostRange{RequestID: "f", NewEpoch: r.NewEpoch, OldReplicaID: "old", OldEpoch: 1, LostAfterLSN: 42, LostUntilNS: barrier.UnixNano()} + if got := p.WorkspaceLostRanges("v"); len(got) != 1 || got[0] != want { + t.Fatalf("lost range %+v; want [%+v]", got, want) + } + reloaded := NewPublisher(nil, WithStore(disk)) + if got := reloaded.WorkspaceLostRanges("v"); len(got) != 1 || got[0] != want { + t.Fatalf("reloaded lost range %+v; want [%+v]", got, want) + } + raw, err := json.Marshal(reloaded.WorkspaceState("v").Moves[0]) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(raw), "Lost") { + t.Fatalf("the move record's encoding changed: %s", raw) + } + }) } } -// A clean move abandons nothing: its record has no lost-range bound, and -// its persisted encoding is unchanged (no LostUntilNS key). +// A clean move abandons nothing and records no lost range. func TestWorkspaceCleanMoveRecordsNoLostRange(t *testing.T) { ctx := context.Background() - disk, _ := newTempStore(t) + disk, dir := newTempStore(t) p := NewPublisher(nil, WithStore(disk)) if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "old", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { t.Fatal(err) @@ -90,18 +106,72 @@ func TestWorkspaceCleanMoveRecordsNoLostRange(t *testing.T) { } req := WorkspaceMoveRequest{RequestID: "c", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetReplicaID: "old", TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"} - r, err := p.MoveWorkspace(ctx, req, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42, Detached: true}) - if err != nil { + if _, err := p.MoveWorkspace(ctx, req, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42, Detached: true}); err != nil { t.Fatal(err) } - if r.LostUntilNS != 0 { - t.Fatalf("clean record LostUntilNS=%d; want none", r.LostUntilNS) + if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 0 { + t.Fatalf("clean move recorded a lost range: %+v", got) } - raw, err := json.Marshal(NewPublisher(nil, WithStore(disk)).WorkspaceState("v").Moves[0]) - if err != nil { - t.Fatal(err) - } - if strings.Contains(string(raw), "LostUntilNS") { - t.Fatalf("clean record encoding changed: %s", raw) + if m, _ := filepath.Glob(filepath.Join(dir, "*"+lostRangeFileExtension)); len(m) != 0 { + t.Fatalf("clean move wrote a lost range file: %v", m) } } + +// lostRangeFaultStore is the file store with injectable failures. +type lostRangeFaultStore struct { + *FileAuthorityStore + failPut, failLostRange bool +} + +var errInjected = errors.New("injected store failure") + +func (s *lostRangeFaultStore) Put(r DurableRecord) error { + if s.failPut && r.Workspace != nil && len(r.Workspace.Moves) > 0 { + return errInjected + } + return s.FileAuthorityStore.Put(r) +} + +func (s *lostRangeFaultStore) PutWorkspaceLostRanges(v string, rs []WorkspaceLostRange) error { + if s.failLostRange { + return errInjected + } + return s.FileAuthorityStore.PutWorkspaceLostRanges(v, rs) +} + +// The lost range is written before the move record: a failed range write +// refuses the move (no epoch issued); a range whose move record then fails +// is an orphan, on disk but never reported. +func TestWorkspaceForcedMoveLostRangeOrdering(t *testing.T) { + t.Run("range write fails", func(t *testing.T) { + disk, _ := newTempStore(t) + store := &lostRangeFaultStore{FileAuthorityStore: disk, failLostRange: true} + p, now, barrier := forcedLostRangeFixture(t, store, false) + *now = barrier.Add(time.Second) + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); !errors.Is(err, errInjected) { + t.Fatalf("move with a failed range write: %v; want refused", err) + } + if line, _ := NewPublisher(nil, WithStore(disk)).VolumeAuthorityLine("v"); line.Epoch != 1 { + t.Fatalf("epoch issued without its lost range: %+v", line) + } + }) + t.Run("move record fails", func(t *testing.T) { + disk, dir := newTempStore(t) + store := &lostRangeFaultStore{FileAuthorityStore: disk, failPut: true} + p, now, barrier := forcedLostRangeFixture(t, store, false) + *now = barrier.Add(time.Second) + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err == nil { + t.Fatal("move issued although its record failed") + } + raw, err := os.ReadFile(filepath.Join(dir, "v"+lostRangeFileExtension)) + if err != nil || !strings.Contains(string(raw), `"RequestID":"f"`) { + t.Fatalf("fixture: no orphan range on disk: %v %s", err, raw) + } + if got := p.WorkspaceLostRanges("v"); len(got) != 0 { + t.Fatalf("orphan reported: %+v", got) + } + if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 0 { + t.Fatalf("orphan reported after reload: %+v", got) + } + }) +} From 65f661ca44dace0d6ef9df937724b9efb47450ea Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:41:04 -0800 Subject: [PATCH 065/150] test(chunkstore): exercise persisted legacy upgrade callers --- .../chunkstore/format_legacy_upgrade_test.go | 213 ++++++++++++++++++ .../testdata/pre_f4_fork_false.json | 1 + .../chunkstore/testdata/pre_f4_fork_true.json | 1 + 3 files changed, 215 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_false.json create mode 100644 seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_true.json diff --git a/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go b/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go new file mode 100644 index 0000000000..3660fa43ee --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go @@ -0,0 +1,213 @@ +package chunkstore + +import ( + "bytes" + "context" + "encoding/json" + "os" + "path" + "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" +) + +// Frozen output of the pre-format-3 CreateSnapshot/Fork producers at 3401cc60. +func preF4ForkFixture(t *testing.T, segmented bool) (*fakeFiler, *Catalog, *ChunkRemote) { + t.Helper() + suffix := "false" + if segmented { + suffix = "true" + } + data, err := os.ReadFile("testdata/pre_f4_fork_" + suffix + ".json") + if err != nil { + t.Fatal(err) + } + var frozen struct { + Entries map[string]*filerpb.Entry + Objects map[string][]byte + } + if err := json.Unmarshal(data, &frozen); err != nil { + t.Fatal(err) + } + f, b := newFakeFiler(), newFakeBlobs() + f.entries = frozen.Entries + c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) + if err != nil { + t.Fatal(err) + } + c.now = func() time.Time { return time.Unix(1000, 0) } + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + if err := r.Put(context.Background(), "legacy-data", bytes.Repeat([]byte{0x41}, 8*4096)); err != nil { + t.Fatal(err) + } + for key, body := range frozen.Objects { + if err := r.Put(context.Background(), key, body); err != nil { + t.Fatal(err) + } + } + return f, c, r +} +func assertLegacyImage(t *testing.T, r *ChunkRemote) { + t.Helper() + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if h.RemoteLSN != 7 || len(h.Chunks) != 1 { + t.Fatalf("legacy image/frontier lost: %+v", h) + } + data, err := r.Get(context.Background(), h.Chunks[0].Key) + if err != nil || !bytes.Equal(data, bytes.Repeat([]byte{0x41}, 8*4096)) { + t.Fatalf("legacy bytes changed: %v", err) + } +} +func TestFormatUpgradeLegacyIncompleteFork(t *testing.T) { + for _, segmented := range []bool{false, true} { + name := "flat" + if segmented { + name = "segmented" + } + t.Run(name, func(t *testing.T) { + f, c, r := preF4ForkFixture(t, segmented) + _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}) + if err != nil { + t.Fatalf("old incomplete fork retry: %v", err) + } + dst, err := NewChunkRemote(f, r.blobs, path.Join(catBase, "v2")) + if err != nil { + t.Fatal(err) + } + assertLegacyImage(t, dst) + e, err := f.LookupEntry(context.Background(), path.Join(catBase, "v2"), headName) + if err != nil { + t.Fatal(err) + } + var doc struct{ Format int } + if json.Unmarshal(e.Content, &doc) != nil || doc.Format != 3 { + t.Fatal("fork data must be format3") + } + }) + } +} +func TestFormatUpgradeLegacyForkIdentityStillRefusesChangedImage(t *testing.T) { + for _, segmented := range []bool{false, true} { + t.Run(map[bool]string{false: "flat", true: "segmented"}[segmented], func(t *testing.T) { + f, c, _ := preF4ForkFixture(t, segmented) + p := snapPath(t, f, "v1", "s1") + var s snapDoc + if err := json.Unmarshal(f.entries[p].Content, &s); err != nil { + t.Fatal(err) + } + var h map[string]any + if err := json.Unmarshal(s.Head, &h); err != nil { + t.Fatal(err) + } + h["remote_lsn"] = float64(8) + s.Head, _ = json.Marshal(h) + f.entries[p].Content, _ = json.Marshal(s) + if _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}); CodeOf(err) != CodeTargetExists { + t.Fatalf("changed image admitted or identity not reached: %v", err) + } + }) + } +} +func TestFormatUpgradeLegacySnapshotAndDelete(t *testing.T) { + t.Run("snapshot", func(t *testing.T) { + f, c, r := preF4ForkFixture(t, false) + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "upgraded", RequestID: "new-snapshot"}, h); err != nil { + t.Fatalf("legacy snapshot: %v", err) + } + e := f.entries[snapPath(t, f, "v1", "upgraded")] + var s snapDoc + if err := json.Unmarshal(e.Content, &s); err != nil { + t.Fatal(err) + } + var doc struct{ Format int } + json.Unmarshal(s.Head, &doc) + if doc.Format != 3 { + t.Fatal("snapshot contains flat data") + } + assertLegacyImage(t, r) + }) + t.Run("delete", func(t *testing.T) { + f, c, r := preF4ForkFixture(t, false) + for p := range f.entries { + if p != path.Join(catBase, "v1", headName) && p != path.Join(catBase, "v1", volumeName) && !bytes.Contains([]byte(p), []byte("/keys/")) { + delete(f.entries, p) + } + } + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + h.Holder = "" + h.Epoch = 0 + f.entries[path.Join(catBase, "v1", headName)] = legacyHeadFixture(t, h) + c.retainHook = func(stage, _ string) { + if stage == hookHeadMarked { + assertLegacyImage(t, r) + e := f.entries[path.Join(catBase, "v1", headName)] + var d struct{ Format int } + json.Unmarshal(e.Content, &d) + if d.Format != 3 { + t.Fatal("delete mark contains flat data") + } + } + } + res, err := c.DeleteVolume(context.Background(), "v1", nil) + if err != nil || !res.Completed { + t.Fatalf("legacy delete: %+v %v", res, err) + } + }) +} + +type legacyUpgradeView struct{} + +func (legacyUpgradeView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, Healthy: true} +} +func TestFormatUpgradeLegacyProviderTakeover(t *testing.T) { + f, _, r := preF4ForkFixture(t, false) + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-new/r1", ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, legacyUpgradeView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatalf("legacy provider takeover: %v", err) + } + h, err := r.GetHead(ctx) + if err != nil || h.Holder != "node-new/r1" || h.Epoch != 2 { + t.Fatalf("takeover not installed: %+v %v", h, err) + } + e := f.entries[path.Join(catBase, "v1", headName)] + var d struct{ Format int } + json.Unmarshal(e.Content, &d) + if d.Format != 3 { + t.Fatal("takeover wrote flat data") + } + for i := uint32(0); i < 8; i++ { + got, err := s.Read(i) + if err != nil || !bytes.Equal(got, bytes.Repeat([]byte{0x41}, 4096)) { + t.Fatalf("takeover bytes %d: %v", i, err) + } + } + assertLegacyImage(t, r) +} diff --git a/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_false.json b/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_false.json new file mode 100644 index 0000000000..a544d45c09 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_false.json @@ -0,0 +1 @@ +{"Entries":{"/swblock/chunks/v1/HEAD":{"name":"HEAD","attributes":{"file_size":190,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.epoch":"MQ==","swb.gen":"Mg==","swb.holder":"b2xk","swb.kind":"Y2h1bmtoZWFk"},"content":"eyJmb3JtYXQiOjEsImdlbiI6MiwiZXBvY2giOjEsImhvbGRlciI6Im9sZCIsInJlbW90ZV9sc24iOjcsImNodW5rcyI6eyIwIjp7ImtleSI6ImxlZ2FjeS1kYXRhIiwic2hhMjU2IjoiNWZmMDc0ZGRhZDg4YjdmY2I0MzM5Y2I3YTNlNjgzNDEwNjE3OTI4NjllNDM2NzNiMmRlODUyNWE3NTQ3NmJkOCJ9fSwic3RhdGUiOiJhY3RpdmUifQ=="},"/swblock/chunks/v1/VOLUME":{"name":"VOLUME","attributes":{"file_size":139,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiY3JlYXRlIiwiY3JlYXRlZF9ucyI6MTAwMDAwMDAwMDAwMCwicGFyZW50IjpudWxsfQ=="},"/swblock/chunks/v1/snapnames/s1":{"name":"s1","attributes":{"file_size":127,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi01NTJjZmRhNGU0YzI3YzA1","swb.kind":"Y2h1bmtzbmFwbmFtZQ==","swb.req":"b2xkLXNuYXBzaG90"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImF0dGVtcHQiOiIyLTU1MmNmZGE0ZTRjMjdjMDUiLCJjcmVhdGVkX25zIjoxMDAwMDAwMDAwMDAwfQ=="},"/swblock/chunks/v1/snaps/s1/2-552cfda4e4c27c05":{"name":"2-552cfda4e4c27c05","attributes":{"file_size":442,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi01NTJjZmRhNGU0YzI3YzA1","swb.kind":"Y2h1bmtzbmFw","swb.req":"b2xkLXNuYXBzaG90","swb.snap.claims":"WyJ2Mi9vbGQtZm9yayJd","swb.snap.epoch":"MQ==","swb.snap.gen":"Mg==","swb.snap.lsn":"Nw==","swb.snap.state":"YWN0aXZl"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsImNyZWF0ZWRfYnkiOiIiLCJjb25zaXN0ZW5jeSI6ImNyYXNoIiwiaGVhZCI6eyJmb3JtYXQiOjEsImdlbiI6MiwiZXBvY2giOjEsImhvbGRlciI6Im9sZCIsInJlbW90ZV9sc24iOjcsImNodW5rcyI6eyIwIjp7ImtleSI6ImxlZ2FjeS1kYXRhIiwic2hhMjU2IjoiNWZmMDc0ZGRhZDg4YjdmY2I0MzM5Y2I3YTNlNjgzNDEwNjE3OTI4NjllNDM2NzNiMmRlODUyNWE3NTQ3NmJkOCJ9fSwic3RhdGUiOiJhY3RpdmUifSwiZ2VvbWV0cnkiOnsibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OH0sInBhcmVudCI6bnVsbCwibGFiZWxzIjpudWxsLCJleHBpcmVzX2F0X25zIjowfQ=="},"/swblock/chunks/v2/VOLUME":{"name":"VOLUME","attributes":{"file_size":384,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU=","swb.req":"b2xkLWZvcms="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYyIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiZm9yayIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsInBhcmVudCI6eyJ2b2x1bWVfaWQiOiJ2MSIsInNuYXBzaG90IjoiczEiLCJnZW4iOjJ9LCJmb3JrIjp7InJlcXVlc3RfaWQiOiJvbGQtZm9yayIsInNvdXJjZSI6InYxIiwic25hcHNob3QiOiJzMSIsInNvdXJjZV9nZW4iOjIsImhlYWRfc2hhMjU2IjoiNGZlZGEwZWY2ZTA1OGRjNzNmYmFlMWUyZWEwOGU3ZTdlMGVjZWE0OTk2NjY0Y2ViYTFjYTNmODA5ZGFiYTk3MiIsInJlbW90ZV9sc24iOjcsImNodW5rX2NvdW50IjoxLCJxdWFsaWZpZWRfcmVmcyI6MX19"}},"Objects":{}} diff --git a/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_true.json b/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_true.json new file mode 100644 index 0000000000..43bcb01966 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_true.json @@ -0,0 +1 @@ +{"Entries":{"/swblock/chunks/v1/HEAD":{"name":"HEAD","attributes":{"file_size":331,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.epoch":"MQ==","swb.gen":"Mg==","swb.holder":"b2xk","swb.kind":"Y2h1bmtoZWFk"},"content":"eyJzZWdtZW50cyI6eyIwIjp7ImtleSI6IkB2MS9zZWcvZTdiM2VkZGUwNTYwYTM3MjQxZTkxMDJkNjA3ZWJjMTQiLCJzaGEyNTYiOls3NSwyMTgsMTMyLDExMywxNTgsMTcxLDQ1LDIxNCwyMjUsMjE5LDEwNywxNzYsMTczLDQ4LDI0MiwxNTMsMTIsMjMwLDExOCwyMjcsOTAsMTQxLDI0Nyw0LDExMSw1Nyw0OSwyMzcsOTQsMTg0LDg0LDk0XSwib3duZXIiOiJ2MSIsImNvdW50IjoxfX0sImNodW5rX2J5dGVzIjozMjc2OCwiY2h1bmtfY291bnQiOjEsImZvcm1hdCI6MiwiZ2VuIjoyLCJlcG9jaCI6MSwiaG9sZGVyIjoib2xkIiwicmVtb3RlX2xzbiI6Nywic3RhdGUiOiJhY3RpdmUifQ=="},"/swblock/chunks/v1/VOLUME":{"name":"VOLUME","attributes":{"file_size":139,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiY3JlYXRlIiwiY3JlYXRlZF9ucyI6MTAwMDAwMDAwMDAwMCwicGFyZW50IjpudWxsfQ=="},"/swblock/chunks/v1/snapnames/s1":{"name":"s1","attributes":{"file_size":127,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi03ZDc0ZTg5MWU0MTZhMmI5","swb.kind":"Y2h1bmtzbmFwbmFtZQ==","swb.req":"b2xkLXNuYXBzaG90"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImF0dGVtcHQiOiIyLTdkNzRlODkxZTQxNmEyYjkiLCJjcmVhdGVkX25zIjoxMDAwMDAwMDAwMDAwfQ=="},"/swblock/chunks/v1/snaps/s1/2-7d74e891e416a2b9":{"name":"2-7d74e891e416a2b9","attributes":{"file_size":583,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi03ZDc0ZTg5MWU0MTZhMmI5","swb.kind":"Y2h1bmtzbmFw","swb.req":"b2xkLXNuYXBzaG90","swb.snap.claims":"WyJ2Mi9vbGQtZm9yayJd","swb.snap.epoch":"MQ==","swb.snap.gen":"Mg==","swb.snap.lsn":"Nw==","swb.snap.state":"YWN0aXZl"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsImNyZWF0ZWRfYnkiOiIiLCJjb25zaXN0ZW5jeSI6ImNyYXNoIiwiaGVhZCI6eyJzZWdtZW50cyI6eyIwIjp7ImtleSI6IkB2MS9zZWcvZTdiM2VkZGUwNTYwYTM3MjQxZTkxMDJkNjA3ZWJjMTQiLCJzaGEyNTYiOls3NSwyMTgsMTMyLDExMywxNTgsMTcxLDQ1LDIxNCwyMjUsMjE5LDEwNywxNzYsMTczLDQ4LDI0MiwxNTMsMTIsMjMwLDExOCwyMjcsOTAsMTQxLDI0Nyw0LDExMSw1Nyw0OSwyMzcsOTQsMTg0LDg0LDk0XSwib3duZXIiOiJ2MSIsImNvdW50IjoxfX0sImNodW5rX2J5dGVzIjozMjc2OCwiY2h1bmtfY291bnQiOjEsImZvcm1hdCI6MiwiZ2VuIjoyLCJlcG9jaCI6MSwiaG9sZGVyIjoib2xkIiwicmVtb3RlX2xzbiI6Nywic3RhdGUiOiJhY3RpdmUifSwiZ2VvbWV0cnkiOnsibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OH0sInBhcmVudCI6bnVsbCwibGFiZWxzIjpudWxsLCJleHBpcmVzX2F0X25zIjowfQ=="},"/swblock/chunks/v2/VOLUME":{"name":"VOLUME","attributes":{"file_size":384,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU=","swb.req":"b2xkLWZvcms="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYyIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiZm9yayIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsInBhcmVudCI6eyJ2b2x1bWVfaWQiOiJ2MSIsInNuYXBzaG90IjoiczEiLCJnZW4iOjJ9LCJmb3JrIjp7InJlcXVlc3RfaWQiOiJvbGQtZm9yayIsInNvdXJjZSI6InYxIiwic25hcHNob3QiOiJzMSIsInNvdXJjZV9nZW4iOjIsImhlYWRfc2hhMjU2IjoiY2U3OTJiODQ3NWQ2OGY3OTcwNzNlMTA0Nzc1NTFlYmUzYzBlMTQ2NzdmNTNmYjIxMzZkYmM2MDQ4YmVlODU1MSIsInJlbW90ZV9sc24iOjcsImNodW5rX2NvdW50IjoxLCJxdWFsaWZpZWRfcmVmcyI6MX19"}},"Objects":{"seg/e7b3edde0560a37241e9102d607ebc14":"eyJmb3JtYXQiOjEsInJhbmdlIjowLCJjaHVua19ieXRlcyI6MzI3NjgsIm93bmVyIjoidjEiLCJjaHVua3MiOnsiMCI6eyJLZXkiOiJAdjEvbGVnYWN5LWRhdGEiLCJTSEEyNTYiOls5NSwyNDAsMTE2LDIyMSwxNzMsMTM2LDE4MywyNTIsMTgwLDUxLDE1NiwxODMsMTYzLDIzMCwxMzEsNjUsNiwyMywxNDYsMTM0LDE1OCw2NywxMDMsNTksNDUsMjMyLDgyLDkwLDExNyw3MSwxMDcsMjE2XX19fQ=="}} From b7856e4793fa3aaa87db816bf5c83f5c7d3121c0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:41:22 -0800 Subject: [PATCH 066/150] test(chunkstore): use fixture blob store --- .../chunkstore/format_legacy_upgrade_test.go | 426 +++++++++--------- 1 file changed, 213 insertions(+), 213 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go b/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go index 3660fa43ee..83286ec9ac 100644 --- a/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go +++ b/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go @@ -1,213 +1,213 @@ -package chunkstore - -import ( - "bytes" - "context" - "encoding/json" - "os" - "path" - "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" -) - -// Frozen output of the pre-format-3 CreateSnapshot/Fork producers at 3401cc60. -func preF4ForkFixture(t *testing.T, segmented bool) (*fakeFiler, *Catalog, *ChunkRemote) { - t.Helper() - suffix := "false" - if segmented { - suffix = "true" - } - data, err := os.ReadFile("testdata/pre_f4_fork_" + suffix + ".json") - if err != nil { - t.Fatal(err) - } - var frozen struct { - Entries map[string]*filerpb.Entry - Objects map[string][]byte - } - if err := json.Unmarshal(data, &frozen); err != nil { - t.Fatal(err) - } - f, b := newFakeFiler(), newFakeBlobs() - f.entries = frozen.Entries - c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) - if err != nil { - t.Fatal(err) - } - c.now = func() time.Time { return time.Unix(1000, 0) } - r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err != nil { - t.Fatal(err) - } - if err := r.Put(context.Background(), "legacy-data", bytes.Repeat([]byte{0x41}, 8*4096)); err != nil { - t.Fatal(err) - } - for key, body := range frozen.Objects { - if err := r.Put(context.Background(), key, body); err != nil { - t.Fatal(err) - } - } - return f, c, r -} -func assertLegacyImage(t *testing.T, r *ChunkRemote) { - t.Helper() - h, err := r.GetHead(context.Background()) - if err != nil { - t.Fatal(err) - } - if h.RemoteLSN != 7 || len(h.Chunks) != 1 { - t.Fatalf("legacy image/frontier lost: %+v", h) - } - data, err := r.Get(context.Background(), h.Chunks[0].Key) - if err != nil || !bytes.Equal(data, bytes.Repeat([]byte{0x41}, 8*4096)) { - t.Fatalf("legacy bytes changed: %v", err) - } -} -func TestFormatUpgradeLegacyIncompleteFork(t *testing.T) { - for _, segmented := range []bool{false, true} { - name := "flat" - if segmented { - name = "segmented" - } - t.Run(name, func(t *testing.T) { - f, c, r := preF4ForkFixture(t, segmented) - _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}) - if err != nil { - t.Fatalf("old incomplete fork retry: %v", err) - } - dst, err := NewChunkRemote(f, r.blobs, path.Join(catBase, "v2")) - if err != nil { - t.Fatal(err) - } - assertLegacyImage(t, dst) - e, err := f.LookupEntry(context.Background(), path.Join(catBase, "v2"), headName) - if err != nil { - t.Fatal(err) - } - var doc struct{ Format int } - if json.Unmarshal(e.Content, &doc) != nil || doc.Format != 3 { - t.Fatal("fork data must be format3") - } - }) - } -} -func TestFormatUpgradeLegacyForkIdentityStillRefusesChangedImage(t *testing.T) { - for _, segmented := range []bool{false, true} { - t.Run(map[bool]string{false: "flat", true: "segmented"}[segmented], func(t *testing.T) { - f, c, _ := preF4ForkFixture(t, segmented) - p := snapPath(t, f, "v1", "s1") - var s snapDoc - if err := json.Unmarshal(f.entries[p].Content, &s); err != nil { - t.Fatal(err) - } - var h map[string]any - if err := json.Unmarshal(s.Head, &h); err != nil { - t.Fatal(err) - } - h["remote_lsn"] = float64(8) - s.Head, _ = json.Marshal(h) - f.entries[p].Content, _ = json.Marshal(s) - if _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}); CodeOf(err) != CodeTargetExists { - t.Fatalf("changed image admitted or identity not reached: %v", err) - } - }) - } -} -func TestFormatUpgradeLegacySnapshotAndDelete(t *testing.T) { - t.Run("snapshot", func(t *testing.T) { - f, c, r := preF4ForkFixture(t, false) - h, err := r.GetHead(context.Background()) - if err != nil { - t.Fatal(err) - } - if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "upgraded", RequestID: "new-snapshot"}, h); err != nil { - t.Fatalf("legacy snapshot: %v", err) - } - e := f.entries[snapPath(t, f, "v1", "upgraded")] - var s snapDoc - if err := json.Unmarshal(e.Content, &s); err != nil { - t.Fatal(err) - } - var doc struct{ Format int } - json.Unmarshal(s.Head, &doc) - if doc.Format != 3 { - t.Fatal("snapshot contains flat data") - } - assertLegacyImage(t, r) - }) - t.Run("delete", func(t *testing.T) { - f, c, r := preF4ForkFixture(t, false) - for p := range f.entries { - if p != path.Join(catBase, "v1", headName) && p != path.Join(catBase, "v1", volumeName) && !bytes.Contains([]byte(p), []byte("/keys/")) { - delete(f.entries, p) - } - } - h, err := r.GetHead(context.Background()) - if err != nil { - t.Fatal(err) - } - h.Holder = "" - h.Epoch = 0 - f.entries[path.Join(catBase, "v1", headName)] = legacyHeadFixture(t, h) - c.retainHook = func(stage, _ string) { - if stage == hookHeadMarked { - assertLegacyImage(t, r) - e := f.entries[path.Join(catBase, "v1", headName)] - var d struct{ Format int } - json.Unmarshal(e.Content, &d) - if d.Format != 3 { - t.Fatal("delete mark contains flat data") - } - } - } - res, err := c.DeleteVolume(context.Background(), "v1", nil) - if err != nil || !res.Completed { - t.Fatalf("legacy delete: %+v %v", res, err) - } - }) -} - -type legacyUpgradeView struct{} - -func (legacyUpgradeView) Projection() frontend.Projection { - return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, Healthy: true} -} -func TestFormatUpgradeLegacyProviderTakeover(t *testing.T) { - f, _, r := preF4ForkFixture(t, false) - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-new/r1", ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, legacyUpgradeView{}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { p.Close() }) - s, err := p.EnsureStorage("v1") - if err != nil { - t.Fatal(err) - } - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if _, err := p.RecoverVolume(ctx, "v1"); err != nil { - t.Fatalf("legacy provider takeover: %v", err) - } - h, err := r.GetHead(ctx) - if err != nil || h.Holder != "node-new/r1" || h.Epoch != 2 { - t.Fatalf("takeover not installed: %+v %v", h, err) - } - e := f.entries[path.Join(catBase, "v1", headName)] - var d struct{ Format int } - json.Unmarshal(e.Content, &d) - if d.Format != 3 { - t.Fatal("takeover wrote flat data") - } - for i := uint32(0); i < 8; i++ { - got, err := s.Read(i) - if err != nil || !bytes.Equal(got, bytes.Repeat([]byte{0x41}, 4096)) { - t.Fatalf("takeover bytes %d: %v", i, err) - } - } - assertLegacyImage(t, r) -} +package chunkstore + +import ( + "bytes" + "context" + "encoding/json" + "os" + "path" + "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" +) + +// Frozen output of the pre-format-3 CreateSnapshot/Fork producers at 3401cc60. +func preF4ForkFixture(t *testing.T, segmented bool) (*fakeFiler, *Catalog, *ChunkRemote) { + t.Helper() + suffix := "false" + if segmented { + suffix = "true" + } + data, err := os.ReadFile("testdata/pre_f4_fork_" + suffix + ".json") + if err != nil { + t.Fatal(err) + } + var frozen struct { + Entries map[string]*filerpb.Entry + Objects map[string][]byte + } + if err := json.Unmarshal(data, &frozen); err != nil { + t.Fatal(err) + } + f, b := newFakeFiler(), newFakeBlobs() + f.entries = frozen.Entries + c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) + if err != nil { + t.Fatal(err) + } + c.now = func() time.Time { return time.Unix(1000, 0) } + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + if err := r.Put(context.Background(), "legacy-data", bytes.Repeat([]byte{0x41}, 8*4096)); err != nil { + t.Fatal(err) + } + for key, body := range frozen.Objects { + if err := r.Put(context.Background(), key, body); err != nil { + t.Fatal(err) + } + } + return f, c, r +} +func assertLegacyImage(t *testing.T, r *ChunkRemote) { + t.Helper() + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if h.RemoteLSN != 7 || len(h.Chunks) != 1 { + t.Fatalf("legacy image/frontier lost: %+v", h) + } + data, err := r.Get(context.Background(), h.Chunks[0].Key) + if err != nil || !bytes.Equal(data, bytes.Repeat([]byte{0x41}, 8*4096)) { + t.Fatalf("legacy bytes changed: %v", err) + } +} +func TestFormatUpgradeLegacyIncompleteFork(t *testing.T) { + for _, segmented := range []bool{false, true} { + name := "flat" + if segmented { + name = "segmented" + } + t.Run(name, func(t *testing.T) { + f, c, r := preF4ForkFixture(t, segmented) + _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}) + if err != nil { + t.Fatalf("old incomplete fork retry: %v", err) + } + dst, err := NewChunkRemote(f, r.b, path.Join(catBase, "v2")) + if err != nil { + t.Fatal(err) + } + assertLegacyImage(t, dst) + e, err := f.LookupEntry(context.Background(), path.Join(catBase, "v2"), headName) + if err != nil { + t.Fatal(err) + } + var doc struct{ Format int } + if json.Unmarshal(e.Content, &doc) != nil || doc.Format != 3 { + t.Fatal("fork data must be format3") + } + }) + } +} +func TestFormatUpgradeLegacyForkIdentityStillRefusesChangedImage(t *testing.T) { + for _, segmented := range []bool{false, true} { + t.Run(map[bool]string{false: "flat", true: "segmented"}[segmented], func(t *testing.T) { + f, c, _ := preF4ForkFixture(t, segmented) + p := snapPath(t, f, "v1", "s1") + var s snapDoc + if err := json.Unmarshal(f.entries[p].Content, &s); err != nil { + t.Fatal(err) + } + var h map[string]any + if err := json.Unmarshal(s.Head, &h); err != nil { + t.Fatal(err) + } + h["remote_lsn"] = float64(8) + s.Head, _ = json.Marshal(h) + f.entries[p].Content, _ = json.Marshal(s) + if _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}); CodeOf(err) != CodeTargetExists { + t.Fatalf("changed image admitted or identity not reached: %v", err) + } + }) + } +} +func TestFormatUpgradeLegacySnapshotAndDelete(t *testing.T) { + t.Run("snapshot", func(t *testing.T) { + f, c, r := preF4ForkFixture(t, false) + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "upgraded", RequestID: "new-snapshot"}, h); err != nil { + t.Fatalf("legacy snapshot: %v", err) + } + e := f.entries[snapPath(t, f, "v1", "upgraded")] + var s snapDoc + if err := json.Unmarshal(e.Content, &s); err != nil { + t.Fatal(err) + } + var doc struct{ Format int } + json.Unmarshal(s.Head, &doc) + if doc.Format != 3 { + t.Fatal("snapshot contains flat data") + } + assertLegacyImage(t, r) + }) + t.Run("delete", func(t *testing.T) { + f, c, r := preF4ForkFixture(t, false) + for p := range f.entries { + if p != path.Join(catBase, "v1", headName) && p != path.Join(catBase, "v1", volumeName) && !bytes.Contains([]byte(p), []byte("/keys/")) { + delete(f.entries, p) + } + } + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + h.Holder = "" + h.Epoch = 0 + f.entries[path.Join(catBase, "v1", headName)] = legacyHeadFixture(t, h) + c.retainHook = func(stage, _ string) { + if stage == hookHeadMarked { + assertLegacyImage(t, r) + e := f.entries[path.Join(catBase, "v1", headName)] + var d struct{ Format int } + json.Unmarshal(e.Content, &d) + if d.Format != 3 { + t.Fatal("delete mark contains flat data") + } + } + } + res, err := c.DeleteVolume(context.Background(), "v1", nil) + if err != nil || !res.Completed { + t.Fatalf("legacy delete: %+v %v", res, err) + } + }) +} + +type legacyUpgradeView struct{} + +func (legacyUpgradeView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, Healthy: true} +} +func TestFormatUpgradeLegacyProviderTakeover(t *testing.T) { + f, _, r := preF4ForkFixture(t, false) + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-new/r1", ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, legacyUpgradeView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatalf("legacy provider takeover: %v", err) + } + h, err := r.GetHead(ctx) + if err != nil || h.Holder != "node-new/r1" || h.Epoch != 2 { + t.Fatalf("takeover not installed: %+v %v", h, err) + } + e := f.entries[path.Join(catBase, "v1", headName)] + var d struct{ Format int } + json.Unmarshal(e.Content, &d) + if d.Format != 3 { + t.Fatal("takeover wrote flat data") + } + for i := uint32(0); i < 8; i++ { + got, err := s.Read(i) + if err != nil || !bytes.Equal(got, bytes.Repeat([]byte{0x41}, 4096)) { + t.Fatalf("takeover bytes %d: %v", i, err) + } + } + assertLegacyImage(t, r) +} From 49b9fe67b7e3da312a5cc07052aa4f7b43a6a4c8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:33:33 -0800 Subject: [PATCH 067/150] fix(storage): retain checkpoint proof across newer WAL appends --- .../checkpoint_append_progress_v3_test.go | 131 ++++++++++++++++++ .../core/storage/chunk_layer_map_v3.go | 3 +- .../walstore_map_checkpoint_v3_test.go | 8 +- seaweed-block/core/storage/walstore_v3.go | 15 +- 4 files changed, 142 insertions(+), 15 deletions(-) create mode 100644 seaweed-block/core/storage/checkpoint_append_progress_v3_test.go diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go new file mode 100644 index 0000000000..e16a466364 --- /dev/null +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -0,0 +1,131 @@ +package storage + +import ( + "bytes" + "errors" + "testing" +) + +func TestChunkLayerV3_CheckpointProgressUnderContinuousAppends(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + remote := newFakeChunkRemote() + mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(0, blk(1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + realSync := s.v3.ownedMap.syncFile + t.Cleanup(func() { s.v3.ownedMap.syncFile = realSync }) + refusals := 0 + for round := uint32(0); round < 8; round++ { + injected := false + s.v3.ownedMap.syncFile = func() error { + if !injected { + injected = true + if _, err := s.Write(round+1, blk(byte(round+2))); err != nil { + return err + } + } + return realSync() + } + err := s.flusher.flushOnce() + s.v3.ownedMap.syncFile = realSync + if err != nil && !errors.Is(err, ErrMapCoverageStale) { + t.Fatal(err) + } + if errors.Is(err, ErrMapCoverageStale) { + refusals++ + } + if !injected { + t.Fatal("cycle did not overlap a write") + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + cp := s.CheckpointLSN() + t.Logf("continuous writes: cycles8 refusals%d cp%d wack%d dirty%d", refusals, cp, s.v3.wack.Load(), s.dm.len()) + if cp == 0 { + t.Fatal("checkpoint made no progress across eight completed extent/map persistence cycles while newer appends continued") + } +} + +func TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + remote := newFakeChunkRemote() + layer := mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(1, blk(0x11)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + s.v3.testMapPrepared = func() { + if _, err := s.WriteBatch(1, [][]byte{blk(0xB2), blk(0xC3)}); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + s.v3.testMapPrepared = nil + d := s.v3.pub.current() + if d.CheckpointLSN != 1 || d.MapCoveredCheckpoint != 1 || s.dm.len() != 2 { + t.Fatalf("prefix cp=%d C=%d dirty=%d", d.CheckpointLSN, d.MapCoveredCheckpoint, s.dm.len()) + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err = r.Recover(); err != nil { + t.Fatal(err) + } + for lba, want := range map[uint32][]byte{1: blk(0xB2), 2: blk(0xC3)} { + if !bytes.Equal(readV3(t, r, lba), want) { + t.Fatalf("replayed LBA%d lost", lba) + } + } + restored := mustAttach(t, r, remote, ctConfig(1)) + cut, err := restored.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + image := remote.imageOf(t, cut.Head) + if !bytes.Equal(image[4096:8192], blk(0xB2)) || !bytes.Equal(image[8192:12288], blk(0xC3)) { + t.Fatal("capture omitted newer replayed batch") + } +} + +func TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + h := beginV3(t, s, 0, idA) + cp := s.CheckpointLSN() + prepared, err := s.prepareOwnedMapCheckpointV3(cp) + if err != nil { + t.Fatal(err) + } + before := s.v3.pub.current() + if err = h.WriteBase(1, blk(0xA7)); err != nil { + t.Fatal(err) + } + if _, err = s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("effective BASE mutation proof accepted: %v", err) + } + if s.v3.pub.current() != before { + t.Fatal("stale BASE candidate changed slots") + } +} diff --git a/seaweed-block/core/storage/chunk_layer_map_v3.go b/seaweed-block/core/storage/chunk_layer_map_v3.go index 295c436f5e..28b62756b0 100644 --- a/seaweed-block/core/storage/chunk_layer_map_v3.go +++ b/seaweed-block/core/storage/chunk_layer_map_v3.go @@ -9,7 +9,8 @@ func (l *chunkLayerImpl) usesOwnedMapV3() bool { return l.s.v3 != nil && l.s.v3. // (or an authority-checked no-op), outside bmMu/stMu and the capture barrier. // The capture's mutation versions were sampled under the quiesced barrier. // Store.mu prevents a WAL append from slipping between the version check and -// the UNKNOWN update. A later write updates max LSN and invalidates proofs. +// the UNKNOWN update. A later WAL append updates max LSN and stays retained; +// an effective UNKNOWN change or lifecycle transition invalidates proofs. // A failed map publication leaves the old disk UNKNOWN conservative; a map // persistence failure also latches the store, while the remote HEAD remains // the successfully captured image. No remote durability claim is undone. diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go index b479497f55..27bba23235 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go @@ -144,8 +144,10 @@ func TestWALStoreV3_PreparedCheckpointRefusesChangedProof(t *testing.T) { release() select { case err := <-done: - if !errors.Is(err, ErrMapCoverageStale) { + if event == "recover" && !errors.Is(err, ErrMapCoverageStale) { t.Errorf("stale prepared checkpoint=%v", err) + } else if event == "write" && err != nil { + t.Errorf("newer retained append invalidated prefix coverage: %v", err) } case <-time.After(5 * time.Second): t.Fatal("flusher did not settle") @@ -156,8 +158,10 @@ func TestWALStoreV3_PreparedCheckpointRefusesChangedProof(t *testing.T) { t.Fatal("flusher result without join") } s.v3.testMapPrepared = nil - if s.v3.pub.current() != before { + if event == "recover" && s.v3.pub.current() != before { t.Error("stale proof published a checkpoint") + } else if event == "write" && s.CheckpointLSN() != 1 { + t.Error("newer retained append blocked the older checkpoint") } if s.stickyIOFault() != nil { t.Error("proof refusal incorrectly latched a persistence fault") diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index ea7f8d68fd..d894405060 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -654,13 +654,9 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, e if s.v3.w == nil { return 0, errWALBindingV3 // a half-published reset before its Recover } - // Reserve proof invalidation before the WAL can change. This is under - // the existing store lock; a refused append only causes conservative retry. - if s.v3.mapProof != nil { - if err := s.v3.mapProof.mutatedV3(); err != nil { - return 0, err - } - } + // A strictly newer append stays in the retained WAL suffix. It cannot + // invalidate coverage of an older checkpoint prefix; effective BASE and + // lifecycle mutations still invalidate the map proof at their own seams. if err := s.rolloverCheckpointV3Locked(); err != nil { return 0, err } @@ -710,11 +706,6 @@ func (s *WALStore) writeBatchV3Locked(startLBA uint32, blocks [][]byte, firstLSN s.instr.recordWALCopy(len(payload), time.Since(copyStart)) n := uint64(len(blocks)) lastLSN := firstLSN + n - 1 - if s.v3.mapProof != nil { - if err := s.v3.mapProof.mutatedV3(); err != nil { - return nil, err - } - } e := walEntryV3{LSN: firstLSN, BatchCount: n, Type: walEntryWriteBatch, LBA: uint64(startLBA), Length: uint32(len(payload)), Data: payload} if err := s.rolloverCheckpointV3Locked(); err != nil { return nil, err From 7887101d269758c865fc967a2b5964a9bbc9ebd9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:35:46 -0800 Subject: [PATCH 068/150] docs: record prefix proof regression coverage --- seaweed-block/docs/design/invariants.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 43a8867335..653ffda191 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -335,7 +335,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | | `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | @@ -355,7 +355,7 @@ Notes: - `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged. - `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. -- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. Writes invalidate proofs before append and update per-chunk max LSN under store.mu, while Recover rebuilds that volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. +- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. Effective BASE/UNKNOWN changes and lifecycle boundaries still invalidate proofs. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. - `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. Sidecar extents are reused only after neither slot nor a pending or uncertain candidate references them; see `chunk_map_extents_v3.go` and its tests. From 186c7a0897a080788e232878a1ddc0161a5138c6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:40:19 -0800 Subject: [PATCH 069/150] fix(storage): preserve exhausted proof-counter refusal on append --- .../checkpoint_append_progress_v3_test.go | 18 ++++++++++++++++++ seaweed-block/core/storage/walstore_v3.go | 6 ++++++ seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index e16a466364..b964b0ced5 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -129,3 +129,21 @@ func TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof(t *testing.T) { t.Fatal("stale BASE candidate changed slots") } } + +// Removing append-driven increments must not bypass terminal exhaustion. +func TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend(t *testing.T) { + for _, batch := range []bool{false, true} { + s, _ := newMappedCheckpointStoreV3(t) + before := s.NextLSN() + s.v3.mapProof.mutation.Store(counterMaxV3) + var err error + if batch { + _, err = s.WriteBatch(1, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.Write(1, blk(1)) + } + if !errors.Is(err, ErrCounterExhausted) || s.NextLSN() != before || s.dm.len() != 0 { + t.Fatalf("exhaustion bypassed: batch=%t err=%v next=%d dirty=%d", batch, err, s.NextLSN(), s.dm.len()) + } + } +} diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index d894405060..8691653109 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -657,6 +657,9 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, e // A strictly newer append stays in the retained WAL suffix. It cannot // invalidate coverage of an older checkpoint prefix; effective BASE and // lifecycle mutations still invalidate the map proof at their own seams. + if p := s.v3.mapProof; p != nil && p.mutation.Load() >= counterMaxV3 { + return 0, ErrCounterExhausted + } if err := s.rolloverCheckpointV3Locked(); err != nil { return 0, err } @@ -706,6 +709,9 @@ func (s *WALStore) writeBatchV3Locked(startLBA uint32, blocks [][]byte, firstLSN s.instr.recordWALCopy(len(payload), time.Since(copyStart)) n := uint64(len(blocks)) lastLSN := firstLSN + n - 1 + if p := s.v3.mapProof; p != nil && p.mutation.Load() >= counterMaxV3 { + return nil, ErrCounterExhausted + } e := walEntryV3{LSN: firstLSN, BatchCount: n, Type: walEntryWriteBatch, LBA: uint64(startLBA), Length: uint32(len(payload)), Data: payload} if err := s.rolloverCheckpointV3Locked(); err != nil { return nil, err diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 653ffda191..624b409247 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -335,7 +335,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | | `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | From c728fb4191f3043bc4881bc5dd5102c6d8cee8bd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:41:36 -0800 Subject: [PATCH 070/150] test(storage): cover prefix proofs across rollover and hydration --- .../checkpoint_append_progress_v3_test.go | 179 ++++++++++++++++++ .../storage/walstore_map_checkpoint_v3.go | 2 + seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 182 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index b964b0ced5..910d5408b3 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -3,6 +3,7 @@ package storage import ( "bytes" "errors" + "path/filepath" "testing" ) @@ -19,6 +20,7 @@ func TestChunkLayerV3_CheckpointProgressUnderContinuousAppends(t *testing.T) { realSync := s.v3.ownedMap.syncFile t.Cleanup(func() { s.v3.ownedMap.syncFile = realSync }) refusals := 0 + previousCP := uint64(0) for round := uint32(0); round < 8; round++ { injected := false s.v3.ownedMap.syncFile = func() error { @@ -41,6 +43,11 @@ func TestChunkLayerV3_CheckpointProgressUnderContinuousAppends(t *testing.T) { if !injected { t.Fatal("cycle did not overlap a write") } + if cp := s.CheckpointLSN(); cp <= previousCP { + t.Fatalf("cycle %d: checkpoint %d did not advance beyond %d", round, cp, previousCP) + } else { + previousCP = cp + } if _, err := s.Sync(); err != nil { t.Fatal(err) } @@ -147,3 +154,175 @@ func TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend(t *testing.T) { } } } + +// A write's real fallback rollover can run after a map candidate was prepared. +// It preserves the older prefix and the later append remains available to replay. +func TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(1) + writeSynced(t, s, 1, 2) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(2) + if err != nil { + t.Fatal(err) + } + tail := s.v3.w.reclaimThroughV3(2) + before := s.v3.pub.current() + if tail <= before.RetainedTail { + t.Fatal("setup: no releasable retained record") + } + // One real slot publication advances the current tail only. The next Write + // must bring the fallback forward before it can reuse that released range. + if _, err := s.v3.pub.publish(nil, nil, func(d *descriptorV3) error { + d.RetainedTail = tail + d.RetainedHead = max(d.RetainedHead, tail) + return nil + }); err != nil { + t.Fatal(err) + } + current, floor, ok := s.v3.pub.walSnapshotV3() + if !ok || floor >= tail { + t.Fatal("setup: fallback did not pin rollover") + } + if lsn, err := s.Write(3, blk(0xD3)); err != nil || lsn != 3 { + t.Fatalf("write: lsn %d err %v", lsn, err) + } + after := s.v3.pub.current() + if after.SlotGen != current.SlotGen+1 { + t.Fatal("Write did not execute the fallback rollover") + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatalf("prefix publication after rollover: %v", err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + d, floor, ok := s.v3.pub.walSnapshotV3() + if !ok || d.CheckpointLSN != 2 || d.MapCoveredCheckpoint != 2 || d.W < 3 || floor != tail || d.RetainedTail != tail { + t.Fatalf("prefix/suffix boundary: cp%d C%d W%d floor%d tail%d want%d", d.CheckpointLSN, d.MapCoveredCheckpoint, d.W, floor, d.RetainedTail, tail) + } + s.SetRecoveryRetentionLSNs(1) + var scanned []RecoveryEntry + if err := s.ScanLBAs(3, func(e RecoveryEntry) error { scanned = append(scanned, e); return nil }); err != nil || len(scanned) != 1 || scanned[0].LSN != 3 || !bytes.Equal(scanned[0].Data, blk(0xD3)) { + t.Fatalf("retained suffix: %+v err %v", scanned, err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if !bytes.Equal(readV3(t, r, 3), blk(0xD3)) { + t.Fatal("retained suffix lost after reopen") + } +} + +func TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix(t *testing.T) { + path := filepath.Join(t.TempDir(), "hydrating") + s, err := createMappedWALStoreV3ForTest(path, ctNumBlocks, ctBlockSize, v3TestWAL, WModeStrict, ctChunkBlocks) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + image := make([]byte, ctNumBlocks*ctBlockSize) + copy(image[9*ctBlockSize:], blk(0xA9)) + remote := newFakeChunkRemote() + remote.seedHead(t, image, 10, 1) + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + layer := mustAttach(t, s, remote, cfg).(*chunkLayerImpl) + prepared, err := s.prepareOwnedMapCheckpointV3(10) + if err != nil { + t.Fatal(err) + } + layer.stMu.Lock() + absent := layer.absent[2] + layer.stMu.Unlock() + if !absent { + t.Fatal("setup: chunk is not absent") + } + if got, err := s.Read(9); err != nil || !bytes.Equal(got, blk(0xA9)) { + t.Fatalf("lazy read: %v", err) + } + layer.stMu.Lock() + absent = layer.absent[2] + layer.stMu.Unlock() + if absent { + t.Fatal("read did not hydrate chunk") + } + if !prepared.proof.validV3(s.v3.mapProof) { + t.Fatal("lazy fill invalidated the checkpoint prefix") + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatalf("publish after lazy fill: %v", err) + } +} + +// At every cycle the ring reaches the real admission soft-pressure range. +// An append overlaps map persistence, yet each completed cycle must reclaim; +// none may require a cut or new remote HEAD to escape repeated proof refusal. +func TestChunkLayerV3_CheckpointProgressAtWALPressure(t *testing.T) { + for _, mode := range []WMode{WModeStrict, WModeLagged} { + t.Run(map[WMode]string{WModeStrict: "A", WModeLagged: "C"}[mode], func(t *testing.T) { + path := filepath.Join(t.TempDir(), "pressure") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 64*1024, mode, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + realSync := s.v3.ownedMap.syncFile + t.Cleanup(func() { s.v3.ownedMap.syncFile = realSync }) + previousCP := uint64(0) + for cycle := 0; cycle < 8; cycle++ { + for s.walUsedFraction() < 0.72 { + if _, err := s.Write(uint32(s.NextLSN()%64), blk(byte(s.NextLSN()))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + injected := false + s.v3.ownedMap.syncFile = func() error { + if !injected { + injected = true + if _, err := s.Write(uint32(s.NextLSN()%64), blk(byte(s.NextLSN()))); err != nil { + return err + } + } + return realSync() + } + err := s.flusher.flushOnce() + s.v3.ownedMap.syncFile = realSync + if err != nil { + t.Fatalf("pressure cycle%d: %v", cycle, err) + } + cp := s.CheckpointLSN() + if !injected || cp <= previousCP { + t.Fatalf("no progress cycle%d cp%d previous%d", cycle, cp, previousCP) + } + previousCP = cp + } + floor, ok := s.v3.pub.reuseFloor() + if !ok || floor < 5*64*1024 { + t.Fatalf("no sustained ring reuse: floor%d", floor) + } + t.Logf("cycles8 checkpoint%d floor%d busy0", previousCP, floor) + }) + } +} diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index 029d0ba210..3b9fe9aca1 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -36,6 +36,8 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati return nil, ErrMapCoverageStale } proof := domain.snapshotV3() + // Entries may already contain LSNs above cp from earlier appends: max-LSN + // entries are monotone and idempotent under retained-suffix replay. entries := append([]chunkLSNEntryV3(nil), v.mapEntries...) v.pub.descMu.Unlock() s.mu.RUnlock() diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 624b409247..aef36d1bbf 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -355,7 +355,7 @@ Notes: - `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged. - `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. -- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. Effective BASE/UNKNOWN changes and lifecycle boundaries still invalidate proofs. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. +- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. The entry snapshot may already contain LSNs above cp from pre-snapshot appends; max-LSN entries remain monotone and idempotent under replay. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. Effective BASE/UNKNOWN changes and lifecycle boundaries still invalidate proofs. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. - `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. Sidecar extents are reused only after neither slot nor a pending or uncertain candidate references them; see `chunk_map_extents_v3.go` and its tests. From 1a9dc60643f547763aee780329e4862ee29d77f6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:42:46 -0800 Subject: [PATCH 071/150] fix(chunkstore): upgrade legacy data callers and preserve fork identity --- .../core/frontend/chunkstore/catalog.go | 26 ++++-- .../frontend/chunkstore/manifest_upgrade.go | 80 +++++++++++++++++++ .../core/frontend/chunkstore/volume_delete.go | 31 +++++-- .../core/frontend/durable/provider_chunk.go | 1 + seaweed-block/core/storage/chunk_manifest.go | 2 +- seaweed-block/core/storage/chunk_restore.go | 21 +++++ seaweed-block/core/storage/chunk_seam.go | 3 + 7 files changed, 151 insertions(+), 13 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/manifest_upgrade.go diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 1e1889e3d0..76f343b0c5 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -227,8 +227,9 @@ type SnapshotInfo struct { attempt string // the attempt the name resolved to, when read by name - head storage.ChunkHead - geo Geometry + head storage.ChunkHead + geo Geometry + digest string // identity uses the embedded writer version, not today's serializer } // Head returns the HEAD the snapshot copied. @@ -669,6 +670,10 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) { if err != nil { return fail("%v", err) } + digest, err := snapshotHeadDigest(head, doc.Head) + if err != nil { + return fail("HEAD identity: %v", err) + } state := string(e.Extended[extSnapState]) if state != SnapActive && state != SnapDeleting { return fail("state %q", state) @@ -680,7 +685,7 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) { VolumeID: doc.VolumeID, Name: doc.Name, HeadGen: head.Gen, HeadEpoch: head.Epoch, CutLSN: head.RemoteLSN, CreatedNs: doc.CreatedNs, State: state, ChunkCount: manifestCount(head), ManifestBytes: len(e.GetContent()), Consistency: doc.Consistency, Labels: doc.Labels, Parent: doc.Parent, ExpiresAtNs: doc.ExpiresAtNs, - Class: doc.Class, head: head, geo: doc.Geometry, + Class: doc.Class, head: head, geo: doc.Geometry, digest: digest, }, doc.RequestID, nil } @@ -866,6 +871,11 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe return SnapshotInfo{}, refuseDeleted(vol, "it cannot be snapshotted") } + head, upgradeIDs, err := c.prepareLegacyHead(ctx, root, head, head, v.Geometry) + defer c.dropManifestIntents(ctx, root, upgradeIDs) + if err != nil { + return SnapshotInfo{}, err + } headEnt, err := headEntry(head) if err != nil { return SnapshotInfo{}, err @@ -1227,10 +1237,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, fmt.Errorf("chunkstore: snapshot %s/%s has no geometry", req.Source, req.Snapshot) } src := snap.Head() - digest, err := headDigest(src) - if err != nil { - return ForkResult{}, err - } + digest := snap.digest head := storage.ChunkHead{Gen: 1, Epoch: 0, Holder: "", RemoteLSN: src.RemoteLSN, Chunks: make(map[uint64]storage.ChunkRef, len(src.Chunks)), State: storage.ChunkHeadActive} qualified := 0 if src.Segments != nil { @@ -1281,6 +1288,11 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) existing = vol } + head, upgradeIDs, err := c.prepareLegacyHead(ctx, dstRoot, storage.ChunkHead{}, head, snap.geo) + defer c.dropManifestIntents(ctx, dstRoot, upgradeIDs) + if err != nil { + return ForkResult{}, err + } he, err := headEntry(head) if err != nil { return ForkResult{}, err diff --git a/seaweed-block/core/frontend/chunkstore/manifest_upgrade.go b/seaweed-block/core/frontend/chunkstore/manifest_upgrade.go new file mode 100644 index 0000000000..8a9887873b --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/manifest_upgrade.go @@ -0,0 +1,80 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func (c *Catalog) prepareLegacyHead(ctx context.Context, root string, base, next storage.ChunkHead, geo Geometry) (storage.ChunkHead, []string, error) { + if next.Segments != nil || len(next.Chunks) == 0 { + return next, nil, nil + } + if c.blobs == nil { + return next, nil, errors.New("chunkstore: legacy data upgrade needs blob storage") + } + r, err := NewChunkRemote(c.f, c.blobs, root) + if err != nil { + return next, nil, err + } + return r.PrepareManifest(ctx, base, next, uint64(geo.BlockSize)*uint64(geo.ChunkBlocks)) +} +func (c *Catalog) dropManifestIntents(ctx context.Context, root string, ids []string) { + for _, id := range ids { + c.dropIntent(ctx, root, id) + } +} + +// Fork identity is a persisted protocol. Old snapshots keep the pre-format-3 +// canonical encoding even when their next publication upgrades the manifest. +func snapshotHeadDigest(h storage.ChunkHead, embedded json.RawMessage) (string, error) { + var version struct { + Format int `json:"format"` + } + if err := json.Unmarshal(embedded, &version); err != nil { + return "", err + } + if version.Format == 3 { + return headDigest(h) + } + type oldHead struct { + Segments map[uint64]legacySegmentRefDoc `json:"segments,omitempty"` + ChunkBytes uint64 `json:"chunk_bytes,omitempty"` + ChunkCount int `json:"chunk_count,omitempty"` + Format int `json:"format"` + Gen uint64 `json:"gen"` + Epoch uint64 `json:"epoch"` + Holder string `json:"holder"` + RemoteLSN uint64 `json:"remote_lsn"` + Chunks map[uint64]refDoc `json:"chunks,omitempty"` + State string `json:"state,omitempty"` + DetachedBy *detachedByDoc `json:"detachedBy,omitempty"` + } + d := oldHead{Format: version.Format, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: h.State} + if h.DetachedBy != nil { + d.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen} + } + if version.Format == 2 { + d.Segments = map[uint64]legacySegmentRefDoc{} + d.ChunkBytes = h.ChunkBytes + d.ChunkCount = h.ManifestChunkCount + for idx, ref := range h.Segments { + d.Segments[idx] = legacySegmentRefDoc{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count} + } + } else { + d.Chunks = map[uint64]refDoc{} + for idx, ref := range h.Chunks { + d.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} + } + } + body, err := json.Marshal(d) + if err != nil { + return "", err + } + sum := sha256.Sum256(body) + return hex.EncodeToString(sum[:]), nil +} diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete.go b/seaweed-block/core/frontend/chunkstore/volume_delete.go index 0526990ae7..bfa4b8d787 100644 --- a/seaweed-block/core/frontend/chunkstore/volume_delete.go +++ b/seaweed-block/core/frontend/chunkstore/volume_delete.go @@ -244,17 +244,38 @@ func headDeletingOrDeleted(h storage.ChunkHead) bool { // refuses to anyone else. func (c *Catalog) writeHead(ctx context.Context, root string, cur, next storage.ChunkHead) error { next.Gen = cur.Gen + 1 + var ids []string + if next.Segments == nil && len(next.Chunks) != 0 { + v, ok, err := c.ReadVolume(ctx, path.Base(root)) + if err != nil { + return err + } + if !ok { + return errors.New("chunkstore: legacy delete needs VOLUME geometry") + } + next, ids, err = c.prepareLegacyHead(ctx, root, cur, next, v.Geometry) + if err != nil { + c.dropManifestIntents(ctx, root, ids) + return err + } + } e, err := headEntry(next) if err != nil { + c.dropManifestIntents(ctx, root, ids) return err } if cur.Gen == 0 { - return c.f.CreateEntry(ctx, root, e, true) + err = c.f.CreateEntry(ctx, root, e, true) + } else { + err = c.f.UpdateEntry(ctx, root, e, map[string][]byte{ + extGen: []byte(strconv.FormatUint(cur.Gen, 10)), extEpoch: []byte(strconv.FormatUint(cur.Epoch, 10)), + }) } - return c.f.UpdateEntry(ctx, root, e, map[string][]byte{ - extGen: []byte(strconv.FormatUint(cur.Gen, 10)), - extEpoch: []byte(strconv.FormatUint(cur.Epoch, 10)), - }) + // Unknown publication retains protection; a later sweep can settle it. + if err == nil || lostCondition(err) { + c.dropManifestIntents(ctx, root, ids) + } + return err } func lostCondition(err error) bool { diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 7b4da71e7d..0c29479953 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -309,6 +309,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h } cfg := storage.ChunkLayerConfig{ ChunkBlocks: p.cfg.ChunkBlocks, + RestoreChunkBytes: uint64(ws.BlockSize()) * uint64(p.cfg.ChunkBlocks), Epoch: lin.epoch, Holder: holder, FreshFromHead: h.fresh, diff --git a/seaweed-block/core/storage/chunk_manifest.go b/seaweed-block/core/storage/chunk_manifest.go index 28e4297cf8..c460c0fe99 100644 --- a/seaweed-block/core/storage/chunk_manifest.go +++ b/seaweed-block/core/storage/chunk_manifest.go @@ -14,7 +14,7 @@ type ChunkSegment struct { } // ChunkManifestBuilder prepares immutable segments before the existing root -// CAS. Returned intents belong to the cut and follow its settlement rules. +// CAS. Returned intents belong to the publishing caller and follow its settlement rules. type ChunkManifestBuilder interface { PrepareManifest(context.Context, ChunkHead, ChunkHead, uint64) (ChunkHead, []string, error) } diff --git a/seaweed-block/core/storage/chunk_restore.go b/seaweed-block/core/storage/chunk_restore.go index c95f8a9d1f..1a011df27b 100644 --- a/seaweed-block/core/storage/chunk_restore.go +++ b/seaweed-block/core/storage/chunk_restore.go @@ -57,11 +57,31 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi // A new holder's takeover starts serving the same image as active. The // previous holder's final-cut proof belongs only to its detached HEAD. next.State, next.DetachedBy = chunkHeadActive, nil + var intents []string + settled := true // no root RPC sent yet + defer func() { + if settled { + for _, id := range intents { + _ = remote.DeleteIntent(context.WithoutCancel(ctx), id) + } + } + }() + if builder, ok := remote.(ChunkManifestBuilder); ok && next.Segments == nil && len(next.Chunks) != 0 { + if cfg.RestoreChunkBytes == 0 { + return ChunkHead{}, errors.New("storage: legacy HEAD claim needs validated chunk geometry") + } + next, intents, err = builder.PrepareManifest(ctx, head, next, cfg.RestoreChunkBytes) + if err != nil { + return ChunkHead{}, err + } + } if err := allowed(); err != nil { return ChunkHead{}, err } + settled = false // an ambiguous CAS keeps its segment intents gen, casErr := remote.CASHead(ctx, ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, next) if casErr == nil { + settled = true next.Gen = gen return next, allowed() } @@ -71,6 +91,7 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi if readErr != nil { return ChunkHead{}, fmt.Errorf("storage: HEAD claim unresolved: %w", errors.Join(casErr, readErr)) } + settled = errors.Is(casErr, ErrChunkHeadPrecondition) || current.Gen > head.Gen if current.Gen > head.Gen && sameProposal(current, next) { return current, allowed() } diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 790456f6e7..5f14d2f5d8 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -333,6 +333,9 @@ type chunkLayerConfig struct { // while its frontend is gated. An error leaves remote ownership unchanged. // No store/layer/remote lock is held across the callback. PrepareRestore func(head chunkHead) error + // RestoreChunkBytes is the local, validated geometry for upgrading a flat + // legacy image during an ownership claim; it is never inferred from data. + RestoreChunkBytes uint64 // CaptureAllowed is supplied by the store owner. It is an admission // check, made when a capture starts and again right before its HEAD CAS: // it refuses a cut during a BASE install or rebuild, or when this node is From ae0f74cb16ac9ac063d41f0e6ceae81afd348380 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:44:05 -0800 Subject: [PATCH 072/150] test(storage): measure birth sampler maximum default geometry and lock wait --- .../core/storage/chunk_birth_budget_test.go | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_birth_budget_test.go diff --git a/seaweed-block/core/storage/chunk_birth_budget_test.go b/seaweed-block/core/storage/chunk_birth_budget_test.go new file mode 100644 index 0000000000..5535c69edf --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_budget_test.go @@ -0,0 +1,65 @@ +package storage + +import ( + "testing" + "time" +) + +// Metadata-only maximum-volume/default-chunk shape; no volume-sized image or +// device is allocated. This measures the added sampler, not a complete cut. +func BenchmarkCaptureBirthsMaxVolumeDefaultChunk(b *testing.B) { + const count = 1 << 22 // ceil((16 TiB - 4 KiB) / 4 MiB) + candidates := make(map[uint64]bool, count) + s := &WALStore{v3: &walStoreV3State{mapEntries: make([]chunkLSNEntryV3, count), mapProof: newMapProofEpochV3()}} + for i := uint64(0); i < count; i++ { + candidates[i] = true + s.v3.mapEntries[i].LSN = i + 1 + } + l := &chunkLayerImpl{s: s} + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.captureMu.Lock() + out := l.captureBirths(candidates, count) + s.captureMu.Unlock() + if len(out) != count || out[0] != 1 || out[count-1] != count { + b.Fatal("worst-shape birth mismatch") + } + } +} +func TestCaptureBirthsIncludesStoreLockWait(t *testing.T) { + s := &WALStore{} + l := &chunkLayerImpl{s: s} + candidates := map[uint64]bool{0: true} + s.mu.Lock() + locked := true + done := make(chan map[uint64]uint64, 1) + t.Cleanup(func() { + if locked { + s.mu.Unlock() + } + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("sampler did not join") + } + }) + go func() { s.captureMu.Lock(); out := l.captureBirths(candidates, 7); s.captureMu.Unlock(); done <- out }() + select { + case out := <-done: + done <- out + t.Fatal("sampler bypassed store lock") + case <-time.After(25 * time.Millisecond): + } + s.mu.Unlock() + locked = false + select { + case out := <-done: + done <- out + if out[0] != 7 { + t.Fatal("legacy frontier changed") + } + case <-time.After(5 * time.Second): + t.Fatal("sampler did not finish after lock release") + } +} From 3aa38eadd8eaaa6e465213f730c0f6b36d1c4b68 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:50:33 -0800 Subject: [PATCH 073/150] test: expose checkpoint persistence refusals and successes --- .../durable/checkpoint_status_test.go | 62 +++++++++++++++++++ .../storage/checkpoint_diagnostics_test.go | 51 +++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/checkpoint_status_test.go create mode 100644 seaweed-block/core/storage/checkpoint_diagnostics_test.go diff --git a/seaweed-block/core/frontend/durable/checkpoint_status_test.go b/seaweed-block/core/frontend/durable/checkpoint_status_test.go new file mode 100644 index 0000000000..7b46ce5f64 --- /dev/null +++ b/seaweed-block/core/frontend/durable/checkpoint_status_test.go @@ -0,0 +1,62 @@ +package durable_test + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestDurableProvider_CheckpointPersistenceStatus(t *testing.T) { + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: 64, ChunkBlocks: 4, ChunkCaptureInterval: 0, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + be, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := be.Write(context.Background(), 0, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + if err := be.Sync(context.Background()); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(5 * time.Second) + for { + statuses := p.DurableStatuses() + raw, err := json.Marshal(statuses) + if err != nil { + t.Fatal(err) + } + var wire []struct { + CheckpointPersistence *struct { + Successes uint64 + Refusals uint64 + Failures uint64 + } + } + if err := json.Unmarshal(raw, &wire); err != nil { + t.Fatal(err) + } + if len(wire) == 1 && wire[0].CheckpointPersistence != nil && wire[0].CheckpointPersistence.Successes > 0 { + return + } + if time.Now().After(deadline) { + t.Fatalf("no checkpoint persist status in durable response: %s", raw) + } + time.Sleep(10 * time.Millisecond) + } +} diff --git a/seaweed-block/core/storage/checkpoint_diagnostics_test.go b/seaweed-block/core/storage/checkpoint_diagnostics_test.go new file mode 100644 index 0000000000..d811d47dde --- /dev/null +++ b/seaweed-block/core/storage/checkpoint_diagnostics_test.go @@ -0,0 +1,51 @@ +package storage + +import ( + "encoding/json" + "errors" + "strings" + "testing" +) + +func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + s.v3.testMapPrepared = func() { + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + } + before := s.v3.pub.current() + err := s.flusher.flushOnce() + if !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("refusal: %v", err) + } + if !strings.Contains(err.Error(), "proof_changed") { + t.Errorf("missing refusal reason: %v", err) + } + if s.v3.pub.current() != before || s.dm.len() != 2 || s.stickyIOFault() != nil { + t.Fatal("refusal changed publication/retry/fault state") + } + raw, _ := json.Marshal(s.FlusherInstrumentation()) + var counts map[string]uint64 + if err := json.Unmarshal(raw, &counts); err != nil { + t.Fatal(err) + } + if counts["CheckpointRefusals"] != 1 || counts["CheckpointSuccesses"] != 0 { + t.Fatalf("refusal counters: %s", raw) + } + s.v3.testMapPrepared = nil + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + raw, _ = json.Marshal(s.FlusherInstrumentation()) + if err := json.Unmarshal(raw, &counts); err != nil { + t.Fatal(err) + } + if counts["CheckpointRefusals"] != 1 || counts["CheckpointSuccesses"] != 1 || s.CheckpointLSN() != 2 || s.dm.len() != 0 { + t.Fatalf("retry counters/state: %s cp=%d", raw, s.CheckpointLSN()) + } +} From 0df88965e97aebcf15e53c01864507ac7da3361c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:52:26 -0800 Subject: [PATCH 074/150] storage: report checkpoint retry reasons and cumulative outcomes --- .../durable/checkpoint_status_test.go | 3 + .../core/frontend/durable/provider.go | 31 ++++----- .../core/frontend/durable/storage_adapter.go | 42 +++++++----- .../core/storage/checkpoint_diagnostics.go | 64 ++++++++++++++++++ .../storage/checkpoint_diagnostics_test.go | 67 +++++++++++++++++++ .../core/storage/chunk_map_publication_v3.go | 20 +++--- seaweed-block/core/storage/flusher.go | 9 +-- .../core/storage/flusher_instrumentation.go | 9 +++ .../storage/walstore_map_checkpoint_v3.go | 10 +-- 9 files changed, 204 insertions(+), 51 deletions(-) create mode 100644 seaweed-block/core/storage/checkpoint_diagnostics.go diff --git a/seaweed-block/core/frontend/durable/checkpoint_status_test.go b/seaweed-block/core/frontend/durable/checkpoint_status_test.go index 7b46ce5f64..b3ad4cb9ce 100644 --- a/seaweed-block/core/frontend/durable/checkpoint_status_test.go +++ b/seaweed-block/core/frontend/durable/checkpoint_status_test.go @@ -21,6 +21,9 @@ func TestDurableProvider_CheckpointPersistenceStatus(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { p.Close() }) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index f305998a2e..eef6e4d0dc 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -251,21 +251,22 @@ type volHandle struct { // handle. It intentionally exposes lineage and readiness facts without giving // callers a control surface. type VolumeStatus struct { - VolumeID string - Path string - Impl string - ReplicaID string - Epoch uint64 - EndpointVersion uint64 - Latched bool - Operational bool - FrontierKnown bool - DurableLSN uint64 - RetainedLSN uint64 - HeadLSN uint64 - Evidence string - Closed bool - WriteProfile WriteProfileStatus + VolumeID string + Path string + Impl string + ReplicaID string + Epoch uint64 + EndpointVersion uint64 + Latched bool + Operational bool + FrontierKnown bool + DurableLSN uint64 + RetainedLSN uint64 + HeadLSN uint64 + Evidence string + Closed bool + WriteProfile WriteProfileStatus + CheckpointPersistence *storage.CheckpointPersistenceStatus `json:",omitempty"` // Chunk is the chunk layer's state and cut counters; walstore-chunk // volumes only. Chunk *ChunkStatus diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 2aab01a159..440d1b3e47 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -288,6 +288,13 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus if c, ok := b.storage.(interface{ HolesSuspected() uint64 }); ok { holes = c.HolesSuspected() } + var checkpoint *storage.CheckpointPersistenceStatus + if reporter, ok := b.storage.(interface { + CheckpointPersistence() storage.CheckpointPersistenceStatus + }); ok { + snapshot := reporter.CheckpointPersistence() + checkpoint = &snapshot + } writeProfile := b.WriteProfile() if instrumented, ok := b.storage.(storage.WriteInstrumented); ok { storageProfile := instrumented.WriteInstrumentation() @@ -316,23 +323,24 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus writeProfile.DirtyMapUpdateDurationNanos = storageProfile.DirtyMapUpdateDurationNanos } return VolumeStatus{ - Warnings: warnings, - HolesSuspected: holes, - VolumeID: volumeID, - Path: path, - Impl: impl, - ReplicaID: id.ReplicaID, - Epoch: id.Epoch, - EndpointVersion: id.EndpointVersion, - Latched: id.Epoch > 0 && id.EndpointVersion > 0, - Operational: b.operational.Load(), - FrontierKnown: true, - DurableLSN: durableLSN, - RetainedLSN: retainedLSN, - HeadLSN: headLSN, - Evidence: evidence, - Closed: closed, - WriteProfile: writeProfile, + Warnings: warnings, + HolesSuspected: holes, + VolumeID: volumeID, + Path: path, + Impl: impl, + ReplicaID: id.ReplicaID, + Epoch: id.Epoch, + EndpointVersion: id.EndpointVersion, + Latched: id.Epoch > 0 && id.EndpointVersion > 0, + Operational: b.operational.Load(), + FrontierKnown: true, + DurableLSN: durableLSN, + RetainedLSN: retainedLSN, + HeadLSN: headLSN, + Evidence: evidence, + Closed: closed, + WriteProfile: writeProfile, + CheckpointPersistence: checkpoint, } } diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go new file mode 100644 index 0000000000..2fc3fd3af5 --- /dev/null +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -0,0 +1,64 @@ +package storage + +import ( + "errors" + "log" + "time" +) + +// CheckpointPersistenceStatus counts flusher checkpoint calls in this open. +// Success includes a safely clamped/unchanged checkpoint; it is not a slot-write +// count. Fields are cumulative atomic observations, not a coherent frontier. +type CheckpointPersistenceStatus struct { + Successes uint64 + Refusals uint64 + Failures uint64 +} + +func (s *WALStore) CheckpointPersistence() CheckpointPersistenceStatus { + if s.flusher == nil { + return CheckpointPersistenceStatus{} + } + i := &s.flusher.instr + return CheckpointPersistenceStatus{i.checkpointSuccesses.Load(), i.checkpointRefusals.Load(), i.checkpointFailures.Load()} +} + +func (i *flusherInstrumentation) recordCheckpoint(err error) { + switch { + case err == nil: + i.checkpointSuccesses.Add(1) + case errors.Is(err, ErrMapCoverageStale): + i.checkpointRefusals.Add(1) + default: + i.checkpointFailures.Add(1) + } +} + +type mapCoverageRefusal string + +func (r mapCoverageRefusal) Error() string { return ErrMapCoverageStale.Error() + ": " + string(r) } +func (r mapCoverageRefusal) Unwrap() error { return ErrMapCoverageStale } + +// Owned exclusively by the flusher run loop; no storage lock or I/O ordering +// changes. Terminal errors are never rate limited. +type checkpointLogLimiter struct { + last time.Time + suppressed uint64 +} + +func (l *checkpointLogLimiter) report(err error, now time.Time) { + if !errors.Is(err, ErrMapCoverageStale) { + log.Printf("storage: flusher: %v", err) + return + } + if !l.last.IsZero() && now.Sub(l.last) < 30*time.Second { + l.suppressed++ + return + } + var reason mapCoverageRefusal + if !errors.As(err, &reason) { + reason = "unspecified" + } + log.Printf("storage: flusher: checkpoint deferred reason=%s suppressed=%d: %v", reason, l.suppressed, err) + l.last, l.suppressed = now, 0 +} diff --git a/seaweed-block/core/storage/checkpoint_diagnostics_test.go b/seaweed-block/core/storage/checkpoint_diagnostics_test.go index d811d47dde..2670beb977 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics_test.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics_test.go @@ -1,14 +1,19 @@ package storage import ( + "bytes" "encoding/json" "errors" + "fmt" + "log" "strings" "testing" + "time" ) func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) { s, _ := newMappedCheckpointStoreV3(t) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) writeSynced(t, s, 1, 1) s.v3.testMapPrepared = func() { if _, err := s.Write(2, blk(2)); err != nil { @@ -49,3 +54,65 @@ func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) { t.Fatalf("retry counters/state: %s cp=%d", raw, s.CheckpointLSN()) } } + +func TestCheckpointDiagnostics_PrepareRefusalAndIOFailure(t *testing.T) { + for _, fault := range []bool{false, true} { + t.Run(fmt.Sprint(fault), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + writeSynced(t, s, 1, 1) + realSync := s.v3.ownedMap.syncFile + injected := errors.New("checkpoint map fsync fault") + once := false + s.v3.ownedMap.syncFile = func() error { + if fault { + return injected + } + if !once { + once = true + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + } + return realSync() + } + err := s.flusher.flushOnce() + got := s.CheckpointPersistence() + if fault { + if !errors.Is(err, injected) || got.Failures != 1 || got.Refusals != 0 || s.stickyIOFault() == nil { + t.Fatalf("fault %v counts=%+v", err, got) + } + } else { + if !errors.Is(err, ErrMapCoverageStale) || !strings.Contains(err.Error(), "proof_changed_during_prepare") || got.Refusals != 1 || got.Failures != 0 || s.stickyIOFault() != nil { + t.Fatalf("refusal %v counts=%+v", err, got) + } + } + if got.Successes != 0 || s.CheckpointLSN() != 0 || s.dm.len() == 0 { + t.Fatal("failed checkpoint advanced or lost retry ownership") + } + }) + } +} + +func TestCheckpointDiagnostics_LogRateLimit(t *testing.T) { + var out bytes.Buffer + old := log.Writer() + log.SetOutput(&out) + t.Cleanup(func() { log.SetOutput(old) }) + var limiter checkpointLogLimiter + now := time.Unix(100, 0) + stale := fmt.Errorf("persist checkpoint: %w", mapCoverageRefusal("proof_changed")) + limiter.report(stale, now) + for i := 0; i < 5; i++ { + limiter.report(stale, now.Add(time.Second)) + } + // A terminal failure must remain visible while refusals are suppressed. + terminal := errors.New("real fsync fault") + limiter.report(terminal, now.Add(2*time.Second)) + limiter.report(terminal, now.Add(3*time.Second)) + limiter.report(stale, now.Add(30*time.Second)) + got := out.String() + if strings.Count(got, "checkpoint deferred") != 2 || strings.Count(got, "real fsync fault") != 2 || !strings.Contains(got, "reason=proof_changed suppressed=5") { + t.Fatalf("logs: %s", got) + } +} diff --git a/seaweed-block/core/storage/chunk_map_publication_v3.go b/seaweed-block/core/storage/chunk_map_publication_v3.go index 8869949475..2ef10237b2 100644 --- a/seaweed-block/core/storage/chunk_map_publication_v3.go +++ b/seaweed-block/core/storage/chunk_map_publication_v3.go @@ -57,7 +57,7 @@ type preparedMapPublicationV3 struct { // Preparation takes the sidecar mutex and I/O only, before store/desc locks. func prepareMapPublicationV3(m *chunkLSNMapV3, d *mapProofEpochV3, g, C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (*preparedMapPublicationV3, error) { if m == nil || d == nil { - return nil, ErrMapCoverageStale + return nil, mapCoverageRefusal("map_binding_missing") } proof := d.snapshotV3() c, e := m.Prepare(g, C, entries, prior) @@ -66,7 +66,7 @@ func prepareMapPublicationV3(m *chunkLSNMapV3, d *mapProofEpochV3, g, C uint64, } if !proof.validV3(d) { m.abandonCandidateV3(c) // prepared but never publishable - return nil, ErrMapCoverageStale + return nil, mapCoverageRefusal("proof_changed_during_prepare") } return &preparedMapPublicationV3{candidate: c, proof: proof}, nil } @@ -84,13 +84,13 @@ func sameMapTupleV3(d descriptorV3, c *chunkMapCandidateV3) bool { // even when none of its pages belong to the selected generation. func (p *descriptorPublisherV3) bindMapV3(c *chunkMapCandidateV3, d *mapProofEpochV3) error { if c == nil || c.owner == nil || d == nil { - return ErrMapCoverageStale + return mapCoverageRefusal("map_binding_missing") } p.descMu.Lock() current, other, otherValid := p.cur, p.other, p.otherValid p.descMu.Unlock() if !sameMapTupleV3(current, c) { - return ErrMapCoverageStale + return mapCoverageRefusal("map_tuple_changed") } if _, _, e := readChunkLSNMapV3(c.owner.fd, current, c.owner.chunkBlocks); e != nil { return e @@ -106,7 +106,7 @@ func (p *descriptorPublisherV3) bindMapV3(c *chunkMapCandidateV3, d *mapProofEpo p.descMu.Lock() defer p.descMu.Unlock() if p.cur != current || p.otherValid != otherValid || (otherValid && p.other != other) { - return ErrMapCoverageStale + return mapCoverageRefusal("descriptor_changed_during_bind") } p.mapCurrent = c p.mapDomain = d @@ -115,7 +115,7 @@ func (p *descriptorPublisherV3) bindMapV3(c *chunkMapCandidateV3, d *mapProofEpo func (p *descriptorPublisherV3) validateMapPublicationV3(next descriptorV3, prepared *preparedMapPublicationV3) error { if p.mapCurrent == nil { if prepared != nil { - return ErrMapCoverageStale + return mapCoverageRefusal("map_not_bound") } return nil } // dark core not bound yet @@ -123,20 +123,20 @@ func (p *descriptorPublisherV3) validateMapPublicationV3(next descriptorV3, prep if prepared != nil { c = prepared.candidate if c == nil || c.owner != p.mapCurrent.owner || !prepared.proof.validV3(p.mapDomain) { - return ErrMapCoverageStale + return mapCoverageRefusal("proof_changed") } if c.generation <= p.mapCurrent.generation || c.covered < p.mapCurrent.covered { - return ErrMapCoverageStale + return mapCoverageRefusal("candidate_superseded") } } if !sameMapTupleV3(next, c) || c.covered < next.CheckpointLSN || c.covered > next.W { - return ErrMapCoverageStale + return mapCoverageRefusal("map_coverage_mismatch") } return nil } func (p *descriptorPublisherV3) publishMapV3(storeMu sync.Locker, snap func(), prepared *preparedMapPublicationV3, mutate func(*descriptorV3) error) (descriptorV3, error) { if prepared == nil || prepared.candidate == nil { - return descriptorV3{}, ErrMapCoverageStale + return descriptorV3{}, mapCoverageRefusal("candidate_missing") } d, err := p.publishWithMapV3(storeMu, snap, func(d *descriptorV3) error { if mutate != nil { diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index 6d52d7bf24..930e057a89 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -3,7 +3,6 @@ package storage import ( "encoding/binary" "fmt" - "log" "sort" "sync" "sync/atomic" @@ -111,6 +110,7 @@ func (f *flusher) runWithStartSignal(started chan<- struct{}) { if started != nil { close(started) } + var diagnostics checkpointLogLimiter for { select { case <-f.stopCh: @@ -120,11 +120,11 @@ func (f *flusher) runWithStartSignal(started chan<- struct{}) { return case <-ticker.C: if err := f.flushOnce(); err != nil { - log.Printf("storage: flusher: %v", err) + diagnostics.report(err, time.Now()) } case <-f.notifyCh: if err := f.flushOnce(); err != nil { - log.Printf("storage: flusher (notify): %v", err) + diagnostics.report(err, time.Now()) } } } @@ -283,6 +283,7 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { } else { publishErr = store.persistCheckpointAndRelease(maxLSN, maxLSNPhys, maxLSNEntrySize) } + f.instr.recordCheckpoint(publishErr) if err := publishErr; err != nil { return fmt.Errorf("flusher: persist checkpoint %d: %w", maxLSN, err) } @@ -313,7 +314,7 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { store.mu.Lock() if !store.v3.flushLifetimeValidV3(recoveryGen) { store.mu.Unlock() - return ErrMapCoverageStale + return mapCoverageRefusal("recovery_lifetime_changed") } checkpoint = store.checkpointLSN if checkpoint >= maxLSN && maxLSN+1 > store.walTail { diff --git a/seaweed-block/core/storage/flusher_instrumentation.go b/seaweed-block/core/storage/flusher_instrumentation.go index 3d7cf587fb..ec3fcf1827 100644 --- a/seaweed-block/core/storage/flusher_instrumentation.go +++ b/seaweed-block/core/storage/flusher_instrumentation.go @@ -12,6 +12,9 @@ const maxCheckpointWriteBytes = 1 << 20 // checkpoint work. Operation counters include failed attempts; byte counters // include only successful writes. type FlusherInstrumentationStatus struct { + CheckpointSuccesses uint64 + CheckpointRefusals uint64 + CheckpointFailures uint64 CyclesStarted uint64 CyclesSucceeded uint64 CyclesFailed uint64 @@ -63,6 +66,9 @@ type FlusherInstrumentationStatus struct { } type flusherInstrumentation struct { + checkpointSuccesses atomic.Uint64 + checkpointRefusals atomic.Uint64 + checkpointFailures atomic.Uint64 cyclesStarted atomic.Uint64 cyclesSucceeded atomic.Uint64 cyclesFailed atomic.Uint64 @@ -284,6 +290,9 @@ func updateAtomicMax(target *atomic.Uint64, value uint64) { func (i *flusherInstrumentation) snapshot() FlusherInstrumentationStatus { return FlusherInstrumentationStatus{ + CheckpointSuccesses: i.checkpointSuccesses.Load(), + CheckpointRefusals: i.checkpointRefusals.Load(), + CheckpointFailures: i.checkpointFailures.Load(), CyclesStarted: i.cyclesStarted.Load(), CyclesSucceeded: i.cyclesSucceeded.Load(), CyclesFailed: i.cyclesFailed.Load(), diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index 3b9fe9aca1..a21d4f86a0 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -33,7 +33,7 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati if prior == nil || prior.owner != v.ownedMap || domain != v.mapProof { v.pub.descMu.Unlock() s.mu.RUnlock() - return nil, ErrMapCoverageStale + return nil, mapCoverageRefusal("map_binding_changed") } proof := domain.snapshotV3() // Entries may already contain LSNs above cp from earlier appends: max-LSN @@ -47,7 +47,7 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati } if !proof.validV3(domain) { v.ownedMap.abandonCandidateV3(c) // prepared but never publishable - return nil, ErrMapCoverageStale + return nil, mapCoverageRefusal("proof_changed_during_prepare") } return &preparedMapPublicationV3{candidate: c, proof: proof}, nil } @@ -72,7 +72,7 @@ func (s *WALStore) persistOwnedMapCheckpointV3(highestLSN, recoveryGen uint64) e s.mu.Lock() defer s.mu.Unlock() if !v.flushLifetimeValidV3(recoveryGen) { - return ErrMapCoverageStale + return mapCoverageRefusal("recovery_lifetime_changed") } return s.rolloverCheckpointV3Locked() } @@ -120,7 +120,7 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) // I/O and could belong to a newer Recover lifetime than those bytes. if !v.flushLifetimeValidV3(recoveryGen) { prepared.abandonV3() - return descriptorV3{}, ErrMapCoverageStale + return descriptorV3{}, mapCoverageRefusal("recovery_lifetime_changed") } wack := v.wack.Load() if seed { @@ -128,7 +128,7 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) } if wack < cp { prepared.abandonV3() - return descriptorV3{}, ErrMapCoverageStale + return descriptorV3{}, mapCoverageRefusal("checkpoint_above_wack") } s.mu.RLock() retention := s.recoveryRetentionLSNs From b97352083ae9dc508d30975d30fb22cd36e5d6c4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:53:32 -0800 Subject: [PATCH 075/150] storage: print the stable checkpoint refusal reason --- seaweed-block/core/storage/checkpoint_diagnostics.go | 2 +- seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go index 2fc3fd3af5..46aa71e185 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -59,6 +59,6 @@ func (l *checkpointLogLimiter) report(err error, now time.Time) { if !errors.As(err, &reason) { reason = "unspecified" } - log.Printf("storage: flusher: checkpoint deferred reason=%s suppressed=%d: %v", reason, l.suppressed, err) + log.Printf("storage: flusher: checkpoint deferred reason=%s suppressed=%d: %v", string(reason), l.suppressed, err) l.last, l.suppressed = now, 0 } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index aef36d1bbf..4592eb7d82 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -63,7 +63,7 @@ stateDiagram-v2 | FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | | any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | -Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. +Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestCheckpointDiagnostics_RefusalThenSuccess`, `TestCheckpointDiagnostics_PrepareRefusalAndIOFailure`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. Public walstore Create now selects mapped format v3/impl3 (mode C by default, mode A by create option). Open and offline readonly use A/B slot and owned-map validation; valid legacy formats are refused with `ErrUnsupportedLegacyFormat`, rather than silently retrofitted. The temporary old-engine/raw-codec test scope and every named native replacement are recorded in [the legacy inventory](format-v3-legacy-test-inventory.md). Native recovery validates nonce/cursor binding and a contiguous physical LSN prefix before applying the mode-specific W rule; an acknowledged-range integrity failure blocks startup. The provider's create geometry, auto probe, capture, HEAD restore and readonly/status controls exercise the public selector (`INV-WAL-V3-ACTIVATION-001`). Before reading v3 slots, both read/write and offline read-only open acquire an exclusive nonblocking file lock; the offline migration CLI acquires the same lock before any descriptor read or mutation (`INV-WAL-V3-OWNER-001`). Contention refuses open/migration without changing bytes; descriptor close or process exit releases ownership. This implements the existing offline-migration precondition, not a new serving state. The mapped v3 checkpoint also carries a complete-record physical tail through the covered LSN minus the configured retention window; partial batches remain retained. The existing sole publisher then performs metadata-only rollover when the fallback still pins that prefix. Reuse still requires both valid same-nonce slot tails and retirement of checkpointed dirty references under writer exclusion; idle, unchanged-checkpoint and admission paths also settle a pinned fallback. An unlocked catch-up scan revalidates the coherent checkpoint and tail before emitting anything. A failed rollover latches and grants no reuse (`INV-WAL-V3-RECLAIM-001`). From d6023969a06ab7930a32ff6e316bee897446a79c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:54:29 -0800 Subject: [PATCH 076/150] storage: distinguish recovery and map generation refusals --- .../core/host/volume/status_server_test.go | 24 ++++++++++++------- seaweed-block/core/storage/descriptor_v3.go | 2 +- seaweed-block/core/storage/walstore_v3.go | 4 ++-- 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/host/volume/status_server_test.go b/seaweed-block/core/host/volume/status_server_test.go index 50fffb65d1..cbdf18d3eb 100644 --- a/seaweed-block/core/host/volume/status_server_test.go +++ b/seaweed-block/core/host/volume/status_server_test.go @@ -7,6 +7,7 @@ import ( "bytes" "context" "encoding/json" + "github.com/seaweedfs/seaweed-block/core/storage" "net/http" "net/http/httptest" "strings" @@ -981,15 +982,16 @@ func TestStatusServer_DurableStatusEndpoint_EnabledAfterStart_ReturnsLineage(t * } defer func() { _ = s.Close(context.Background()) }() s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{ - VolumeID: "v1", - Path: "/tmp/v1.bin", - Impl: "smartwal", - ReplicaID: "r1", - Epoch: 1, - EndpointVersion: 1, - Latched: true, - Operational: true, - Evidence: "recovered LSN=0", + VolumeID: "v1", + Path: "/tmp/v1.bin", + Impl: "smartwal", + ReplicaID: "r1", + Epoch: 1, + EndpointVersion: 1, + Latched: true, + Operational: true, + Evidence: "recovered LSN=0", + CheckpointPersistence: &storage.CheckpointPersistenceStatus{Successes: 3, Refusals: 2, Failures: 1}, }}}) resp, err := http.Get("http://" + addr + "/status/durable?volume=v1") @@ -1015,6 +1017,10 @@ func TestStatusServer_DurableStatusEndpoint_EnabledAfterStart_ReturnsLineage(t * if len(body.Volumes) != 1 || !body.Volumes[0].Latched || !body.Volumes[0].Operational || body.Volumes[0].Epoch != 1 { t.Fatalf("unexpected durable volume body: %+v", body.Volumes) } + checkpoint := body.Volumes[0].CheckpointPersistence + if checkpoint == nil || checkpoint.Successes != 3 || checkpoint.Refusals != 2 || checkpoint.Failures != 1 { + t.Fatalf("checkpoint counters missing from HTTP response: %+v", checkpoint) + } } func TestG9B_StatusProjection_ReturnedReplicaCanBeDurableReadyButFrontendNotReady(t *testing.T) { diff --git a/seaweed-block/core/storage/descriptor_v3.go b/seaweed-block/core/storage/descriptor_v3.go index 1300ef199a..62310d03a4 100644 --- a/seaweed-block/core/storage/descriptor_v3.go +++ b/seaweed-block/core/storage/descriptor_v3.go @@ -332,7 +332,7 @@ func mergeDescriptorV3Mode(cur, next *descriptorV3, reset bool) error { next.MapLineage != cur.MapLineage || next.MapFormatID != cur.MapFormatID { if next.MapGeneration <= cur.MapGeneration { return fmt.Errorf("%w: %w: map root change without a higher generation (%d -> %d)", - ErrMapCoverageStale, errDescriptorTransition, cur.MapGeneration, next.MapGeneration) + mapCoverageRefusal("map_generation_not_increasing"), errDescriptorTransition, cur.MapGeneration, next.MapGeneration) } if next.MapLineage != cur.MapLineage { return fmt.Errorf("%w: map lineage change outside an install or reset", errDescriptorTransition) diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 8691653109..cf6f2cdbc7 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -1091,7 +1091,7 @@ func (f *flusher) readDirtyRecordV3Cached(e snapshotEntry, cache *flushRecordCac store := f.store d := store.v3.pub.current() if cache != nil && !store.v3.flushLifetimeValidV3(cache.recoveryGen) { - return nil, 0, ErrMapCoverageStale + return nil, 0, mapCoverageRefusal("recovery_lifetime_changed") } var entry walEntryV3 var size uint64 @@ -1160,7 +1160,7 @@ func (s *WALStore) persistCheckpointV3(highestLSN, recoveryGen uint64) error { v.syncMu.Lock() defer v.syncMu.Unlock() if !v.flushLifetimeValidV3(recoveryGen) { - return ErrMapCoverageStale + return mapCoverageRefusal("recovery_lifetime_changed") } wack := v.wack.Load() if wack < checkpoint { From 4129cc3668a7bf828040c49b998bf676bf75ac65 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:45:22 -0800 Subject: [PATCH 077/150] test(storage): compose checkpoint diagnostics with prefix and extent guards --- seaweed-block/core/storage/checkpoint_diagnostics_test.go | 7 +++++++ seaweed-block/core/storage/chunk_map_extents_v3_test.go | 5 +++-- seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_diagnostics_test.go b/seaweed-block/core/storage/checkpoint_diagnostics_test.go index 2670beb977..9bdba0daf2 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics_test.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics_test.go @@ -19,6 +19,10 @@ func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) { if _, err := s.Write(2, blk(2)); err != nil { t.Fatal(err) } + // Simulate the effective-mutation class; newer WAL appends alone are safe. + if err := s.v3.mapProof.mutatedV3(); err != nil { + t.Fatal(err) + } } before := s.v3.pub.current() err := s.flusher.flushOnce() @@ -73,6 +77,9 @@ func TestCheckpointDiagnostics_PrepareRefusalAndIOFailure(t *testing.T) { if _, err := s.Write(2, blk(2)); err != nil { t.Fatal(err) } + if err := s.v3.mapProof.mutatedV3(); err != nil { + t.Fatal(err) + } } return realSync() } diff --git a/seaweed-block/core/storage/chunk_map_extents_v3_test.go b/seaweed-block/core/storage/chunk_map_extents_v3_test.go index 72cf43e1af..e920af07a0 100644 --- a/seaweed-block/core/storage/chunk_map_extents_v3_test.go +++ b/seaweed-block/core/storage/chunk_map_extents_v3_test.go @@ -1,6 +1,7 @@ package storage import ( + "errors" "os" "path/filepath" "testing" @@ -430,7 +431,7 @@ func TestChunkMapExtentsV3ProofStalePreparesStayBounded(t *testing.T) { } cp := s.v3.pub.current().CheckpointLSN for i := 0; i < 150; i++ { - if _, err := s.prepareOwnedMapCheckpointV3(cp); err != ErrMapCoverageStale { + if _, err := s.prepareOwnedMapCheckpointV3(cp); !errors.Is(err, ErrMapCoverageStale) { t.Fatalf("checkpoint prepare %d: err = %v, want ErrMapCoverageStale", i, err) } } @@ -438,7 +439,7 @@ func TestChunkMapExtentsV3ProofStalePreparesStayBounded(t *testing.T) { for i := 0; i < 150; i++ { g += 1000 entries := append([]chunkLSNEntryV3(nil), s.v3.mapEntries...) - if _, err := prepareMapPublicationV3(m, s.v3.mapProof, g, cp, entries, nil); err != ErrMapCoverageStale { + if _, err := prepareMapPublicationV3(m, s.v3.mapProof, g, cp, entries, nil); !errors.Is(err, ErrMapCoverageStale) { t.Fatalf("publication prepare %d: err = %v, want ErrMapCoverageStale", i, err) } } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 4592eb7d82..3f27e03cc6 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -335,7 +335,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | | `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | From 2aebe5f044dd812ba6215dbae30dcbba6d42c3de Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:47:20 -0800 Subject: [PATCH 078/150] test(chunkstore): refuse changed content at identical legacy frontier --- .../chunkstore/format_legacy_upgrade_test.go | 435 +++++++++--------- 1 file changed, 222 insertions(+), 213 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go b/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go index 83286ec9ac..ee4a1779e2 100644 --- a/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go +++ b/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go @@ -1,213 +1,222 @@ -package chunkstore - -import ( - "bytes" - "context" - "encoding/json" - "os" - "path" - "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" -) - -// Frozen output of the pre-format-3 CreateSnapshot/Fork producers at 3401cc60. -func preF4ForkFixture(t *testing.T, segmented bool) (*fakeFiler, *Catalog, *ChunkRemote) { - t.Helper() - suffix := "false" - if segmented { - suffix = "true" - } - data, err := os.ReadFile("testdata/pre_f4_fork_" + suffix + ".json") - if err != nil { - t.Fatal(err) - } - var frozen struct { - Entries map[string]*filerpb.Entry - Objects map[string][]byte - } - if err := json.Unmarshal(data, &frozen); err != nil { - t.Fatal(err) - } - f, b := newFakeFiler(), newFakeBlobs() - f.entries = frozen.Entries - c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) - if err != nil { - t.Fatal(err) - } - c.now = func() time.Time { return time.Unix(1000, 0) } - r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err != nil { - t.Fatal(err) - } - if err := r.Put(context.Background(), "legacy-data", bytes.Repeat([]byte{0x41}, 8*4096)); err != nil { - t.Fatal(err) - } - for key, body := range frozen.Objects { - if err := r.Put(context.Background(), key, body); err != nil { - t.Fatal(err) - } - } - return f, c, r -} -func assertLegacyImage(t *testing.T, r *ChunkRemote) { - t.Helper() - h, err := r.GetHead(context.Background()) - if err != nil { - t.Fatal(err) - } - if h.RemoteLSN != 7 || len(h.Chunks) != 1 { - t.Fatalf("legacy image/frontier lost: %+v", h) - } - data, err := r.Get(context.Background(), h.Chunks[0].Key) - if err != nil || !bytes.Equal(data, bytes.Repeat([]byte{0x41}, 8*4096)) { - t.Fatalf("legacy bytes changed: %v", err) - } -} -func TestFormatUpgradeLegacyIncompleteFork(t *testing.T) { - for _, segmented := range []bool{false, true} { - name := "flat" - if segmented { - name = "segmented" - } - t.Run(name, func(t *testing.T) { - f, c, r := preF4ForkFixture(t, segmented) - _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}) - if err != nil { - t.Fatalf("old incomplete fork retry: %v", err) - } - dst, err := NewChunkRemote(f, r.b, path.Join(catBase, "v2")) - if err != nil { - t.Fatal(err) - } - assertLegacyImage(t, dst) - e, err := f.LookupEntry(context.Background(), path.Join(catBase, "v2"), headName) - if err != nil { - t.Fatal(err) - } - var doc struct{ Format int } - if json.Unmarshal(e.Content, &doc) != nil || doc.Format != 3 { - t.Fatal("fork data must be format3") - } - }) - } -} -func TestFormatUpgradeLegacyForkIdentityStillRefusesChangedImage(t *testing.T) { - for _, segmented := range []bool{false, true} { - t.Run(map[bool]string{false: "flat", true: "segmented"}[segmented], func(t *testing.T) { - f, c, _ := preF4ForkFixture(t, segmented) - p := snapPath(t, f, "v1", "s1") - var s snapDoc - if err := json.Unmarshal(f.entries[p].Content, &s); err != nil { - t.Fatal(err) - } - var h map[string]any - if err := json.Unmarshal(s.Head, &h); err != nil { - t.Fatal(err) - } - h["remote_lsn"] = float64(8) - s.Head, _ = json.Marshal(h) - f.entries[p].Content, _ = json.Marshal(s) - if _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}); CodeOf(err) != CodeTargetExists { - t.Fatalf("changed image admitted or identity not reached: %v", err) - } - }) - } -} -func TestFormatUpgradeLegacySnapshotAndDelete(t *testing.T) { - t.Run("snapshot", func(t *testing.T) { - f, c, r := preF4ForkFixture(t, false) - h, err := r.GetHead(context.Background()) - if err != nil { - t.Fatal(err) - } - if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "upgraded", RequestID: "new-snapshot"}, h); err != nil { - t.Fatalf("legacy snapshot: %v", err) - } - e := f.entries[snapPath(t, f, "v1", "upgraded")] - var s snapDoc - if err := json.Unmarshal(e.Content, &s); err != nil { - t.Fatal(err) - } - var doc struct{ Format int } - json.Unmarshal(s.Head, &doc) - if doc.Format != 3 { - t.Fatal("snapshot contains flat data") - } - assertLegacyImage(t, r) - }) - t.Run("delete", func(t *testing.T) { - f, c, r := preF4ForkFixture(t, false) - for p := range f.entries { - if p != path.Join(catBase, "v1", headName) && p != path.Join(catBase, "v1", volumeName) && !bytes.Contains([]byte(p), []byte("/keys/")) { - delete(f.entries, p) - } - } - h, err := r.GetHead(context.Background()) - if err != nil { - t.Fatal(err) - } - h.Holder = "" - h.Epoch = 0 - f.entries[path.Join(catBase, "v1", headName)] = legacyHeadFixture(t, h) - c.retainHook = func(stage, _ string) { - if stage == hookHeadMarked { - assertLegacyImage(t, r) - e := f.entries[path.Join(catBase, "v1", headName)] - var d struct{ Format int } - json.Unmarshal(e.Content, &d) - if d.Format != 3 { - t.Fatal("delete mark contains flat data") - } - } - } - res, err := c.DeleteVolume(context.Background(), "v1", nil) - if err != nil || !res.Completed { - t.Fatalf("legacy delete: %+v %v", res, err) - } - }) -} - -type legacyUpgradeView struct{} - -func (legacyUpgradeView) Projection() frontend.Projection { - return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, Healthy: true} -} -func TestFormatUpgradeLegacyProviderTakeover(t *testing.T) { - f, _, r := preF4ForkFixture(t, false) - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-new/r1", ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, legacyUpgradeView{}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { p.Close() }) - s, err := p.EnsureStorage("v1") - if err != nil { - t.Fatal(err) - } - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if _, err := p.RecoverVolume(ctx, "v1"); err != nil { - t.Fatalf("legacy provider takeover: %v", err) - } - h, err := r.GetHead(ctx) - if err != nil || h.Holder != "node-new/r1" || h.Epoch != 2 { - t.Fatalf("takeover not installed: %+v %v", h, err) - } - e := f.entries[path.Join(catBase, "v1", headName)] - var d struct{ Format int } - json.Unmarshal(e.Content, &d) - if d.Format != 3 { - t.Fatal("takeover wrote flat data") - } - for i := uint32(0); i < 8; i++ { - got, err := s.Read(i) - if err != nil || !bytes.Equal(got, bytes.Repeat([]byte{0x41}, 4096)) { - t.Fatalf("takeover bytes %d: %v", i, err) - } - } - assertLegacyImage(t, r) -} +package chunkstore + +import ( + "bytes" + "context" + "encoding/json" + "os" + "path" + "strings" + "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" +) + +// Frozen output of the pre-format-3 CreateSnapshot/Fork producers at 3401cc60. +func preF4ForkFixture(t *testing.T, segmented bool) (*fakeFiler, *Catalog, *ChunkRemote) { + t.Helper() + suffix := "false" + if segmented { + suffix = "true" + } + data, err := os.ReadFile("testdata/pre_f4_fork_" + suffix + ".json") + if err != nil { + t.Fatal(err) + } + var frozen struct { + Entries map[string]*filerpb.Entry + Objects map[string][]byte + } + if err := json.Unmarshal(data, &frozen); err != nil { + t.Fatal(err) + } + f, b := newFakeFiler(), newFakeBlobs() + f.entries = frozen.Entries + c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) + if err != nil { + t.Fatal(err) + } + c.now = func() time.Time { return time.Unix(1000, 0) } + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + if err := r.Put(context.Background(), "legacy-data", bytes.Repeat([]byte{0x41}, 8*4096)); err != nil { + t.Fatal(err) + } + for key, body := range frozen.Objects { + if err := r.Put(context.Background(), key, body); err != nil { + t.Fatal(err) + } + } + return f, c, r +} +func assertLegacyImage(t *testing.T, r *ChunkRemote) { + t.Helper() + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if h.RemoteLSN != 7 || len(h.Chunks) != 1 { + t.Fatalf("legacy image/frontier lost: %+v", h) + } + data, err := r.Get(context.Background(), h.Chunks[0].Key) + if err != nil || !bytes.Equal(data, bytes.Repeat([]byte{0x41}, 8*4096)) { + t.Fatalf("legacy bytes changed: %v", err) + } +} +func TestFormatUpgradeLegacyIncompleteFork(t *testing.T) { + for _, segmented := range []bool{false, true} { + name := "flat" + if segmented { + name = "segmented" + } + t.Run(name, func(t *testing.T) { + f, c, r := preF4ForkFixture(t, segmented) + _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}) + if err != nil { + t.Fatalf("old incomplete fork retry: %v", err) + } + dst, err := NewChunkRemote(f, r.b, path.Join(catBase, "v2")) + if err != nil { + t.Fatal(err) + } + assertLegacyImage(t, dst) + e, err := f.LookupEntry(context.Background(), path.Join(catBase, "v2"), headName) + if err != nil { + t.Fatal(err) + } + var doc struct{ Format int } + if json.Unmarshal(e.Content, &doc) != nil || doc.Format != 3 { + t.Fatal("fork data must be format3") + } + }) + } +} +func TestFormatUpgradeLegacyForkIdentityStillRefusesChangedImage(t *testing.T) { + for _, segmented := range []bool{false, true} { + t.Run(map[bool]string{false: "flat", true: "segmented"}[segmented], func(t *testing.T) { + f, c, _ := preF4ForkFixture(t, segmented) + p := snapPath(t, f, "v1", "s1") + var s snapDoc + if err := json.Unmarshal(f.entries[p].Content, &s); err != nil { + t.Fatal(err) + } + var h map[string]any + if err := json.Unmarshal(s.Head, &h); err != nil { + t.Fatal(err) + } + // Preserve generation/frontier: only immutable content identity changes. + if segmented { + ref := h["segments"].(map[string]any)["0"].(map[string]any) + sum := ref["sha256"].([]any) + sum[0] = float64((int(sum[0].(float64)) + 1) % 256) + } else { + ref := h["chunks"].(map[string]any)["0"].(map[string]any) + ref["sha256"] = strings.Repeat("0", 64) + } + s.Head, _ = json.Marshal(h) + f.entries[p].Content, _ = json.Marshal(s) + if _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}); CodeOf(err) != CodeTargetExists { + t.Fatalf("changed image admitted or identity not reached: %v", err) + } + }) + } +} +func TestFormatUpgradeLegacySnapshotAndDelete(t *testing.T) { + t.Run("snapshot", func(t *testing.T) { + f, c, r := preF4ForkFixture(t, false) + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "upgraded", RequestID: "new-snapshot"}, h); err != nil { + t.Fatalf("legacy snapshot: %v", err) + } + e := f.entries[snapPath(t, f, "v1", "upgraded")] + var s snapDoc + if err := json.Unmarshal(e.Content, &s); err != nil { + t.Fatal(err) + } + var doc struct{ Format int } + json.Unmarshal(s.Head, &doc) + if doc.Format != 3 { + t.Fatal("snapshot contains flat data") + } + assertLegacyImage(t, r) + }) + t.Run("delete", func(t *testing.T) { + f, c, r := preF4ForkFixture(t, false) + for p := range f.entries { + if p != path.Join(catBase, "v1", headName) && p != path.Join(catBase, "v1", volumeName) && !bytes.Contains([]byte(p), []byte("/keys/")) { + delete(f.entries, p) + } + } + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + h.Holder = "" + h.Epoch = 0 + f.entries[path.Join(catBase, "v1", headName)] = legacyHeadFixture(t, h) + c.retainHook = func(stage, _ string) { + if stage == hookHeadMarked { + assertLegacyImage(t, r) + e := f.entries[path.Join(catBase, "v1", headName)] + var d struct{ Format int } + json.Unmarshal(e.Content, &d) + if d.Format != 3 { + t.Fatal("delete mark contains flat data") + } + } + } + res, err := c.DeleteVolume(context.Background(), "v1", nil) + if err != nil || !res.Completed { + t.Fatalf("legacy delete: %+v %v", res, err) + } + }) +} + +type legacyUpgradeView struct{} + +func (legacyUpgradeView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, Healthy: true} +} +func TestFormatUpgradeLegacyProviderTakeover(t *testing.T) { + f, _, r := preF4ForkFixture(t, false) + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-new/r1", ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, legacyUpgradeView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatalf("legacy provider takeover: %v", err) + } + h, err := r.GetHead(ctx) + if err != nil || h.Holder != "node-new/r1" || h.Epoch != 2 { + t.Fatalf("takeover not installed: %+v %v", h, err) + } + e := f.entries[path.Join(catBase, "v1", headName)] + var d struct{ Format int } + json.Unmarshal(e.Content, &d) + if d.Format != 3 { + t.Fatal("takeover wrote flat data") + } + for i := uint32(0); i < 8; i++ { + got, err := s.Read(i) + if err != nil || !bytes.Equal(got, bytes.Repeat([]byte{0x41}, 4096)) { + t.Fatalf("takeover bytes %d: %v", i, err) + } + } + assertLegacyImage(t, r) +} From fcf5dc72d7ead9e0b46b530ba7d3df7334cfbf96 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:49:51 -0800 Subject: [PATCH 079/150] storage: decide unheld on one locked descriptor Fold of the #258 review: - the probe opens the volume once, locks that descriptor first, then identifies the same open file as v3: a path replaced between two opens can no longer yield a false unheld, and a locked file is held whatever it is; - locking before reading also fixes Windows, where an owner's byte lock refused the probe's earlier read (it reported unknown, not held); - the test reaps its holder process on every path; the CLI test closes its store unconditionally; - the usage text adds that the probe is momentary and reserves nothing. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/volume_unheld.go | 4 +++ .../cmd/sw-block/volume_unheld_test.go | 9 ++++- seaweed-block/core/storage/volume_unheld.go | 30 +++++++++++----- .../core/storage/volume_unheld_test.go | 36 +++++++++++++++++-- seaweed-block/core/storage/walstore_v3.go | 11 ++++-- 5 files changed, 75 insertions(+), 15 deletions(-) diff --git a/seaweed-block/cmd/sw-block/volume_unheld.go b/seaweed-block/cmd/sw-block/volume_unheld.go index 8d72c84b1f..81d2c12d0e 100644 --- a/seaweed-block/cmd/sw-block/volume_unheld.go +++ b/seaweed-block/cmd/sw-block/volume_unheld.go @@ -21,6 +21,10 @@ This proof is per host and for local filesystems only. It says nothing about another host, and nothing on a network or shared mount. It does not prove the owner process is dead: host cleanup must require BOTH this command's exit 0 AND the host tooling's own check that the recorded owner process is gone. + +The probe holds the lock only for an instant and reserves nothing: it does not +keep a new owner out after it returns, and an owner opening the volume at that +instant is refused. Run it only when the owner is believed gone. ` // runOpsVolumeUnheld is `sw-block ops volume-unheld`. diff --git a/seaweed-block/cmd/sw-block/volume_unheld_test.go b/seaweed-block/cmd/sw-block/volume_unheld_test.go index bedae3cef7..868f276778 100644 --- a/seaweed-block/cmd/sw-block/volume_unheld_test.go +++ b/seaweed-block/cmd/sw-block/volume_unheld_test.go @@ -19,6 +19,12 @@ func TestOpsVolumeUnheldExitCodes(t *testing.T) { if err != nil { t.Fatal(err) } + closed := false + t.Cleanup(func() { + if !closed { + _ = s.Close() + } + }) junk := filepath.Join(t.TempDir(), "junk.bin") if err := os.WriteFile(junk, make([]byte, 64<<10), 0o644); err != nil { t.Fatal(err) @@ -31,6 +37,7 @@ func TestOpsVolumeUnheldExitCodes(t *testing.T) { if code, out, _ := runIt("--path", path); code != 1 || !strings.HasPrefix(out, "held:") { t.Fatalf("open store: exit %d %q; want 1 held", code, out) } + closed = true if err := s.Close(); err != nil { t.Fatal(err) } @@ -48,7 +55,7 @@ func TestOpsVolumeUnheldExitCodes(t *testing.T) { } } _, _, usage := runIt() - for _, want := range []string{"per host", "local filesystems only", "network or shared mount", "BOTH"} { + for _, want := range []string{"per host", "local filesystems only", "network or shared mount", "BOTH", "reserves nothing", "is refused"} { if !strings.Contains(usage, want) { t.Fatalf("usage lacks %q:\n%s", want, usage) } diff --git a/seaweed-block/core/storage/volume_unheld.go b/seaweed-block/core/storage/volume_unheld.go index c42e74b58e..b3f9709a9e 100644 --- a/seaweed-block/core/storage/volume_unheld.go +++ b/seaweed-block/core/storage/volume_unheld.go @@ -19,26 +19,38 @@ var ErrVolumeHeld = errors.New("storage: volume held by a live owner on this hos // // The proof is per host and for local filesystems only: it says nothing // about a process on another host, and nothing on a network or shared mount, -// where advisory lock semantics vary. It is not proof the owner process is -// dead; host cleanup must check that separately. The probe holds the lock -// only for an instant, but an owner opening the volume in that instant is +// where advisory lock semantics vary. It covers the file at path when the +// probe opens it, not a file renamed away earlier. It is not proof the owner +// process is dead; host cleanup must check that separately. The probe holds +// the lock only for an instant and leaves no reservation behind, so it does +// not keep a new owner out; an owner opening the volume in that instant is // refused with ErrWALStoreLocked: probe only when the owner is believed gone. func ProbeVolumeUnheld(path string) error { - // Only a v3 owner takes the lock; for any other file a free lock proves - // nothing. - if err := ProbeWALStoreV3(path); err != nil { - return fmt.Errorf("storage: %s is not a v3 volume, unheld cannot be proven: %w", path, err) - } + // One descriptor for both steps, locked first: the answer is about the + // file this descriptor opened, whatever the path names afterwards, and + // on Windows an owner's byte lock would refuse a read made before ours. f, err := os.Open(path) if err != nil { return err } defer f.Close() // closing releases the probe's lock + if hook := testProbeUnheldAfterOpen; hook != nil { + hook() + } switch err := LockWALStoreFile(f); { case errors.Is(err, ErrWALStoreLocked): - return ErrVolumeHeld + return ErrVolumeHeld // held, whatever the file is: the safe answer case err != nil: return err } + // Only a v3 owner takes the lock; for any other file a free lock proves + // nothing. + if err := probeWALStoreV3At(f); err != nil { + return fmt.Errorf("storage: %s is not a v3 volume, unheld cannot be proven: %w", path, err) + } return nil } + +// testProbeUnheldAfterOpen, test-only, runs in ProbeVolumeUnheld after the +// open, before the lock. +var testProbeUnheldAfterOpen func() diff --git a/seaweed-block/core/storage/volume_unheld_test.go b/seaweed-block/core/storage/volume_unheld_test.go index 97fcee13aa..43014a98b6 100644 --- a/seaweed-block/core/storage/volume_unheld_test.go +++ b/seaweed-block/core/storage/volume_unheld_test.go @@ -5,6 +5,7 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "testing" "time" @@ -107,7 +108,8 @@ func TestProbeVolumeUnheldHolderProcessDies(t *testing.T) { t.Fatal(err) } exited := make(chan struct{}) - t.Cleanup(func() { // kill and reap the holder, bounded + go func() { _ = cmd.Wait(); close(exited) }() // reaped on every path + t.Cleanup(func() { // kill the holder and join its reaper, bounded _ = cmd.Process.Kill() select { case <-exited: @@ -132,7 +134,6 @@ func TestProbeVolumeUnheldHolderProcessDies(t *testing.T) { if err := ProbeVolumeUnheld(path); !errors.Is(err, ErrVolumeHeld) { t.Fatalf("held by a live process: %v; want ErrVolumeHeld", err) } - go func() { _ = cmd.Wait(); close(exited) }() if err := cmd.Process.Kill(); err != nil { t.Fatal(err) } @@ -145,3 +146,34 @@ func TestProbeVolumeUnheldHolderProcessDies(t *testing.T) { t.Fatalf("after the holder died: %v; want unheld", err) } } + +// The answer is about the file the probe opened: a held volume whose path is +// replaced (by an unlocked non-v3 file) between the probe's open and its lock +// is still reported held, never unheld. +func TestProbeVolumeUnheldDecidesOnTheOpenedFile(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("an open file cannot be renamed over on Windows") + } + path := createClosedV3Volume(t) + s, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + junk := filepath.Join(filepath.Dir(path), "junk.bin") + if err := os.WriteFile(junk, make([]byte, 64<<10), 0o644); err != nil { + t.Fatal(err) + } + replaced := false + testProbeUnheldAfterOpen = func() { + replaced = os.Rename(junk, path) == nil + } + t.Cleanup(func() { testProbeUnheldAfterOpen = nil }) + err = ProbeVolumeUnheld(path) + if !replaced { + t.Fatal("fixture: the path was not replaced after the open") + } + if !errors.Is(err, ErrVolumeHeld) { + t.Fatalf("held volume replaced at its path mid-probe: %v; want ErrVolumeHeld", err) + } +} diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index ea7f8d68fd..5b395c8fff 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -165,14 +165,19 @@ func ProbeWALStoreV3(path string) error { return err } defer f.Close() + return probeWALStoreV3At(f) +} + +// probeWALStoreV3At is ProbeWALStoreV3 on an already open file. +func probeWALStoreV3At(r io.ReaderAt) error { a, b := make([]byte, slotSizeV3), make([]byte, slotSizeV3) - if _, err := f.ReadAt(a, 0); err != nil { + if _, err := r.ReadAt(a, 0); err != nil { return err } - if _, err := f.ReadAt(b, slotBOffsetV3); err != nil { + if _, err := r.ReadAt(b, slotBOffsetV3); err != nil { return err } - _, _, err = selectSlotV3(a, b, nil) + _, _, err := selectSlotV3(a, b, nil) return err } From 574c035e681124cc2e2fa36479da42294b2f61c1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:50:41 -0800 Subject: [PATCH 080/150] storage: gofmt the unheld probe test Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/volume_unheld_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/volume_unheld_test.go b/seaweed-block/core/storage/volume_unheld_test.go index 43014a98b6..7a23e26b7f 100644 --- a/seaweed-block/core/storage/volume_unheld_test.go +++ b/seaweed-block/core/storage/volume_unheld_test.go @@ -108,8 +108,9 @@ func TestProbeVolumeUnheldHolderProcessDies(t *testing.T) { t.Fatal(err) } exited := make(chan struct{}) - go func() { _ = cmd.Wait(); close(exited) }() // reaped on every path - t.Cleanup(func() { // kill the holder and join its reaper, bounded + // Reaped on every path; the cleanup kills the holder and joins its reaper. + go func() { _ = cmd.Wait(); close(exited) }() + t.Cleanup(func() { _ = cmd.Process.Kill() select { case <-exited: From 7cb029615872ee6c512891643f5277a810174243 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 03:00:27 -0800 Subject: [PATCH 081/150] fix(storage): preserve caller cancellation during claim intent retirement --- seaweed-block/core/storage/chunk_restore.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_restore.go b/seaweed-block/core/storage/chunk_restore.go index 1a011df27b..e34a11251b 100644 --- a/seaweed-block/core/storage/chunk_restore.go +++ b/seaweed-block/core/storage/chunk_restore.go @@ -62,7 +62,7 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi defer func() { if settled { for _, id := range intents { - _ = remote.DeleteIntent(context.WithoutCancel(ctx), id) + _ = remote.DeleteIntent(ctx, id) } } }() From ffb5cbbe4e43692820a307079344a76bb4ddd267 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 03:05:07 -0800 Subject: [PATCH 082/150] authority: every store records lost ranges; a resumed reservation needs its range Fold of the #255 r2 review: - the lost-range methods are part of AuthorityStore instead of an optional capability, so no store (and no wrapper embedding one) can issue a forced move without recording its range; - a pending forced reservation resumes only with the exact range recorded before it; a missing one is refused, never recomputed (a new request records a fresh range); - fault hooks inside the file store cover a failure before the rename and one at the directory sync. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sparrow/bootstrap_test.go | 7 + seaweed-block/core/authority/authority.go | 12 +- .../core/authority/authority_restart_test.go | 5 + .../core/authority/authority_store.go | 10 ++ seaweed-block/core/authority/workspace.go | 9 + .../core/authority/workspace_lost_range.go | 49 ++++-- .../authority/workspace_lost_range_test.go | 162 ++++++++++++++++++ 7 files changed, 231 insertions(+), 23 deletions(-) diff --git a/seaweed-block/cmd/sparrow/bootstrap_test.go b/seaweed-block/cmd/sparrow/bootstrap_test.go index 5f226fbd33..84d855faaa 100644 --- a/seaweed-block/cmd/sparrow/bootstrap_test.go +++ b/seaweed-block/cmd/sparrow/bootstrap_test.go @@ -430,3 +430,10 @@ func TestBootstrap_Close_Idempotent(t *testing.T) { t.Fatalf("second Close must be idempotent: %v", err) } } + +func (s *indexFailingAuthorityStore) PutWorkspaceLostRanges(string, []authority.WorkspaceLostRange) error { + return nil +} +func (s *indexFailingAuthorityStore) LoadWorkspaceLostRanges() (map[string][]authority.WorkspaceLostRange, []error, error) { + return nil, nil, nil +} diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 321165423b..52f8d7fe1f 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -285,14 +285,12 @@ func (p *Publisher) reloadFromStore() { } } p.loadErrs = append(p.loadErrs, skips...) - if ls, ok := p.store.(WorkspaceLostRangeStore); ok { - ranges, lskips, lerr := ls.LoadWorkspaceLostRanges() - if lerr != nil { - panic(fmt.Sprintf("authority: lost range load failure: %v", lerr)) - } - p.lostRanges = ranges - p.loadErrs = append(p.loadErrs, lskips...) + ranges, lskips, lerr := p.store.LoadWorkspaceLostRanges() + if lerr != nil { + panic(fmt.Sprintf("authority: lost range load failure: %v", lerr)) } + p.lostRanges = ranges + p.loadErrs = append(p.loadErrs, lskips...) for _, rec := range records { p.refreshLeaseViewLocked(rec.VolumeID) if rec.Workspace != nil { diff --git a/seaweed-block/core/authority/authority_restart_test.go b/seaweed-block/core/authority/authority_restart_test.go index eb0cf7e578..8a152c4e24 100644 --- a/seaweed-block/core/authority/authority_restart_test.go +++ b/seaweed-block/core/authority/authority_restart_test.go @@ -369,3 +369,8 @@ func (f *failingStore) Close() error { return nil } // Silence unused import warning if adapter is not referenced // directly in this file's test bodies. var _ = adapter.AssignmentInfo{} + +func (f *failingStore) PutWorkspaceLostRanges(string, []WorkspaceLostRange) error { return nil } +func (f *failingStore) LoadWorkspaceLostRanges() (map[string][]WorkspaceLostRange, []error, error) { + return nil, nil, nil +} diff --git a/seaweed-block/core/authority/authority_store.go b/seaweed-block/core/authority/authority_store.go index 680fb2a087..8a3864ac62 100644 --- a/seaweed-block/core/authority/authority_store.go +++ b/seaweed-block/core/authority/authority_store.go @@ -80,6 +80,16 @@ type AuthorityStore interface { // Publisher.apply). Put(record DurableRecord) error + // PutWorkspaceLostRanges replaces a volume's forced-move lost ranges + // atomically, beside (never inside) its authority record, so the record + // stays readable by binaries that predate them. Every store must record + // them: a forced move does not issue without its range. + PutWorkspaceLostRanges(volumeID string, ranges []WorkspaceLostRange) error + + // LoadWorkspaceLostRanges returns every volume's lost ranges, with + // per-file skip errors; only an index-level failure returns err. + LoadWorkspaceLostRanges() (map[string][]WorkspaceLostRange, []error, error) + // Close releases store resources. Idempotent. Close() error } diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index ce4342dcb7..6d6301e1b3 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -302,6 +302,15 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra if r.Issued || !sameWorkspaceRequest(r, q) { return nil, 0, fmt.Errorf("workspace move reservation differs") } + // A forced reservation issues only with the exact range recorded + // before it; a missing one (a reservation older than lost ranges, + // or a skipped side file) is refused, never recomputed: a new + // request records a fresh range. + if r.Kind == "forced" { + if _, ok := p.lostRangeLocked(q.VolumeID, r.RequestID, r.NewEpoch); !ok { + return nil, 0, fmt.Errorf("workspace forced move reservation %s has no recorded lost range; retry with a new request id", r.RequestID) + } + } s.Moves[idx].Issued = true s.Lease = nil s.Ack = nil diff --git a/seaweed-block/core/authority/workspace_lost_range.go b/seaweed-block/core/authority/workspace_lost_range.go index dab767f3fd..40d26cd5ae 100644 --- a/seaweed-block/core/authority/workspace_lost_range.go +++ b/seaweed-block/core/authority/workspace_lost_range.go @@ -25,15 +25,6 @@ type WorkspaceLostRange struct { LostUntilNS int64 } -// WorkspaceLostRangeStore is an optional AuthorityStore capability. The -// ranges live beside the authority record, never in it, so the record body -// and its checksum stay readable by binaries that predate them (those load -// only *.v3auth.json). A store without it records no lost range. -type WorkspaceLostRangeStore interface { - PutWorkspaceLostRanges(volumeID string, ranges []WorkspaceLostRange) error - LoadWorkspaceLostRanges() (map[string][]WorkspaceLostRange, []error, error) -} - // lostRangeFileExtension does not end in storeFileExtension: authority // loaders, old and new, never read these files. const lostRangeFileExtension = ".lostrange.json" @@ -82,6 +73,9 @@ func (s *FileAuthorityStore) PutWorkspaceLostRanges(volumeID string, ranges []Wo if werr == nil { werr = f.Sync() } + if werr == nil { + werr = testLostRangeFault("before-rename") + } if cerr := f.Close(); werr == nil { werr = cerr } @@ -98,6 +92,9 @@ func (s *FileAuthorityStore) PutWorkspaceLostRanges(volumeID string, ranges []Wo return fmt.Errorf("authority_store: lost range directory open: %w", err) } serr := d.Sync() + if serr == nil { + serr = testLostRangeFault("directory-sync") + } if cerr := d.Close(); serr == nil { serr = cerr } @@ -149,14 +146,34 @@ func (s *FileAuthorityStore) LoadWorkspaceLostRanges() (map[string][]WorkspaceLo return out, skips, nil } +// testLostRangeFaultHook, test-only, fails PutWorkspaceLostRanges at a named +// step ("before-rename", "directory-sync") when it returns an error. +var testLostRangeFaultHook func(step string) error + +func testLostRangeFault(step string) error { + if h := testLostRangeFaultHook; h != nil { + return h(step) + } + return nil +} + +// lostRangeLocked returns volume's recorded range for (requestID, newEpoch). +// Called under p.mu. +func (p *Publisher) lostRangeLocked(volume, requestID string, newEpoch uint64) (WorkspaceLostRange, bool) { + for _, e := range p.lostRanges[volume] { + if e.RequestID == requestID && e.NewEpoch == newEpoch { + return e, true + } + } + return WorkspaceLostRange{}, false +} + // recordLostRangeLocked durably records r for volume before the move record -// that issues it is written; a store without the capability records nothing. -// An entry whose move never issues is an orphan, ignored on read. Called -// under p.mu. +// that issues it is written. An entry whose move never issues is an orphan, +// ignored on read. Called under p.mu. func (p *Publisher) recordLostRangeLocked(volume string, r WorkspaceLostRange) error { - ls, ok := p.store.(WorkspaceLostRangeStore) - if !ok { - return nil + if p.store == nil { + return fmt.Errorf("workspace forced move: no store to record the lost range") } next := make([]WorkspaceLostRange, 0, len(p.lostRanges[volume])+1) for _, e := range p.lostRanges[volume] { @@ -165,7 +182,7 @@ func (p *Publisher) recordLostRangeLocked(volume string, r WorkspaceLostRange) e } } next = append(next, r) - if err := ls.PutWorkspaceLostRanges(volume, next); err != nil { + if err := p.store.PutWorkspaceLostRanges(volume, next); err != nil { return fmt.Errorf("workspace forced move: record lost range: %w", err) } p.lostRanges[volume] = next diff --git a/seaweed-block/core/authority/workspace_lost_range_test.go b/seaweed-block/core/authority/workspace_lost_range_test.go index 096f6f5141..4be162bd56 100644 --- a/seaweed-block/core/authority/workspace_lost_range_test.go +++ b/seaweed-block/core/authority/workspace_lost_range_test.go @@ -175,3 +175,165 @@ func TestWorkspaceForcedMoveLostRangeOrdering(t *testing.T) { } }) } + +// issueFailStore fails the authority write that would issue a move, leaving +// its reservation pending on disk (a crash between reservation and issue). +type issueFailStore struct { + *FileAuthorityStore + failIssue bool +} + +func (s *issueFailStore) Put(r DurableRecord) error { + if s.failIssue && r.Workspace != nil { + for _, m := range r.Workspace.Moves { + if m.Issued { + return errInjected + } + } + } + return s.FileAuthorityStore.Put(r) +} + +// A pending forced reservation resumes only with the exact range recorded +// before it: after a reload the retry issues it with that range (not one +// recomputed at the retry); without it the retry is refused, and a new +// request records a fresh range. +func TestWorkspaceForcedReservationResumeNeedsItsRange(t *testing.T) { + for _, missing := range []bool{false, true} { + t.Run(map[bool]string{false: "range kept", true: "range missing"}[missing], func(t *testing.T) { + disk, dir := newTempStore(t) + store := &issueFailStore{FileAuthorityStore: disk, failIssue: true} + p, now, barrier := forcedLostRangeFixture(t, store, false) + *now = barrier.Add(time.Second) + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err == nil { + t.Fatal("fixture: the issue write did not fail") + } + st := NewPublisher(nil, WithStore(disk)).WorkspaceState("v") + if st == nil || len(st.Moves) != 1 || st.Moves[0].Issued { + t.Fatalf("fixture: no pending reservation on disk: %+v", st) + } + want := WorkspaceLostRange{RequestID: "f", NewEpoch: st.Moves[0].NewEpoch, OldReplicaID: "old", OldEpoch: 1, LostAfterLSN: 42, LostUntilNS: barrier.UnixNano()} + if missing { + if err := os.Remove(filepath.Join(dir, "v"+lostRangeFileExtension)); err != nil { + t.Fatal(err) + } + } + later := barrier.Add(time.Hour) // a recomputed bound would differ + q := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, func() time.Time { return later })) + later = later.Add(time.Minute) // past the reload's own restart deadline + r, err := q.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead) + if missing { + if err == nil || !strings.Contains(err.Error(), "no recorded lost range") { + t.Fatalf("resume without its range: %v; want refused", err) + } + if line, _ := q.VolumeAuthorityLine("v"); line.Epoch != 1 { + t.Fatalf("epoch issued without a range: %+v", line) + } + fresh := forcedLostRangeReq + fresh.RequestID = "f2" + r2, err := q.MoveWorkspace(context.Background(), fresh, forcedLostRangeHead) + if err != nil { + t.Fatalf("a new request after the refused resume: %v", err) + } + if got := q.WorkspaceLostRanges("v"); len(got) != 1 || got[0].RequestID != "f2" || got[0].NewEpoch != r2.NewEpoch { + t.Fatalf("new request range %+v", got) + } + return + } + if err != nil || !r.Issued || r.NewEpoch != want.NewEpoch { + t.Fatalf("resume: %+v %v", r, err) + } + if got := q.WorkspaceLostRanges("v"); len(got) != 1 || got[0] != want { + t.Fatalf("resumed range %+v; want the recorded [%+v]", got, want) + } + }) + } +} + +// Failures inside the file store: before the rename nothing is published +// and no temp file is left; after the rename (directory sync) the range may +// be on disk as an orphan. Either way the move is refused with no epoch, the +// orphan is not reported, and a retry issues with exactly one range. +func TestWorkspaceLostRangeFileFaults(t *testing.T) { + for _, step := range []string{"before-rename", "directory-sync"} { + t.Run(step, func(t *testing.T) { + disk, dir := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, false) + *now = barrier.Add(time.Second) + testLostRangeFaultHook = func(s string) error { + if s == step { + return errInjected + } + return nil + } + t.Cleanup(func() { testLostRangeFaultHook = nil }) + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); !errors.Is(err, errInjected) { + t.Fatalf("move with a failed range write: %v; want refused", err) + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 1 { + t.Fatalf("epoch issued: %+v", line) + } + _, statErr := os.Stat(filepath.Join(dir, "v"+lostRangeFileExtension)) + temps, _ := filepath.Glob(filepath.Join(dir, "*"+lostRangeFileExtension+tempSuffix)) + if len(temps) != 0 { + t.Fatalf("temp file left: %v", temps) + } + if step == "before-rename" && statErr == nil { + t.Fatal("range published although the write failed before the rename") + } + if step == "directory-sync" && statErr != nil { + t.Fatalf("fixture: the rename did not land: %v", statErr) + } + if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 0 { + t.Fatalf("orphan reported: %+v", got) + } + testLostRangeFaultHook = nil + r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead) + if err != nil { + t.Fatal("retry:", err) + } + if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 1 || got[0].NewEpoch != r.NewEpoch { + t.Fatalf("after the retry: %+v; want one range", got) + } + }) + } +} + +// A store wrapper that embeds AuthorityStore forwards the lost ranges: a +// forced move through it records its range. +func TestWorkspaceLostRangeThroughAStoreWrapper(t *testing.T) { + disk, _ := newTempStore(t) + wrapped := &workspaceFailStore{AuthorityStore: disk} + p, now, barrier := forcedLostRangeFixture(t, wrapped, false) + *now = barrier.Add(time.Second) + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err != nil { + t.Fatal(err) + } + if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 1 { + t.Fatalf("range through a wrapper: %+v", got) + } +} + +// Budget evidence (logged, not asserted): the added critical-section write, +// one file of the volume's whole range history plus two fsyncs, for a short +// and a long history. +func TestWorkspaceLostRangeWriteCost(t *testing.T) { + disk, _ := newTempStore(t) + for _, n := range []int{1, 1000} { + ranges := make([]WorkspaceLostRange, n) + for i := range ranges { + ranges[i] = WorkspaceLostRange{RequestID: "request-" + strings.Repeat("x", 24), NewEpoch: uint64(i + 2), OldReplicaID: "r1", OldEpoch: uint64(i + 1), LostAfterLSN: 1 << 40, LostUntilNS: 1 << 60} + } + var worst time.Duration + for i := 0; i < 5; i++ { + start := time.Now() + if err := disk.PutWorkspaceLostRanges("v", ranges); err != nil { + t.Fatal(err) + } + if d := time.Since(start); d > worst { + worst = d + } + } + t.Logf("lost range write: %d entries, worst of 5 = %v", n, worst) + } +} From 194f1552e2da9bd1427e000eadf868a7685be873 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 03:05:35 -0800 Subject: [PATCH 083/150] test(storage): cover no-sync pressure and speculative prefix boundaries --- .../checkpoint_append_progress_v3_test.go | 343 +++++++++++++++++- .../storage/walstore_map_checkpoint_v3.go | 4 +- seaweed-block/core/storage/walstore_v3.go | 2 +- seaweed-block/docs/design/invariants.md | 4 +- 4 files changed, 343 insertions(+), 10 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index 910d5408b3..602d819a9b 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -2,9 +2,11 @@ package storage import ( "bytes" + "encoding/binary" "errors" "path/filepath" "testing" + "time" ) func TestChunkLayerV3_CheckpointProgressUnderContinuousAppends(t *testing.T) { @@ -288,20 +290,28 @@ func TestChunkLayerV3_CheckpointProgressAtWALPressure(t *testing.T) { realSync := s.v3.ownedMap.syncFile t.Cleanup(func() { s.v3.ownedMap.syncFile = realSync }) previousCP := uint64(0) + expected := make(map[uint32][]byte) + write := func() error { + lsn := s.NextLSN() + lba := uint32(lsn % 64) + data := checkpointProgressBlock(lsn) + if _, err := s.Write(lba, data); err != nil { + return err + } + expected[lba] = data + return nil + } for cycle := 0; cycle < 8; cycle++ { for s.walUsedFraction() < 0.72 { - if _, err := s.Write(uint32(s.NextLSN()%64), blk(byte(s.NextLSN()))); err != nil { + if err := write(); err != nil { t.Fatal(err) } } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } injected := false s.v3.ownedMap.syncFile = func() error { if !injected { injected = true - if _, err := s.Write(uint32(s.NextLSN()%64), blk(byte(s.NextLSN()))); err != nil { + if err := write(); err != nil { return err } } @@ -322,7 +332,328 @@ func TestChunkLayerV3_CheckpointProgressAtWALPressure(t *testing.T) { if !ok || floor < 5*64*1024 { t.Fatalf("no sustained ring reuse: floor%d", floor) } - t.Logf("cycles8 checkpoint%d floor%d busy0", previousCP, floor) + for lba, want := range expected { + if got, err := s.Read(lba); err != nil || !bytes.Equal(got, want) { + t.Fatalf("no-Flush readback LBA%d: %v", lba, err) + } + } + t.Logf("no client Sync: cycles8 checkpoint%d floor%d busy0", previousCP, floor) + }) + } +} + +func checkpointProgressBlock(lsn uint64) []byte { + data := make([]byte, 4096) + for i := 0; i < len(data); i += 8 { + binary.LittleEndian.PutUint64(data[i:i+8], lsn*4096+uint64(i)) + } + return data +} + +// An active history pin gives one bounded, typed refusal; local flusher work +// after releasing it restores progress without a client Sync or new remote cut. +func TestCheckpointV3_NoFlushPressureWithRealPin(t *testing.T) { + path := filepath.Join(t.TempDir(), "pinned") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 64*1024, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 0, anyActive: true}) + expected := make(map[uint32][]byte) + for s.walUsedFraction() < 0.90 { + lsn := s.NextLSN() + lba := uint32(lsn) + data := checkpointProgressBlock(lsn) + if _, err := s.Write(lba, data); err != nil { + t.Fatal(err) + } + expected[lba] = data + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if s.CheckpointLSN() != 0 || s.v3.wack.Load() == 0 { + t.Fatal("real retention pin did not constrain an internally synced checkpoint") + } + next := s.NextLSN() + start := time.Now() + _, err = s.Write(uint32(next), checkpointProgressBlock(next)) + elapsed := time.Since(start) + if !errors.Is(err, ErrWALPressureTimeout) || elapsed >= 5*time.Second || s.NextLSN() != next { + t.Fatalf("pinned busy: err%v elapsed%v next%d want%d", err, elapsed, s.NextLSN(), next) + } + count := 0 + if err := s.ScanLBAs(1, func(e RecoveryEntry) error { + count++ + if e.LSN != uint64(count) || !bytes.Equal(e.Data, expected[e.LBA]) { + return errors.New("pinned retained prefix differs from submitted bytes") + } + return nil + }); err != nil || count != len(expected) { + t.Fatalf("pinned exact prefix count%d want%d: %v", count, len(expected), err) + } + s.SetRecycleFloorSource(nil) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } // no Write/Sync wakes it + if s.CheckpointLSN() != next-1 { + t.Fatal("released pin did not permit passive local checkpoint progress") + } + if lsn, err := s.Write(uint32(next), checkpointProgressBlock(next)); err != nil || lsn != next { + t.Fatalf("retry: %d %v", lsn, err) + } + expected[uint32(next)] = checkpointProgressBlock(next) + for lba, want := range expected { + if got, err := s.Read(lba); err != nil || !bytes.Equal(got, want) { + t.Fatalf("pinned readback LBA%d: %v", lba, err) + } + } + t.Logf("busy1 elapsed%v retained%d checkpoint%d", elapsed, count, s.CheckpointLSN()) +} + +func TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(1) + writeSynced(t, s, 1, 2) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(2) + if err != nil { + t.Fatal(err) + } + tail := s.v3.w.reclaimThroughV3(2) + if _, err := s.v3.pub.publish(nil, nil, func(d *descriptorV3) error { + d.RetainedTail = tail + d.RetainedHead = max(d.RetainedHead, tail) + return nil + }); err != nil { + t.Fatal(err) + } + before := s.v3.pub.current() + _, floor, ok := s.v3.pub.walSnapshotV3() + if !ok || floor >= tail { + t.Fatal("setup: no pinned fallback") + } + injected := errors.New("append rollover slot fault") + s.v3.testBeforeSlotWrite = func() error { return injected } + _, err = s.Write(3, blk(0xD3)) + s.v3.testBeforeSlotWrite = nil + if !errors.Is(err, injected) || s.stickyIOFault() == nil || s.NextLSN() != 3 || s.dm.len() != 0 { + t.Fatalf("rollover fault: %v next%d dirty%d", err, s.NextLSN(), s.dm.len()) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err == nil { + t.Fatal("held candidate published through sticky rollover failure") + } + if s.v3.pub.current() != before { + t.Fatal("rollover fault changed authoritative tuple") + } + if nextFloor, _ := s.v3.pub.reuseFloor(); nextFloor != floor { + t.Fatal("failed rollover released fallback floor") + } +} + +// Max-LSN map entries may include unsynced writes above both cp and W. A +// reused LSN can then set UNKNOWN without changing the prefix proof token. +func TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + remote := newFakeChunkRemote() + layer := mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(1, blk(0xA1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if s.v3.mapEntries[0].Unknown { + t.Fatal("setup: initial definite cut did not clear UNKNOWN") + } + if _, err := s.Write(1, blk(0xA2)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, blk(0xA3)); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + e := prepared.candidate.entries[0] + if e.LSN != 3 || e.Unknown || d.CheckpointLSN != 1 || d.W != 1 { + t.Fatalf("speculative maximum: entry%+v cp%d W%d", e, d.CheckpointLSN, d.W) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatal(err) + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + damageRecord(t, path, 2) // unacknowledged record2 tears; the following3 is dropped + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if r.NextLSN() != 2 || r.v3.mapEntries[0].LSN != 3 { + t.Fatal("dropped suffix did not leave the conservative persisted maximum") + } + held, err := r.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + if held.candidate.entries[0].Unknown { + t.Fatal("setup: held candidate already UNKNOWN") + } + if lsn, err := r.Write(1, blk(0xB2)); err != nil || lsn != 2 { + t.Fatalf("reused LSN: %d %v", lsn, err) + } + if !r.v3.mapEntries[0].Unknown || r.v3.mapEntries[0].LSN != 3 { + t.Fatal("reused LSN did not conservatively set UNKNOWN beneath the high maximum") + } + if !held.proof.validV3(r.v3.mapProof) { + t.Fatal("reused ordered append invalidated the older prefix") + } + if _, err := r.v3.pub.publishMapV3(&r.mu, nil, held, nil); err != nil { + t.Fatal(err) + } + if _, err := r.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, r) + r.mu.Lock() + r.closed = true + r.mu.Unlock() + r2, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r2.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r2.Close() }) + if _, err := r2.Recover(); err != nil { + t.Fatal(err) + } + if !r2.v3.mapEntries[0].Unknown || !bytes.Equal(readV3(t, r2, 1), blk(0xB2)) { + t.Fatal("replay did not restore UNKNOWN and exact reused-LSN bytes") + } + restored := mustAttach(t, r2, remote, ctConfig(2)) + cut, err := restored.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + image := remote.imageOf(t, cut.Head) + if !bytes.Equal(image[4096:8192], blk(0xB2)) { + t.Fatal("capture treated the speculative maximum as remotely clean") + } +} + +func TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush(t *testing.T) { + for _, flush := range []bool{false, true} { + t.Run(map[bool]string{false: "wal", true: "extent"}[flush], func(t *testing.T) { + path := filepath.Join(t.TempDir(), "hydrating") + s, err := createMappedWALStoreV3ForTest(path, ctNumBlocks, ctBlockSize, v3TestWAL, WModeStrict, ctChunkBlocks) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + image := make([]byte, ctNumBlocks*ctBlockSize) + copy(image[8*ctBlockSize:], blk(0xA8)) + copy(image[9*ctBlockSize:], blk(0xA9)) + remote := newFakeChunkRemote() + remote.seedHead(t, image, 10, 1) + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + layer := mustAttach(t, s, remote, cfg) + held, err := s.prepareOwnedMapCheckpointV3(10) + if err != nil { + t.Fatal(err) + } + entered, release := holdNextGet(t, remote) + done := make(chan error, 1) + go func() { + got, err := s.Read(9) + if err == nil && !bytes.Equal(got, blk(0xB9)) { + err = errors.New("held read did not return newer local bytes") + } + done <- err + }() + waitKey(t, entered, "cold fill before a competing local write") + if _, err := s.Write(9, blk(0xB9)); err != nil { + t.Fatal(err) + } + if flush { + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + } + dirty := s.dm.len() + release() + if err := waitErr(t, done, "fill and post-miss WAL recheck"); err != nil { + t.Fatal(err) + } + if s.dm.len() != dirty || !held.proof.validV3(s.v3.mapProof) { + t.Fatal("hydration manufactured logical dirt or invalidated the prefix proof") + } + before := s.v3.pub.current() + _, err = s.v3.pub.publishMapV3(&s.mu, nil, held, nil) + if flush { + if !errors.Is(err, ErrMapCoverageStale) || s.v3.pub.current() != before { + t.Fatalf("superseded candidate after flush: %v", err) + } + } else { + if err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + if !bytes.Equal(readV3(t, s, 8), blk(0xA8)) || !bytes.Equal(readV3(t, s, 9), blk(0xB9)) { + t.Fatal("HEAD fill or local write was overwritten") + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if !bytes.Equal(readV3(t, r, 8), blk(0xA8)) || !bytes.Equal(readV3(t, r, 9), blk(0xB9)) { + t.Fatal("reopen lost exact hydrated/local bytes") + } }) } } diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index a21d4f86a0..ee902f622d 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -7,6 +7,8 @@ package storage // Caller holds WALStore.mu. Higher-LSN writes update the max; a reused or // lower/equal effective LSN is conservative UNKNOWN, independent of the max. +// A reused ordered LSN below a speculative max can set UNKNOWN here without +// invalidating a prefix proof; the max and retained suffix stay conservative. // Capture is the only future owner allowed to clear UNKNOWN after a version // check. Keeping it set here cannot manufacture a remotely clean chunk. func (s *WALStore) recordMapWriteV3(lba, lsn uint64) { @@ -36,7 +38,7 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati return nil, mapCoverageRefusal("map_binding_changed") } proof := domain.snapshotV3() - // Entries may already contain LSNs above cp from earlier appends: max-LSN + // Entries may already contain LSNs above cp or W from earlier appends: max-LSN // entries are monotone and idempotent under retained-suffix replay. entries := append([]chunkLSNEntryV3(nil), v.mapEntries...) v.pub.descMu.Unlock() diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index cf6f2cdbc7..76d28a7d93 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -655,7 +655,7 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, e return 0, errWALBindingV3 // a half-published reset before its Recover } // A strictly newer append stays in the retained WAL suffix. It cannot - // invalidate coverage of an older checkpoint prefix; effective BASE and + // invalidate coverage of an older checkpoint prefix; BASE writes, capture UNKNOWN clearing and // lifecycle mutations still invalidate the map proof at their own seams. if p := s.v3.mapProof; p != nil && p.mutation.Load() >= counterMaxV3 { return 0, ErrCounterExhausted diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 3f27e03cc6..40c144fa06 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -335,7 +335,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | | `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | @@ -355,7 +355,7 @@ Notes: - `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged. - `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. -- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. The entry snapshot may already contain LSNs above cp from pre-snapshot appends; max-LSN entries remain monotone and idempotent under replay. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. Effective BASE/UNKNOWN changes and lifecycle boundaries still invalidate proofs. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. +- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. The entry snapshot may already contain LSNs above cp or W from pre-snapshot appends; max-LSN entries remain monotone and idempotent under replay. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. BASE writes, capture UNKNOWN clearing and lifecycle boundaries still invalidate proofs. A reused ordered LSN below a speculative retained map maximum can set UNKNOWN without invalidating the prefix; the high max and replayed retained suffix remain conservative. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. - `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. Sidecar extents are reused only after neither slot nor a pending or uncertain candidate references them; see `chunk_map_extents_v3.go` and its tests. From 33a6adf6ca9781399403ccdf54af7dd9e7b49534 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 03:09:17 -0800 Subject: [PATCH 084/150] test(storage): require reuse refusal after uncertain rollover --- .../core/storage/checkpoint_append_progress_v3_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index 602d819a9b..b6dc94bb2a 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -451,8 +451,8 @@ func TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate(t *testing.T) { if s.v3.pub.current() != before { t.Fatal("rollover fault changed authoritative tuple") } - if nextFloor, _ := s.v3.pub.reuseFloor(); nextFloor != floor { - t.Fatal("failed rollover released fallback floor") + if nextFloor, valid := s.v3.pub.reuseFloor(); valid || nextFloor != 0 { + t.Fatal("uncertain rollover must disable reuse until reopen") } } From 9acab6eebaeb7fc0c33a203dbdbf70d57c1cb3d0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 03:10:31 -0800 Subject: [PATCH 085/150] test(storage): sync hydrated extents before reopen assertions --- .../storage/checkpoint_append_progress_v3_test.go | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index b6dc94bb2a..e693f76698 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -624,13 +624,12 @@ func TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush(t *testing.T) { if !errors.Is(err, ErrMapCoverageStale) || s.v3.pub.current() != before { t.Fatalf("superseded candidate after flush: %v", err) } - } else { - if err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } + } else if err != nil { + t.Fatal(err) + } + // Cover the hydrated extent bytes too before the reopen oracle. + if _, err := s.Sync(); err != nil { + t.Fatal(err) } if !bytes.Equal(readV3(t, s, 8), blk(0xA8)) || !bytes.Equal(readV3(t, s, 9), blk(0xB9)) { t.Fatal("HEAD fill or local write was overwritten") From 370be25e9489d77b3d7d33b647c3a309585f7a08 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 03:13:45 -0800 Subject: [PATCH 086/150] test(storage): isolate cut proof invalidation from map generation --- .../checkpoint_append_progress_v3_test.go | 34 +++++++++++++++++++ seaweed-block/core/storage/walstore_v3.go | 4 +-- seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index e693f76698..b12f704f6c 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -656,3 +656,37 @@ func TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush(t *testing.T) { }) } } + +func TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + layer := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + writeSynced(t, s, 1, 1) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + held, err := s.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + if !s.v3.mapEntries[0].Unknown { + t.Fatal("setup: no UNKNOWN to clear") + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if s.v3.mapEntries[0].Unknown { + t.Fatal("definite cut did not clear UNKNOWN") + } + // Inspect the proof itself so the newer map generation cannot mask a missing + // clear-invalidation guard in the publication refusal below. + if held.proof.validV3(s.v3.mapProof) { + t.Fatal("capture UNKNOWN clearing left the old proof valid") + } + before := s.v3.pub.current() + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, held, nil); !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("old capture proof: %v", err) + } + if s.v3.pub.current() != before { + t.Fatal("capture-stale candidate changed a slot") + } +} diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 76d28a7d93..9d48c7374a 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -655,8 +655,8 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, e return 0, errWALBindingV3 // a half-published reset before its Recover } // A strictly newer append stays in the retained WAL suffix. It cannot - // invalidate coverage of an older checkpoint prefix; BASE writes, capture UNKNOWN clearing and - // lifecycle mutations still invalidate the map proof at their own seams. + // invalidate coverage of an older checkpoint prefix. BASE writes, capture + // UNKNOWN clearing and lifecycle mutations still invalidate at their seams. if p := s.v3.mapProof; p != nil && p.mutation.Load() >= counterMaxV3 { return 0, ErrCounterExhausted } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 40c144fa06..9177bc28cf 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -335,7 +335,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | | `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`, `TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | From ee8b72735af0c6352621382e3886e28021381052 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 03:30:57 -0800 Subject: [PATCH 087/150] storage: #252 fold: no new payload I/O after expiry, short locks block, keep storage cause Takes over codex03's fix/write-command-budget at 2d6d9711. - P1 (codex01): appendWriteV3 / writeBatchV3Locked take the command budget and check it after rolloverCheckpointV3Locked (its metadata I/O completes and stays owned) and before the payload append, so an expired command never starts new payload WAL I/O. Red test: TestWALStoreV3WriteBudgetRefusesNewPayloadAfterRollover (single, batch). - P1 (claude05/codex01): the short locks (s.mu in Write/WriteBatch and the pressure sampler's s.mu, descMu, writer.mu) are taken blocking again, so they keep RWMutex writer preference; the budget is checked once they are held. Only captureMu/lifecycleMu keep the bounded wait. Red test: TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders. The polling-era lock tests become TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait. - P1 (codex01): a batch that returns a committed prefix plus a storage error keeps that error when a required observer then fails: the classifier sees both causes (errors.Join), so a physical fault stays terminal. Red test: TestStorageBackendPartialBatchPhysicalFaultSurvivesObserverDeadline. - P2: the contextless Write/WriteBatch fallbacks refuse an already-expired command before a fresh mutation. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/storage_adapter.go | 46 +++++- .../durable/write_command_budget_p1_test.go | 76 ++++++++++ seaweed-block/core/storage/base_install_v3.go | 2 +- seaweed-block/core/storage/walstore.go | 12 +- seaweed-block/core/storage/walstore_v3.go | 30 +++- .../core/storage/write_command_budget.go | 22 +-- .../storage/write_command_budget_p1_test.go | 137 ++++++++++++++++++ .../core/storage/write_command_budget_test.go | 58 +------- 8 files changed, 301 insertions(+), 82 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/write_command_budget_p1_test.go create mode 100644 seaweed-block/core/storage/write_command_budget_p1_test.go diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 3762626fc4..2f860425ff 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -761,7 +761,7 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte) var err error if writer, ok := b.storage.(storage.ContextWriter); ok { lsn, err = writer.WriteContext(ctx, lba, block) - } else { + } else if err = expiredCommand(ctx); err == nil { lsn, err = b.storage.Write(lba, block) } writeLock.Unlock() @@ -803,7 +803,7 @@ func (b *StorageBackend) writeFullBlockBatch(ctx context.Context, startLBA uint3 var err error if writer, ok := batcher.(storage.ContextWriteBatcher); ok { lsns, err = writer.WriteBatchContext(ctx, startLBA, blocks) - } else { + } else if err = expiredCommand(ctx); err == nil { lsns, err = batcher.WriteBatch(startLBA, blocks) } unlock() @@ -816,14 +816,14 @@ func (b *StorageBackend) writeFullBlockBatch(ctx context.Context, startLBA uint3 log.Printf("durable: replication batch fan-out failed lba=%d blocks=%d: %v", startLBA, len(lsns), obsErr) if policy == WriteAckRequireObserverAck { - return len(lsns) * bs, replicationWriteError(ctx, obsErr) + return len(lsns) * bs, replicationWriteError(ctx, withStorageCause(startLBA, blockCount, err, obsErr)) } } } else { for i, lsn := range lsns { block := blocks[i] lba := startLBA + uint32(i) - if obsErr := b.observeWrite(ctx, lba, lsn, block, obs, policy); obsErr != nil { + if obsErr := b.observeWriteCause(ctx, lba, lsn, block, obs, policy, withStorageCause(startLBA, blockCount, err, nil)); obsErr != nil { return (i + 1) * bs, obsErr } } @@ -859,6 +859,13 @@ func (b *StorageBackend) lockLBARange(startLBA uint32, blockCount int) func() { } func (b *StorageBackend) observeWrite(ctx context.Context, lba uint32, lsn uint64, block []byte, obs WriteObserver, policy WriteAckPolicy) error { + return b.observeWriteCause(ctx, lba, lsn, block, obs, policy, nil) +} + +// observeWriteCause is observeWrite with the storage failure of the same +// command (nil if none): a required observer's error is classified together +// with it, so a physical storage fault is never reclassified as retryable. +func (b *StorageBackend) observeWriteCause(ctx context.Context, lba uint32, lsn uint64, block []byte, obs WriteObserver, policy WriteAckPolicy, storageErr error) error { // Replication fan-out (T4a-6 hook). Error is logged best-effort // unless the ack policy requires observer acknowledgement. if obs == nil { @@ -868,12 +875,29 @@ func (b *StorageBackend) observeWrite(ctx context.Context, lba uint32, lsn uint6 log.Printf("durable: replication fan-out failed lba=%d lsn=%d: %v", lba, lsn, werr) if policy == WriteAckRequireObserverAck { + if storageErr != nil { + werr = errors.Join(storageErr, werr) + } return replicationWriteError(ctx, werr) } } return nil } +// withStorageCause joins a batch's storage error (nil if none) with an +// observer error, so the classifier sees the complete error set (#252): +// a committed prefix may come back together with a physical failure. +func withStorageCause(startLBA uint32, blockCount int, storageErr, obsErr error) error { + if storageErr == nil { + return obsErr + } + se := fmt.Errorf("durable: write batch lba=%d blocks=%d: %w", startLBA, blockCount, storageErr) + if obsErr == nil { + return se + } + return errors.Join(se, obsErr) +} + // Classify the observer cause before adding the acknowledgement sentinel; // otherwise that sentinel would obscure a pure caller deadline at the target. func replicationWriteError(ctx context.Context, err error) error { @@ -887,3 +911,17 @@ func replicationWriteError(ctx context.Context, err error) error { // Compile-time check that StorageBackend satisfies frontend.Backend. // Catches interface drift at build time rather than runtime. var _ frontend.Backend = (*StorageBackend)(nil) + +// expiredCommand refuses a fresh mutation through a contextless storage +// fallback once the command is already expired or cancelled (#252); a pure +// deadline is retryable busy, as on the context-aware path. +func expiredCommand(ctx context.Context) error { + err := ctx.Err() + if err == nil { + return nil + } + if frontend.IsWriteDeadline(ctx, err) { + return fmt.Errorf("%w: %w", frontend.ErrBackendBusy, err) + } + return err +} diff --git a/seaweed-block/core/frontend/durable/write_command_budget_p1_test.go b/seaweed-block/core/frontend/durable/write_command_budget_p1_test.go new file mode 100644 index 0000000000..e529b86102 --- /dev/null +++ b/seaweed-block/core/frontend/durable/write_command_budget_p1_test.go @@ -0,0 +1,76 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// partialFaultStore commits the first block of a batch and returns that prefix +// together with a physical error (the shape parallelwal and smartwal return), +// after the command's deadline has passed. +type partialFaultStore struct { + storage.LogicalStorage + fault error +} + +func (s *partialFaultStore) WriteBatch(lba uint32, blocks [][]byte) ([]uint64, error) { + lsn, err := s.LogicalStorage.Write(lba, blocks[0]) + if err != nil { + return nil, err + } + return []uint64{lsn}, s.fault +} +func (s *partialFaultStore) WriteBatchContext(ctx context.Context, lba uint32, blocks [][]byte) ([]uint64, error) { + <-ctx.Done() + return s.WriteBatch(lba, blocks) +} + +// #252 P1-3: a committed prefix plus a physical storage error, then a required +// batch observer that reports a pure expired deadline: the physical fault must +// stay in the error (terminal), never be reclassified as retryable busy. +func TestStorageBackendPartialBatchPhysicalFaultSurvivesObserverDeadline(t *testing.T) { + for _, batchObserver := range []bool{true, false} { + name := map[bool]string{true: "batch-observer", false: "per-block-observer"}[batchObserver] + t.Run(name, func(t *testing.T) { + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} + physical := errors.New("injected physical WAL append failure") + s := &partialFaultStore{LogicalStorage: storage.NewBlockStore(8, 4096), fault: physical} + b := durable.NewStorageBackend(s, newStubView(healthyProj(id)), id) + b.SetOperational(true, "test") + deadlineOnly := func(ctx context.Context) error { return ctx.Err() } + obs := writeObserverFunc{observe: func(ctx context.Context, _ uint32, _ uint64, _ []byte) error { return deadlineOnly(ctx) }} + if batchObserver { + b.SetWriteObserver(batchWriteObserverFunc{writeObserverFunc: obs, observeBatch: func(ctx context.Context, _ uint32, _ []uint64, _ [][]byte) error { return deadlineOnly(ctx) }}) + } else { + b.SetWriteObserver(obs) + b.SetWriteAckPolicy(durable.WriteAckBestEffort) // the per-block path is taken without a batch observer only off the required policy + } + if batchObserver { + b.SetWriteAckPolicy(durable.WriteAckRequireObserverAck) + } + ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) + defer cancel() + data := append(bytes.Repeat([]byte{0xA1}, 4096), bytes.Repeat([]byte{0xB2}, 4096)...) + n, err := b.Write(ctx, 0, data) + if n != 4096 { + t.Fatalf("committed bytes %d, want exactly the 4096-byte prefix (err %v)", n, err) + } + if !errors.Is(err, physical) { + t.Fatalf("physical storage fault lost: %v", err) + } + if errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("physical storage fault reclassified as retryable busy: %v", err) + } + if batchObserver && !errors.Is(err, durable.ErrReplicationAckUnavailable) { + t.Fatalf("required observer failure lost its ACK identity: %v", err) + } + }) + } +} diff --git a/seaweed-block/core/storage/base_install_v3.go b/seaweed-block/core/storage/base_install_v3.go index 9b3ef91ecb..da1a87d2d6 100644 --- a/seaweed-block/core/storage/base_install_v3.go +++ b/seaweed-block/core/storage/base_install_v3.go @@ -423,7 +423,7 @@ func (s *WALStore) applyEntryV3(lba uint32, data []byte, lsn uint64, installLane return fmt.Errorf("%w: %d above %d", ErrInstallLSNGap, lsn, anchor) } dataCopy := append([]byte(nil), data...) - phys, err := s.appendWriteV3(lba, dataCopy, lsn) + phys, err := s.appendWriteV3(lba, dataCopy, lsn, nil) s.walMutation.Add(1) if err != nil { if installLane && errors.Is(err, errWALFull) { diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 208da4f639..78296be616 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -801,9 +801,7 @@ func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (u } commitLockStart := time.Now() - if err := s.acquireWriteLock(ctx, deadline, s.mu.TryLock, s.mu.Lock); err != nil { - return 0, err - } + s.mu.Lock() // a short lock: blocking keeps RWMutex writer preference (#252); the budget is checked below s.instr.recordWriteCommitLockWait(time.Since(commitLockStart)) if s.closed { s.mu.Unlock() @@ -832,7 +830,7 @@ func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (u var walRelOff uint64 var err error if s.v3 != nil { - walRelOff, err = s.appendWriteV3(lba, data, lsn) + walRelOff, err = s.appendWriteV3(lba, data, lsn, func() error { return s.writeBudgetError(ctx, deadline) }) } else { walRelOff, err = s.wal.append(entry) } @@ -912,9 +910,7 @@ func (s *WALStore) WriteBatchContext(ctx context.Context, startLBA uint32, block } commitLockStart := time.Now() - if err := s.acquireWriteLock(ctx, deadline, s.mu.TryLock, s.mu.Lock); err != nil { - return nil, err - } + s.mu.Lock() // a short lock: blocking keeps RWMutex writer preference (#252); the budget is checked below s.instr.recordWriteCommitLockWait(time.Since(commitLockStart)) if s.closed { s.mu.Unlock() @@ -930,7 +926,7 @@ func (s *WALStore) WriteBatchContext(ctx context.Context, startLBA uint32, block } firstLSN := s.nextLSN if s.v3 != nil { - lsns, err := s.writeBatchV3Locked(startLBA, blocks, firstLSN) + lsns, err := s.writeBatchV3Locked(startLBA, blocks, firstLSN, func() error { return s.writeBudgetError(ctx, deadline) }) s.mu.Unlock() return lsns, err } diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index ea7f8d68fd..84b2312cab 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -81,6 +81,9 @@ type walStoreV3State struct { testRecoverHold func() testBatchBeforeAck func() testSyncBeforeCompletion func() + // testAfterRollover runs in a v3 write after the checkpoint rollover and + // before the payload append (write-command budget, #252). + testAfterRollover func() testMapPrepared func() // outside all publication locks, after owned-map persistence // testReadResolved runs in a v3 read after the dirty map resolved the // LBA's WAL position and before the record is read. @@ -649,7 +652,10 @@ func (s *WALStore) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset u // appendWriteV3 is the v3 body of Write's append, under s.mu. DurableLSN is // the acknowledged W at append time; a pwrite failure latches the store. -func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, error) { +// budget (nil = none) is the guest command's budget: checked after a +// checkpoint rollover (whose metadata I/O completes) and before any new +// payload WAL I/O, so an expired command never starts one. +func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64, budget func() error) (uint64, error) { e := walEntryV3{LSN: lsn, Type: walEntryWrite, LBA: uint64(lba), Length: uint32(len(data)), Data: data} if s.v3.w == nil { return 0, errWALBindingV3 // a half-published reset before its Recover @@ -664,6 +670,9 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, e if err := s.rolloverCheckpointV3Locked(); err != nil { return 0, err } + if err := s.v3BudgetAfterRollover(budget); err != nil { + return 0, err + } phys, err := s.v3.w.append(e, s.v3.wack.Load()) if err != nil { if errors.Is(err, errWALPwrite) { @@ -682,10 +691,10 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, e // it (one CRC32C); the writer consumes the whole LSN range (DESIGN 6.7, // r16). A single block is an ordinary write record. Each block's dirty // entry names its data offset inside the record. -func (s *WALStore) writeBatchV3Locked(startLBA uint32, blocks [][]byte, firstLSN uint64) ([]uint64, error) { +func (s *WALStore) writeBatchV3Locked(startLBA uint32, blocks [][]byte, firstLSN uint64, budget func() error) ([]uint64, error) { start := time.Now() if len(blocks) == 1 { - phys, err := s.appendWriteV3(startLBA, blocks[0], firstLSN) + phys, err := s.appendWriteV3(startLBA, blocks[0], firstLSN, budget) s.instr.appendLatency.Observe(time.Since(start)) s.walMutation.Add(1) if err != nil { @@ -719,6 +728,9 @@ func (s *WALStore) writeBatchV3Locked(startLBA uint32, blocks [][]byte, firstLSN if err := s.rolloverCheckpointV3Locked(); err != nil { return nil, err } + if err := s.v3BudgetAfterRollover(budget); err != nil { + return nil, err + } phys, err := s.v3.w.append(e, s.v3.wack.Load()) s.instr.appendLatency.Observe(time.Since(start)) s.walMutation.Add(1) @@ -1182,3 +1194,15 @@ func (s *WALStore) persistCheckpointV3(highestLSN, recoveryGen uint64) error { s.mu.Unlock() return nil } + +// v3BudgetAfterRollover is the last budget check of a v3 write: after the +// rollover's metadata I/O (completed, owned) and before the payload append. +func (s *WALStore) v3BudgetAfterRollover(budget func() error) error { + if h := s.v3.testAfterRollover; h != nil { + h() + } + if budget == nil { + return nil + } + return budget() +} diff --git a/seaweed-block/core/storage/write_command_budget.go b/seaweed-block/core/storage/write_command_budget.go index 32a77c3b88..58dedfb926 100644 --- a/seaweed-block/core/storage/write_command_budget.go +++ b/seaweed-block/core/storage/write_command_budget.go @@ -38,8 +38,11 @@ func (s *WALStore) writeBudgetError(ctx context.Context, deadline time.Time) err return nil } -// A parked command owns no new physical I/O. Stop waiting for admission locks -// on expiry without a helper goroutine that could acquire them after return. +// A parked command owns no new physical I/O. Stop waiting for the long +// admission locks (captureMu, lifecycleMu: held across a capture barrier or a +// lifecycle transition) on expiry, without a helper goroutine that could +// acquire them after return. Short locks (s.mu, descMu, writer.mu) are taken +// blocking, so they keep RWMutex writer preference (#252). func (s *WALStore) acquireWriteLock(ctx context.Context, deadline time.Time, try func() bool, lock func()) error { if deadline.IsZero() && ctx.Done() == nil { lock() @@ -76,10 +79,13 @@ func (s *WALStore) writePressureSample(ctx context.Context, deadline time.Time) return nil } return func() (float64, error) { - if err := s.acquireWriteLock(ctx, deadline, s.mu.TryRLock, s.mu.RLock); err != nil { + // Short locks block (RWMutex writer preference, #252); the budget is + // checked once they are held. + s.mu.RLock() + defer s.mu.RUnlock() + if err := s.writeBudgetError(ctx, deadline); err != nil { return 0, err } - defer s.mu.RUnlock() if s.closed { return 0, errVolumeClosed } @@ -89,15 +95,11 @@ func (s *WALStore) writePressureSample(ctx context.Context, deadline time.Time) return 0, nil } // append still refuses the missing binding p := v.pub - if err := s.acquireWriteLock(ctx, deadline, p.descMu.TryLock, p.descMu.Lock); err != nil { - return 0, err - } + p.descMu.Lock() floor, valid := p.reuseFloorLocked() d := p.cur p.descMu.Unlock() // preserve snapshot ordering: no descriptor -> writer edge - if err := s.acquireWriteLock(ctx, deadline, w.mu.TryLock, w.mu.Lock); err != nil { - return 0, err - } + w.mu.Lock() defer w.mu.Unlock() if !valid || d.WALSize == 0 || d.Nonce != w.nonce || w.head < floor || w.head-floor > d.WALSize { return 0, nil diff --git a/seaweed-block/core/storage/write_command_budget_p1_test.go b/seaweed-block/core/storage/write_command_budget_p1_test.go new file mode 100644 index 0000000000..3236bb0c71 --- /dev/null +++ b/seaweed-block/core/storage/write_command_budget_p1_test.go @@ -0,0 +1,137 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" +) + +// #252 P1-1: an expired command never starts NEW payload WAL I/O. The rollover +// (its metadata I/O completes and stays owned) is held until the command has +// expired; the write must then refuse before the payload append: writer head, +// next LSN and dirty map unchanged, the block still reads its old bytes. +func TestWALStoreV3WriteBudgetRefusesNewPayloadAfterRollover(t *testing.T) { + for _, batch := range []bool{false, true} { + name := map[bool]string{false: "single", true: "batch"}[batch] + t.Run(name, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + ctx, cancel := context.WithTimeout(context.Background(), 400*time.Millisecond) + defer cancel() + held := make(chan struct{}) + s.v3.testAfterRollover = func() { close(held); <-ctx.Done() } + head, next, dirty := s.v3.w.head, s.NextLSN(), s.dm.len() + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 0, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.WriteContext(ctx, 0, blk(1)) + } + select { + case <-held: + default: + t.Fatal("the write never reached the post-rollover point") + } + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatalf("expired command after rollover: %v", err) + } + if s.v3.w.head != head || s.NextLSN() != next || s.dm.len() != dirty { + t.Fatalf("expired command started payload WAL I/O: head %d->%d next %d->%d dirty %d->%d", + head, s.v3.w.head, next, s.NextLSN(), dirty, s.dm.len()) + } + s.v3.testAfterRollover = nil + if got, err := s.Read(0); err != nil || bytes.Equal(got, blk(1)) { + t.Fatalf("refused write visible: %v", err) + } + if _, err := s.WriteContext(context.Background(), 0, blk(3)); err != nil { + t.Fatalf("a fresh write after the refusal: %v", err) + } + }) + } +} + +// #252 P1-2: short locks keep RWMutex writer preference. Continuous overlapping +// readers must not starve a healthy-capacity write into a busy expiry. +func TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders(t *testing.T) { + for _, batch := range []bool{false, true} { + name := map[bool]string{false: "single", true: "batch"}[batch] + t.Run(name, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + var stop atomic.Bool + var wg sync.WaitGroup + t.Cleanup(func() { stop.Store(true); wg.Wait() }) + // steady overlapping readers of the store lock (each holds it ~2 ms, + // staggered): some reader is almost always inside, as under heavy + // read traffic. A blocking Lock registers as a waiting writer and + // gets in; a TryLock poll would keep failing until the deadline. + for i := 0; i < 8; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + time.Sleep(time.Duration(i) * 250 * time.Microsecond) + for !stop.Load() { + s.mu.RLock() + time.Sleep(2 * time.Millisecond) + s.mu.RUnlock() + } + }(i) + } + time.Sleep(10 * time.Millisecond) + for i := 0; i < 5; i++ { // within the test WAL (auto-flush is off) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 0, [][]byte{blk(byte(i)), blk(byte(i + 1))}) + } else { + _, err = s.WriteContext(ctx, 0, blk(byte(i))) + } + cancel() + if err != nil { + t.Fatalf("write %d starved by readers: %v", i, err) + } + } + }) + } +} + +// Short locks block; an expired command refuses after the wait, without +// mutating (revises the polling-era lock tests to the agreed lock policy). +func TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait(t *testing.T) { + for _, lock := range []string{"store", "descriptor", "writer"} { + t.Run(lock, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + var unlock func() + switch lock { + case "store": + s.mu.Lock() + unlock = s.mu.Unlock + case "descriptor": + s.v3.pub.descMu.Lock() + unlock = s.v3.pub.descMu.Unlock + default: + s.v3.w.mu.Lock() + unlock = s.v3.w.mu.Unlock + } + var once sync.Once + release := func() { once.Do(unlock) } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + done := make(chan error, 1) + t.Cleanup(func() { release(); <-done }) + go func() { _, err := s.WriteContext(ctx, 0, blk(1)); done <- err }() + <-ctx.Done() // the command expires while the short lock is held + release() + err := <-done + done <- err // for the cleanup join + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatalf("expired writer after a %s lock wait: %v", lock, err) + } + if s.NextLSN() != 1 || s.dm.len() != 0 { + t.Fatal("expired writer mutated after the lock wait") + } + }) + } +} diff --git a/seaweed-block/core/storage/write_command_budget_test.go b/seaweed-block/core/storage/write_command_budget_test.go index 77f65864f1..6a6ba9c2c3 100644 --- a/seaweed-block/core/storage/write_command_budget_test.go +++ b/seaweed-block/core/storage/write_command_budget_test.go @@ -81,62 +81,8 @@ func TestWALStoreV3WriteBudgetKeepsTerminalFault(t *testing.T) { } } -func TestWALStoreV3WriteBudgetBoundsAppendLockWait(t *testing.T) { - s, _ := newMappedCheckpointStoreV3(t) - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) - defer cancel() - s.mu.Lock() - done := make(chan error, 1) - go func() { _, err := s.WriteContext(ctx, 0, blk(1)); done <- err }() - select { - case err := <-done: - if !errors.Is(err, ErrWALPressureTimeout) { - s.mu.Unlock() - t.Fatal(err) - } - case <-time.After(time.Second): - s.mu.Unlock() - t.Fatal("expired writer still waits for append lock") - } - s.mu.Unlock() - if s.NextLSN() != 1 || s.dm.len() != 0 { - t.Fatal("expired append waiter mutated") - } -} - -func TestWALStoreV3WriteBudgetBoundsPressureLocks(t *testing.T) { - for _, name := range []string{"descriptor", "writer"} { - t.Run(name, func(t *testing.T) { - s, _ := newMappedCheckpointStoreV3(t) - var unlock func() - if name == "descriptor" { - s.v3.pub.descMu.Lock() - unlock = s.v3.pub.descMu.Unlock - } else { - s.v3.w.mu.Lock() - unlock = s.v3.w.mu.Unlock - } - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) - defer cancel() - done := make(chan error, 1) - go func() { _, err := s.WriteContext(ctx, 0, blk(1)); done <- err }() - select { - case err := <-done: - if !errors.Is(err, ErrWALPressureTimeout) { - unlock() - t.Fatal(err) - } - case <-time.After(time.Second): - unlock() - t.Fatal("pressure snapshot did not respect command deadline") - } - unlock() - if s.NextLSN() != 1 || s.dm.len() != 0 { - t.Fatal("timed-out pressure sample granted a write") - } - }) - } -} +// The polling-era append/pressure lock tests are replaced by +// TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait (short locks block, #252). func TestWALStoreV3WritePressureSampleMatchesOccupancy(t *testing.T) { s, _ := newMappedCheckpointStoreV3(t) From 5eeb4ddf6eba15ea9edc4b9b4403841a3439e98d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 03:51:25 -0800 Subject: [PATCH 088/150] storage: #252 fold: the WAL writer checks the command budget before its first payload write Review fold (codex01 r4 residual P1): the post-rollover check still preceded w.append's descriptor snapshot, writer lock wait and encoding; a concurrent Sync's slot write can hold the descriptor lock (without the store lock) until the command expires. walWriterV3.append now takes the budget and checks it after those waits and the encoding, before the first physical write (no cancellation of a write already started). Red test: TestWALStoreV3WriteBudgetRefusesAfterDescriptorWaitBehindSync (a real Sync parked at its leader point, released after the write's rollover snapshot, holding the descriptor lock in its slot write until expiry). P2: codex03's TestWALStoreV3WriteBudgetRechecksAfterRollover (real pinned fallback, rollover slot I/O held/faulted; expired/healthy/fault) and TestWALStoreV3LocalBudgetIncludesWitnessedCaptureWait from his local amendment evidence; test cleanup joins are bounded; the invariant ledger names the current tests and the short-lock/writer-budget rules. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/wal_io_v3.go | 11 +- seaweed-block/core/storage/wal_io_v3_test.go | 38 ++--- .../core/storage/wal_lsn_order_v3_test.go | 20 +-- seaweed-block/core/storage/walstore_v3.go | 4 +- .../write_budget_rollover_controls_test.go | 157 ++++++++++++++++++ .../storage/write_command_budget_p1_test.go | 93 ++++++++++- seaweed-block/docs/design/invariants.md | 2 +- 7 files changed, 290 insertions(+), 35 deletions(-) create mode 100644 seaweed-block/core/storage/write_budget_rollover_controls_test.go diff --git a/seaweed-block/core/storage/wal_io_v3.go b/seaweed-block/core/storage/wal_io_v3.go index 59a05ffd2c..f89e568695 100644 --- a/seaweed-block/core/storage/wal_io_v3.go +++ b/seaweed-block/core/storage/wal_io_v3.go @@ -62,7 +62,11 @@ func newWALWriterV3(fd *os.File, pub *descriptorPublisherV3) (*walWriterV3, erro return &walWriterV3{pub: pub, nonce: d.Nonce, head: d.RetainedHead, highestLSN: max(d.CheckpointLSN, d.BaseLSN), writeAt: fd.WriteAt}, nil } -func (w *walWriterV3) append(e walEntryV3, durableLSN uint64) (uint64, error) { +// budget (nil = none) is the guest command's budget: checked after the +// descriptor snapshot, the writer lock wait and the encoding, before the first +// physical write, so an expired command starts no new payload I/O (#252). It +// never cancels a write already started. +func (w *walWriterV3) append(e walEntryV3, durableLSN uint64, budget func() error) (uint64, error) { // Descriptor snapshot precedes the writer lock. A concurrent floor advance // makes this snapshot conservative; reset must quiesce/recreate the writer. d, floor, ok := w.pub.walSnapshotV3() @@ -148,6 +152,11 @@ func (w *walWriterV3) append(e walEntryV3, durableLSN uint64) (uint64, error) { } return nil } + if budget != nil { + if err := budget(); err != nil { + return 0, err + } + } if len(pad) > 0 { if err := write(pad, w.head); err != nil { return 0, err diff --git a/seaweed-block/core/storage/wal_io_v3_test.go b/seaweed-block/core/storage/wal_io_v3_test.go index b113a13bf5..1190ff70a1 100644 --- a/seaweed-block/core/storage/wal_io_v3_test.go +++ b/seaweed-block/core/storage/wal_io_v3_test.go @@ -77,7 +77,7 @@ func TestWALIOV3_RealWriterReopenScan(t *testing.T) { // Caller binding fields are overwritten, not trusted. e.Nonce = [16]byte{0xFF} e.LogicalStart = 999 - if _, err := w.append(e, i-1); err != nil { + if _, err := w.append(e, i-1, nil); err != nil { t.Fatal(err) } } @@ -116,7 +116,7 @@ func TestWALIOV3_WrapPaddingAndSlack(t *testing.T) { start := uint64(size) - remaining f, p, w := newWALIOTestV3(t, start, start) d := p.current() - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryWrite, LBA: 1, Length: d.BlockSize, Data: make([]byte, d.BlockSize)}, 0); err != nil { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryWrite, LBA: 1, Length: d.BlockSize, Data: make([]byte, d.BlockSize)}, 0, nil); err != nil { t.Fatal(err) } if err := f.Sync(); err != nil { @@ -187,7 +187,7 @@ func TestWALIOV3_InstalledScanBeginsAtMaxTail(t *testing.T) { d.CheckpointLSN = 5 d.W = 5 d.MapCoveredCheckpoint = 5 - if _, err := w.append(walEntryV3{LSN: 6, Type: walEntryBarrier}, 5); err != nil { + if _, err := w.append(walEntryV3{LSN: 6, Type: walEntryBarrier}, 5, nil); err != nil { t.Fatal(err) } r, err := scanWALV3(f, d) @@ -207,20 +207,20 @@ func TestWALIOV3_ValidatedFrontierIntervals(t *testing.T) { d.BaseState = BaseInstalling d.BaseInstallID = [16]byte{1} d.BaseLSN = 100 - if _, err := w.append(walEntryV3{LSN: 102, Type: walEntryBarrier}, 100); err != nil { + if _, err := w.append(walEntryV3{LSN: 102, Type: walEntryBarrier}, 100, nil); err != nil { t.Fatal(err) } before := w.logicalHeadV3() - if _, err := w.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100); !errors.Is(err, ErrWALLSNOrder) { + if _, err := w.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100, nil); !errors.Is(err, ErrWALLSNOrder) { t.Fatalf("non-monotone101=%v", err) } if w.logicalHeadV3() != before { t.Fatal("refused101 advanced cursor") } - if _, err := w.append(walEntryV3{LSN: 104, Type: walEntryBarrier}, 100); err != nil { + if _, err := w.append(walEntryV3{LSN: 104, Type: walEntryBarrier}, 100, nil); err != nil { t.Fatal(err) } - if _, err := w.append(walEntryV3{LSN: 103, Type: walEntryBarrier}, 100); !errors.Is(err, ErrWALLSNOrder) { + if _, err := w.append(walEntryV3{LSN: 103, Type: walEntryBarrier}, 100, nil); !errors.Is(err, ErrWALLSNOrder) { t.Fatalf("late gap fill103=%v", err) } r, err := scanWALV3(f, d) @@ -236,7 +236,7 @@ func TestWALIOV3_FloorAndPwriteFailureRefuse(t *testing.T) { f, p, w := newWALIOTestV3(t, 16*1024, 0) _ = f before := w.logicalHeadV3() - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); !errors.Is(err, errWALFull) { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, errWALFull) { t.Fatalf("full ring error=%v", err) } if w.logicalHeadV3() != before { @@ -245,7 +245,7 @@ func TestWALIOV3_FloorAndPwriteFailureRefuse(t *testing.T) { if _, err := p.publish(nil, nil, func(d *descriptorV3) error { d.RetainedTail = 16 * 1024; return nil }); err != nil { t.Fatal(err) } - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); !errors.Is(err, errWALFull) { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, errWALFull) { t.Fatalf("fallback tail must still pin: %v", err) } if ok, err := p.rolloverIfPinned(); err != nil || !ok { @@ -253,10 +253,10 @@ func TestWALIOV3_FloorAndPwriteFailureRefuse(t *testing.T) { } calls := 0 w.writeAt = func(b []byte, off int64) (int, error) { calls++; return 1, io.ErrShortWrite } - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); !errors.Is(err, errWALPwrite) { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, errWALPwrite) { t.Fatalf("append failure=%v", err) } - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); !errors.Is(err, errWALPwrite) || calls != 1 { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, errWALPwrite) || calls != 1 { t.Fatal("failed append retried physical I/O") } } @@ -270,7 +270,7 @@ func TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned(t *testing.T) { } data := make([]byte, d.BlockSize) copy(data[100:], inner) - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryWrite, LBA: 4, Length: d.BlockSize, Data: data}, 0); err != nil { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryWrite, LBA: 4, Length: d.BlockSize, Data: data}, 0, nil); err != nil { t.Fatal(err) } r, err := scanWALV3(f, d) @@ -288,7 +288,7 @@ func TestWALIOV3_ConcurrentAppendsHaveUniqueCursors(t *testing.T) { done := make(chan error, 40) // Forty callers race the same first LSN: exactly one may consume it. for n := 0; n < 40; n++ { - go func() { _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); done <- err }() + go func() { _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); done <- err }() } deadline := time.NewTimer(5 * time.Second) defer deadline.Stop() @@ -310,7 +310,7 @@ func TestWALIOV3_ConcurrentAppendsHaveUniqueCursors(t *testing.T) { } // The caller's allocator serializes the subsequent increasing stream. for lsn := uint64(2); lsn <= 40; lsn++ { - if _, err := w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 0); err != nil { + if _, err := w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 0, nil); err != nil { t.Fatal(err) } } @@ -327,7 +327,7 @@ func TestWALIOV3_CounterRefusalBeforePwrite(t *testing.T) { _, _, w := newWALIOTestV3(t, counterMaxV3-30, counterMaxV3-30) calls := 0 w.writeAt = func(b []byte, off int64) (int, error) { calls++; return len(b), nil } - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); !errors.Is(err, ErrCounterExhausted) || calls != 0 { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, ErrCounterExhausted) || calls != 0 { t.Fatalf("counter error=%v writes=%d", err, calls) } } @@ -347,7 +347,7 @@ func TestWALIOV3_LastRepresentableRecordStillRecovers(t *testing.T) { start := uint64(counterMaxV3) - 70 f, p, w := newWALIOTestV3(t, start, start) d := p.current() - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); err != nil { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); err != nil { t.Fatal(err) } r, err := scanWALV3(f, d) @@ -357,14 +357,14 @@ func TestWALIOV3_LastRepresentableRecordStillRecovers(t *testing.T) { if len(r.Records) != 1 || r.Frontier != 1 || r.End != counterMaxV3 { t.Fatalf("last representable scan=%+v", r) } - if _, err := w.append(walEntryV3{LSN: 2, Type: walEntryBarrier}, 0); !errors.Is(err, ErrCounterExhausted) { + if _, err := w.append(walEntryV3{LSN: 2, Type: walEntryBarrier}, 0, nil); !errors.Is(err, ErrCounterExhausted) { t.Fatalf("next append=%v", err) } } func TestWALIOV3_RestoreCursorDoesNotPublishOrResetNonce(t *testing.T) { f, p, w := newWALIOTestV3(t, 0, 0) - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); err != nil { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); err != nil { t.Fatal(err) } r, err := scanWALV3(f, p.current()) @@ -420,7 +420,7 @@ func TestWALIOV3_UncertainPublisherStopsExistingAndNewWriters(t *testing.T) { } writes := 0 w.writeAt = func(b []byte, off int64) (int, error) { writes++; return f.WriteAt(b, off) } - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); err == nil { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); err == nil { t.Fatal("existing writer accepted uncertain publication") } if writes != 0 { diff --git a/seaweed-block/core/storage/wal_lsn_order_v3_test.go b/seaweed-block/core/storage/wal_lsn_order_v3_test.go index fa5dfaf3a1..174a3bb624 100644 --- a/seaweed-block/core/storage/wal_lsn_order_v3_test.go +++ b/seaweed-block/core/storage/wal_lsn_order_v3_test.go @@ -10,7 +10,7 @@ func TestWALLSNOrderV3_RefusesDuplicateAndLower(t *testing.T) { for _, lsn := range []uint64{9, 10} { t.Run(map[uint64]string{9: "lower", 10: "equal"}[lsn], func(t *testing.T) { f, p, w := newWALIOTestV3(t, 0, 0) - if _, e := w.append(walEntryV3{LSN: 10, Type: walEntryBarrier}, 0); e != nil { + if _, e := w.append(walEntryV3{LSN: 10, Type: walEntryBarrier}, 0, nil); e != nil { t.Fatal(e) } before := make([]byte, p.current().WALSize) @@ -18,7 +18,7 @@ func TestWALLSNOrderV3_RefusesDuplicateAndLower(t *testing.T) { t.Fatal(e) } head := w.logicalHeadV3() - if _, e := w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 0); !errors.Is(e, ErrWALLSNOrder) { + if _, e := w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 0, nil); !errors.Is(e, ErrWALLSNOrder) { t.Fatalf("non-increasing LSN %d verdict after10: %v", lsn, e) } after := make([]byte, len(before)) @@ -34,13 +34,13 @@ func TestWALLSNOrderV3_RefusesDuplicateAndLower(t *testing.T) { func TestWALLSNOrderV3_BatchConsumesFullRange(t *testing.T) { _, p, w := newWALIOTestV3(t, 0, 0) bs := p.current().BlockSize - if _, e := w.append(walEntryV3{LSN: 10, BatchCount: 2, Type: walEntryWriteBatch, Length: 2 * bs, Data: make([]byte, 2*bs)}, 0); e != nil { + if _, e := w.append(walEntryV3{LSN: 10, BatchCount: 2, Type: walEntryWriteBatch, Length: 2 * bs, Data: make([]byte, 2*bs)}, 0, nil); e != nil { t.Fatal(e) } - if _, e := w.append(walEntryV3{LSN: 11, Type: walEntryBarrier}, 0); !errors.Is(e, ErrWALLSNOrder) { + if _, e := w.append(walEntryV3{LSN: 11, Type: walEntryBarrier}, 0, nil); !errors.Is(e, ErrWALLSNOrder) { t.Fatalf("overlap with batch last LSN: %v", e) } - if _, e := w.append(walEntryV3{LSN: 12, Type: walEntryBarrier}, 0); e != nil { + if _, e := w.append(walEntryV3{LSN: 12, Type: walEntryBarrier}, 0, nil); e != nil { t.Fatal(e) } } @@ -56,7 +56,7 @@ func TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier(t *testing.T) { t.Fatal(e) } for _, lsn := range []uint64{101, 104} { - if _, e = w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 100); e != nil { + if _, e = w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 100, nil); e != nil { t.Fatal(e) } } @@ -80,10 +80,10 @@ func TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier(t *testing.T) { if e = recovered.restoreScanV3(r); e != nil { t.Fatal(e) } - if _, e = recovered.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100); !errors.Is(e, ErrWALLSNOrder) { + if _, e = recovered.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100, nil); !errors.Is(e, ErrWALLSNOrder) { t.Fatalf("restored kept frontier duplicate: %v", e) } - if _, e = recovered.append(walEntryV3{LSN: 102, Type: walEntryBarrier}, 100); e != nil { + if _, e = recovered.append(walEntryV3{LSN: 102, Type: walEntryBarrier}, 100, nil); e != nil { t.Fatalf("dropped104 pinned next102: %v", e) } } @@ -99,10 +99,10 @@ func TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed(t *testing.T) { if e != nil { t.Fatal(e) } - if _, e = w.append(walEntryV3{LSN: 100, Type: walEntryBarrier}, 100); !errors.Is(e, ErrWALLSNOrder) { + if _, e = w.append(walEntryV3{LSN: 100, Type: walEntryBarrier}, 100, nil); !errors.Is(e, ErrWALLSNOrder) { t.Fatalf("descriptor floor100 not consumed: %v", e) } - if _, e = w.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100); e != nil { + if _, e = w.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100, nil); e != nil { t.Fatal(e) } } diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 84b2312cab..a243862c41 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -673,7 +673,7 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64, budget fun if err := s.v3BudgetAfterRollover(budget); err != nil { return 0, err } - phys, err := s.v3.w.append(e, s.v3.wack.Load()) + phys, err := s.v3.w.append(e, s.v3.wack.Load(), budget) if err != nil { if errors.Is(err, errWALPwrite) { s.latchV3(err) @@ -731,7 +731,7 @@ func (s *WALStore) writeBatchV3Locked(startLBA uint32, blocks [][]byte, firstLSN if err := s.v3BudgetAfterRollover(budget); err != nil { return nil, err } - phys, err := s.v3.w.append(e, s.v3.wack.Load()) + phys, err := s.v3.w.append(e, s.v3.wack.Load(), budget) s.instr.appendLatency.Observe(time.Since(start)) s.walMutation.Add(1) if err != nil { diff --git a/seaweed-block/core/storage/write_budget_rollover_controls_test.go b/seaweed-block/core/storage/write_budget_rollover_controls_test.go new file mode 100644 index 0000000000..19e56c13a7 --- /dev/null +++ b/seaweed-block/core/storage/write_budget_rollover_controls_test.go @@ -0,0 +1,157 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" +) + +// A completed metadata rollover is retained, but it does not authorize new +// payload I/O after the command's original admission deadline. +func TestWALStoreV3WriteBudgetRechecksAfterRollover(t *testing.T) { + for _, batch := range []bool{false, true} { + for _, outcome := range []string{"expired", "healthy", "fault"} { + t.Run(fmt.Sprintf("batch=%t/%s", batch, outcome), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(2) + writeSynced(t, s, 0, 1) + writeSynced(t, s, 1, 2) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + s.SetRecoveryRetentionLSNs(1) + tail := s.v3.w.reclaimThroughV3(d.CheckpointLSN - 1) + if _, err := s.v3.pub.publish(nil, nil, func(n *descriptorV3) error { + n.RetainedTail = tail + n.RetainedHead = max(n.RetainedHead, tail) + return nil + }); err != nil { + t.Fatal(err) + } + if floor, ok := s.v3.pub.reuseFloor(); !ok || floor >= tail { + t.Fatal("no pinned fallback") + } + wait := 100 * time.Millisecond + if outcome == "healthy" { + wait = 5 * time.Second + } + ctx, cancel := context.WithTimeout(context.Background(), wait) + defer cancel() + boom := errors.New("rollover slot fault") + writeSlot := s.v3.pub.io.writeSlot + calls := 0 + s.v3.pub.io.writeSlot = func(off int64, b []byte) error { + calls++ + if outcome != "healthy" { + <-ctx.Done() + } + if outcome == "fault" { + return boom + } + return writeSlot(off, b) + } + defer func() { s.v3.pub.io.writeSlot = writeSlot }() + head, next, dirty := s.v3.w.logicalHeadV3(), s.NextLSN(), s.dm.len() + gen := s.v3.pub.current().SlotGen + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 2, [][]byte{blk(3), blk(4)}) + } else { + _, err = s.WriteContext(ctx, 2, blk(3)) + } + if calls != 1 { + t.Fatalf("rollover calls=%d err=%v", calls, err) + } + if outcome == "healthy" { + if err != nil || s.NextLSN() <= next { + t.Fatalf("healthy write: %v", err) + } + return + } + if s.NextLSN() != next || s.v3.w.logicalHeadV3() != head || s.dm.len() != dirty { + t.Fatal("refused command started payload I/O") + } + if outcome == "fault" { + if !errors.Is(err, boom) || s.stickyIOFault() == nil { + t.Fatalf("terminal fault masked: %v", err) + } + return + } + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatalf("expired command: %v", err) + } + if s.v3.pub.current().SlotGen <= gen { + t.Fatal("completed rollover was rolled back") + } + if floor, ok := s.v3.pub.reuseFloor(); !ok || floor != tail { + t.Fatalf("completed rollover not retained: %d %v", floor, ok) + } + }) + } + } +} + +type budgetCaptureWaitContext struct { + context.Context + parked chan struct{} + once sync.Once +} + +func (c *budgetCaptureWaitContext) Done() <-chan struct{} { + c.once.Do(func() { close(c.parked) }) + return c.Context.Done() +} +func TestWALStoreV3LocalBudgetIncludesWitnessedCaptureWait(t *testing.T) { + for _, batch := range []bool{false, true} { + t.Run(fmt.Sprint(batch), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.admissionTimeout = 40 * time.Millisecond + ctx := &budgetCaptureWaitContext{Context: context.Background(), parked: make(chan struct{})} + s.captureMu.Lock() + locked := true + done := make(chan error, 1) + defer func() { + if locked { + s.captureMu.Unlock() + } + select { + case <-done: + case <-time.After(time.Second): + t.Error("writer failed to join after release") + } + }() + go func() { + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 0, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.WriteContext(ctx, 0, blk(1)) + } + done <- err + }() + select { + case <-ctx.parked: + case <-time.After(time.Second): + t.Fatal("capture waiter was not witnessed") + } + select { + case err := <-done: + done <- err + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatal(err) + } + case <-time.After(time.Second): + t.Fatal("local budget restarted behind capture lock") + } + s.captureMu.Unlock() + locked = false + if s.NextLSN() != 1 || s.dm.len() != 0 { + t.Fatal("expired local waiter mutated") + } + }) + } +} diff --git a/seaweed-block/core/storage/write_command_budget_p1_test.go b/seaweed-block/core/storage/write_command_budget_p1_test.go index 3236bb0c71..e670a2652d 100644 --- a/seaweed-block/core/storage/write_command_budget_p1_test.go +++ b/seaweed-block/core/storage/write_command_budget_p1_test.go @@ -62,7 +62,16 @@ func TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders(t *testing.T) { s, _ := newMappedCheckpointStoreV3(t) var stop atomic.Bool var wg sync.WaitGroup - t.Cleanup(func() { stop.Store(true); wg.Wait() }) + t.Cleanup(func() { + stop.Store(true) + joined := make(chan struct{}) + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("reader goroutines did not finish") + } + }) // steady overlapping readers of the store lock (each holds it ~2 ms, // staggered): some reader is almost always inside, as under heavy // read traffic. A blocking Lock registers as a waiting writer and @@ -120,7 +129,14 @@ func TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) defer cancel() done := make(chan error, 1) - t.Cleanup(func() { release(); <-done }) + t.Cleanup(func() { + release() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("writer did not finish after the release") + } + }) go func() { _, err := s.WriteContext(ctx, 0, blk(1)); done <- err }() <-ctx.Done() // the command expires while the short lock is held release() @@ -135,3 +151,76 @@ func TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait(t *testing.T) { }) } } + +// #252 residual P1: the budget is checked inside the WAL writer, after its +// descriptor snapshot and writer lock wait. A real concurrent Sync holds the +// descriptor lock (its slot write, without the store lock) until the command +// has expired; the append waiting behind it must then refuse before any +// payload write, and the Sync completes normally. +func TestWALStoreV3WriteBudgetRefusesAfterDescriptorWaitBehindSync(t *testing.T) { + for _, batch := range []bool{false, true} { + name := map[bool]string{false: "single", true: "batch"}[batch] + t.Run(name, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + if _, err := s.Write(7, blk(7)); err != nil { // unsynced: the Sync has a slot to publish + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 400*time.Millisecond) + defer cancel() + entered := make(chan struct{}) + var enterOnce sync.Once + s.v3.testBeforeSlotWrite = func() error { + enterOnce.Do(func() { close(entered) }) + <-ctx.Done() // the command expires while the Sync holds the descriptor lock + return nil + } + // The Sync runs first and parks at its leader point (past its store + // lock phase); the write's post-rollover hook releases it, so it takes + // the descriptor lock for its slot write after the write's rollover + // snapshot and before the write's own append snapshot. + atLeader, proceed := make(chan struct{}), make(chan struct{}) + var leaderOnce, proceedOnce sync.Once + release := func() { proceedOnce.Do(func() { close(proceed) }) } + s.v3.testLeaderWaiting = func() { + leaderOnce.Do(func() { close(atLeader); <-proceed }) + } + syncDone := make(chan error, 1) + t.Cleanup(func() { + release() + cancel() + select { + case <-syncDone: + case <-time.After(5 * time.Second): + t.Error("the concurrent Sync did not finish") + } + }) + go func() { _, err := s.Sync(); syncDone <- err }() + <-atLeader + s.v3.testAfterRollover = func() { + release() + <-entered + } + head := s.v3.w.head + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 0, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.WriteContext(ctx, 0, blk(1)) + } + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatalf("expired command after the descriptor wait: %v", err) + } + if s.v3.w.head != head { + t.Fatalf("expired command started payload WAL I/O after the descriptor wait: head %d -> %d", head, s.v3.w.head) + } + if err := <-syncDone; err != nil { + t.Fatalf("the concurrent Sync: %v", err) + } + syncDone <- nil + s.v3.testAfterRollover, s.v3.testBeforeSlotWrite, s.v3.testLeaderWaiting = nil, nil, nil + if _, err := s.WriteContext(context.Background(), 0, blk(3)); err != nil { + t.Fatalf("a fresh write after the refusal: %v", err) + } + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0d394ff0f2..9ee002abfa 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -332,7 +332,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-RECORD-001` | An impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | | `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB | -| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. One earliest command deadline spans adapter batches and bounded store admission locks/snapshots; expiry before append preserves the WAL/nextLSN/dirty state. Issued WAL I/O retains its existing lifecycle ownership. Pure caller expiry stays retryable through required-observer classification and NVMe; a provided physical cause remains terminal. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire`; `write_command_budget.go`; `StorageBackend.Write`; NVMe `handleWrite` | `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestSessionWriteBudgetIncludesDispatchQueue`, `TestWALStoreV3WriteBudgetBoundsAppendLockWait`, `TestWALStoreV3WriteBudgetBoundsPressureLocks`, `TestWALStoreV3WritePressureSampleMatchesOccupancy`, `TestStorageBackendExpiredWriteDoesNotAppend`, `TestStorageBackendRequiredObserverDeadlineStaysRetryable`; `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | +| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. One earliest command deadline spans adapter batches and the long store admission waits (capture, lifecycle); short locks (store, descriptor, WAL writer) are taken blocking and keep RWMutex writer preference, with the deadline checked once held. The deadline is checked again after a checkpoint rollover and inside the WAL writer after its descriptor snapshot, lock wait and encoding, before the first payload write: an expired command starts no new payload WAL I/O, and expiry before append preserves the WAL/nextLSN/dirty state. A batch that returns a committed prefix with a storage error keeps that error in the classified error set. Issued WAL I/O retains its existing lifecycle ownership. Pure caller expiry stays retryable through required-observer classification and NVMe; a provided physical cause remains terminal. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire`; `write_command_budget.go`; `StorageBackend.Write`; NVMe `handleWrite` | `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestSessionWriteBudgetIncludesDispatchQueue`, `TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait`, `TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders`, `TestWALStoreV3WriteBudgetRefusesNewPayloadAfterRollover`, `TestWALStoreV3WriteBudgetRechecksAfterRollover`, `TestWALStoreV3WriteBudgetRefusesAfterDescriptorWaitBehindSync`, `TestStorageBackendPartialBatchPhysicalFaultSurvivesObserverDeadline`, `TestWALStoreV3WritePressureSampleMatchesOccupancy`, `TestStorageBackendExpiredWriteDoesNotAppend`, `TestStorageBackendRequiredObserverDeadlineStaysRetryable`; `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | | `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint releases only complete validated record ends covered by the checkpoint and outside the retention window; an installing BASE retains its install suffix. Physical recovery rebuilds the volatile boundary index only from the trusted kept scan, without restoring a disconnect cursor. Tail/head/map/checkpoint/W publish together, followed by metadata-only rollover; both slot tails still pin reuse. Failure grants no reuse and retains exact dirty retry identity. Checkpoint publication excludes writer admission through both-slot rollover and dirty-reference retirement. Idle, unchanged-checkpoint and admission settle pending rollover; catch-up revalidates tail/checkpoint before delivering its buffered scan. | M1 checkpoint / existing two-slot retirement | `wal_io_v3.go` `reclaimThroughV3`, `rememberReclaimScanV3`; `walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `descriptor_v3.go` `rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse`, `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint`, tagged `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB | | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | From 3abdc01336f9906cedef156a6e9a83ec0514ded2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 04:19:30 -0800 Subject: [PATCH 089/150] test(storage): settle held hydration workers before cleanup --- .../checkpoint_append_progress_v3_test.go | 31 +++++++++++++------ 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index b12f704f6c..4ddf562718 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -591,7 +591,19 @@ func TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush(t *testing.T) { } entered, release := holdNextGet(t, remote) done := make(chan error, 1) + joined := make(chan struct{}) + // Release the fetch before joining, including failures before release(). + // Register before launch so store/layer cleanup never precedes the join. + t.Cleanup(func() { + release() + select { + case <-joined: + case <-time.After(ctLocalBound): + t.Errorf("held hydration reader did not settle within %v after release", ctLocalBound) + } + }) go func() { + defer close(joined) got, err := s.Read(9) if err == nil && !bytes.Equal(got, blk(0xB9)) { err = errors.New("held read did not return newer local bytes") @@ -599,17 +611,18 @@ func TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush(t *testing.T) { done <- err }() waitKey(t, entered, "cold fill before a competing local write") - if _, err := s.Write(9, blk(0xB9)); err != nil { - t.Fatal(err) - } - if flush { - if _, err := s.Sync(); err != nil { - t.Fatal(err) + within(t, "local write and optional flush while hydration is held", func() error { + if _, err := s.Write(9, blk(0xB9)); err != nil { + return err } - if err := s.flusher.flushOnce(); err != nil { - t.Fatal(err) + if flush { + if _, err := s.Sync(); err != nil { + return err + } + return s.flusher.flushOnce() } - } + return nil + }) dirty := s.dm.len() release() if err := waitErr(t, done, "fill and post-miss WAL recheck"); err != nil { From e9aecf52dc0c08ae34eb85e9c2afc1116dc4e5ee Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 04:42:38 -0800 Subject: [PATCH 090/150] master: name the precondition that refused a workspace move MoveWorkspace refused four different conditions with one message and no log line: an unknown source, an unregistered target node, a target that is the source, and target endpoints that are not registered. Each now has its own FailedPrecondition message, logged with the volume and request. The endpoint refusal also says what is registered: the node's own pair for a volume without per-volume bindings, else its live bindings on that node (a slot-1 target on a node registered at slot 0 shows up here). Co-Authored-By: Claude Opus 5.5 --- .../master/workspace_move_refusal_test.go | 128 ++++++++++++++++++ .../core/host/master/workspace_service.go | 37 ++++- 2 files changed, 163 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/host/master/workspace_move_refusal_test.go diff --git a/seaweed-block/core/host/master/workspace_move_refusal_test.go b/seaweed-block/core/host/master/workspace_move_refusal_test.go new file mode 100644 index 0000000000..1fb70288de --- /dev/null +++ b/seaweed-block/core/host/master/workspace_move_refusal_test.go @@ -0,0 +1,128 @@ +package master + +import ( + "bytes" + "context" + "log" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +type syncBuffer struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *syncBuffer) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.Write(p) +} + +func (s *syncBuffer) String() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.String() +} + +// A refused move names the precondition that failed, in the gRPC status and +// in the master log: an unknown source, an unregistered target node, a +// target that is the source, or target endpoints that are not registered +// (with what is registered: the node's pair, or the volume's live bindings +// on that node). A slot-1 target on a node registered at slot 0 is the last +// kind. +func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { + logs := &syncBuffer{} + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + Logger: log.New(logs, "", 0), + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil + }}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn) + for _, n := range []lifecycle.NodeRegistration{ + {ServerID: "node-a", DataAddr: "127.0.0.1:19101", CtrlAddr: "127.0.0.1:19102"}, + {ServerID: "node-b", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"}, + } { + if _, err := m.Lifecycle().Nodes.RegisterNode(n); err != nil { + t.Fatal(err) + } + } + for _, v := range []string{"placed", "unplaced", "bound"} { + if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: v, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + } + if _, err := m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "placed", DesiredRF: 1, + Candidates: []lifecycle.PlacementCandidate{{VolumeID: "placed", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { + t.Fatal(err) + } + // "bound" has explicit per-volume bindings: its source on node-a and a + // prepared target on node-b at slot 2. + for _, b := range []*control.WorkspaceBinding{ + {VolumeId: "bound", ServerId: "node-a", DataAddr: "127.0.0.1:19121", CtrlAddr: "127.0.0.1:19122"}, + {VolumeId: "bound", ServerId: "node-b", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322"}, + } { + if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + } + if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "bound", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + + move := func(vol, server, data, ctrl string) *control.WorkspaceMove { + return &control.WorkspaceMove{RequestId: vol + "-" + server + "-" + data, VolumeId: vol, ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", + TargetServerId: server, TargetDataAddr: data, TargetCtrlAddr: ctrl, Kind: "clean"} + } + for _, c := range []struct { + name string + q *control.WorkspaceMove + want string + }{ + {"unknown source", move("unplaced", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"), `move source unknown: no issued move or placement names replica "r1" at epoch 1`}, + {"unknown target node", move("placed", "node-z", "127.0.0.1:19301", "127.0.0.1:19302"), `move target node "node-z" is not registered`}, + {"target is the source", move("placed", "node-a", "127.0.0.1:19101", "127.0.0.1:19102"), `move target "node-a" is the current source host`}, + {"slot-1 target, node registered at slot 0", move("placed", "node-b", "127.0.0.1:19311", "127.0.0.1:19312"), + `move target endpoints 127.0.0.1:19311/127.0.0.1:19312 on "node-b" are not registered (the node registers 127.0.0.1:19301/127.0.0.1:19302; no per-volume binding is prepared)`}, + {"explicit binding elsewhere", move("bound", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"), + `move target endpoints 127.0.0.1:19301/127.0.0.1:19302 on "node-b" are not registered (live bindings on that node: 127.0.0.1:19321/127.0.0.1:19322)`}, + } { + t.Run(c.name, func(t *testing.T) { + _, err := ws.MoveWorkspace(ctx, c.q) + if status.Code(err) != codes.FailedPrecondition || status.Convert(err).Message() != c.want { + t.Fatalf("refusal %v; want FailedPrecondition %q", err, c.want) + } + if line := `MoveWorkspace refused volume="` + c.q.VolumeId + `" request="` + c.q.RequestId + `": ` + c.want; !strings.Contains(logs.String(), line) { + t.Fatalf("log lacks %q:\n%s", line, logs.String()) + } + }) + } + // The slot-0 target passes these preconditions (it fails later, at the + // clean-move ACK check, for a different reason). + _, err = ws.MoveWorkspace(ctx, move("placed", "node-b", "127.0.0.1:19301", "127.0.0.1:19302")) + if err == nil || strings.Contains(err.Error(), "move target") || strings.Contains(err.Error(), "move source") { + t.Fatalf("slot-0 target: %v; want past the endpoint preconditions", err) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index f8a068cff9..1fb9cd5af5 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -2,6 +2,8 @@ package master import ( "context" + "fmt" + "strings" "time" "github.com/seaweedfs/seaweed-block/core/authority" @@ -163,8 +165,20 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) matched = true } } - if oldHost == "" || !ok || target.ServerID == oldHost || !matched { - return nil, status.Error(codes.FailedPrecondition, "move needs known source slot and registered target endpoints") + var refusal string + switch { + case oldHost == "": + refusal = fmt.Sprintf("move source unknown: no issued move or placement names replica %q at epoch %d", q.GetExpectedReplicaId(), q.GetExpectedEpoch()) + case !ok: + refusal = fmt.Sprintf("move target node %q is not registered", q.GetTargetServerId()) + case target.ServerID == oldHost: + refusal = fmt.Sprintf("move target %q is the current source host", target.ServerID) + case !matched: + refusal = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit)) + } + if refusal != "" { + s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal) + return nil, status.Error(codes.FailedPrecondition, refusal) } if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { return nil, workspaceError(err) @@ -180,6 +194,25 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) return grantFact(r), nil } +// registeredTargetEndpoints describes what a move to target may name: the +// node's own pair for a volume without explicit bindings, else its live +// bindings on that node. +func registeredTargetEndpoints(target lifecycle.NodeRegistration, bindings []lifecycle.WorkspaceBinding, explicit bool) string { + if !explicit { + return fmt.Sprintf("the node registers %s/%s; no per-volume binding is prepared", target.DataAddr, target.CtrlAddr) + } + var live []string + for _, b := range bindings { + if !b.Retired && b.ServerID == target.ServerID { + live = append(live, b.DataAddr+"/"+b.CtrlAddr) + } + } + if len(live) == 0 { + return "the volume has explicit bindings but none live on that node" + } + return "live bindings on that node: " + strings.Join(live, ", ") +} + func (s *services) QueryWorkspace(ctx context.Context, q *control.WorkspaceVolume) (*control.WorkspaceStatus, error) { s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() From d8c42d0928eacb3384fd207e6acb9dd5a4a095da Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 04:57:41 -0800 Subject: [PATCH 091/150] master: a move target may use any port on the target node's host A volume without per-volume bindings could move only to the target node's single registered address pair, which models one slot per node: a host serving several slots refused every move whose target landed on a slot other than the registered one (slot 1 while slot 0 is held). The target now needs both endpoints on the node's registered hosts (literal host part, any port, no name resolution), and the existing collision check still refuses endpoints another live assignment or binding owns. Volumes with per-volume bindings keep the exact binding match. Co-Authored-By: Claude Opus 5.5 --- .../master/workspace_move_refusal_test.go | 19 +-- .../host/master/workspace_move_slot_test.go | 114 ++++++++++++++++++ .../core/host/master/workspace_service.go | 20 ++- 3 files changed, 142 insertions(+), 11 deletions(-) create mode 100644 seaweed-block/core/host/master/workspace_move_slot_test.go diff --git a/seaweed-block/core/host/master/workspace_move_refusal_test.go b/seaweed-block/core/host/master/workspace_move_refusal_test.go index 1fb70288de..61ec0f4c67 100644 --- a/seaweed-block/core/host/master/workspace_move_refusal_test.go +++ b/seaweed-block/core/host/master/workspace_move_refusal_test.go @@ -39,8 +39,7 @@ func (s *syncBuffer) String() string { // in the master log: an unknown source, an unregistered target node, a // target that is the source, or target endpoints that are not registered // (with what is registered: the node's pair, or the volume's live bindings -// on that node). A slot-1 target on a node registered at slot 0 is the last -// kind. +// on that node). func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { logs := &syncBuffer{} m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, @@ -104,8 +103,8 @@ func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { {"unknown source", move("unplaced", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"), `move source unknown: no issued move or placement names replica "r1" at epoch 1`}, {"unknown target node", move("placed", "node-z", "127.0.0.1:19301", "127.0.0.1:19302"), `move target node "node-z" is not registered`}, {"target is the source", move("placed", "node-a", "127.0.0.1:19101", "127.0.0.1:19102"), `move target "node-a" is the current source host`}, - {"slot-1 target, node registered at slot 0", move("placed", "node-b", "127.0.0.1:19311", "127.0.0.1:19312"), - `move target endpoints 127.0.0.1:19311/127.0.0.1:19312 on "node-b" are not registered (the node registers 127.0.0.1:19301/127.0.0.1:19302; no per-volume binding is prepared)`}, + {"target on another host", move("placed", "node-b", "10.9.9.9:19311", "127.0.0.1:19312"), + `move target endpoints 10.9.9.9:19311/127.0.0.1:19312 on "node-b" are not registered (not on the node's hosts: it registers 127.0.0.1:19301/127.0.0.1:19302; no per-volume binding is prepared)`}, {"explicit binding elsewhere", move("bound", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"), `move target endpoints 127.0.0.1:19301/127.0.0.1:19302 on "node-b" are not registered (live bindings on that node: 127.0.0.1:19321/127.0.0.1:19322)`}, } { @@ -119,10 +118,12 @@ func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { } }) } - // The slot-0 target passes these preconditions (it fails later, at the - // clean-move ACK check, for a different reason). - _, err = ws.MoveWorkspace(ctx, move("placed", "node-b", "127.0.0.1:19301", "127.0.0.1:19302")) - if err == nil || strings.Contains(err.Error(), "move target") || strings.Contains(err.Error(), "move source") { - t.Fatalf("slot-0 target: %v; want past the endpoint preconditions", err) + // Slot-0 and slot-1 targets on the node's host pass these preconditions + // (they fail later, at the clean-move ACK check, for a different reason). + for _, data := range []string{"127.0.0.1:19301", "127.0.0.1:19311"} { + _, err = ws.MoveWorkspace(ctx, move("placed", "node-b", data, "127.0.0.1:19312")) + if err == nil || strings.Contains(err.Error(), "move target") || strings.Contains(err.Error(), "move source") { + t.Fatalf("target %s on the node's host: %v; want past the endpoint preconditions", data, err) + } } } diff --git a/seaweed-block/core/host/master/workspace_move_slot_test.go b/seaweed-block/core/host/master/workspace_move_slot_test.go new file mode 100644 index 0000000000..70046c2073 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_move_slot_test.go @@ -0,0 +1,114 @@ +package master + +import ( + "context" + "strconv" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// The T08 shape: two volumes without per-volume bindings, nodes registered +// at slot 0 of their host. "a1" holds slot 0 on node-a; "a2" lives on +// node-b and moves back to node-a. Its target lands on slot 1 (slot 0 is +// held) and is granted; a target on a1's live slot-0 endpoints is refused by +// the collision check, and one on another host's address by the ownership +// check. The grant routes a2 to the slot-1 endpoints it asked for. +func TestWorkspaceMoveToAnotherSlotOnTheTargetHost(t *testing.T) { + heads := map[string]authority.WorkspaceHead{"a2": {Gen: 9, Epoch: 1, Holder: "node-b/r1", RemoteLSN: 42, Detached: true}} + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + WorkspaceHeadReader: func(_ context.Context, v string) (authority.WorkspaceHead, error) { return heads[v], nil }}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn) + slot := func(base, n int) (string, string) { + return "127.0.0.1:" + strconv.Itoa(base+10*n+1), "127.0.0.1:" + strconv.Itoa(base+10*n+2) + } + for _, n := range []struct { + id string + base int + }{{"node-a", 19100}, {"node-b", 19300}} { + d, c := slot(n.base, 0) + if _, err := m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: n.id, DataAddr: d, CtrlAddr: c}); err != nil { + t.Fatal(err) + } + } + place := func(vol, server string, base int) authority.AuthorityBasis { + t.Helper() + if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: vol, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + if _, err := m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: vol, DesiredRF: 1, + Candidates: []lifecycle.PlacementCandidate{{VolumeID: vol, ServerID: server, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { + t.Fatal(err) + } + d, c := slot(base, 0) + if _, err := control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: vol, ReplicaId: "r1", DataAddr: d, CtrlAddr: c}}}); err != nil { + t.Fatal(err) + } + if _, err := m.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + return waitAuthorityLine(t, m.Publisher(), vol) + } + a1 := place("a1", "node-a", 19100) // holds node-a slot 0 + a2 := place("a2", "node-b", 19300) + if a1.DataAddr != "127.0.0.1:19101" || a2.DataAddr != "127.0.0.1:19301" { + t.Fatalf("fixture lines a1=%+v a2=%+v", a1, a2) + } + // a2 stops cleanly on node-b: lease, revocation, ACK of its detached HEAD. + id := &control.WorkspaceIdentity{VolumeId: "a2", ReplicaId: "r1", Epoch: a2.Epoch} + if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil { + t.Fatal(err) + } + if _, err := ws.RevokeWorkspace(ctx, id); err != nil { + t.Fatal(err) + } + if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil { + t.Fatal(err) + } + move := func(req, data, ctrl string) *control.WorkspaceMove { + return &control.WorkspaceMove{RequestId: req, VolumeId: "a2", ExpectedReplicaId: "r1", ExpectedEpoch: a2.Epoch, TargetReplicaId: "r1", + TargetServerId: "node-a", TargetDataAddr: data, TargetCtrlAddr: ctrl, Kind: "clean"} + } + d0, c0 := slot(19100, 0) + if _, err := ws.MoveWorkspace(ctx, move("onto-a1", d0, c0)); err == nil || !strings.Contains(err.Error(), "endpoint belongs to live assignment") { + t.Fatalf("move onto a1's live slot-0 endpoints: %v; want the collision refusal", err) + } + if _, err := ws.MoveWorkspace(ctx, move("other-host", "10.9.9.9:19111", "10.9.9.9:19112")); err == nil || !strings.Contains(err.Error(), `endpoints 10.9.9.9:19111/10.9.9.9:19112 on "node-a" are not registered`) { + t.Fatalf("move to another host's address: %v; want the ownership refusal", err) + } + d1, c1 := slot(19100, 1) + if _, err := ws.MoveWorkspace(ctx, move("ctrl-other-host", d1, "10.9.9.9:19112")); err == nil || !strings.Contains(err.Error(), `on "node-a" are not registered`) { + t.Fatalf("move with its ctrl endpoint on another host: %v; want the ownership refusal", err) + } + g, err := ws.MoveWorkspace(ctx, move("slot-1", d1, c1)) + if err != nil { + t.Fatalf("move to node-a slot 1 while slot 0 is held: %v", err) + } + line, ok := m.Publisher().VolumeAuthorityLine("a2") + if !g.Issued || g.NewHost != "node-a" || g.OldHost != "node-b" || !ok || line.Epoch != g.NewEpoch || line.DataAddr != d1 || line.CtrlAddr != c1 { + t.Fatalf("grant %+v line %+v; want a2 issued on node-a at %s/%s", g, line, d1, c1) + } + if l1, _ := m.Publisher().VolumeAuthorityLine("a1"); l1.DataAddr != d0 || l1.Epoch != a1.Epoch { + t.Fatalf("a1 changed: %+v", l1) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 1fb9cd5af5..6df4603586 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -3,6 +3,7 @@ package master import ( "context" "fmt" + "net" "strings" "time" @@ -159,7 +160,11 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) if err != nil { return nil, workspaceError(err) } - matched := !explicit && target.DataAddr == q.GetTargetDataAddr() && target.CtrlAddr == q.GetTargetCtrlAddr() + // A volume without per-volume bindings may move to any port on the + // target node's registered hosts (a host runs several slots); the + // collision check below still refuses endpoints another assignment or + // binding owns. The host match is the proof the endpoints are that node's. + matched := !explicit && sameHost(q.GetTargetDataAddr(), target.DataAddr) && sameHost(q.GetTargetCtrlAddr(), target.CtrlAddr) for _, b := range bindings { if !b.Retired && b.ServerID == q.GetTargetServerId() && b.DataAddr == q.GetTargetDataAddr() && b.CtrlAddr == q.GetTargetCtrlAddr() { matched = true @@ -194,12 +199,23 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) return grantFact(r), nil } +// sameHost reports whether two host:port addresses name the same host: the +// literal host parts after SplitHostPort, no name resolution. +func sameHost(a, b string) bool { + ha, _, err := net.SplitHostPort(a) + if err != nil { + return false + } + hb, _, err := net.SplitHostPort(b) + return err == nil && ha != "" && ha == hb +} + // registeredTargetEndpoints describes what a move to target may name: the // node's own pair for a volume without explicit bindings, else its live // bindings on that node. func registeredTargetEndpoints(target lifecycle.NodeRegistration, bindings []lifecycle.WorkspaceBinding, explicit bool) string { if !explicit { - return fmt.Sprintf("the node registers %s/%s; no per-volume binding is prepared", target.DataAddr, target.CtrlAddr) + return fmt.Sprintf("not on the node's hosts: it registers %s/%s; no per-volume binding is prepared", target.DataAddr, target.CtrlAddr) } var live []string for _, b := range bindings { From ec40814443919f620fffb43dcb17cdb6231d4763 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 05:34:16 -0800 Subject: [PATCH 092/150] master: validate a move target's endpoints; log a refusal outside the lock Fold of the #260 review: - the target endpoints get the binding endpoint rules before admission (host:port, numeric port 1..65535, data and ctrl distinct), without registering anything: a host match alone admitted ':0', ':65536', a non-numeric or empty port, or identical data and ctrl, and the move would have issued and cleared the source lease; - host parts compare in canonical form (equivalent IP spellings); - the refusal log runs after workspaceMu is released; - the comment no longer calls the host match a proof; the invariants ledger gets the move-admission row. Co-Authored-By: Claude Opus 5.5 --- .../master/workspace_move_refusal_test.go | 73 +++++++++++++++++++ .../host/master/workspace_move_slot_test.go | 19 +++++ .../core/host/master/workspace_service.go | 33 +++++---- .../core/lifecycle/workspace_bindings.go | 19 +++++ seaweed-block/docs/design/invariants.md | 1 + 5 files changed, 131 insertions(+), 14 deletions(-) diff --git a/seaweed-block/core/host/master/workspace_move_refusal_test.go b/seaweed-block/core/host/master/workspace_move_refusal_test.go index 61ec0f4c67..9a7e113705 100644 --- a/seaweed-block/core/host/master/workspace_move_refusal_test.go +++ b/seaweed-block/core/host/master/workspace_move_refusal_test.go @@ -127,3 +127,76 @@ func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { } } } + +// blockingWriter blocks the first write that contains marker until +// released; other writes pass. +type blockingWriter struct { + marker string + entered, release chan struct{} + once sync.Once +} + +func (b *blockingWriter) Write(p []byte) (int, error) { + if !strings.Contains(string(p), b.marker) { + return len(p), nil + } + first := false + b.once.Do(func() { first = true }) + if first { + close(b.entered) + <-b.release + } + return len(p), nil +} + +// A refused move is logged after workspaceMu is released: while the log +// writer is blocked, another workspace RPC still gets the lock. +func TestWorkspaceMoveRefusalLogsOutsideTheWorkspaceLock(t *testing.T) { + w := &blockingWriter{marker: "MoveWorkspace refused", entered: make(chan struct{}), release: make(chan struct{})} + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, Logger: log.New(w, "", 0), + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(w.release) }) } + defer release() + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + ws := control.NewWorkspaceServiceClient(conn) + if _, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { + _, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "r", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", + TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"}) + done <- err + }() + select { + case <-w.entered: + case <-time.After(10 * time.Second): + t.Fatal("the refusal was never logged") + } + qctx, qcancel := context.WithTimeout(ctx, 5*time.Second) + defer qcancel() + if _, err := ws.QueryWorkspace(qctx, &control.WorkspaceVolume{VolumeId: "v"}); err != nil { + t.Fatalf("workspace RPC while the refusal log is blocked: %v; want workspaceMu free", err) + } + release() + select { + case err := <-done: + if status.Code(err) != codes.FailedPrecondition { + t.Fatalf("move: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("the move did not return after the log was released") + } +} diff --git a/seaweed-block/core/host/master/workspace_move_slot_test.go b/seaweed-block/core/host/master/workspace_move_slot_test.go index 70046c2073..f6a31dbac6 100644 --- a/seaweed-block/core/host/master/workspace_move_slot_test.go +++ b/seaweed-block/core/host/master/workspace_move_slot_test.go @@ -100,6 +100,25 @@ func TestWorkspaceMoveToAnotherSlotOnTheTargetHost(t *testing.T) { if _, err := ws.MoveWorkspace(ctx, move("ctrl-other-host", d1, "10.9.9.9:19112")); err == nil || !strings.Contains(err.Error(), `on "node-a" are not registered`) { t.Fatalf("move with its ctrl endpoint on another host: %v; want the ownership refusal", err) } + // Invalid endpoints on the right host are refused before anything is + // written: the epoch, the journal, the lease and the ACK stay as they were. + before := m.Publisher().WorkspaceState("a2") + for _, bad := range []struct{ name, data, ctrl string }{ + {"non-numeric port", "127.0.0.1:bad", c1}, + {"port 0", "127.0.0.1:0", c1}, + {"port 65536", d1, "127.0.0.1:65536"}, + {"empty port", "127.0.0.1:", c1}, + {"data equals ctrl", d1, d1}, + } { + if _, err := ws.MoveWorkspace(ctx, move("bad-"+bad.name, bad.data, bad.ctrl)); err == nil || !strings.Contains(err.Error(), "move target endpoints invalid") { + t.Fatalf("%s: %v; want the invalid-endpoint refusal", bad.name, err) + } + after := m.Publisher().WorkspaceState("a2") + line, _ := m.Publisher().VolumeAuthorityLine("a2") + if line.Epoch != a2.Epoch || after == nil || len(after.Moves) != 0 || after.Ack == nil || before.Ack == nil || *after.Ack != *before.Ack || after.Lease == nil || !after.Lease.Revoking { + t.Fatalf("%s: state changed by a refused move: line %+v state %+v", bad.name, line, after) + } + } g, err := ws.MoveWorkspace(ctx, move("slot-1", d1, c1)) if err != nil { t.Fatalf("move to node-a slot 1 while slot 0 is held: %v", err) diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 6df4603586..fabe00514c 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -3,7 +3,6 @@ package master import ( "context" "fmt" - "net" "strings" "time" @@ -146,6 +145,14 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) } // Remote reads never hold the workspace mutation lock. Re-read every // local precondition below; Publisher checks the expected epoch atomically. + // A refusal is logged after the lock is released (deferred first, so it + // runs last): a slow log writer never holds workspaceMu. + var refusal string + defer func() { + if refusal != "" { + s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal) + } + }() s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() if err := ctx.Err(); err != nil { @@ -161,17 +168,20 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) return nil, workspaceError(err) } // A volume without per-volume bindings may move to any port on the - // target node's registered hosts (a host runs several slots); the - // collision check below still refuses endpoints another assignment or - // binding owns. The host match is the proof the endpoints are that node's. + // target node's registered hosts (a host runs several slots): the host + // match ties the endpoints to that node's registration (it trusts the + // registration; it is not an identity proof). The collision check below + // still refuses endpoints another assignment or binding owns. matched := !explicit && sameHost(q.GetTargetDataAddr(), target.DataAddr) && sameHost(q.GetTargetCtrlAddr(), target.CtrlAddr) + endpointErr := lifecycle.ValidateWorkspaceEndpoints(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: q.GetTargetServerId(), DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}) for _, b := range bindings { if !b.Retired && b.ServerID == q.GetTargetServerId() && b.DataAddr == q.GetTargetDataAddr() && b.CtrlAddr == q.GetTargetCtrlAddr() { matched = true } } - var refusal string switch { + case endpointErr != nil: + refusal = fmt.Sprintf("move target endpoints invalid: %v", endpointErr) case oldHost == "": refusal = fmt.Sprintf("move source unknown: no issued move or placement names replica %q at epoch %d", q.GetExpectedReplicaId(), q.GetExpectedEpoch()) case !ok: @@ -182,7 +192,6 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) refusal = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit)) } if refusal != "" { - s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal) return nil, status.Error(codes.FailedPrecondition, refusal) } if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { @@ -199,15 +208,11 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) return grantFact(r), nil } -// sameHost reports whether two host:port addresses name the same host: the -// literal host parts after SplitHostPort, no name resolution. +// sameHost reports whether two host:port addresses name the same host: +// canonical host parts (equivalent IP spellings equal), no name resolution. func sameHost(a, b string) bool { - ha, _, err := net.SplitHostPort(a) - if err != nil { - return false - } - hb, _, err := net.SplitHostPort(b) - return err == nil && ha != "" && ha == hb + ha := lifecycle.WorkspaceEndpointHost(a) + return ha != "" && ha == lifecycle.WorkspaceEndpointHost(b) } // registeredTargetEndpoints describes what a move to target may name: the diff --git a/seaweed-block/core/lifecycle/workspace_bindings.go b/seaweed-block/core/lifecycle/workspace_bindings.go index 5d51a472ba..d3fbefd8e9 100644 --- a/seaweed-block/core/lifecycle/workspace_bindings.go +++ b/seaweed-block/core/lifecycle/workspace_bindings.go @@ -119,6 +119,25 @@ func validateWorkspaceBinding(b WorkspaceBinding) error { return nil } +// ValidateWorkspaceEndpoints applies a binding's endpoint rules (host:port +// with a numeric port 1..65535, data and ctrl distinct) without registering +// anything. +func ValidateWorkspaceEndpoints(b WorkspaceBinding) error { return validateWorkspaceBinding(b) } + +// WorkspaceEndpointHost returns addr's host in canonical form (equivalent IP +// spellings compare equal; names lower-cased; no DNS), or "" if addr is not +// host:port. +func WorkspaceEndpointHost(addr string) string { + h, _, err := net.SplitHostPort(addr) + if err != nil || h == "" { + return "" + } + if ip := net.ParseIP(h); ip != nil { + return ip.String() + } + return strings.ToLower(h) +} + // Compare numeric ports and equivalent IP spellings without DNS/network I/O. func workspaceEndpointKey(addr string) string { h, p, err := net.SplitHostPort(addr) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6ee4916e12..671d0687e1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -93,6 +93,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | +| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding; each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | | Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | | Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` | From 6a063f2ec87d786718602a8c546b7f1c960fa49e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 05:44:54 -0800 Subject: [PATCH 093/150] test: freeze the publisher clock while the extension write is held (#247 hang) TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose hung ~9m40s in a loaded qual run (goroutine dump: one extender held in the store hook, four queued on p.mu, renewers looping, the test in the progress loop). Cause: a test bug. The test's publisher clock was real time with a 2 s TTL; while the held extension write holds p.mu no horizon can move, so a late test goroutine let horizons expire, renewals were refused, and the progress condition (a grant under the hold for every eligible volume) could never hold. Not a product stall: renewals never waited for the store. The clock is now frozen while the extension write is held and resumes from the frozen instant at the release (no jump over a horizon), so extensions again run in real time alongside the writers and Close. A 3.5 s late test goroutine after the hold is now part of the test; without the freeze it fails ('revoke ACK: lease expired'). Co-Authored-By: Claude Opus 5.5 --- .../authority/workspace_lease_horizon_test.go | 34 +++++++++++++++++-- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 128cfc0291..efb2111d50 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -617,7 +617,27 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { var extensions atomic.Int64 heldEntered, heldRelease := make(chan struct{}), make(chan struct{}) var holdOnce, releaseOnce sync.Once - releaseHold := func() { releaseOnce.Do(func() { close(heldRelease) }) } + // The publisher clock is frozen while the extension write is held (#247 + // hang): the held write holds p.mu, so every other volume's extender queues + // and no horizon can move. With a running clock a late test goroutine could + // let horizons expire before each volume got a grant under the hold (the + // progress condition never holds), or before the writers run after the + // release (a revoke ACK finds the lease expired). This test is about lock + // and store ordering, not about lease expiry. + var frozenNS atomic.Int64 // 0 = running + // At the release the clock resumes from the frozen instant (the offset takes + // back the time spent held), so it neither jumps over a horizon nor runs + // backwards; extensions then run in real time alongside writers and Close. + var offNS atomic.Int64 + releaseHold := func() { + releaseOnce.Do(func() { + if f := frozenNS.Load(); f != 0 { + offNS.Add(-int64(time.Since(time.Unix(0, f)))) + frozenNS.Store(0) + } + close(heldRelease) + }) + } var classifying atomic.Bool var holding atomic.Bool // set when the extension write is held, before it blocks hs.setBefore(func(r DurableRecord) error { @@ -638,6 +658,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { first := false holdOnce.Do(func() { first = true }) if first { + frozenNS.Store(time.Now().Add(time.Duration(offNS.Load())).UnixNano()) holding.Store(true) // before the hold: a renewal started after this saw it close(heldEntered) <-heldRelease @@ -648,9 +669,13 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // The publisher clock is real time plus an offset. The forced-move volume // is granted at offset -10 s, so by offset 0 its horizon + skew barrier has // passed; the clock only moves forward. - var offNS atomic.Int64 offNS.Store(int64(-10 * time.Second)) - p := NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, func() time.Time { return time.Now().Add(time.Duration(offNS.Load())) })) + p := NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, func() time.Time { + if f := frozenNS.Load(); f != 0 { + return time.Unix(0, f) + } + return time.Now().Add(time.Duration(offNS.Load())) + })) t.Cleanup(p.CloseWorkspaceExtenders) ctx := context.Background() bindAndGrant(t, p, vol(forcedVol), "r") // never renewed again @@ -736,6 +761,9 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // Handshake 1: the first extension write is held inside the store. <-heldEntered // progress, no timer (#227): renewers keep triggering extensions + // A late test goroutine (machine load), longer than a horizon (1.5 x TTL): + // with the clock frozen under the hold, no volume can lose its lease here. + time.Sleep(3500 * time.Millisecond) // Handshake 2: renewals keep succeeding while it is held. // Progress, no timer (#227): every eligible volume gains a grant from a call // that STARTED while the extension write was held (a reply computed before From 385ad024f4e8f48b6887ee7af76204fc5147f19b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 05:51:34 -0800 Subject: [PATCH 094/150] test: #262 fold: one test-clock transaction per Now/Freeze/Resume; failure exits on the hold waits Review fold (codex01, test only): the frozen check, time.Now and the offset were separate reads, so a reader paused across freeze+release could see the clock go backwards. leaseTestClock serializes Now/Freeze/Resume/SetOffset under one mutex and never returns an earlier time than a previous Now. TestLeaseTestClockMonotonicAcrossFreezeResume runs readers across 50 freeze/resume transitions. The held-entered and under-hold progress waits get 30 s real-time failure exits (never a pass); the cleanup releases the hold and joins every worker. Co-Authored-By: Claude Opus 5.5 --- .../authority/workspace_lease_horizon_test.go | 191 +++++++++++++++--- 1 file changed, 162 insertions(+), 29 deletions(-) diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index efb2111d50..56ad9facd5 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -624,22 +624,19 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // progress condition never holds), or before the writers run after the // release (a revoke ACK finds the lease expired). This test is about lock // and store ordering, not about lease expiry. - var frozenNS atomic.Int64 // 0 = running - // At the release the clock resumes from the frozen instant (the offset takes - // back the time spent held), so it neither jumps over a horizon nor runs - // backwards; extensions then run in real time alongside writers and Close. - var offNS atomic.Int64 + // At the release the clock resumes from the frozen instant, so it neither + // jumps over a horizon nor runs backwards; extensions then run in real time + // alongside writers and Close. Now/Freeze/Resume are one transaction each. + clock := &leaseTestClock{} releaseHold := func() { releaseOnce.Do(func() { - if f := frozenNS.Load(); f != 0 { - offNS.Add(-int64(time.Since(time.Unix(0, f)))) - frozenNS.Store(0) - } + clock.Resume() close(heldRelease) }) } var classifying atomic.Bool - var holding atomic.Bool // set when the extension write is held, before it blocks + var holding atomic.Bool // set when the extension write is held, before it blocks + var heldVol atomic.Value // string: the volume whose extension write is held hs.setBefore(func(r DurableRecord) error { time.Sleep(5 * time.Millisecond) // a slow store if !classifying.Load() || r.Workspace == nil || r.Workspace.Lease == nil { @@ -658,8 +655,9 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { first := false holdOnce.Do(func() { first = true }) if first { - frozenNS.Store(time.Now().Add(time.Duration(offNS.Load())).UnixNano()) - holding.Store(true) // before the hold: a renewal started after this saw it + clock.Freeze() + heldVol.Store(r.VolumeID) // the volume whose extension write is held + holding.Store(true) // before the hold: a renewal started after this saw it close(heldEntered) <-heldRelease } @@ -669,17 +667,12 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // The publisher clock is real time plus an offset. The forced-move volume // is granted at offset -10 s, so by offset 0 its horizon + skew barrier has // passed; the clock only moves forward. - offNS.Store(int64(-10 * time.Second)) - p := NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, func() time.Time { - if f := frozenNS.Load(); f != 0 { - return time.Unix(0, f) - } - return time.Now().Add(time.Duration(offNS.Load())) - })) + clock.SetOffset(-10 * time.Second) + p := NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, clock.Now)) t.Cleanup(p.CloseWorkspaceExtenders) ctx := context.Background() bindAndGrant(t, p, vol(forcedVol), "r") // never renewed again - offNS.Store(0) + clock.SetOffset(0) for i := 0; i < n; i++ { if i != forcedVol { bindAndGrant(t, p, vol(i), "r") @@ -692,7 +685,9 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { classifying.Store(true) var grants [n]atomic.Int64 - var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held + var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held + var returnedUnderHold [n]atomic.Int64 // calls (any outcome) that started while the extension write was held + var otherRefusals atomic.Value // string: a refusal under the hold that is not horizon exhaustion var maxGrant [n]atomic.Int64 var slowest atomic.Int64 stop := make(chan struct{}) @@ -745,6 +740,16 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { if d := int64(time.Since(start)); d > slowest.Load() { slowest.Store(d) } + if fresh { + returnedUnderHold[i].Add(1) + // With the clock frozen and every extension queued behind the + // held write, a horizon left without host validity is refused + // by design; any other refusal here is a failure. + if err != nil && !strings.Contains(err.Error(), "leaves no host validity") && + !strings.Contains(err.Error(), "expired or revoking") { + otherRefusals.CompareAndSwap(nil, fmt.Sprintf("%s: %v", vol(i), err)) + } + } if err == nil && !l.Revoking { grants[i].Add(1) if fresh { @@ -760,26 +765,44 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { } // Handshake 1: the first extension write is held inside the store. - <-heldEntered // progress, no timer (#227): renewers keep triggering extensions + // Progress handshakes (#227) with a real-time failure exit (never a pass): + // the cleanup releases the hold and joins every worker. + select { + case <-heldEntered: // renewers keep triggering extensions + case <-time.After(30 * time.Second): + t.Fatal("no extension write was held within 30 s") + } // A late test goroutine (machine load), longer than a horizon (1.5 x TTL): // with the clock frozen under the hold, no volume can lose its lease here. time.Sleep(3500 * time.Millisecond) - // Handshake 2: renewals keep succeeding while it is held. - // Progress, no timer (#227): every eligible volume gains a grant from a call - // that STARTED while the extension write was held (a reply computed before - // the hold does not count). Renewals that waited for it would never return. - for { + // Handshake 2: renewals never wait for the held store write (#205). + // Progress, no timer (#227): every eligible volume has a call that STARTED + // while the extension write was held and returned (a reply computed before + // the hold does not count); renewals that waited for it would never return. + // Grants under the hold are clamped to each volume's durable horizon: under + // the frozen clock a volume whose horizon leaves no host validity is refused + // by design, so grants are reported, and only horizon refusals are allowed. + held, _ := heldVol.Load().(string) + for give := time.Now().Add(30 * time.Second); ; time.Sleep(5 * time.Millisecond) { all := true for _, i := range eligible { - if underHold[i].Load() == 0 { + if returnedUnderHold[i].Load() == 0 { all = false } } if all { break } - time.Sleep(5 * time.Millisecond) + if time.Now().After(give) { + t.Fatalf("under the held extension of %s within 30 s: grants %v, returned calls %v", held, + underHoldCounts(&underHold, eligible), underHoldCounts(&returnedUnderHold, eligible)) + } } + if r, _ := otherRefusals.Load().(string); r != "" { + t.Fatalf("under the held extension of %s: refusal other than horizon exhaustion: %s", held, r) + } + t.Logf("under the held extension of %s: grants %v, returned calls %v", held, + underHoldCounts(&underHold, eligible), underHoldCounts(&returnedUnderHold, eligible)) // Writers and Close start while the extension write is held. writersStarted = true go func() { @@ -1007,3 +1030,113 @@ func TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite(t *testing.T) { t.Fatal("aborted extender left the single-flight flag set") } } + +// leaseTestClock is a test publisher clock: real time plus an offset, or a +// frozen instant. Now, Freeze, Resume and SetOffset are each one transaction +// under mu, and Now never returns an earlier time than a previous Now. +type leaseTestClock struct { + mu sync.Mutex + off time.Duration + frozen time.Time // zero = running + last time.Time +} + +func (c *leaseTestClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + t := c.frozen + if t.IsZero() { + t = time.Now().Add(c.off) + } + if t.Before(c.last) { + t = c.last + } + c.last = t + return t +} + +// Freeze stops the clock at its current reading. +func (c *leaseTestClock) Freeze() { + c.mu.Lock() + defer c.mu.Unlock() + if c.frozen.IsZero() { + c.frozen = time.Now().Add(c.off) + if c.frozen.Before(c.last) { + c.frozen = c.last + } + } +} + +// Resume restarts a frozen clock from its frozen instant. +func (c *leaseTestClock) Resume() { + c.mu.Lock() + defer c.mu.Unlock() + if !c.frozen.IsZero() { + c.off = c.frozen.Sub(time.Now()) + c.frozen = time.Time{} + } +} + +func (c *leaseTestClock) SetOffset(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.off = d +} + +func underHoldCounts(u *[8]atomic.Int64, eligible []int) []int64 { + out := make([]int64, 0, len(eligible)) + for _, i := range eligible { + out = append(out, u[i].Load()) + } + return out +} + +// Readers running across freeze/resume transitions never see the test clock +// go backwards, and a resume does not jump forward over the frozen interval. +func TestLeaseTestClockMonotonicAcrossFreezeResume(t *testing.T) { + c := &leaseTestClock{} + var stop atomic.Bool + var wg sync.WaitGroup + errs := make(chan string, 8) + for r := 0; r < 4; r++ { + wg.Add(1) + go func() { + defer wg.Done() + prev := c.Now() + for !stop.Load() { + now := c.Now() + if now.Before(prev) { + select { + case errs <- fmt.Sprintf("clock went backwards: %v after %v", now, prev): + default: + } + return + } + prev = now + } + }() + } + for k := 0; k < 50; k++ { + c.Freeze() + at := c.Now() + time.Sleep(2 * time.Millisecond) + if got := c.Now(); !got.Equal(at) { + t.Fatalf("frozen clock moved: %v -> %v", at, got) + } + r0 := time.Now() + c.Resume() + got := c.Now() + // After a resume the clock advances by at most the real time since the + // resume began (no jump over the frozen interval), and never backwards. + if got.Before(at) || got.Sub(at) > time.Since(r0) { + t.Fatalf("resume moved the clock by %v (real time since resume %v)", got.Sub(at), time.Since(r0)) + } + time.Sleep(time.Millisecond) + } + stop.Store(true) + wg.Wait() + close(errs) + for e := range errs { + t.Fatal(e) + } +} From faceab21d3f56057993cfd4dc7d6724569f6e726 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 06:45:24 -0800 Subject: [PATCH 095/150] test(nvme): reproduce reads during delayed chunk attachment --- .../durable/takeover_read_ready_test.go | 66 +++++++++++++++++++ .../frontend/nvme/read_ready_retry_test.go | 45 +++++++++++++ 2 files changed, 111 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/takeover_read_ready_test.go create mode 100644 seaweed-block/core/frontend/nvme/read_ready_retry_test.go diff --git a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go new file mode 100644 index 0000000000..c10221bc3f --- /dev/null +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -0,0 +1,66 @@ +package durable_test + +import ( + "bytes" + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" +) + +// The frontend can connect after authority arrives but before the fresh +// host finishes attaching HEAD. That window must not become a read EIO. +func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { + remote := newGated(seededRemote(t)) + remote.holdGetHead = make(chan struct{}) + view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + p := chunkProvider(t, t.TempDir(), remote, view, 0) + // Release before provider cleanup joins the authority/attach worker. + defer remote.release() + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) + waitEntered(t, remote, "gethead") + backend, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + handler := nvme.NewIOHandler(nvme.HandlerConfig{Backend: backend, BlockSize: 4096, VolumeSize: pcBlocks * 4096, NSID: 1}) + command := nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1} + start := time.Now() + result := handler.Handle(context.Background(), command) + elapsed := time.Since(start) + // Keep the actual deferred attach parked for the takeover race interval. + time.Sleep(2500 * time.Millisecond) + remote.release() + if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 { + t.Fatalf("read before HEAD attach: SCT=%#x SC=%#x data=%d reason=%s; want retryable namespace not ready", result.SCT, result.SC, len(result.Data), result.Reason) + } + if elapsed >= 5*time.Second { + t.Fatalf("read before attach took %s", elapsed) + } + deadline := time.Now().Add(5 * time.Second) + for { + result = handler.Handle(context.Background(), command) + if result.AsError() == nil { + break + } + if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady { + t.Fatalf("read while attach settles: %v", result.AsError()) + } + if time.Now().After(deadline) { + t.Fatal("attach did not make the same read operational") + } + time.Sleep(10 * time.Millisecond) + } + if !bytes.Equal(result.Data, block(0x33)) { + t.Fatal("first operational read did not return exact HEAD bytes") + } + t.Logf("pre-attach read returned in %s; same read recovered exact HEAD bytes after 2.5s attach delay", elapsed) +} diff --git a/seaweed-block/core/frontend/nvme/read_ready_retry_test.go b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go new file mode 100644 index 0000000000..ea34c9f88b --- /dev/null +++ b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go @@ -0,0 +1,45 @@ +package nvme + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" +) + +type readyReadBackend struct { + frontend.Backend + err error +} + +func (b *readyReadBackend) Read(context.Context, int64, []byte) (int, error) { return 0, b.err } + +func TestSessionReadNotReadyIsRetryable(t *testing.T) { + for _, tc := range []struct { + name string + err error + sct, sc uint8 + dnr bool + }{ + {"attach-pending", fmt.Errorf("awaiting HEAD attach: %w", frontend.ErrNotReady), SCTGeneric, SCNamespaceNotReady, false}, + {"physical-fault", errors.New("physical read failure"), SCTGeneric, SCInternalError, true}, + {"closed", frontend.ErrBackendClosed, SCTPathRelated, SCPathAsymAccessInaccessible, true}, + {"stale", frontend.ErrStalePrimary, SCTPathRelated, SCPathAsymAccessTransition, true}, + } { + t.Run(tc.name, func(t *testing.T) { + backend := &readyReadBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), err: tc.err} + s := &Session{handler: NewIOHandler(HandlerConfig{Backend: backend}), respCh: make(chan *response, 1), done: make(chan struct{})} + req := &Request{} + req.capsule.OpCode = ioRead + req.capsule.NSID = 1 + s.handleRead(context.Background(), req) + resp := <-s.respCh + if want := MakeStatusField(tc.sct, tc.sc, tc.dnr); resp.resp.Status != want { + t.Fatalf("wire status=%#x want=%#x", resp.resp.Status, want) + } + }) + } +} From 93529c04fdc67d238d71670b85b8ef7cb0723099 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 06:46:42 -0800 Subject: [PATCH 096/150] test(durable): hold takeover after visible HEAD claim --- .../durable/takeover_read_ready_test.go | 44 ++++++++++++++++--- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go index c10221bc3f..aa70b911f7 100644 --- a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -3,22 +3,48 @@ package durable_test import ( "bytes" "context" + "sync" "testing" "time" "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/storage" ) +// Hold the return from a successful takeover CAS: an external observer can +// see the new owner while provider attachment is still in flight. +type heldTakeoverClaim struct { + storage.ChunkRemote + claimed chan struct{} + release chan struct{} + once sync.Once +} + +func (r *heldTakeoverClaim) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + gen, err := r.ChunkRemote.CASHead(ctx, expected, next) + if err != nil || next.Epoch != 4 { + return gen, err + } + r.once.Do(func() { close(r.claimed) }) + select { + case <-r.release: + return gen, nil + case <-ctx.Done(): + return gen, ctx.Err() + } +} + // The frontend can connect after authority arrives but before the fresh // host finishes attaching HEAD. That window must not become a read EIO. func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { - remote := newGated(seededRemote(t)) - remote.holdGetHead = make(chan struct{}) + remote := &heldTakeoverClaim{ChunkRemote: seededRemote(t), claimed: make(chan struct{}), release: make(chan struct{})} + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(remote.release) }) } view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) p := chunkProvider(t, t.TempDir(), remote, view, 0) // Release before provider cleanup joins the authority/attach worker. - defer remote.release() + defer release() if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -26,7 +52,15 @@ func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { t.Fatal(err) } view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) - waitEntered(t, remote, "gethead") + select { + case <-remote.claimed: + case <-time.After(10 * time.Second): + t.Fatal("takeover CAS never became visible") + } + head, err := remote.GetHead(context.Background()) + if err != nil || head.Epoch != 4 || head.Holder != "r1" { + t.Fatalf("takeover HEAD: %+v, %v", head, err) + } backend, err := p.Open(context.Background(), "v1") if err != nil { t.Fatal(err) @@ -38,7 +72,7 @@ func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { elapsed := time.Since(start) // Keep the actual deferred attach parked for the takeover race interval. time.Sleep(2500 * time.Millisecond) - remote.release() + release() if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 { t.Fatalf("read before HEAD attach: SCT=%#x SC=%#x data=%d reason=%s; want retryable namespace not ready", result.SCT, result.SC, len(result.Data), result.Reason) } From bdf45a43f8d0bfe1a14334ad1c7de73c1a7ded92 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 06:47:49 -0800 Subject: [PATCH 097/150] fix(nvme): retry reads while the backend is not ready --- seaweed-block/core/frontend/errors.go | 3 ++- seaweed-block/core/frontend/nvme/io.go | 8 ++++++-- seaweed-block/core/frontend/nvme/read_ready_retry_test.go | 2 ++ seaweed-block/docs/design/invariants.md | 1 + 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/frontend/errors.go b/seaweed-block/core/frontend/errors.go index 0368d64e3e..84691012a8 100644 --- a/seaweed-block/core/frontend/errors.go +++ b/seaweed-block/core/frontend/errors.go @@ -9,7 +9,8 @@ import "errors" var ErrStalePrimary = errors.New("frontend: stale primary lineage") // ErrNotReady is returned by Provider.Open when the projection -// never reports healthy before the context deadline. +// never reports healthy before the context deadline, and by a Backend +// while local recovery or chunk attachment is not yet operational. var ErrNotReady = errors.New("frontend: volume not ready") // ErrBackendClosed is returned by Backend.Read / Backend.Write diff --git a/seaweed-block/core/frontend/nvme/io.go b/seaweed-block/core/frontend/nvme/io.go index 4615b3d08a..d2ac487081 100644 --- a/seaweed-block/core/frontend/nvme/io.go +++ b/seaweed-block/core/frontend/nvme/io.go @@ -76,7 +76,7 @@ type IOResult struct { SC uint8 Data []byte // read payload (nil for writes / errors) Reason string - retryable bool // only transient backend pressure clears wire DNR + retryable bool // transient pressure or readiness refusal clears wire DNR } func (r IOResult) completionStatus() uint16 { return MakeStatusField(r.SCT, r.SC, !r.retryable) } @@ -296,7 +296,8 @@ func (h *IOHandler) write(ctx context.Context, cmd IOCommand) IOResult { // mapBackendError translates frontend errors into NVMe CQE // status tuples. ErrStalePrimary → ANA Transition; -// ErrBackendClosed → ANA Inaccessible; anything else → Internal +// ErrBackendClosed → ANA Inaccessible; ErrNotReady → retryable Namespace +// Not Ready; anything else → Internal // Error (fail-closed; real-backend-specific mapping lands with // T3). func mapBackendError(err error, op string) IOResult { @@ -317,6 +318,9 @@ func mapBackendError(err error, op string) IOResult { Reason: "backend closed on " + op, } } + if errors.Is(err, frontend.ErrNotReady) { + return IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, Reason: "backend not ready on " + op + ": " + err.Error(), retryable: true} + } return IOResult{ SCT: SCTGeneric, SC: SCInternalError, diff --git a/seaweed-block/core/frontend/nvme/read_ready_retry_test.go b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go index ea34c9f88b..92c6536202 100644 --- a/seaweed-block/core/frontend/nvme/read_ready_retry_test.go +++ b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go @@ -25,6 +25,8 @@ func TestSessionReadNotReadyIsRetryable(t *testing.T) { dnr bool }{ {"attach-pending", fmt.Errorf("awaiting HEAD attach: %w", frontend.ErrNotReady), SCTGeneric, SCNamespaceNotReady, false}, + {"not-ready-closed", errors.Join(frontend.ErrNotReady, frontend.ErrBackendClosed), SCTPathRelated, SCPathAsymAccessInaccessible, true}, + {"not-ready-stale", errors.Join(frontend.ErrNotReady, frontend.ErrStalePrimary), SCTPathRelated, SCPathAsymAccessTransition, true}, {"physical-fault", errors.New("physical read failure"), SCTGeneric, SCInternalError, true}, {"closed", frontend.ErrBackendClosed, SCTPathRelated, SCPathAsymAccessInaccessible, true}, {"stale", frontend.ErrStalePrimary, SCTPathRelated, SCPathAsymAccessTransition, true}, diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6ee4916e12..bf9e12bfba 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -54,6 +54,7 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | +| `INV-FE-NVME-READY-001` | An NVMe I/O refused with `ErrNotReady` returns Namespace Not Ready (SC0x82), DNR=0, without reading or mutating storage; closed/stale lineage retain their ANA errors and physical I/O faults retain Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable` | — | ACTIVE | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | From 25ef2bbbb0eebe86fc767fd2497a160d1dbbf05b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:04:53 -0800 Subject: [PATCH 098/150] test(durable): model host retry exhaustion during attachment --- .../durable/takeover_read_ready_test.go | 103 ++++++++++++------ 1 file changed, 67 insertions(+), 36 deletions(-) diff --git a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go index aa70b911f7..7866a30a52 100644 --- a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -3,48 +3,57 @@ package durable_test import ( "bytes" "context" + "errors" "sync" "testing" "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" "github.com/seaweedfs/seaweed-block/core/storage" ) -// Hold the return from a successful takeover CAS: an external observer can -// see the new owner while provider attachment is still in flight. +// External observers see the committed takeover HEAD while attachment is +// held in the provider-owned worker, without a separate test goroutine. type heldTakeoverClaim struct { storage.ChunkRemote - claimed chan struct{} - release chan struct{} - once sync.Once + claimed chan struct{} + release chan struct{} + once, releaseOnce sync.Once + holdFor time.Duration } +func (r *heldTakeoverClaim) unblock() { r.releaseOnce.Do(func() { close(r.release) }) } func (r *heldTakeoverClaim) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { gen, err := r.ChunkRemote.CASHead(ctx, expected, next) if err != nil || next.Epoch != 4 { return gen, err } r.once.Do(func() { close(r.claimed) }) + var expired <-chan time.Time + if r.holdFor > 0 { + timer := time.NewTimer(r.holdFor) + defer timer.Stop() + expired = timer.C + } select { case <-r.release: return gen, nil + case <-expired: + return gen, nil case <-ctx.Done(): return gen, ctx.Err() } } -// The frontend can connect after authority arrives but before the fresh -// host finishes attaching HEAD. That window must not become a read EIO. -func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { - remote := &heldTakeoverClaim{ChunkRemote: seededRemote(t), claimed: make(chan struct{}), release: make(chan struct{})} - var releaseOnce sync.Once - release := func() { releaseOnce.Do(func() { close(remote.release) }) } +func pendingTakeoverRead(t *testing.T, hold time.Duration) (*durable.DurableProvider, frontend.Backend, *nvme.IOHandler) { + t.Helper() + remote := &heldTakeoverClaim{ChunkRemote: seededRemote(t), claimed: make(chan struct{}), release: make(chan struct{}), holdFor: hold} view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) p := chunkProvider(t, t.TempDir(), remote, view, 0) - // Release before provider cleanup joins the authority/attach worker. - defer release() + // Registered after provider cleanup, so release precedes its worker join. + t.Cleanup(remote.unblock) if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -66,35 +75,57 @@ func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { t.Fatal(err) } handler := nvme.NewIOHandler(nvme.HandlerConfig{Backend: backend, BlockSize: 4096, VolumeSize: pcBlocks * 4096, NSID: 1}) + return p, backend, handler +} + +// Model Linux max_retries=5 and CRD=0: at most six attempts, no sleeps. +// A status-only fix exhausts them during attachment and becomes guest EIO. +func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { + _, _, handler := pendingTakeoverRead(t, 2500*time.Millisecond) command := nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1} start := time.Now() - result := handler.Handle(context.Background(), command) - elapsed := time.Since(start) - // Keep the actual deferred attach parked for the takeover race interval. - time.Sleep(2500 * time.Millisecond) - release() - if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 { - t.Fatalf("read before HEAD attach: SCT=%#x SC=%#x data=%d reason=%s; want retryable namespace not ready", result.SCT, result.SC, len(result.Data), result.Reason) - } - if elapsed >= 5*time.Second { - t.Fatalf("read before attach took %s", elapsed) - } - deadline := time.Now().Add(5 * time.Second) - for { - result = handler.Handle(context.Background(), command) + for attempt := 0; attempt <= 5; attempt++ { + result := handler.Handle(context.Background(), command) if result.AsError() == nil { - break + if !bytes.Equal(result.Data, block(0x33)) { + t.Fatal("guest read returned incorrect HEAD bytes") + } + if elapsed := time.Since(start); elapsed >= 5*time.Second { + t.Fatalf("guest read took %s", elapsed) + } + t.Logf("guest read succeeded on attempt%d after%s (max5 immediate retries)", attempt+1, time.Since(start)) + return } if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady { - t.Fatalf("read while attach settles: %v", result.AsError()) + t.Fatalf("guest read terminal status: %v", result.AsError()) } - if time.Now().After(deadline) { - t.Fatal("attach did not make the same read operational") - } - time.Sleep(10 * time.Millisecond) } - if !bytes.Equal(result.Data, block(0x33)) { - t.Fatal("first operational read did not return exact HEAD bytes") + t.Fatal("guest EIO: all six immediate attempts exhausted before chunk attach") +} + +func TestWALStoreChunk_PendingReadWaitIsBounded(t *testing.T) { + _, _, handler := pendingTakeoverRead(t, 0) + start := time.Now() + result := handler.Handle(context.Background(), nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1}) + elapsed := time.Since(start) + if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 { + t.Fatalf("pending read result: %+v", result) } - t.Logf("pre-attach read returned in %s; same read recovered exact HEAD bytes after 2.5s attach delay", elapsed) + if elapsed < 3500*time.Millisecond || elapsed >= 5*time.Second { + t.Fatalf("pending read wait=%s; want bounded readiness wait below5s", elapsed) + } +} + +func TestWALStoreChunk_PendingReadHonoursEarlierDeadline(t *testing.T) { + _, backend, _ := pendingTakeoverRead(t, 0) + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond) + defer cancel() + start := time.Now() + n, err := backend.Read(ctx, 33*4096, make([]byte, 4096)) + if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("deadline read: n=%d err=%v", n, err) + } + if time.Since(start) >= time.Second { + t.Fatal("read ignored earlier deadline") + } } From dcf85fb41f0dcbe8c466ba241a9649f0e636565c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:07:58 -0800 Subject: [PATCH 099/150] fix(durable): wait for chunk read readiness before host retries --- .../core/frontend/durable/provider.go | 1 + .../frontend/durable/read_ready_wait_test.go | 60 ++++++++++++++ .../core/frontend/durable/storage_adapter.go | 78 ++++++++++++++++++- seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 138 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/read_ready_wait_test.go diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 2e89b88c45..df35c996ee 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -820,6 +820,7 @@ func (p *DurableProvider) wrap(volumeID, path string, impl ImplName, s storage.L EndpointVersion: proj.EndpointVersion, } b := NewStorageBackend(s, p.view, id) + b.waitReadReady = p.cfg.Impl == ImplWALStoreChunk return &volHandle{storage: s, backend: b, path: path, impl: impl}, nil } diff --git a/seaweed-block/core/frontend/durable/read_ready_wait_test.go b/seaweed-block/core/frontend/durable/read_ready_wait_test.go new file mode 100644 index 0000000000..e9296bca88 --- /dev/null +++ b/seaweed-block/core/frontend/durable/read_ready_wait_test.go @@ -0,0 +1,60 @@ +package durable + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { + // No storage is needed: this read must never pass the operational gate. + b := &StorageBackend{waitReadReady: true} + b.opEvidence.Store("attachment pending") + done := make(chan error, 1) + joined := make(chan struct{}) + t.Cleanup(func() { + _ = b.Close() + select { + case <-joined: + case <-time.After(time.Second): + t.Error("pending read did not settle after Close") + } + }) + go func() { + defer close(joined) + _, err := b.Read(context.Background(), 0, make([]byte, 4096)) + done <- err + }() + deadline := time.Now().Add(time.Second) + for { + b.mu.Lock() + registered := b.readyChanged != nil + b.mu.Unlock() + if registered { + break + } + if time.Now().After(deadline) { + t.Fatal("read did not register a readiness notification") + } + time.Sleep(time.Millisecond) + } + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + if err := b.StopIO(ctx, "attachment still pending"); err != nil { + t.Fatalf("waiting read held I/O admission: %v", err) + } + if err := b.Close(); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + if !errors.Is(err, frontend.ErrBackendClosed) { + t.Fatalf("Close wake error=%v", err) + } + case <-time.After(time.Second): + t.Fatal("Close did not wake registered read") + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 2aab01a159..84c754d49f 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -159,8 +159,12 @@ type StorageBackend struct { // false; provider flips true after Recover() succeeds (T3b). // opEvidence is the reason reported when operational=false // (e.g., "awaiting recovery", "local epoch ahead of assignment"). - operational atomic.Bool - opEvidence atomic.Value // string + // Chunk-managed reads may wait before admission for attachment to finish. + // waitReadReady is fixed at provider construction; readyChanged is under mu. + waitReadReady bool + readyChanged chan struct{} + operational atomic.Bool + opEvidence atomic.Value // string // ioMu is the I/O admission boundary: every Read, Write and Sync holds // its read side for the whole operation, gate included, so StopIO can @@ -343,6 +347,7 @@ func (b *StorageBackend) Close() error { b.mu.Lock() defer b.mu.Unlock() b.closed = true + b.notifyReadReadyLocked() return nil } @@ -371,12 +376,14 @@ func (b *StorageBackend) SetWriteObserver(obs WriteObserver) error { err = fmt.Errorf("durable: write observer not installed: ship LSN: %w", err) b.mu.Lock() b.observerErr = err + b.notifyReadReadyLocked() b.mu.Unlock() return err } } b.mu.Lock() b.observer, b.observerErr = obs, nil + b.notifyReadReadyLocked() b.mu.Unlock() return nil } @@ -401,6 +408,7 @@ func (b *StorageBackend) seedAndRebase(seed func() error) error { err = fmt.Errorf("durable: write observer ship LSN after the frontier seed: %w", err) b.mu.Lock() b.observerErr = err + b.notifyReadReadyLocked() b.mu.Unlock() return err } @@ -444,8 +452,11 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) { evidence = "not operational" } } + b.mu.Lock() b.opEvidence.Store(evidence) b.operational.Store(ok) + b.notifyReadReadyLocked() + b.mu.Unlock() } // StopIO makes the backend refuse every new Read, Write and Sync with @@ -532,6 +543,12 @@ func (b *StorageBackend) Sync(ctx context.Context) error { // end-of-volume return zero bytes (no error). Every read is gated. func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, error) { release, err := b.admit() + if err != nil && b.waitReadReady && errors.Is(err, frontend.ErrNotReady) { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, 4*time.Second) + defer cancel() + release, err = b.awaitReadAdmission(ctx) + } if err != nil { return 0, err } @@ -539,9 +556,66 @@ func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, if len(p) == 0 { return 0, nil } + if b.waitReadReady && ctx.Err() != nil { + return 0, b.readReadyTimeout(ctx.Err()) + } return b.readBytes(offset, p) } +// notifyReadReadyLocked wakes readers without making them hold ioMu while +// the provider is attaching or draining the backend. Caller holds mu. +func (b *StorageBackend) notifyReadReadyLocked() { + if b.readyChanged != nil { + close(b.readyChanged) + b.readyChanged = nil + } +} + +// awaitReadAdmission waits only after a gate refusal, before any storage I/O. +// The four-second readiness allowance is capped by an earlier caller deadline. +func (b *StorageBackend) awaitReadAdmission(ctx context.Context) (func(), error) { + for { + b.mu.Lock() + if b.readyChanged == nil { + b.readyChanged = make(chan struct{}) + } + changed := b.readyChanged + terminal := b.closed || b.observerErr != nil + b.mu.Unlock() + if err := ctx.Err(); err != nil { + return nil, b.readReadyTimeout(err) + } + release, err := b.admit() + if err == nil { + if cause := ctx.Err(); cause != nil { + release() + return nil, b.readReadyTimeout(cause) + } + return release, nil + } + if !errors.Is(err, frontend.ErrNotReady) || terminal || b.operational.Load() { + return release, err + } + select { + case <-changed: + case <-ctx.Done(): + return nil, b.readReadyTimeout(ctx.Err()) + } + } +} + +func (b *StorageBackend) readReadyTimeout(cause error) error { + // A concurrent Close, fence or observer failure must retain its gate error. + err := b.readyCheck() + b.mu.Lock() + observerFailed := b.observerErr != nil + b.mu.Unlock() + if err != nil && (!errors.Is(err, frontend.ErrNotReady) || observerFailed) { + return err + } + return fmt.Errorf("%w: %w: chunk attachment readiness: %w", frontend.ErrNotReady, frontend.ErrBackendBusy, cause) +} + // Write persists up to len(p) bytes at offset. Partial-block // writes perform a read-modify-write: fetch the current block, // overlay the partial range, write the full block back. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index bf9e12bfba..e0a5b5e425 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -54,7 +54,7 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | -| `INV-FE-NVME-READY-001` | An NVMe I/O refused with `ErrNotReady` returns Namespace Not Ready (SC0x82), DNR=0, without reading or mutating storage; closed/stale lineage retain their ANA errors and physical I/O faults retain Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable` | — | ACTIVE | +| `INV-FE-NVME-READY-001` | Chunk-managed reads wait up to 4s (or an earlier caller deadline) for operational readiness before storage admission; NVMe readiness timeout/refusal returns Namespace Not Ready (SC0x82), DNR=0, without reading or mutating storage; closed/stale lineage retain their ANA errors and physical I/O faults retain Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable`; `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` | — | ACTIVE | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | From f12c8f73582e9dd6e3e593877553ff6e3458cb65 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:08:58 -0800 Subject: [PATCH 100/150] test(durable): witness pending read before drain and close --- .../frontend/durable/read_ready_wait_test.go | 106 ++++++++++-------- .../core/frontend/durable/storage_adapter.go | 5 + 2 files changed, 66 insertions(+), 45 deletions(-) diff --git a/seaweed-block/core/frontend/durable/read_ready_wait_test.go b/seaweed-block/core/frontend/durable/read_ready_wait_test.go index e9296bca88..36b4b41bc1 100644 --- a/seaweed-block/core/frontend/durable/read_ready_wait_test.go +++ b/seaweed-block/core/frontend/durable/read_ready_wait_test.go @@ -3,6 +3,7 @@ package durable import ( "context" "errors" + "sync" "testing" "time" @@ -10,51 +11,66 @@ import ( ) func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { - // No storage is needed: this read must never pass the operational gate. - b := &StorageBackend{waitReadReady: true} - b.opEvidence.Store("attachment pending") - done := make(chan error, 1) - joined := make(chan struct{}) - t.Cleanup(func() { - _ = b.Close() - select { - case <-joined: - case <-time.After(time.Second): - t.Error("pending read did not settle after Close") + for _, drain := range []bool{false, true} { + name := "close" + if drain { + name = "drain-then-close" } - }) - go func() { - defer close(joined) - _, err := b.Read(context.Background(), 0, make([]byte, 4096)) - done <- err - }() - deadline := time.Now().Add(time.Second) - for { - b.mu.Lock() - registered := b.readyChanged != nil - b.mu.Unlock() - if registered { - break - } - if time.Now().After(deadline) { - t.Fatal("read did not register a readiness notification") - } - time.Sleep(time.Millisecond) - } - ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) - defer cancel() - if err := b.StopIO(ctx, "attachment still pending"); err != nil { - t.Fatalf("waiting read held I/O admission: %v", err) - } - if err := b.Close(); err != nil { - t.Fatal(err) - } - select { - case err := <-done: - if !errors.Is(err, frontend.ErrBackendClosed) { - t.Fatalf("Close wake error=%v", err) - } - case <-time.After(time.Second): - t.Fatal("Close did not wake registered read") + t.Run(name, func(t *testing.T) { + // No storage is needed: this read must never pass the operational gate. + b := &StorageBackend{waitReadReady: true} + b.opEvidence.Store("attachment pending") + registered := make(chan struct{}, 1) + resume := make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(resume) }) } + b.testBeforeReadReadyWait = func() { + select { + case registered <- struct{}{}: + default: + } + <-resume + } + done := make(chan error, 1) + joined := make(chan struct{}) + t.Cleanup(func() { + release() + _ = b.Close() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("pending read did not settle after release and Close") + } + }) + go func() { + defer close(joined) + _, err := b.Read(context.Background(), 0, make([]byte, 4096)) + done <- err + }() + select { + case <-registered: + case <-time.After(time.Second): + t.Fatal("read did not register a readiness notification") + } + if drain { + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + if err := b.StopIO(ctx, "attachment still pending"); err != nil { + t.Fatalf("waiting read held I/O admission: %v", err) + } + } + if err := b.Close(); err != nil { + t.Fatal(err) + } + release() + select { + case err := <-done: + if !errors.Is(err, frontend.ErrBackendClosed) { + t.Fatalf("Close wake error=%v", err) + } + case <-time.After(time.Second): + t.Fatal("Close did not wake registered read") + } + }) } } diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 84c754d49f..5737aebd1a 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -149,6 +149,8 @@ type StorageBackend struct { // testBeforeIOLock, test-only, runs in admit after the readiness check, // right before the I/O lock (an arrival handshake for queued I/O). testBeforeIOLock func() + // Runs outside locks after a read registers its readiness notification. + testBeforeReadReadyWait func() storage storage.LogicalStorage view frontend.ProjectionView @@ -596,6 +598,9 @@ func (b *StorageBackend) awaitReadAdmission(ctx context.Context) (func(), error) if !errors.Is(err, frontend.ErrNotReady) || terminal || b.operational.Load() { return release, err } + if hook := b.testBeforeReadReadyWait; hook != nil { + hook() + } select { case <-changed: case <-ctx.Done(): From 7da8006648fb376b965e20da3fb6b6c3c0cf2f6c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:09:58 -0800 Subject: [PATCH 101/150] test(nvme): pin zero retry delay for readiness policy --- .../frontend/nvme/read_ready_retry_test.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/seaweed-block/core/frontend/nvme/read_ready_retry_test.go b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go index 92c6536202..0b89d1dfad 100644 --- a/seaweed-block/core/frontend/nvme/read_ready_retry_test.go +++ b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go @@ -45,3 +45,21 @@ func TestSessionReadNotReadyIsRetryable(t *testing.T) { }) } } + +func TestReadinessRetryDelayIsNotAdvertised(t *testing.T) { + s := &Session{target: &Target{cfg: TargetConfig{VolumeID: "v1"}}, handler: &IOHandler{}, ctrl: &adminController{}, respCh: make(chan *response, 1), done: make(chan struct{})} + controller := s.buildIdentifyController() + for offset := 128; offset < 134; offset++ { + if controller[offset] != 0 { + t.Fatalf("CRDT byte%d=%d; host-policy control assumes no retry delay", offset, controller[offset]) + } + } + req := &Request{} + req.capsule.D10 = 0x16 // Host Behavior Support, including ACRE. + if err := s.handleSetFeatures(req); err != nil { + t.Fatal(err) + } + if got := (<-s.respCh).resp.Status; got != MakeStatusField(SCTGeneric, SCInvalidField, true) { + t.Fatalf("unsupported Host Behavior status=%#x", got) + } +} From eb698f98fd0ea3284fcbd5c087df5192ea5dd004 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:28:16 -0800 Subject: [PATCH 102/150] test: require pending takeover writes to await attachment --- .../frontend/durable/takeover_read_ready_test.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go index 7866a30a52..5a34305758 100644 --- a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -129,3 +129,19 @@ func TestWALStoreChunk_PendingReadHonoursEarlierDeadline(t *testing.T) { t.Fatal("read ignored earlier deadline") } } + +func TestWALStoreChunk_TakeoverWriteWaitsForAttach(t *testing.T) { + _, backend, _ := pendingTakeoverRead(t, 2500*time.Millisecond) + start := time.Now() + n, err := backend.Write(context.Background(), 33*4096, block(0x74)) + if err != nil || n != 4096 { + t.Fatalf("pending write: n=%d err=%v", n, err) + } + if elapsed := time.Since(start); elapsed >= 5*time.Second { + t.Fatalf("write waited %s", elapsed) + } + got := make([]byte, 4096) + if n, err := backend.Read(context.Background(), 33*4096, got); err != nil || n != 4096 || !bytes.Equal(got, block(0x74)) { + t.Fatalf("attached write readback: n=%d err=%v", n, err) + } +} From 486289c30a595258135fd9d06cd22016ae427a7a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:30:15 -0800 Subject: [PATCH 103/150] fix: wait for chunk attachment before admitting takeover reads and writes --- .../core/frontend/durable/provider.go | 3 +- .../frontend/durable/read_ready_wait_test.go | 29 +++++--- .../core/frontend/durable/storage_adapter.go | 74 ++++++++++++------- .../durable/takeover_read_ready_test.go | 28 ++++++- seaweed-block/docs/design/invariants.md | 2 +- 5 files changed, 97 insertions(+), 39 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index df35c996ee..17d3e64aac 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -820,7 +820,6 @@ func (p *DurableProvider) wrap(volumeID, path string, impl ImplName, s storage.L EndpointVersion: proj.EndpointVersion, } b := NewStorageBackend(s, p.view, id) - b.waitReadReady = p.cfg.Impl == ImplWALStoreChunk return &volHandle{storage: s, backend: b, path: path, impl: impl}, nil } @@ -878,7 +877,7 @@ func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (R // Recovered; I/O stays refused until the layer attaches under // the master's assignment (the authority wait flips it). report.Evidence += "; chunk layer awaiting master authority" - h.backend.SetOperational(false, report.Evidence) + h.backend.setChunkAttachPending(report.Evidence) return report, nil } if err := chunkFenced(volumeID, h); err != nil { diff --git a/seaweed-block/core/frontend/durable/read_ready_wait_test.go b/seaweed-block/core/frontend/durable/read_ready_wait_test.go index 36b4b41bc1..9127a3932a 100644 --- a/seaweed-block/core/frontend/durable/read_ready_wait_test.go +++ b/seaweed-block/core/frontend/durable/read_ready_wait_test.go @@ -11,14 +11,11 @@ import ( ) func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { - for _, drain := range []bool{false, true} { - name := "close" - if drain { - name = "drain-then-close" - } + for _, mode := range []string{"close", "drain-then-close", "fence", "write-close"} { + name := mode t.Run(name, func(t *testing.T) { // No storage is needed: this read must never pass the operational gate. - b := &StorageBackend{waitReadReady: true} + b := &StorageBackend{waitAttachReady: true} b.opEvidence.Store("attachment pending") registered := make(chan struct{}, 1) resume := make(chan struct{}) @@ -44,7 +41,12 @@ func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { }) go func() { defer close(joined) - _, err := b.Read(context.Background(), 0, make([]byte, 4096)) + var err error + if mode == "write-close" { + _, err = b.Write(context.Background(), 0, make([]byte, 4096)) + } else { + _, err = b.Read(context.Background(), 0, make([]byte, 4096)) + } done <- err }() select { @@ -52,20 +54,27 @@ func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { case <-time.After(time.Second): t.Fatal("read did not register a readiness notification") } - if drain { + if mode == "drain-then-close" { ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) defer cancel() if err := b.StopIO(ctx, "attachment still pending"); err != nil { t.Fatalf("waiting read held I/O admission: %v", err) } } - if err := b.Close(); err != nil { + want := frontend.ErrBackendClosed + if mode == "fence" { + b.mu.Lock() + b.chunkFenced = func() bool { return true } + b.mu.Unlock() + b.SetOperational(false, "fenced") + want = frontend.ErrStalePrimary + } else if err := b.Close(); err != nil { t.Fatal(err) } release() select { case err := <-done: - if !errors.Is(err, frontend.ErrBackendClosed) { + if !errors.Is(err, want) { t.Fatalf("Close wake error=%v", err) } case <-time.After(time.Second): diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 5737aebd1a..9aa62d7176 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -161,12 +161,12 @@ type StorageBackend struct { // false; provider flips true after Recover() succeeds (T3b). // opEvidence is the reason reported when operational=false // (e.g., "awaiting recovery", "local epoch ahead of assignment"). - // Chunk-managed reads may wait before admission for attachment to finish. - // waitReadReady is fixed at provider construction; readyChanged is under mu. - waitReadReady bool - readyChanged chan struct{} - operational atomic.Bool - opEvidence atomic.Value // string + // Only a successfully recovered chunk volume awaiting attachment may wait. + // waitAttachReady and readyChanged are protected by mu. + waitAttachReady bool + readyChanged chan struct{} + operational atomic.Bool + opEvidence atomic.Value // string // ioMu is the I/O admission boundary: every Read, Write and Sync holds // its read side for the whole operation, gate included, so StopIO can @@ -457,6 +457,7 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) { b.mu.Lock() b.opEvidence.Store(evidence) b.operational.Store(ok) + b.waitAttachReady = false b.notifyReadReadyLocked() b.mu.Unlock() } @@ -544,13 +545,7 @@ func (b *StorageBackend) Sync(ctx context.Context) error { // Read copies up to len(p) bytes starting at offset. Reads past // end-of-volume return zero bytes (no error). Every read is gated. func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, error) { - release, err := b.admit() - if err != nil && b.waitReadReady && errors.Is(err, frontend.ErrNotReady) { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, 4*time.Second) - defer cancel() - release, err = b.awaitReadAdmission(ctx) - } + release, err := b.admitAfterAttach(ctx) if err != nil { return 0, err } @@ -558,13 +553,39 @@ func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, if len(p) == 0 { return 0, nil } - if b.waitReadReady && ctx.Err() != nil { - return 0, b.readReadyTimeout(ctx.Err()) + if ctx.Err() != nil { + return 0, b.attachReadyTimeout(ctx.Err()) } return b.readBytes(offset, p) } -// notifyReadReadyLocked wakes readers without making them hold ioMu while +// setChunkAttachPending is used only after successful local recovery. +func (b *StorageBackend) setChunkAttachPending(evidence string) { + b.mu.Lock() + b.opEvidence.Store(evidence) + b.operational.Store(false) + b.waitAttachReady = true + b.notifyReadReadyLocked() + b.mu.Unlock() +} + +func (b *StorageBackend) admitAfterAttach(ctx context.Context) (func(), error) { + release, err := b.admit() + if !errors.Is(err, frontend.ErrNotReady) { + return release, err + } + b.mu.Lock() + pending := b.waitAttachReady + b.mu.Unlock() + if !pending { + return release, err + } + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + return b.awaitAttachAdmission(ctx) +} + +// notifyReadReadyLocked wakes waiting I/O without making them hold ioMu while // the provider is attaching or draining the backend. Caller holds mu. func (b *StorageBackend) notifyReadReadyLocked() { if b.readyChanged != nil { @@ -573,25 +594,25 @@ func (b *StorageBackend) notifyReadReadyLocked() { } } -// awaitReadAdmission waits only after a gate refusal, before any storage I/O. -// The four-second readiness allowance is capped by an earlier caller deadline. -func (b *StorageBackend) awaitReadAdmission(ctx context.Context) (func(), error) { +// awaitAttachAdmission waits only after a gate refusal, before any storage I/O. +// The three-second readiness allowance is capped by an earlier caller deadline. +func (b *StorageBackend) awaitAttachAdmission(ctx context.Context) (func(), error) { for { b.mu.Lock() if b.readyChanged == nil { b.readyChanged = make(chan struct{}) } changed := b.readyChanged - terminal := b.closed || b.observerErr != nil + terminal := b.closed || b.observerErr != nil || !b.waitAttachReady b.mu.Unlock() if err := ctx.Err(); err != nil { - return nil, b.readReadyTimeout(err) + return nil, b.attachReadyTimeout(err) } release, err := b.admit() if err == nil { if cause := ctx.Err(); cause != nil { release() - return nil, b.readReadyTimeout(cause) + return nil, b.attachReadyTimeout(cause) } return release, nil } @@ -604,12 +625,12 @@ func (b *StorageBackend) awaitReadAdmission(ctx context.Context) (func(), error) select { case <-changed: case <-ctx.Done(): - return nil, b.readReadyTimeout(ctx.Err()) + return nil, b.attachReadyTimeout(ctx.Err()) } } } -func (b *StorageBackend) readReadyTimeout(cause error) error { +func (b *StorageBackend) attachReadyTimeout(cause error) error { // A concurrent Close, fence or observer failure must retain its gate error. err := b.readyCheck() b.mu.Lock() @@ -628,7 +649,7 @@ func (b *StorageBackend) readReadyTimeout(cause error) error { func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int, error) { iolatency.BackendEnter(ctx) defer iolatency.BackendExit(ctx) - release, err := b.admit() + release, err := b.admitAfterAttach(ctx) if err != nil { log.Printf("durable: StorageBackend.Write gate-rejected offset=%d: %v", offset, err) return 0, err @@ -637,6 +658,9 @@ func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int if len(p) == 0 { return 0, nil } + if ctx.Err() != nil { + return 0, b.attachReadyTimeout(ctx.Err()) + } b.profile.recordBackendWriteRequest(len(p)) start := time.Now() n, err := b.writeBytes(ctx, offset, p) diff --git a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go index 5a34305758..e4ef2d6708 100644 --- a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -111,7 +111,7 @@ func TestWALStoreChunk_PendingReadWaitIsBounded(t *testing.T) { if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 { t.Fatalf("pending read result: %+v", result) } - if elapsed < 3500*time.Millisecond || elapsed >= 5*time.Second { + if elapsed < 2500*time.Millisecond || elapsed >= 5*time.Second { t.Fatalf("pending read wait=%s; want bounded readiness wait below5s", elapsed) } } @@ -145,3 +145,29 @@ func TestWALStoreChunk_TakeoverWriteWaitsForAttach(t *testing.T) { t.Fatalf("attached write readback: n=%d err=%v", n, err) } } + +func TestWALStoreChunk_PendingWriteHonoursEarlierDeadline(t *testing.T) { + _, backend, _ := pendingTakeoverRead(t, 0) + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond) + defer cancel() + n, err := backend.Write(ctx, 33*4096, block(0x74)) + if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("pending write deadline: n=%d err=%v", n, err) + } +} + +func TestWALStoreChunk_PendingAttachBeyondHostRetryBudget(t *testing.T) { + _, _, handler := pendingTakeoverRead(t, 0) + for attempt := 0; attempt <= 5; attempt++ { + start := time.Now() + result := handler.Handle(context.Background(), nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1}) + if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 { + t.Fatalf("attempt%d exposed data or terminal status: %+v", attempt, result) + } + if elapsed := time.Since(start); elapsed < 2500*time.Millisecond || elapsed >= 5*time.Second { + t.Fatalf("attempt%d wait=%s", attempt, elapsed) + } + } + // A permanently unavailable backend still exhausts a finite host retry policy; + // this control promises retryable completions and no bytes, not infinite availability. +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e0a5b5e425..7cc2239ab8 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -54,7 +54,7 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | -| `INV-FE-NVME-READY-001` | Chunk-managed reads wait up to 4s (or an earlier caller deadline) for operational readiness before storage admission; NVMe readiness timeout/refusal returns Namespace Not Ready (SC0x82), DNR=0, without reading or mutating storage; closed/stale lineage retain their ANA errors and physical I/O faults retain Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable`; `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` | — | ACTIVE | +| `INV-FE-NVME-READY-001` | Reads and writes on successfully recovered chunk volumes awaiting attachment wait up to 3s (or an earlier caller deadline) for attachment readiness before storage admission; NVMe readiness timeout/refusal returns Namespace Not Ready (SC0x82), DNR=0, without reading or mutating storage; closed/stale lineage retain their ANA errors and physical I/O faults retain Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable`; `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` | — | ACTIVE | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | From c8abeec62db9f8291337ca568cb0462472f737f9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:36:47 -0800 Subject: [PATCH 104/150] docs: place readiness invariant in the frontend ledger --- seaweed-block/docs/design/invariants.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7cc2239ab8..ff41a1e2ea 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -54,7 +54,6 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | -| `INV-FE-NVME-READY-001` | Reads and writes on successfully recovered chunk volumes awaiting attachment wait up to 3s (or an earlier caller deadline) for attachment readiness before storage admission; NVMe readiness timeout/refusal returns Namespace Not Ready (SC0x82), DNR=0, without reading or mutating storage; closed/stale lineage retain their ANA errors and physical I/O faults retain Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable`; `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` | — | ACTIVE | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | @@ -305,7 +304,7 @@ snapshot lifetime; local persistence does not bypass it. ## Part B. Invariant ledger -80 rows: 69 ACTIVE, 11 STUB; 15 kept from the internal ledger, 65 new. +81 rows: 70 ACTIVE, 11 STUB; 15 kept from the internal ledger, 66 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. @@ -315,6 +314,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w |---|---|---|---|---|---|---| | `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | +| `INV-FE-NVME-READY-001` | Reads and writes on successfully recovered chunk volumes awaiting attachment wait up to 3s (or an earlier caller deadline) for attachment readiness before storage admission; NVMe readiness timeout/refusal returns Namespace Not Ready (SC0x82), DNR=0, without reading or mutating storage; closed/stale lineage retain their ANA errors and physical I/O faults retain Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable`; `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` | — | ACTIVE | | `INV-WAL-REPLAY-LWW-001` | Replay applies the highest LSN per LBA, independent of the physical scan order. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALStoreRecoverLastWriterWinsAcrossScanOrder` (`core/storage/walstore_recovery_lww_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | | `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the on-disk superblock has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_writer.go` `spaceUsed`, `tailPersisted`; `core/storage/walstore.go` `persistCheckpointReleasing` | `TestWALWriterReuseIsBoundedByTheDurableTail`, `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherSnapshotCutPreservesSyncedWrites` (`core/storage/flusher_snapshot_cut_test.go`); `TestWALStoreCheckpointSIGKILLCrashWindows` (`core/storage/walstore_checkpoint_crash_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | From 4f5be014cafc58546827180f6fbf7a1b25031f12 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:42:29 -0800 Subject: [PATCH 105/150] test: #262 under-hold oracle with witnessed headroom; set-up and revoke/ACK on a frozen clock - The extension write is held only when every eligible volume (and the clean volume) has positive host validity at the frozen instant, read from its own renewal view; under the hold every renewal started before the writers must grant (any refusal fails). - The clock is frozen through the set-up binds (fsync writes could outlast a TTL and expire the first-bound volume before its renewer started) and from the hold until the clean volume's revoke ACK (queued behind every extension write); it then resumes from the frozen instant. - The clock unit test registers stop + a bounded join before its readers start, so every exit settles them. Co-Authored-By: Claude Opus 5.5 --- .../authority/workspace_lease_horizon_test.go | 137 ++++++++++++++---- 1 file changed, 105 insertions(+), 32 deletions(-) diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 56ad9facd5..2a43a9c5b9 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -616,7 +616,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { lastEpoch := map[string]uint64{} var extensions atomic.Int64 heldEntered, heldRelease := make(chan struct{}), make(chan struct{}) - var holdOnce, releaseOnce sync.Once + var releaseOnce sync.Once // The publisher clock is frozen while the extension write is held (#247 // hang): the held write holds p.mu, so every other volume's extender queues // and no horizon can move. With a running clock a late test goroutine could @@ -624,19 +624,53 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // progress condition never holds), or before the writers run after the // release (a revoke ACK finds the lease expired). This test is about lock // and store ordering, not about lease expiry. - // At the release the clock resumes from the frozen instant, so it neither - // jumps over a horizon nor runs backwards; extensions then run in real time - // alongside writers and Close. Now/Freeze/Resume are one transaction each. + // The clock stays frozen after the release until the clean volume's revoke + // ACK: the endpoint refreshes, the revocation and the ACK queue on p.mu + // behind every volume's extension write (fsync), which on a loaded machine + // can outlast the clean volume's grant, and a revoking lease is never + // extended (in-time ACK has its own tests). The writer then resumes the + // clock from the frozen instant, so it neither jumps over a horizon nor runs + // backwards; extensions run in real time alongside the moves and Close. + // Now/Freeze/Resume are one transaction each. clock := &leaseTestClock{} releaseHold := func() { - releaseOnce.Do(func() { - clock.Resume() - close(heldRelease) - }) + releaseOnce.Do(func() { close(heldRelease) }) } var classifying atomic.Bool var holding atomic.Bool // set when the extension write is held, before it blocks var heldVol atomic.Value // string: the volume whose extension write is held + var holdTaken atomic.Bool + var holdMu sync.Mutex + var skippedHolds atomic.Int64 // extension writes not held: some eligible volume lacked headroom + var p *Publisher + // headroom witnesses, at the frozen instant and from each volume's own + // renewal view (the fields RenewWorkspaceLease reads, under the leaf + // leaseMu), that a renewal of every eligible volume and of the clean volume + // grants positive host validity: lease present and live, durable horizon + // minus half the skew after now, and now before the granted deadline. The + // frozen clock and the queued extenders keep it so for the whole hold and, + // for the clean volume, through its revocation and ACK. + var noHeadroom atomic.Value // string: the last volume found without headroom, and why + headroom := func() bool { + now := clock.Now().UnixNano() + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + for _, i := range append(append([]int{}, eligible...), cleanVol) { // the clean volume is revoked and ACKed frozen + lv := p.leaseViews[vol(i)] + if lv == nil || !lv.d.bound || !lv.d.leasePresent || lv.d.revoking || lv.d.movePending || + lv.d.uncertain || lv.d.storeless || lv.d.horizon-lv.d.maxSkewNS/2 <= now || now >= lv.deadline.UnixNano() { + why := "no view" + if lv != nil { + why = fmt.Sprintf("bound=%v present=%v revoking=%v pending=%v uncertain=%v validity=%v deadline-now=%v", + lv.d.bound, lv.d.leasePresent, lv.d.revoking, lv.d.movePending, lv.d.uncertain, + time.Duration(lv.d.horizon-lv.d.maxSkewNS/2-now), time.Duration(lv.deadline.UnixNano()-now)) + } + noHeadroom.Store(vol(i) + ": " + why) + return false + } + } + return true + } hs.setBefore(func(r DurableRecord) error { time.Sleep(5 * time.Millisecond) // a slow store if !classifying.Load() || r.Workspace == nil || r.Workspace.Lease == nil { @@ -653,9 +687,21 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { if ext { extensions.Add(1) first := false - holdOnce.Do(func() { first = true }) + if !holdTaken.Load() { + holdMu.Lock() + if !holdTaken.Load() { + clock.Freeze() + if headroom() { + holdTaken.Store(true) + first = true + } else { + clock.Resume() // try again at a later extension write + skippedHolds.Add(1) + } + } + holdMu.Unlock() + } if first { - clock.Freeze() heldVol.Store(r.VolumeID) // the volume whose extension write is held holding.Store(true) // before the hold: a renewal started after this saw it close(heldEntered) @@ -668,11 +714,16 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // is granted at offset -10 s, so by offset 0 its horizon + skew barrier has // passed; the clock only moves forward. clock.SetOffset(-10 * time.Second) - p := NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, clock.Now)) + p = NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, clock.Now)) t.Cleanup(p.CloseWorkspaceExtenders) ctx := context.Background() bindAndGrant(t, p, vol(forcedVol), "r") // never renewed again clock.SetOffset(0) + // Set-up writes are real store writes (fsync): on a loaded machine binding + // the volumes can take longer than a TTL, and the first-bound volume would + // expire before its renewer starts (by design it never recovers). The clock + // stays frozen through the set-up and resumes just before the renewers. + clock.Freeze() for i := 0; i < n; i++ { if i != forcedVol { bindAndGrant(t, p, vol(i), "r") @@ -682,12 +733,14 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { st := p.WorkspaceState(vol(i)) lastH[vol(i)], lastEpoch[vol(i)] = st.Lease.ExpiresAtNS, st.Lease.Epoch } + clock.Resume() classifying.Store(true) var grants [n]atomic.Int64 var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held var returnedUnderHold [n]atomic.Int64 // calls (any outcome) that started while the extension write was held - var otherRefusals atomic.Value // string: a refusal under the hold that is not horizon exhaustion + var refusedUnderHold atomic.Value // string: a refusal of a call started under the hold, before the writers + var writersGo atomic.Bool // set before the writers start var maxGrant [n]atomic.Int64 var slowest atomic.Int64 stop := make(chan struct{}) @@ -701,6 +754,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // every worker, and only then let the fixtures close. t.Cleanup(func() { releaseHold() + clock.Resume() stopRenewers() settled := make(chan struct{}) go func() { wg.Wait(); close(settled) }() @@ -735,6 +789,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { default: } fresh := holding.Load() // the call starts while the extension write is held + beforeWriters := !writersGo.Load() start := time.Now() l, err := p.RenewWorkspaceLease(ctx, vol(i), "r", 1) if d := int64(time.Since(start)); d > slowest.Load() { @@ -742,12 +797,11 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { } if fresh { returnedUnderHold[i].Add(1) - // With the clock frozen and every extension queued behind the - // held write, a horizon left without host validity is refused - // by design; any other refusal here is a failure. - if err != nil && !strings.Contains(err.Error(), "leaves no host validity") && - !strings.Contains(err.Error(), "expired or revoking") { - otherRefusals.CompareAndSwap(nil, fmt.Sprintf("%s: %v", vol(i), err)) + // Headroom was witnessed at the frozen instant: until the + // writers start, every such renewal must grant (any refusal, + // a horizon error included, fails). + if beforeWriters && (err != nil || l.Revoking) { + refusedUnderHold.CompareAndSwap(nil, fmt.Sprintf("%s: %+v %v", vol(i), l, err)) } } if err == nil && !l.Revoking { @@ -770,23 +824,27 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { select { case <-heldEntered: // renewers keep triggering extensions case <-time.After(30 * time.Second): - t.Fatal("no extension write was held within 30 s") + nh, _ := noHeadroom.Load().(string) + t.Fatalf("no extension write was held within 30 s (%d extension writes, %d not held for lack of headroom; last: %s)", + extensions.Load(), skippedHolds.Load(), nh) } // A late test goroutine (machine load), longer than a horizon (1.5 x TTL): // with the clock frozen under the hold, no volume can lose its lease here. time.Sleep(3500 * time.Millisecond) - // Handshake 2: renewals never wait for the held store write (#205). - // Progress, no timer (#227): every eligible volume has a call that STARTED - // while the extension write was held and returned (a reply computed before + // Handshake 2: renewals keep succeeding while it is held. + // Progress, no timer (#227): every eligible volume gains a grant from a call + // that STARTED while the extension write was held (a reply computed before // the hold does not count); renewals that waited for it would never return. - // Grants under the hold are clamped to each volume's durable horizon: under - // the frozen clock a volume whose horizon leaves no host validity is refused - // by design, so grants are reported, and only horizon refusals are allowed. + // The hold was taken only with headroom witnessed for every eligible volume + // at the frozen instant, so no refusal is allowed here. held, _ := heldVol.Load().(string) for give := time.Now().Add(30 * time.Second); ; time.Sleep(5 * time.Millisecond) { + if r, _ := refusedUnderHold.Load().(string); r != "" { + t.Fatalf("under the held extension of %s, with headroom witnessed: refused %s", held, r) + } all := true for _, i := range eligible { - if returnedUnderHold[i].Load() == 0 { + if underHold[i].Load() == 0 { all = false } } @@ -798,12 +856,10 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { underHoldCounts(&underHold, eligible), underHoldCounts(&returnedUnderHold, eligible)) } } - if r, _ := otherRefusals.Load().(string); r != "" { - t.Fatalf("under the held extension of %s: refusal other than horizon exhaustion: %s", held, r) - } - t.Logf("under the held extension of %s: grants %v, returned calls %v", held, - underHoldCounts(&underHold, eligible), underHoldCounts(&returnedUnderHold, eligible)) + t.Logf("under the held extension of %s (%d extension writes not held for lack of headroom): grants %v", held, + skippedHolds.Load(), underHoldCounts(&underHold, eligible)) // Writers and Close start while the extension write is held. + writersGo.Store(true) writersStarted = true go func() { for k := 0; k < 5; k++ { @@ -812,11 +868,16 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { return } } + // Still frozen since the hold (the refreshes above needed p.mu, which the + // held write owned); the clean volume's headroom was witnessed then. if err := p.BeginWorkspaceRevocation(ctx, vol(cleanVol), "r", 1); err != nil { + clock.Resume() writersDone <- fmt.Errorf("revocation: %w", err) return } - if err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil { + err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}) + clock.Resume() + if err != nil { writersDone <- fmt.Errorf("ack: %w", err) return } @@ -1098,6 +1159,18 @@ func TestLeaseTestClockMonotonicAcrossFreezeResume(t *testing.T) { var stop atomic.Bool var wg sync.WaitGroup errs := make(chan string, 8) + // Registered before launch: every exit, a Fatal included, stops and joins + // the readers (bounded). + t.Cleanup(func() { + stop.Store(true) + joined := make(chan struct{}) + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(10 * time.Second): + t.Error("clock readers did not settle") + } + }) for r := 0; r < 4; r++ { wg.Add(1) go func() { From b967075b56c90a2a31548a256b2dca46b6fd6b82 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:44:52 -0800 Subject: [PATCH 106/150] test: witness attach readiness races and start holds at the first waiter --- .../frontend/durable/export_chunk_test.go | 5 ++++ .../frontend/durable/read_ready_wait_test.go | 27 +++++++++++++++++++ .../core/frontend/durable/storage_adapter.go | 4 +++ .../durable/takeover_read_ready_test.go | 12 ++++++++- 4 files changed, 47 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/durable/export_chunk_test.go b/seaweed-block/core/frontend/durable/export_chunk_test.go index 7a499b43d7..7c74e579b7 100644 --- a/seaweed-block/core/frontend/durable/export_chunk_test.go +++ b/seaweed-block/core/frontend/durable/export_chunk_test.go @@ -24,3 +24,8 @@ func SetTestDetachTrace(p *DurableProvider, f func(stage string, deadline time.T // SetTestBeforeIOLock runs f in the backend's admission, right before the I/O // lock (test-only). func SetTestBeforeIOLock(b frontend.Backend, f func()) { b.(*StorageBackend).testBeforeIOLock = f } + +// SetTestBeforeAttachWait observes the first registered readiness wait. +func SetTestBeforeAttachWait(b frontend.Backend, f func()) { + b.(*StorageBackend).testBeforeReadReadyWait = f +} diff --git a/seaweed-block/core/frontend/durable/read_ready_wait_test.go b/seaweed-block/core/frontend/durable/read_ready_wait_test.go index 9127a3932a..c19c8c1373 100644 --- a/seaweed-block/core/frontend/durable/read_ready_wait_test.go +++ b/seaweed-block/core/frontend/durable/read_ready_wait_test.go @@ -83,3 +83,30 @@ func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { }) } } + +type readinessProjection frontend.Projection + +func (p readinessProjection) Projection() frontend.Projection { return frontend.Projection(p) } + +func TestAttachReadinessTimeoutPreservesStaleLineage(t *testing.T) { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + b := &StorageBackend{id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 2, EndpointVersion: 1, Healthy: true}} + b.setChunkAttachPending("pending") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + b.testBeforeReadReadyWait = func() { b.SetOperational(true, "attached under another epoch"); cancel() } + _, err := b.Read(ctx, 0, make([]byte, 4096)) + if !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("timeout lost stale lineage: %v", err) + } +} + +func TestAttachReadinessPublicationRetriesAdmission(t *testing.T) { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + b := &StorageBackend{id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}} + b.setChunkAttachPending("pending") + b.testAfterAttachRefusal = func() { b.SetOperational(true, "attached") } + if _, err := b.Read(context.Background(), 0, nil); err != nil { + t.Fatalf("readiness publication returned the old refusal: %v", err) + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 9aa62d7176..3859070cf9 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -151,6 +151,7 @@ type StorageBackend struct { testBeforeIOLock func() // Runs outside locks after a read registers its readiness notification. testBeforeReadReadyWait func() + testAfterAttachRefusal func() storage storage.LogicalStorage view frontend.ProjectionView @@ -574,6 +575,9 @@ func (b *StorageBackend) admitAfterAttach(ctx context.Context) (func(), error) { if !errors.Is(err, frontend.ErrNotReady) { return release, err } + if hook := b.testAfterAttachRefusal; hook != nil { + hook() + } b.mu.Lock() pending := b.waitAttachReady b.mu.Unlock() diff --git a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go index e4ef2d6708..e2278f7b30 100644 --- a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -22,6 +22,7 @@ type heldTakeoverClaim struct { release chan struct{} once, releaseOnce sync.Once holdFor time.Duration + readRegistered chan struct{} } func (r *heldTakeoverClaim) unblock() { r.releaseOnce.Do(func() { close(r.release) }) } @@ -33,6 +34,13 @@ func (r *heldTakeoverClaim) CASHead(ctx context.Context, expected storage.ChunkH r.once.Do(func() { close(r.claimed) }) var expired <-chan time.Time if r.holdFor > 0 { + select { + case <-r.readRegistered: + case <-r.release: + return gen, nil + case <-ctx.Done(): + return gen, ctx.Err() + } timer := time.NewTimer(r.holdFor) defer timer.Stop() expired = timer.C @@ -49,7 +57,7 @@ func (r *heldTakeoverClaim) CASHead(ctx context.Context, expected storage.ChunkH func pendingTakeoverRead(t *testing.T, hold time.Duration) (*durable.DurableProvider, frontend.Backend, *nvme.IOHandler) { t.Helper() - remote := &heldTakeoverClaim{ChunkRemote: seededRemote(t), claimed: make(chan struct{}), release: make(chan struct{}), holdFor: hold} + remote := &heldTakeoverClaim{ChunkRemote: seededRemote(t), claimed: make(chan struct{}), release: make(chan struct{}), holdFor: hold, readRegistered: make(chan struct{})} view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) p := chunkProvider(t, t.TempDir(), remote, view, 0) // Registered after provider cleanup, so release precedes its worker join. @@ -74,6 +82,8 @@ func pendingTakeoverRead(t *testing.T, hold time.Duration) (*durable.DurableProv if err != nil { t.Fatal(err) } + var firstWait sync.Once + durable.SetTestBeforeAttachWait(backend, func() { firstWait.Do(func() { close(remote.readRegistered) }) }) handler := nvme.NewIOHandler(nvme.HandlerConfig{Backend: backend, BlockSize: 4096, VolumeSize: pcBlocks * 4096, NSID: 1}) return p, backend, handler } From d49f7553af83780d2b503864b183626e45d31737 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:45:45 -0800 Subject: [PATCH 107/150] fix: recheck readiness and stale lineage at attach admission boundaries --- seaweed-block/core/frontend/durable/storage_adapter.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 3859070cf9..7cb579c256 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -582,7 +582,8 @@ func (b *StorageBackend) admitAfterAttach(ctx context.Context) (func(), error) { pending := b.waitAttachReady b.mu.Unlock() if !pending { - return release, err + // Readiness may have published after the initial refusal. + return b.admit() } ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() @@ -636,7 +637,7 @@ func (b *StorageBackend) awaitAttachAdmission(ctx context.Context) (func(), erro func (b *StorageBackend) attachReadyTimeout(cause error) error { // A concurrent Close, fence or observer failure must retain its gate error. - err := b.readyCheck() + err := b.gate() b.mu.Lock() observerFailed := b.observerErr != nil b.mu.Unlock() From 6a38c27aa190bb1aaa55164e37d14019f28332eb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 08:57:46 -0800 Subject: [PATCH 108/150] ci: use the Actions Go cache only on GitHub-hosted runners The self-hosted runner keeps GOCACHE/GOMODCACHE on disk; the setup-go post step uploading them (~4 GB) outlasted the 25-minute job timeout after all tests had passed. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/.github/workflows/test.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/seaweed-block/.github/workflows/test.yml b/seaweed-block/.github/workflows/test.yml index 3af9bd21a6..df5114a0a4 100644 --- a/seaweed-block/.github/workflows/test.yml +++ b/seaweed-block/.github/workflows/test.yml @@ -37,7 +37,11 @@ jobs: uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 with: go-version-file: go.mod - cache: true + # The self-hosted runner keeps GOCACHE/GOMODCACHE on its own disk; + # uploading them as an Actions cache (~4 GB) in the post step + # outlasted the job timeout after every test had passed. Only the + # GitHub-hosted (fork PR) runner uses the Actions cache. + cache: ${{ runner.environment == 'github-hosted' }} cache-dependency-path: go.sum - name: Go version From 88cfb04f71b6890332502cb42b0380b08655ee6a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:50:33 -0800 Subject: [PATCH 109/150] test: expose checkpoint persistence refusals and successes --- .../durable/checkpoint_status_test.go | 62 +++++++++++++++++++ .../storage/checkpoint_diagnostics_test.go | 51 +++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/checkpoint_status_test.go create mode 100644 seaweed-block/core/storage/checkpoint_diagnostics_test.go diff --git a/seaweed-block/core/frontend/durable/checkpoint_status_test.go b/seaweed-block/core/frontend/durable/checkpoint_status_test.go new file mode 100644 index 0000000000..7b46ce5f64 --- /dev/null +++ b/seaweed-block/core/frontend/durable/checkpoint_status_test.go @@ -0,0 +1,62 @@ +package durable_test + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestDurableProvider_CheckpointPersistenceStatus(t *testing.T) { + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: 64, ChunkBlocks: 4, ChunkCaptureInterval: 0, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + be, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := be.Write(context.Background(), 0, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + if err := be.Sync(context.Background()); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(5 * time.Second) + for { + statuses := p.DurableStatuses() + raw, err := json.Marshal(statuses) + if err != nil { + t.Fatal(err) + } + var wire []struct { + CheckpointPersistence *struct { + Successes uint64 + Refusals uint64 + Failures uint64 + } + } + if err := json.Unmarshal(raw, &wire); err != nil { + t.Fatal(err) + } + if len(wire) == 1 && wire[0].CheckpointPersistence != nil && wire[0].CheckpointPersistence.Successes > 0 { + return + } + if time.Now().After(deadline) { + t.Fatalf("no checkpoint persist status in durable response: %s", raw) + } + time.Sleep(10 * time.Millisecond) + } +} diff --git a/seaweed-block/core/storage/checkpoint_diagnostics_test.go b/seaweed-block/core/storage/checkpoint_diagnostics_test.go new file mode 100644 index 0000000000..d811d47dde --- /dev/null +++ b/seaweed-block/core/storage/checkpoint_diagnostics_test.go @@ -0,0 +1,51 @@ +package storage + +import ( + "encoding/json" + "errors" + "strings" + "testing" +) + +func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + s.v3.testMapPrepared = func() { + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + } + before := s.v3.pub.current() + err := s.flusher.flushOnce() + if !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("refusal: %v", err) + } + if !strings.Contains(err.Error(), "proof_changed") { + t.Errorf("missing refusal reason: %v", err) + } + if s.v3.pub.current() != before || s.dm.len() != 2 || s.stickyIOFault() != nil { + t.Fatal("refusal changed publication/retry/fault state") + } + raw, _ := json.Marshal(s.FlusherInstrumentation()) + var counts map[string]uint64 + if err := json.Unmarshal(raw, &counts); err != nil { + t.Fatal(err) + } + if counts["CheckpointRefusals"] != 1 || counts["CheckpointSuccesses"] != 0 { + t.Fatalf("refusal counters: %s", raw) + } + s.v3.testMapPrepared = nil + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + raw, _ = json.Marshal(s.FlusherInstrumentation()) + if err := json.Unmarshal(raw, &counts); err != nil { + t.Fatal(err) + } + if counts["CheckpointRefusals"] != 1 || counts["CheckpointSuccesses"] != 1 || s.CheckpointLSN() != 2 || s.dm.len() != 0 { + t.Fatalf("retry counters/state: %s cp=%d", raw, s.CheckpointLSN()) + } +} From 751fe4ad0e9fb3ce26a7801edbcf89a31fd2e27f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:52:26 -0800 Subject: [PATCH 110/150] storage: report checkpoint retry reasons and cumulative outcomes --- .../durable/checkpoint_status_test.go | 3 + .../core/frontend/durable/provider.go | 31 ++++----- .../core/frontend/durable/storage_adapter.go | 42 +++++++----- .../core/storage/checkpoint_diagnostics.go | 64 ++++++++++++++++++ .../storage/checkpoint_diagnostics_test.go | 67 +++++++++++++++++++ .../core/storage/chunk_map_publication_v3.go | 20 +++--- seaweed-block/core/storage/flusher.go | 9 +-- .../core/storage/flusher_instrumentation.go | 9 +++ .../storage/walstore_map_checkpoint_v3.go | 10 +-- 9 files changed, 204 insertions(+), 51 deletions(-) create mode 100644 seaweed-block/core/storage/checkpoint_diagnostics.go diff --git a/seaweed-block/core/frontend/durable/checkpoint_status_test.go b/seaweed-block/core/frontend/durable/checkpoint_status_test.go index 7b46ce5f64..b3ad4cb9ce 100644 --- a/seaweed-block/core/frontend/durable/checkpoint_status_test.go +++ b/seaweed-block/core/frontend/durable/checkpoint_status_test.go @@ -21,6 +21,9 @@ func TestDurableProvider_CheckpointPersistenceStatus(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { p.Close() }) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 2e89b88c45..2fa5faf8bb 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -253,21 +253,22 @@ type volHandle struct { // handle. It intentionally exposes lineage and readiness facts without giving // callers a control surface. type VolumeStatus struct { - VolumeID string - Path string - Impl string - ReplicaID string - Epoch uint64 - EndpointVersion uint64 - Latched bool - Operational bool - FrontierKnown bool - DurableLSN uint64 - RetainedLSN uint64 - HeadLSN uint64 - Evidence string - Closed bool - WriteProfile WriteProfileStatus + VolumeID string + Path string + Impl string + ReplicaID string + Epoch uint64 + EndpointVersion uint64 + Latched bool + Operational bool + FrontierKnown bool + DurableLSN uint64 + RetainedLSN uint64 + HeadLSN uint64 + Evidence string + Closed bool + WriteProfile WriteProfileStatus + CheckpointPersistence *storage.CheckpointPersistenceStatus `json:",omitempty"` // Chunk is the chunk layer's state and cut counters; walstore-chunk // volumes only. Chunk *ChunkStatus diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 69b2b7ad8a..c7ec6169e9 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -288,6 +288,13 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus if c, ok := b.storage.(interface{ HolesSuspected() uint64 }); ok { holes = c.HolesSuspected() } + var checkpoint *storage.CheckpointPersistenceStatus + if reporter, ok := b.storage.(interface { + CheckpointPersistence() storage.CheckpointPersistenceStatus + }); ok { + snapshot := reporter.CheckpointPersistence() + checkpoint = &snapshot + } writeProfile := b.WriteProfile() if instrumented, ok := b.storage.(storage.WriteInstrumented); ok { storageProfile := instrumented.WriteInstrumentation() @@ -316,23 +323,24 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus writeProfile.DirtyMapUpdateDurationNanos = storageProfile.DirtyMapUpdateDurationNanos } return VolumeStatus{ - Warnings: warnings, - HolesSuspected: holes, - VolumeID: volumeID, - Path: path, - Impl: impl, - ReplicaID: id.ReplicaID, - Epoch: id.Epoch, - EndpointVersion: id.EndpointVersion, - Latched: id.Epoch > 0 && id.EndpointVersion > 0, - Operational: b.operational.Load(), - FrontierKnown: true, - DurableLSN: durableLSN, - RetainedLSN: retainedLSN, - HeadLSN: headLSN, - Evidence: evidence, - Closed: closed, - WriteProfile: writeProfile, + Warnings: warnings, + HolesSuspected: holes, + VolumeID: volumeID, + Path: path, + Impl: impl, + ReplicaID: id.ReplicaID, + Epoch: id.Epoch, + EndpointVersion: id.EndpointVersion, + Latched: id.Epoch > 0 && id.EndpointVersion > 0, + Operational: b.operational.Load(), + FrontierKnown: true, + DurableLSN: durableLSN, + RetainedLSN: retainedLSN, + HeadLSN: headLSN, + Evidence: evidence, + Closed: closed, + WriteProfile: writeProfile, + CheckpointPersistence: checkpoint, } } diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go new file mode 100644 index 0000000000..2fc3fd3af5 --- /dev/null +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -0,0 +1,64 @@ +package storage + +import ( + "errors" + "log" + "time" +) + +// CheckpointPersistenceStatus counts flusher checkpoint calls in this open. +// Success includes a safely clamped/unchanged checkpoint; it is not a slot-write +// count. Fields are cumulative atomic observations, not a coherent frontier. +type CheckpointPersistenceStatus struct { + Successes uint64 + Refusals uint64 + Failures uint64 +} + +func (s *WALStore) CheckpointPersistence() CheckpointPersistenceStatus { + if s.flusher == nil { + return CheckpointPersistenceStatus{} + } + i := &s.flusher.instr + return CheckpointPersistenceStatus{i.checkpointSuccesses.Load(), i.checkpointRefusals.Load(), i.checkpointFailures.Load()} +} + +func (i *flusherInstrumentation) recordCheckpoint(err error) { + switch { + case err == nil: + i.checkpointSuccesses.Add(1) + case errors.Is(err, ErrMapCoverageStale): + i.checkpointRefusals.Add(1) + default: + i.checkpointFailures.Add(1) + } +} + +type mapCoverageRefusal string + +func (r mapCoverageRefusal) Error() string { return ErrMapCoverageStale.Error() + ": " + string(r) } +func (r mapCoverageRefusal) Unwrap() error { return ErrMapCoverageStale } + +// Owned exclusively by the flusher run loop; no storage lock or I/O ordering +// changes. Terminal errors are never rate limited. +type checkpointLogLimiter struct { + last time.Time + suppressed uint64 +} + +func (l *checkpointLogLimiter) report(err error, now time.Time) { + if !errors.Is(err, ErrMapCoverageStale) { + log.Printf("storage: flusher: %v", err) + return + } + if !l.last.IsZero() && now.Sub(l.last) < 30*time.Second { + l.suppressed++ + return + } + var reason mapCoverageRefusal + if !errors.As(err, &reason) { + reason = "unspecified" + } + log.Printf("storage: flusher: checkpoint deferred reason=%s suppressed=%d: %v", reason, l.suppressed, err) + l.last, l.suppressed = now, 0 +} diff --git a/seaweed-block/core/storage/checkpoint_diagnostics_test.go b/seaweed-block/core/storage/checkpoint_diagnostics_test.go index d811d47dde..2670beb977 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics_test.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics_test.go @@ -1,14 +1,19 @@ package storage import ( + "bytes" "encoding/json" "errors" + "fmt" + "log" "strings" "testing" + "time" ) func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) { s, _ := newMappedCheckpointStoreV3(t) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) writeSynced(t, s, 1, 1) s.v3.testMapPrepared = func() { if _, err := s.Write(2, blk(2)); err != nil { @@ -49,3 +54,65 @@ func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) { t.Fatalf("retry counters/state: %s cp=%d", raw, s.CheckpointLSN()) } } + +func TestCheckpointDiagnostics_PrepareRefusalAndIOFailure(t *testing.T) { + for _, fault := range []bool{false, true} { + t.Run(fmt.Sprint(fault), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + writeSynced(t, s, 1, 1) + realSync := s.v3.ownedMap.syncFile + injected := errors.New("checkpoint map fsync fault") + once := false + s.v3.ownedMap.syncFile = func() error { + if fault { + return injected + } + if !once { + once = true + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + } + return realSync() + } + err := s.flusher.flushOnce() + got := s.CheckpointPersistence() + if fault { + if !errors.Is(err, injected) || got.Failures != 1 || got.Refusals != 0 || s.stickyIOFault() == nil { + t.Fatalf("fault %v counts=%+v", err, got) + } + } else { + if !errors.Is(err, ErrMapCoverageStale) || !strings.Contains(err.Error(), "proof_changed_during_prepare") || got.Refusals != 1 || got.Failures != 0 || s.stickyIOFault() != nil { + t.Fatalf("refusal %v counts=%+v", err, got) + } + } + if got.Successes != 0 || s.CheckpointLSN() != 0 || s.dm.len() == 0 { + t.Fatal("failed checkpoint advanced or lost retry ownership") + } + }) + } +} + +func TestCheckpointDiagnostics_LogRateLimit(t *testing.T) { + var out bytes.Buffer + old := log.Writer() + log.SetOutput(&out) + t.Cleanup(func() { log.SetOutput(old) }) + var limiter checkpointLogLimiter + now := time.Unix(100, 0) + stale := fmt.Errorf("persist checkpoint: %w", mapCoverageRefusal("proof_changed")) + limiter.report(stale, now) + for i := 0; i < 5; i++ { + limiter.report(stale, now.Add(time.Second)) + } + // A terminal failure must remain visible while refusals are suppressed. + terminal := errors.New("real fsync fault") + limiter.report(terminal, now.Add(2*time.Second)) + limiter.report(terminal, now.Add(3*time.Second)) + limiter.report(stale, now.Add(30*time.Second)) + got := out.String() + if strings.Count(got, "checkpoint deferred") != 2 || strings.Count(got, "real fsync fault") != 2 || !strings.Contains(got, "reason=proof_changed suppressed=5") { + t.Fatalf("logs: %s", got) + } +} diff --git a/seaweed-block/core/storage/chunk_map_publication_v3.go b/seaweed-block/core/storage/chunk_map_publication_v3.go index 8869949475..2ef10237b2 100644 --- a/seaweed-block/core/storage/chunk_map_publication_v3.go +++ b/seaweed-block/core/storage/chunk_map_publication_v3.go @@ -57,7 +57,7 @@ type preparedMapPublicationV3 struct { // Preparation takes the sidecar mutex and I/O only, before store/desc locks. func prepareMapPublicationV3(m *chunkLSNMapV3, d *mapProofEpochV3, g, C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (*preparedMapPublicationV3, error) { if m == nil || d == nil { - return nil, ErrMapCoverageStale + return nil, mapCoverageRefusal("map_binding_missing") } proof := d.snapshotV3() c, e := m.Prepare(g, C, entries, prior) @@ -66,7 +66,7 @@ func prepareMapPublicationV3(m *chunkLSNMapV3, d *mapProofEpochV3, g, C uint64, } if !proof.validV3(d) { m.abandonCandidateV3(c) // prepared but never publishable - return nil, ErrMapCoverageStale + return nil, mapCoverageRefusal("proof_changed_during_prepare") } return &preparedMapPublicationV3{candidate: c, proof: proof}, nil } @@ -84,13 +84,13 @@ func sameMapTupleV3(d descriptorV3, c *chunkMapCandidateV3) bool { // even when none of its pages belong to the selected generation. func (p *descriptorPublisherV3) bindMapV3(c *chunkMapCandidateV3, d *mapProofEpochV3) error { if c == nil || c.owner == nil || d == nil { - return ErrMapCoverageStale + return mapCoverageRefusal("map_binding_missing") } p.descMu.Lock() current, other, otherValid := p.cur, p.other, p.otherValid p.descMu.Unlock() if !sameMapTupleV3(current, c) { - return ErrMapCoverageStale + return mapCoverageRefusal("map_tuple_changed") } if _, _, e := readChunkLSNMapV3(c.owner.fd, current, c.owner.chunkBlocks); e != nil { return e @@ -106,7 +106,7 @@ func (p *descriptorPublisherV3) bindMapV3(c *chunkMapCandidateV3, d *mapProofEpo p.descMu.Lock() defer p.descMu.Unlock() if p.cur != current || p.otherValid != otherValid || (otherValid && p.other != other) { - return ErrMapCoverageStale + return mapCoverageRefusal("descriptor_changed_during_bind") } p.mapCurrent = c p.mapDomain = d @@ -115,7 +115,7 @@ func (p *descriptorPublisherV3) bindMapV3(c *chunkMapCandidateV3, d *mapProofEpo func (p *descriptorPublisherV3) validateMapPublicationV3(next descriptorV3, prepared *preparedMapPublicationV3) error { if p.mapCurrent == nil { if prepared != nil { - return ErrMapCoverageStale + return mapCoverageRefusal("map_not_bound") } return nil } // dark core not bound yet @@ -123,20 +123,20 @@ func (p *descriptorPublisherV3) validateMapPublicationV3(next descriptorV3, prep if prepared != nil { c = prepared.candidate if c == nil || c.owner != p.mapCurrent.owner || !prepared.proof.validV3(p.mapDomain) { - return ErrMapCoverageStale + return mapCoverageRefusal("proof_changed") } if c.generation <= p.mapCurrent.generation || c.covered < p.mapCurrent.covered { - return ErrMapCoverageStale + return mapCoverageRefusal("candidate_superseded") } } if !sameMapTupleV3(next, c) || c.covered < next.CheckpointLSN || c.covered > next.W { - return ErrMapCoverageStale + return mapCoverageRefusal("map_coverage_mismatch") } return nil } func (p *descriptorPublisherV3) publishMapV3(storeMu sync.Locker, snap func(), prepared *preparedMapPublicationV3, mutate func(*descriptorV3) error) (descriptorV3, error) { if prepared == nil || prepared.candidate == nil { - return descriptorV3{}, ErrMapCoverageStale + return descriptorV3{}, mapCoverageRefusal("candidate_missing") } d, err := p.publishWithMapV3(storeMu, snap, func(d *descriptorV3) error { if mutate != nil { diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index 6d52d7bf24..930e057a89 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -3,7 +3,6 @@ package storage import ( "encoding/binary" "fmt" - "log" "sort" "sync" "sync/atomic" @@ -111,6 +110,7 @@ func (f *flusher) runWithStartSignal(started chan<- struct{}) { if started != nil { close(started) } + var diagnostics checkpointLogLimiter for { select { case <-f.stopCh: @@ -120,11 +120,11 @@ func (f *flusher) runWithStartSignal(started chan<- struct{}) { return case <-ticker.C: if err := f.flushOnce(); err != nil { - log.Printf("storage: flusher: %v", err) + diagnostics.report(err, time.Now()) } case <-f.notifyCh: if err := f.flushOnce(); err != nil { - log.Printf("storage: flusher (notify): %v", err) + diagnostics.report(err, time.Now()) } } } @@ -283,6 +283,7 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { } else { publishErr = store.persistCheckpointAndRelease(maxLSN, maxLSNPhys, maxLSNEntrySize) } + f.instr.recordCheckpoint(publishErr) if err := publishErr; err != nil { return fmt.Errorf("flusher: persist checkpoint %d: %w", maxLSN, err) } @@ -313,7 +314,7 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { store.mu.Lock() if !store.v3.flushLifetimeValidV3(recoveryGen) { store.mu.Unlock() - return ErrMapCoverageStale + return mapCoverageRefusal("recovery_lifetime_changed") } checkpoint = store.checkpointLSN if checkpoint >= maxLSN && maxLSN+1 > store.walTail { diff --git a/seaweed-block/core/storage/flusher_instrumentation.go b/seaweed-block/core/storage/flusher_instrumentation.go index 3d7cf587fb..ec3fcf1827 100644 --- a/seaweed-block/core/storage/flusher_instrumentation.go +++ b/seaweed-block/core/storage/flusher_instrumentation.go @@ -12,6 +12,9 @@ const maxCheckpointWriteBytes = 1 << 20 // checkpoint work. Operation counters include failed attempts; byte counters // include only successful writes. type FlusherInstrumentationStatus struct { + CheckpointSuccesses uint64 + CheckpointRefusals uint64 + CheckpointFailures uint64 CyclesStarted uint64 CyclesSucceeded uint64 CyclesFailed uint64 @@ -63,6 +66,9 @@ type FlusherInstrumentationStatus struct { } type flusherInstrumentation struct { + checkpointSuccesses atomic.Uint64 + checkpointRefusals atomic.Uint64 + checkpointFailures atomic.Uint64 cyclesStarted atomic.Uint64 cyclesSucceeded atomic.Uint64 cyclesFailed atomic.Uint64 @@ -284,6 +290,9 @@ func updateAtomicMax(target *atomic.Uint64, value uint64) { func (i *flusherInstrumentation) snapshot() FlusherInstrumentationStatus { return FlusherInstrumentationStatus{ + CheckpointSuccesses: i.checkpointSuccesses.Load(), + CheckpointRefusals: i.checkpointRefusals.Load(), + CheckpointFailures: i.checkpointFailures.Load(), CyclesStarted: i.cyclesStarted.Load(), CyclesSucceeded: i.cyclesSucceeded.Load(), CyclesFailed: i.cyclesFailed.Load(), diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index 029d0ba210..c8273bb740 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -33,7 +33,7 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati if prior == nil || prior.owner != v.ownedMap || domain != v.mapProof { v.pub.descMu.Unlock() s.mu.RUnlock() - return nil, ErrMapCoverageStale + return nil, mapCoverageRefusal("map_binding_changed") } proof := domain.snapshotV3() entries := append([]chunkLSNEntryV3(nil), v.mapEntries...) @@ -45,7 +45,7 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati } if !proof.validV3(domain) { v.ownedMap.abandonCandidateV3(c) // prepared but never publishable - return nil, ErrMapCoverageStale + return nil, mapCoverageRefusal("proof_changed_during_prepare") } return &preparedMapPublicationV3{candidate: c, proof: proof}, nil } @@ -70,7 +70,7 @@ func (s *WALStore) persistOwnedMapCheckpointV3(highestLSN, recoveryGen uint64) e s.mu.Lock() defer s.mu.Unlock() if !v.flushLifetimeValidV3(recoveryGen) { - return ErrMapCoverageStale + return mapCoverageRefusal("recovery_lifetime_changed") } return s.rolloverCheckpointV3Locked() } @@ -118,7 +118,7 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) // I/O and could belong to a newer Recover lifetime than those bytes. if !v.flushLifetimeValidV3(recoveryGen) { prepared.abandonV3() - return descriptorV3{}, ErrMapCoverageStale + return descriptorV3{}, mapCoverageRefusal("recovery_lifetime_changed") } wack := v.wack.Load() if seed { @@ -126,7 +126,7 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) } if wack < cp { prepared.abandonV3() - return descriptorV3{}, ErrMapCoverageStale + return descriptorV3{}, mapCoverageRefusal("checkpoint_above_wack") } s.mu.RLock() retention := s.recoveryRetentionLSNs From a1209b2d90957e9038a3819a9f871d9151fe7006 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:53:32 -0800 Subject: [PATCH 111/150] storage: print the stable checkpoint refusal reason --- seaweed-block/core/storage/checkpoint_diagnostics.go | 2 +- seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go index 2fc3fd3af5..46aa71e185 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -59,6 +59,6 @@ func (l *checkpointLogLimiter) report(err error, now time.Time) { if !errors.As(err, &reason) { reason = "unspecified" } - log.Printf("storage: flusher: checkpoint deferred reason=%s suppressed=%d: %v", reason, l.suppressed, err) + log.Printf("storage: flusher: checkpoint deferred reason=%s suppressed=%d: %v", string(reason), l.suppressed, err) l.last, l.suppressed = now, 0 } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index f310af1eea..80bd9fb7df 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -63,7 +63,7 @@ stateDiagram-v2 | FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | | any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | -Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. +Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestCheckpointDiagnostics_RefusalThenSuccess`, `TestCheckpointDiagnostics_PrepareRefusalAndIOFailure`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. Public walstore Create now selects mapped format v3/impl3 (mode C by default, mode A by create option). Open and offline readonly use A/B slot and owned-map validation; valid legacy formats are refused with `ErrUnsupportedLegacyFormat`, rather than silently retrofitted. The temporary old-engine/raw-codec test scope and every named native replacement are recorded in [the legacy inventory](format-v3-legacy-test-inventory.md). Native recovery validates nonce/cursor binding and a contiguous physical LSN prefix before applying the mode-specific W rule; an acknowledged-range integrity failure blocks startup. The provider's create geometry, auto probe, capture, HEAD restore and readonly/status controls exercise the public selector (`INV-WAL-V3-ACTIVATION-001`). Before reading v3 slots, both read/write and offline read-only open acquire an exclusive nonblocking file lock; the offline migration CLI acquires the same lock before any descriptor read or mutation (`INV-WAL-V3-OWNER-001`). Contention refuses open/migration without changing bytes; descriptor close or process exit releases ownership. This implements the existing offline-migration precondition, not a new serving state. The mapped v3 checkpoint also carries a complete-record physical tail through the covered LSN minus the configured retention window; partial batches remain retained. The existing sole publisher then performs metadata-only rollover when the fallback still pins that prefix. Reuse still requires both valid same-nonce slot tails and retirement of checkpointed dirty references under writer exclusion; idle, unchanged-checkpoint and admission paths also settle a pinned fallback. An unlocked catch-up scan revalidates the coherent checkpoint and tail before emitting anything. A failed rollover latches and grants no reuse (`INV-WAL-V3-RECLAIM-001`). From 2ed15f2c03dc88f8c4a692224ced6fdfd60cdfe1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:54:29 -0800 Subject: [PATCH 112/150] storage: distinguish recovery and map generation refusals --- .../core/host/volume/status_server_test.go | 24 ++++++++++++------- seaweed-block/core/storage/descriptor_v3.go | 2 +- seaweed-block/core/storage/walstore_v3.go | 4 ++-- 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/host/volume/status_server_test.go b/seaweed-block/core/host/volume/status_server_test.go index 50fffb65d1..cbdf18d3eb 100644 --- a/seaweed-block/core/host/volume/status_server_test.go +++ b/seaweed-block/core/host/volume/status_server_test.go @@ -7,6 +7,7 @@ import ( "bytes" "context" "encoding/json" + "github.com/seaweedfs/seaweed-block/core/storage" "net/http" "net/http/httptest" "strings" @@ -981,15 +982,16 @@ func TestStatusServer_DurableStatusEndpoint_EnabledAfterStart_ReturnsLineage(t * } defer func() { _ = s.Close(context.Background()) }() s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{ - VolumeID: "v1", - Path: "/tmp/v1.bin", - Impl: "smartwal", - ReplicaID: "r1", - Epoch: 1, - EndpointVersion: 1, - Latched: true, - Operational: true, - Evidence: "recovered LSN=0", + VolumeID: "v1", + Path: "/tmp/v1.bin", + Impl: "smartwal", + ReplicaID: "r1", + Epoch: 1, + EndpointVersion: 1, + Latched: true, + Operational: true, + Evidence: "recovered LSN=0", + CheckpointPersistence: &storage.CheckpointPersistenceStatus{Successes: 3, Refusals: 2, Failures: 1}, }}}) resp, err := http.Get("http://" + addr + "/status/durable?volume=v1") @@ -1015,6 +1017,10 @@ func TestStatusServer_DurableStatusEndpoint_EnabledAfterStart_ReturnsLineage(t * if len(body.Volumes) != 1 || !body.Volumes[0].Latched || !body.Volumes[0].Operational || body.Volumes[0].Epoch != 1 { t.Fatalf("unexpected durable volume body: %+v", body.Volumes) } + checkpoint := body.Volumes[0].CheckpointPersistence + if checkpoint == nil || checkpoint.Successes != 3 || checkpoint.Refusals != 2 || checkpoint.Failures != 1 { + t.Fatalf("checkpoint counters missing from HTTP response: %+v", checkpoint) + } } func TestG9B_StatusProjection_ReturnedReplicaCanBeDurableReadyButFrontendNotReady(t *testing.T) { diff --git a/seaweed-block/core/storage/descriptor_v3.go b/seaweed-block/core/storage/descriptor_v3.go index 1300ef199a..62310d03a4 100644 --- a/seaweed-block/core/storage/descriptor_v3.go +++ b/seaweed-block/core/storage/descriptor_v3.go @@ -332,7 +332,7 @@ func mergeDescriptorV3Mode(cur, next *descriptorV3, reset bool) error { next.MapLineage != cur.MapLineage || next.MapFormatID != cur.MapFormatID { if next.MapGeneration <= cur.MapGeneration { return fmt.Errorf("%w: %w: map root change without a higher generation (%d -> %d)", - ErrMapCoverageStale, errDescriptorTransition, cur.MapGeneration, next.MapGeneration) + mapCoverageRefusal("map_generation_not_increasing"), errDescriptorTransition, cur.MapGeneration, next.MapGeneration) } if next.MapLineage != cur.MapLineage { return fmt.Errorf("%w: map lineage change outside an install or reset", errDescriptorTransition) diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 7cd2bd4045..a4d2542241 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -1111,7 +1111,7 @@ func (f *flusher) readDirtyRecordV3Cached(e snapshotEntry, cache *flushRecordCac store := f.store d := store.v3.pub.current() if cache != nil && !store.v3.flushLifetimeValidV3(cache.recoveryGen) { - return nil, 0, ErrMapCoverageStale + return nil, 0, mapCoverageRefusal("recovery_lifetime_changed") } var entry walEntryV3 var size uint64 @@ -1180,7 +1180,7 @@ func (s *WALStore) persistCheckpointV3(highestLSN, recoveryGen uint64) error { v.syncMu.Lock() defer v.syncMu.Unlock() if !v.flushLifetimeValidV3(recoveryGen) { - return ErrMapCoverageStale + return mapCoverageRefusal("recovery_lifetime_changed") } wack := v.wack.Load() if wack < checkpoint { From 8674d46b6daf43aaea8980cb0680415487266128 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 09:41:07 -0800 Subject: [PATCH 113/150] test: retain bounded stale-prepare checks with typed refusal reasons --- seaweed-block/core/storage/chunk_map_extents_v3_test.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/chunk_map_extents_v3_test.go b/seaweed-block/core/storage/chunk_map_extents_v3_test.go index 72cf43e1af..ed343e1a35 100644 --- a/seaweed-block/core/storage/chunk_map_extents_v3_test.go +++ b/seaweed-block/core/storage/chunk_map_extents_v3_test.go @@ -1,6 +1,7 @@ package storage import ( + "errors" "os" "path/filepath" "testing" @@ -430,7 +431,9 @@ func TestChunkMapExtentsV3ProofStalePreparesStayBounded(t *testing.T) { } cp := s.v3.pub.current().CheckpointLSN for i := 0; i < 150; i++ { - if _, err := s.prepareOwnedMapCheckpointV3(cp); err != ErrMapCoverageStale { + _, err := s.prepareOwnedMapCheckpointV3(cp) + var reason mapCoverageRefusal + if !errors.Is(err, ErrMapCoverageStale) || !errors.As(err, &reason) || reason != "proof_changed_during_prepare" { t.Fatalf("checkpoint prepare %d: err = %v, want ErrMapCoverageStale", i, err) } } @@ -438,7 +441,9 @@ func TestChunkMapExtentsV3ProofStalePreparesStayBounded(t *testing.T) { for i := 0; i < 150; i++ { g += 1000 entries := append([]chunkLSNEntryV3(nil), s.v3.mapEntries...) - if _, err := prepareMapPublicationV3(m, s.v3.mapProof, g, cp, entries, nil); err != ErrMapCoverageStale { + _, err := prepareMapPublicationV3(m, s.v3.mapProof, g, cp, entries, nil) + var reason mapCoverageRefusal + if !errors.Is(err, ErrMapCoverageStale) || !errors.As(err, &reason) || reason != "proof_changed_during_prepare" { t.Fatalf("publication prepare %d: err = %v, want ErrMapCoverageStale", i, err) } } From a31c73f1387eed92b2ee507d4d5abd27741c41ab Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 09:43:37 -0800 Subject: [PATCH 114/150] style: align the v3 test hooks after budget integration --- seaweed-block/core/storage/walstore_v3.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index a4d2542241..95b44551c3 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -84,7 +84,7 @@ type walStoreV3State struct { // testAfterRollover runs in a v3 write after the checkpoint rollover and // before the payload append (write-command budget, #252). testAfterRollover func() - testMapPrepared func() // outside all publication locks, after owned-map persistence + testMapPrepared func() // outside all publication locks, after owned-map persistence // testReadResolved runs in a v3 read after the dirty map resolved the // LBA's WAL position and before the record is read. testReadResolved func() From a2deedc49a1508f2c5489dee156ff84f7d50e531 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 10:26:54 -0800 Subject: [PATCH 115/150] storage: report the persisted checkpoint and its last advance CheckpointPersistenceStatus now carries the persisted CheckpointLSN and the count and time of the checkpoint calls that moved it. A success that was clamped or left the checkpoint unchanged is not an advance, so a starved checkpoint shows Successes rising while LastAdvance stays frozen. Co-Authored-By: Claude Opus 5.5 --- .../durable/checkpoint_status_test.go | 13 ++++-- .../core/storage/checkpoint_diagnostics.go | 37 ++++++++++++---- .../storage/checkpoint_diagnostics_test.go | 42 +++++++++++++++++++ seaweed-block/core/storage/flusher.go | 3 +- .../core/storage/flusher_instrumentation.go | 2 + 5 files changed, 85 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/frontend/durable/checkpoint_status_test.go b/seaweed-block/core/frontend/durable/checkpoint_status_test.go index b3ad4cb9ce..e3eed2d4f2 100644 --- a/seaweed-block/core/frontend/durable/checkpoint_status_test.go +++ b/seaweed-block/core/frontend/durable/checkpoint_status_test.go @@ -46,15 +46,20 @@ func TestDurableProvider_CheckpointPersistenceStatus(t *testing.T) { } var wire []struct { CheckpointPersistence *struct { - Successes uint64 - Refusals uint64 - Failures uint64 + Successes uint64 + Refusals uint64 + Failures uint64 + CheckpointLSN uint64 + Advances uint64 + LastAdvance time.Time } } if err := json.Unmarshal(raw, &wire); err != nil { t.Fatal(err) } - if len(wire) == 1 && wire[0].CheckpointPersistence != nil && wire[0].CheckpointPersistence.Successes > 0 { + if len(wire) == 1 && wire[0].CheckpointPersistence != nil && wire[0].CheckpointPersistence.Successes > 0 && + wire[0].CheckpointPersistence.CheckpointLSN > 0 && wire[0].CheckpointPersistence.Advances > 0 && + !wire[0].CheckpointPersistence.LastAdvance.IsZero() { return } if time.Now().After(deadline) { diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go index 46aa71e185..68303be17a 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -8,25 +8,48 @@ import ( // CheckpointPersistenceStatus counts flusher checkpoint calls in this open. // Success includes a safely clamped/unchanged checkpoint; it is not a slot-write -// count. Fields are cumulative atomic observations, not a coherent frontier. +// count. Advances counts only the successes that moved the persisted +// CheckpointLSN, and LastAdvance is when the latest one did (zero: none in +// this open), so a starved checkpoint shows Successes rising while +// LastAdvance stays frozen. Fields are cumulative atomic observations, not a +// coherent frontier. type CheckpointPersistenceStatus struct { - Successes uint64 - Refusals uint64 - Failures uint64 + Successes uint64 + Refusals uint64 + Failures uint64 + CheckpointLSN uint64 + Advances uint64 + LastAdvance time.Time } func (s *WALStore) CheckpointPersistence() CheckpointPersistenceStatus { if s.flusher == nil { - return CheckpointPersistenceStatus{} + return CheckpointPersistenceStatus{CheckpointLSN: s.CheckpointLSN()} } i := &s.flusher.instr - return CheckpointPersistenceStatus{i.checkpointSuccesses.Load(), i.checkpointRefusals.Load(), i.checkpointFailures.Load()} + st := CheckpointPersistenceStatus{ + Successes: i.checkpointSuccesses.Load(), + Refusals: i.checkpointRefusals.Load(), + Failures: i.checkpointFailures.Load(), + CheckpointLSN: s.CheckpointLSN(), + Advances: i.checkpointAdvances.Load(), + } + if ns := i.checkpointLastAdvanceNanos.Load(); ns != 0 { + st.LastAdvance = time.Unix(0, ns) + } + return st } -func (i *flusherInstrumentation) recordCheckpoint(err error) { +// recordCheckpoint classifies one flusher checkpoint call; before and after +// are the persisted CheckpointLSN around it. +func (i *flusherInstrumentation) recordCheckpoint(err error, before, after uint64, now time.Time) { switch { case err == nil: i.checkpointSuccesses.Add(1) + if after > before { + i.checkpointAdvances.Add(1) + i.checkpointLastAdvanceNanos.Store(now.UnixNano()) + } case errors.Is(err, ErrMapCoverageStale): i.checkpointRefusals.Add(1) default: diff --git a/seaweed-block/core/storage/checkpoint_diagnostics_test.go b/seaweed-block/core/storage/checkpoint_diagnostics_test.go index 2670beb977..6eb79badca 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics_test.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics_test.go @@ -116,3 +116,45 @@ func TestCheckpointDiagnostics_LogRateLimit(t *testing.T) { t.Fatalf("logs: %s", got) } } + +// A starved checkpoint: flush cycles keep succeeding (clamped to the +// acknowledged frontier, nothing persisted moves) while the persisted +// CheckpointLSN and the last advance stay frozen. Only a real move of the +// persisted checkpoint counts as an advance. +func TestCheckpointDiagnostics_StarvedCheckpointIsVisible(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + writeSynced(t, s, 1, 1) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + first := s.CheckpointPersistence() + if first.CheckpointLSN != 1 || first.Advances != 1 || first.LastAdvance.IsZero() || first.Successes != 1 { + t.Fatalf("first checkpoint: %+v", first) + } + for i := uint32(0); i < 3; i++ { // written, never synced: the checkpoint is clamped at 1 + if _, err := s.Write(2+i, blk(byte(2+i))); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + } + starved := s.CheckpointPersistence() + if starved.Successes <= first.Successes { + t.Fatalf("flush cycles did not keep succeeding: %+v", starved) + } + if starved.CheckpointLSN != 1 || starved.Advances != 1 || !starved.LastAdvance.Equal(first.LastAdvance) { + t.Fatalf("a clamped success counted as an advance: first %+v starved %+v", first, starved) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + moved := s.CheckpointPersistence() + if moved.CheckpointLSN != s.CheckpointLSN() || moved.CheckpointLSN <= 1 || moved.Advances != 2 || moved.LastAdvance.Before(first.LastAdvance) { + t.Fatalf("after sync the checkpoint advance was not recorded: %+v", moved) + } +} diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index 930e057a89..9c6175e044 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -278,12 +278,13 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { // The released tail is persisted with the checkpoint, before the // writer may reuse those bytes. var publishErr error + cpBefore := store.CheckpointLSN() if store.v3 != nil { publishErr = store.persistCheckpointV3(maxLSN, recoveryGen) } else { publishErr = store.persistCheckpointAndRelease(maxLSN, maxLSNPhys, maxLSNEntrySize) } - f.instr.recordCheckpoint(publishErr) + f.instr.recordCheckpoint(publishErr, cpBefore, store.CheckpointLSN(), time.Now()) if err := publishErr; err != nil { return fmt.Errorf("flusher: persist checkpoint %d: %w", maxLSN, err) } diff --git a/seaweed-block/core/storage/flusher_instrumentation.go b/seaweed-block/core/storage/flusher_instrumentation.go index ec3fcf1827..939da10058 100644 --- a/seaweed-block/core/storage/flusher_instrumentation.go +++ b/seaweed-block/core/storage/flusher_instrumentation.go @@ -69,6 +69,8 @@ type flusherInstrumentation struct { checkpointSuccesses atomic.Uint64 checkpointRefusals atomic.Uint64 checkpointFailures atomic.Uint64 + checkpointAdvances atomic.Uint64 + checkpointLastAdvanceNanos atomic.Int64 cyclesStarted atomic.Uint64 cyclesSucceeded atomic.Uint64 cyclesFailed atomic.Uint64 From 97d8e680917433271c9388453125f6e3569e6c26 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 10:57:40 -0800 Subject: [PATCH 116/150] storage: test that only an advance moves the last-advance time Supplied distinct times show an advancing success updates LastAdvance while an unchanged success, a refusal and a failure keep it; the starved-checkpoint test now requires the second advance to be later. Co-Authored-By: Claude Opus 5.5 --- .../storage/checkpoint_diagnostics_test.go | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/checkpoint_diagnostics_test.go b/seaweed-block/core/storage/checkpoint_diagnostics_test.go index 6eb79badca..8ce1cbcd80 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics_test.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics_test.go @@ -154,7 +154,33 @@ func TestCheckpointDiagnostics_StarvedCheckpointIsVisible(t *testing.T) { t.Fatal(err) } moved := s.CheckpointPersistence() - if moved.CheckpointLSN != s.CheckpointLSN() || moved.CheckpointLSN <= 1 || moved.Advances != 2 || moved.LastAdvance.Before(first.LastAdvance) { + if moved.CheckpointLSN != s.CheckpointLSN() || moved.CheckpointLSN <= 1 || moved.Advances != 2 || !moved.LastAdvance.After(first.LastAdvance) { t.Fatalf("after sync the checkpoint advance was not recorded: %+v", moved) } } + +// Only an advancing success moves LastAdvance; an unchanged success, a +// refusal and a failure leave the latest advance time as it was. +func TestCheckpointDiagnostics_LastAdvanceFollowsOnlyAdvances(t *testing.T) { + var i flusherInstrumentation + t0 := time.Unix(1000, 0) + at := func() time.Time { return time.Unix(0, i.checkpointLastAdvanceNanos.Load()) } + i.recordCheckpoint(nil, 0, 5, t0) + if !at().Equal(t0) || i.checkpointAdvances.Load() != 1 { + t.Fatalf("first advance: %v %d", at(), i.checkpointAdvances.Load()) + } + i.recordCheckpoint(nil, 5, 5, t0.Add(time.Second)) + i.recordCheckpoint(mapCoverageRefusal("proof_changed"), 5, 5, t0.Add(2*time.Second)) + i.recordCheckpoint(errors.New("fsync fault"), 5, 5, t0.Add(3*time.Second)) + if !at().Equal(t0) || i.checkpointAdvances.Load() != 1 { + t.Fatalf("a non-advance moved LastAdvance: %v advances=%d", at(), i.checkpointAdvances.Load()) + } + t1 := t0.Add(4 * time.Second) + i.recordCheckpoint(nil, 5, 9, t1) + if !at().Equal(t1) || i.checkpointAdvances.Load() != 2 { + t.Fatalf("second advance: %v %d", at(), i.checkpointAdvances.Load()) + } + if i.checkpointSuccesses.Load() != 3 || i.checkpointRefusals.Load() != 1 || i.checkpointFailures.Load() != 1 { + t.Fatalf("classification: s=%d r=%d f=%d", i.checkpointSuccesses.Load(), i.checkpointRefusals.Load(), i.checkpointFailures.Load()) + } +} From fa32ab5b325de9392ff880403515604a220362cc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 12:19:16 -0800 Subject: [PATCH 117/150] test: reproduce conservative chunk birth after dropped WAL suffix --- .../core/storage/chunk_birth_export_test.go | 82 +++++++++ .../core/storage/chunk_birth_manifest_test.go | 156 ++++++++++++++++++ 2 files changed, 238 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_birth_export_test.go create mode 100644 seaweed-block/core/storage/chunk_birth_manifest_test.go diff --git a/seaweed-block/core/storage/chunk_birth_export_test.go b/seaweed-block/core/storage/chunk_birth_export_test.go new file mode 100644 index 0000000000..08795edc5e --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_export_test.go @@ -0,0 +1,82 @@ +package storage + +import ( + "bytes" + "testing" +) + +// DroppedSuffixBirthStoreForTest exposes only the recovery fixture to the +// external-package regression, which uses chunkstore's real manifest builder. +func DroppedSuffixBirthStoreForTest(t *testing.T, remote ChunkRemote) *WALStore { + t.Helper() + s, path := newMappedCheckpointStoreV3(t) + layer := mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(1, blk(0xA1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, blk(0xA2)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, blk(0xA3)); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + if e := prepared.candidate.entries[0]; e.LSN != 3 || d.CheckpointLSN != 1 || d.W != 1 { + t.Fatalf("setup entry%+v cp%d W%d", e, d.CheckpointLSN, d.W) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatal(err) + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + damageRecord(t, path, 2) + reopen := func() *WALStore { + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + return r + } + r := reopen() + if r.NextLSN() != 2 || r.v3.mapEntries[0].LSN != 3 { + t.Fatal("missing conservative maximum after dropped suffix") + } + if n, err := r.Write(1, blk(0xB2)); err != nil || n != 2 { + t.Fatalf("reused LSN %d: %v", n, err) + } + if _, err := r.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, r) + r.mu.Lock() + r.closed = true + r.mu.Unlock() + r2 := reopen() + if e := r2.v3.mapEntries[0]; e.LSN != 3 || !e.Unknown || r2.NextLSN() != 3 || !bytes.Equal(readV3(t, r2, 1), blk(0xB2)) { + t.Fatalf("recovered reused image: entry%+v next%d", e, r2.NextLSN()) + } + return r2 +} diff --git a/seaweed-block/core/storage/chunk_birth_manifest_test.go b/seaweed-block/core/storage/chunk_birth_manifest_test.go new file mode 100644 index 0000000000..062f36e959 --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_manifest_test.go @@ -0,0 +1,156 @@ +package storage_test + +import ( + "bytes" + "context" + "fmt" + "path" + "sort" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/protobuf/proto" +) + +// Only the metadata/blob transports are in memory; capture, recovery, +// PrepareManifest, segment encoding, CAS and resolved reads are production. +type birthFiler struct { + mu sync.Mutex + entries map[string]*filerpb.Entry +} + +func (f *birthFiler) LookupEntry(_ context.Context, d, n string) (*filerpb.Entry, error) { + f.mu.Lock() + defer f.mu.Unlock() + e := f.entries[path.Join(d, n)] + if e == nil { + return nil, chunkstore.ErrNotFound + } + return proto.Clone(e).(*filerpb.Entry), nil +} +func (f *birthFiler) CreateEntry(_ context.Context, d string, e *filerpb.Entry, excl bool) error { + f.mu.Lock() + defer f.mu.Unlock() + k := path.Join(d, e.Name) + if excl && f.entries[k] != nil { + return chunkstore.ErrExists + } + f.entries[k] = proto.Clone(e).(*filerpb.Entry) + return nil +} +func (f *birthFiler) UpdateEntry(_ context.Context, d string, e *filerpb.Entry, expected map[string][]byte) error { + f.mu.Lock() + defer f.mu.Unlock() + k := path.Join(d, e.Name) + old := f.entries[k] + if old == nil { + return chunkstore.ErrNotFound + } + for k, v := range expected { + if !bytes.Equal(old.Extended[k], v) { + return chunkstore.ErrPrecondition + } + } + f.entries[k] = proto.Clone(e).(*filerpb.Entry) + return nil +} +func (f *birthFiler) DeleteEntry(_ context.Context, d, n string, expected map[string][]byte) error { + f.mu.Lock() + defer f.mu.Unlock() + k := path.Join(d, n) + for key, v := range expected { + if f.entries[k] == nil || !bytes.Equal(f.entries[k].Extended[key], v) { + return chunkstore.ErrPrecondition + } + } + delete(f.entries, k) + return nil +} +func (f *birthFiler) ListEntries(_ context.Context, d, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { + f.mu.Lock() + defer f.mu.Unlock() + var out []*filerpb.Entry + for k, e := range f.entries { + if path.Dir(k) == d && strings.HasPrefix(e.Name, prefix) && e.Name > after { + out = append(out, proto.Clone(e).(*filerpb.Entry)) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + if limit > 0 && len(out) > int(limit) { + out = out[:limit] + } + return out, nil +} + +type birthBlobs struct { + mu sync.Mutex + data map[string][]byte +} + +func (b *birthBlobs) Put(_ context.Context, d []byte) (string, error) { + b.mu.Lock() + defer b.mu.Unlock() + id := fmt.Sprint(len(b.data) + 1) + b.data[id] = bytes.Clone(d) + return id, nil +} +func (b *birthBlobs) Get(_ context.Context, id string) ([]byte, error) { + b.mu.Lock() + defer b.mu.Unlock() + d, ok := b.data[id] + if !ok { + return nil, chunkstore.ErrNotFound + } + return bytes.Clone(d), nil +} + +func TestChunkBirthDroppedSuffixPublishesWithRealManifest(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + f := &birthFiler{entries: map[string]*filerpb.Entry{}} + b := &birthBlobs{data: map[string][]byte{}} + remote, err := chunkstore.NewChunkRemote(f, b, "/birth/v1") + if err != nil { + t.Fatal(err) + } + s := storage.DroppedSuffixBirthStoreForTest(t, remote) + layer, err := storage.AttachChunkLayer(s, remote, storage.ChunkLayerConfig{ChunkBlocks: 4, Epoch: 2, Holder: "host-a"}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = layer.Close() }) + cut, err := layer.Cut(ctx) + if err != nil { + t.Fatalf("reused-LSN cut must publish without another write: %v", err) + } + h, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if cut.Head.RemoteLSN != 2 || h.RemoteLSN != 2 || h.Chunks[0].BirthLSN != 2 || h.Segments[0].MaxBirthLSN != 2 { + t.Fatalf("cut-image frontier/birth: %+v", h) + } + data, err := remote.Get(ctx, h.Chunks[0].Key) + if err != nil { + t.Fatal(err) + } + want := make([]byte, 4*4096) + copy(want[4096:], bytes.Repeat([]byte{0xB2}, 4096)) + if !bytes.Equal(data, want) { + t.Fatal("published cut differs from recovered B2 image") + } + // The real builder's future-birth guard must still reject corrupt proposals. + invalid := h + invalid.Chunks = map[uint64]storage.ChunkRef{0: h.Chunks[0]} + ref := invalid.Chunks[0] + ref.BirthLSN = 3 + invalid.Chunks[0] = ref + if _, _, err := remote.PrepareManifest(ctx, h, invalid, 4*4096); err == nil { + t.Fatal("future birth was accepted") + } +} From 29b3d2a30d0261fbe002be7c362f8aac72b62790 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 13:35:58 -0800 Subject: [PATCH 118/150] fix: bound conservative chunk birth by captured image frontier --- seaweed-block/core/storage/chunk_birth.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_birth.go b/seaweed-block/core/storage/chunk_birth.go index 85b3f7c273..32e3a1ee95 100644 --- a/seaweed-block/core/storage/chunk_birth.go +++ b/seaweed-block/core/storage/chunk_birth.go @@ -10,7 +10,7 @@ func (l *chunkLayerImpl) captureBirths(candidates map[uint64]bool, frontier uint for idx := range candidates { birth := frontier if l.usesOwnedMapV3() { - birth = l.s.v3.mapEntries[idx].LSN + birth = min(l.s.v3.mapEntries[idx].LSN, frontier) } out[idx] = birth } From 4e53dbcb36c8c59f1323451f21c25542a6826f58 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 13:36:59 -0800 Subject: [PATCH 119/150] docs: clarify conservative map birth and captured frontier --- seaweed-block/core/storage/chunk_birth.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/chunk_birth.go b/seaweed-block/core/storage/chunk_birth.go index 32e3a1ee95..c6862223a8 100644 --- a/seaweed-block/core/storage/chunk_birth.go +++ b/seaweed-block/core/storage/chunk_birth.go @@ -1,8 +1,9 @@ package storage // The caller holds captureMu exclusive, with no layer state lock held. -// An owned-map max is the newest local write in that chunk; base fills do -// not advance it. Other engines use the cut frontier as an upper bound. +// An owned-map max is conservative: recovery can drop an unacked suffix +// while retaining its maximum. Bound it by the same-barrier cut frontier; +// the captured image has no later writes. Preserve lower inherited births. func (l *chunkLayerImpl) captureBirths(candidates map[uint64]bool, frontier uint64) map[uint64]uint64 { out := make(map[uint64]uint64, len(candidates)) l.s.mu.RLock() From 4bee2d11923a9dfd416d887e7ce8398297200648 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 13:46:33 -0800 Subject: [PATCH 120/150] docs: record recovery-bounded cut birth invariant and regression --- seaweed-block/docs/design/invariants.md | 535 ------------------------ 1 file changed, 535 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b88ad2689a..e69de29bb2 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1,535 +0,0 @@ -# Seaweed Block invariants and state machines - -This is the protocol contract of Seaweed Block: the state machines the code implements, the invariants each transition must keep, where each invariant is enforced, which test asserts it, and which TLA+ property models it. It is written for people and for coding agents. Before changing a protocol path, find the machine in Part A and the rows in Part B, and follow the change rules in Part C. - -This document supersedes the internal ledger [`internal/docs/protocol/invariant-ledger.md`](../../internal/docs/protocol/invariant-ledger.md). Every ID from that ledger is kept here and was re-checked against the code; some statements were narrowed to what the tests in this repository actually assert, and each narrowing is noted under its table. The internal file stays for history; new rows go here. - -The design is described in three documents, and this one collects their machines and invariants in one place: the [core design](block-design.md), the [agent workspace design](agent-workspace-design.md) and the [Kubernetes block design](kubernetes-block-design.md). - -**Conventions.** These are the same as in the design documents. - -- Code references name a file and a function, not a line number. Test references name the test function and its file. -- A TLA+ entry names a specification in [`docs/spec/`](../spec/README.md) and an invariant or property defined in it. The models check designs at small scale and are mapped to the code by reading (see the [limits](../spec/README.md#limits)). -- Status: - - `ACTIVE`: a Go test in this repository asserts the statement. - - `STUB`: the code enforces the statement (by reading), but no test asserts it yet. A release note must not claim behaviour backed only by a `STUB` row. - - `ARCHIVED`: a retired row, kept with its reason. There are none yet. -- The rule carried over from the internal ledger still applies: an invariant without a test is a wish, not an invariant. - -## Contents - -- [Part A. State machines](#part-a-state-machines) - - [M1 walstore: open, recover, serve, fault](#m1-walstore-open-recover-serve-fault) - - [M2 Authority: assignment, epoch, lease](#m2-authority-assignment-epoch-lease) - - [M3 Replica role and peer state](#m3-replica-role-and-peer-state) - - [M4 Workspace HEAD holder and takeover](#m4-workspace-head-holder-and-takeover) - - [M5 The cut pipeline](#m5-the-cut-pipeline) - - [M6 Chunk lifecycle](#m6-chunk-lifecycle) -- [Part B. Invariant ledger](#part-b-invariant-ledger) -- [Part C. Change rules](#part-c-change-rules) - ---- - -## Part A. State machines - -Each machine lists its states, the allowed transitions, the guard that must hold for each transition, where the guard is enforced, and the IDs of the Part B rows that protect it. A state name in `code font` is a value in the code; the other names describe a condition and are not code types. - -### M1 walstore: open, recover, serve, fault - -The local storage engine and the durable backend in front of it. Diagrams in the core design: the per-I/O gate in [§1.1](block-design.md#11-frontends-and-the-backend-contract), and the life of one write (appended, synced, in the extent, checkpointed, reusable) in [§1.2](block-design.md#12-walstore-wal-plus-extent). - -```mermaid -stateDiagram-v2 - [*] --> Opened: OpenWALStore / CreateWALStore - Opened --> Recovering: RecoverVolume - Recovering --> Serving: Recover ok, backend operational - Recovering --> RecoveryFailed: Recover error (typed reason) - Serving --> FaultLatched: fsync or WAL append fails - FaultLatched --> Closed: Close - RecoveryFailed --> Closed: Close - Serving --> Closed: Close - Closed --> Opened: reopen -``` - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | -| Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | -| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | -| Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | -| Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001` | -| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse (C11 bitmap/superblock path remains legacy-fixture-only) | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001` | -| Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `noteAppendFailure`, `syncFile` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | -| FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | -| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | - -Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. - -Public walstore Create now selects mapped format v3/impl3 (mode C by default, mode A by create option). Open and offline readonly use A/B slot and owned-map validation; valid legacy formats are refused with `ErrUnsupportedLegacyFormat`, rather than silently retrofitted. The temporary old-engine/raw-codec test scope and every named native replacement are recorded in [the legacy inventory](format-v3-legacy-test-inventory.md). Native recovery validates nonce/cursor binding and a contiguous physical LSN prefix before applying the mode-specific W rule; an acknowledged-range integrity failure blocks startup. The provider's create geometry, auto probe, capture, HEAD restore and readonly/status controls exercise the public selector (`INV-WAL-V3-ACTIVATION-001`). Before reading v3 slots, both read/write and offline read-only open acquire an exclusive nonblocking file lock; the offline migration CLI acquires the same lock before any descriptor read or mutation (`INV-WAL-V3-OWNER-001`). Contention refuses open/migration without changing bytes; descriptor close or process exit releases ownership. This implements the existing offline-migration precondition, not a new serving state. The mapped v3 checkpoint also carries a complete-record physical tail through the covered LSN minus the configured retention window; partial batches remain retained. The existing sole publisher then performs metadata-only rollover when the fallback still pins that prefix. Reuse still requires both valid same-nonce slot tails and retirement of checkpointed dirty references under writer exclusion; idle, unchanged-checkpoint and admission paths also settle a pinned fallback. An unlocked catch-up scan revalidates the coherent checkpoint and tail before emitting anything. A failed rollover latches and grants no reuse (`INV-WAL-V3-RECLAIM-001`). - -Recovery warnings such as `wal_hole_suspected` are recorded in Serving without changing health (`INV-WAL-WARN-NO-HEALTH-001`). The open gaps of this machine (a corrupted synced record mid-history only warns; forged records in user data) are listed in the [core known issues](block-design.md#24-known-issues-and-work-in-progress) and are not ledger rows. - -### M2 Authority: assignment, epoch, lease - -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). - -**Assignment line, per volume.** - -| From | To | Event and guard | Enforced in | Protects | -|---|---|---|---|---| -| Unbound | Bound (epoch 1, endpoint version 1) | `IntentBind`; no slot of this volume holds a present line (checked per volume, also after a restart); to move to another slot use `IntentReassign` | `core/authority/authority.go` `applyWithWorkspaceMove`, `boundReplicaForVolume`; `core/authority/controller.go` `decideVolume` (binds only a volume with no line) | `INV-AUTH-ONE-PRIMARY-001`, `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | -| Bound | Bound (endpoint version + 1) | `IntentRefreshEndpoint`; same epoch; a no-op when the addresses are unchanged | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | -| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` | -| any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing, but its durable outcome may be unknown | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | -| any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` | -| Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | - -**Workspace lease and move, in blockmaster.** - -| From | To | Event and guard | Enforced in | Protects | -|---|---|---|---|---| -| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | -| Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | -| Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | -| Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | -| Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | -| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding; each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001` | -| Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | -| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | -| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` | - -### M3 Replica role and peer state - -The role a blockvolume takes from each assignment, its replica listener's admission, and the primary's view of each replica. This is the replication engine of [core §1.6](block-design.md#16-replication-and-failover) (which has the peer-state diagram) as the Kubernetes line uses it; promotion is in [Kubernetes §6](kubernetes-block-design.md#6-authority-promotion) (diagram) and the failover sequence in [Kubernetes §4](kubernetes-block-design.md#4-replication-and-failover). - -```mermaid -stateDiagram-v2 - [*] --> Unassigned: listener with a floor record, no role yet - Unassigned --> Primary: fact names self, listener fenced at e - Unassigned --> Supporting: fact names another primary, self in peers - Supporting --> Primary: promotion, fact names self at a higher epoch - Primary --> Supporting: fact names another primary, self in peers - Primary --> Excluded: fact names another primary, self not in peers - Supporting --> Excluded: fact names another primary, self not in peers - Excluded --> Supporting: later fact lists self as a peer -``` - -**Host role and listener admission.** - -| From | To | Event and guard | Enforced in | Protects | -|---|---|---|---|---| -| any | (no change) | local readiness blocked (recovery pending or failed): the fact is stored and replayed when readiness clears | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `INV-ROLE-READINESS-BLOCK-001` | -| any | (no change) | a role call below the current desired epoch is refused and does not clear a newer admission failure | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `INV-ROLE-STALE-REPLAY-001` | -| Unassigned, Supporting | Primary at e | the fact names this replica; the replica set is installed; the listener is fenced as primary and its floor e is persisted before the adapter is told | `core/host/volume/host.go` `applyFact`, `fenceSelfWithPeers`; `core/transport/replica.go` `FenceAsPrimary`, `raiseFloor` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001` | -| Unassigned, Primary | Supporting at e | the fact names another primary and lists this replica as a peer; the floor e is persisted first; the frontend stays gated | `core/host/volume/host.go` `applyFact`; `core/transport/replica.go` `AdmitAsReplica` | `INV-FENCE-FLOOR-DURABLE-001` | -| Primary, Supporting | Excluded | the fact names another primary and does not list this replica; ingress is closed, the other line is recorded and the frontend is unhealthy | `core/host/volume/host.go` `applyFact`, `recordOtherLine`; `core/host/volume/projection_bridge.go` `projectionWithSupersede` | `INV-ROLE-SUPERSEDED-001`, `INV-FENCE-STALE-PRIMARY-001` | -| any | role admission failed | the listener cannot be fenced or its floor cannot be persisted; the role is not adopted and the projection is not healthy | `core/host/volume/host.go` `latchRoleAdmission` | `INV-FENCE-FLOOR-DURABLE-001` | -| (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | -| Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | - -**Peer state, as the primary sees each replica** (type `ReplicaState` in `core/replication/peer.go`). A new peer starts `Healthy` (`NewReplicaPeer`). - -| From | To | Event and guard | Enforced in | Protects | -|---|---|---|---|---| -| `Healthy`, `Unknown` | `Degraded` or `CatchingUp` | ship, barrier or fence failure; or a probe that needs catch-up | `core/replication/peer.go` `ReplicaPeer.SetState`, `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | -| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001` | -| `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | -| any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | -| `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | - -`ReplicaPeer.Invalidate`, called on a ship, barrier or fence error, goes through the same gate as `SetState` (`replicaStateTransitionAllowed`): `Healthy`, `Degraded` and `CatchingUp` move to `Degraded`; from `NeedsRebuild` the state is kept and the reason is still logged ([#182](https://github.com/seaweedfs/seaweed-block/issues/182)). A replicated `Sync` is judged per durability mode (`core/replication/durability.go` `EvaluateBarrierAcks`; `INV-REPL-DURABILITY-MODE-001`). - -### M4 Workspace HEAD holder and takeover - -One host at a time holds a workspace volume's HEAD in SeaweedFS. The sequence diagram of a clean and a forced move is in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves); blockmaster's side of the lease is in M2. - -```mermaid -stateDiagram-v2 - state "Lease guard (host)" as G { - [*] --> NoLease - NoLease --> Valid: renewal reply for this volume, replica and epoch - Valid --> Valid: renewal before the local deadline - Valid --> Fenced: deadline passed, invalid reply, or revoking - Fenced --> Drained: frontend and cuts stopped - Drained --> Acked: revocation acknowledged with the HEAD gen - } - state "HEAD holder" as H { - [*] --> Attaching - Attaching --> Claiming: fresh local root - Attaching --> Holder: existing root, HEAD is this holder's - Attaching --> Refused: existing root, HEAD published by another holder - Claiming --> Holder: CAS to this epoch and holder, state active - Claiming --> HolderFenced: HEAD epoch higher, or another holder at this epoch - Holder --> Detached: Detach final cut, state detached - Holder --> HolderFenced: a superseding HEAD is seen - } -``` - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| NoLease, Valid | Valid | the reply names this `{volume, replica, epoch}`, its validity is positive and at most 30 s, and it arrives before the old deadline; the new deadline is anchored to the request start | `core/host/volume/workspace_lease.go` `Refresh` | `INV-WS-LEASE-001`, `INV-WS-FORCED-MOVE-001` | -| Valid | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` | -| Fenced | Drained, Acked | the stop callback succeeded; only then, and only when revoked, the acknowledgement is sent | `core/host/volume/workspace_lease.go` `drain` | `INV-WS-REVOKE-ACK-001` | -| Attaching | Refused | an existing local root whose HEAD another holder has published (`ErrChunkStaleLocalRoot`) | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-STALE-LOCAL-ROOT-001` | -| Claiming | Holder | HEAD epoch not above the master-issued epoch, no other holder at the same epoch; the local frontier is seeded from HEAD before the CAS; I/O opens only after the claim | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-WS-HEAD-CAS-001` | -| Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | -| Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | -| Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | -| Holder | HolderFenced | a HEAD with a higher epoch, or another holder at the same epoch | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | -| Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | - -### M5 The cut pipeline - -A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. The steps are described in [agent workspace §5](agent-workspace-design.md#5-the-cut), and the figure in [§3](agent-workspace-design.md#3-remote-layout) shows them against the remote layout. All steps are in `core/storage/chunk_layer.go` `captureLocked` unless stated. - -```mermaid -stateDiagram-v2 - [*] --> Admit - Admit --> Refused: closed, fenced, detached, base install, reconciling, or lineage or lease invalid - Admit --> Stage: earlier unknown CAS settled - Stage --> Quiesce: at most 3 pre-copy rounds - Quiesce --> OpenWindow: Sync H and D fixed under barrier - OpenWindow --> Copy: release barrier - Copy --> Closed: all candidates done - Copy --> Aborted: error, cancellation, observed fence, recovery or close - Aborted --> Refused: drain owners, cleanup, merge candidates - Copy --> Refused: H below HEAD RemoteLSN - Closed --> Upload: drain and cleanup; intent durable first - Upload --> Manifest - Manifest --> Readmit - Readmit --> Fenced: superseding HEAD - Readmit --> CAS - CAS --> Settled: CAS ok, or a re-read shows the proposal - CAS --> Pending: outcome unknown and HEAD unchanged - CAS --> Fenced: HEAD moved to a superseding holder - CAS --> Refused: HEAD moved otherwise (conflict) - Pending --> Admit: next cut settles it first -``` - -| Step | Guard | Enforced in | Protects | -|---|---|---|---| -| Admit | not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease); no cut while reconciling | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-CUT-RECONCILING-001`, `INV-WS-LEASE-001` | -| Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | -| Stage | while more than the barrier bound would be copied, pre-copy outside the barrier; new keys are covered by an intent first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001` | -| Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | -| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read into buffers; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | -| LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | -| Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after a durable intent names them | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | -| Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | -| No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001` | -| Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-WS-HEAD-CAS-001` | -| CAS | conditional update on `{gen, epoch}`, with `RemoteLSN = H`; refused for a lower epoch, a lower `RemoteLSN`, or a HEAD in a delete state | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001`, `INV-HEAD-DELETE-FROZEN-001` | -| Settled | drop the intents; reset the bitmap to the cut, keeping chunks dirtied after it | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | -| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` | - -### M6 Chunk lifecycle - -HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete). - -**HEAD states** (`active`, `detached`, `deleting`, `purging`, `deleted`, `aborted`). - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | -| `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | -| `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | -| `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | -| `active`, `detached` | `deleting` | a blockmaster deletion reservation exists and HEAD is not held | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `markHeadDeleting` | `INV-VOLDEL-HELD-HEAD-001`, `INV-VOL-ID-NO-REUSE-001` | -| `deleting` | previous state | a snapshot name record exists: the delete is refused and reverted | `core/frontend/chunkstore/volume_delete.go` `snapshotsBlock`, `revertHeadDeleting` | `INV-VOLDEL-COMMIT-001` | -| `deleting` | `purging` | commit point, bound to the same delete incarnation | `core/frontend/chunkstore/volume_delete.go` `commitHeadPurging` | `INV-VOLDEL-COMMIT-001` | -| `purging` | `deleted` | chunks dropped and `VOLUME` marked deleted | `core/frontend/chunkstore/volume_delete.go` `finishHeadDeleted`, `markVolumeDeleted` | `INV-VOL-ID-NO-REUSE-001` | -| `deleting`, `purging`, `deleted` | — | no claim or cut moves HEAD; only the delete's own transitions | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-HEAD-DELETE-FROZEN-001` | -| — | `aborted` | a GC copy sweep settles a dead fork by an exclusive create of an aborted HEAD tombstone, so the fork can never publish | `core/frontend/chunkstore/catalog.go` `AbortFork`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies` | — | - -**Snapshots and forks.** - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | -| name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | -| published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | -| published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001` | - -**Intents and key bindings.** - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | -| intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` | -| intent live | expired | older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001` | -| — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | -| bound | tombstoned, needle deleted | unrooted in two complete marks at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001` | -| tombstoned | (never rebound) | bindings are never removed | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | - ---- - -### Local WAL-pressure durability progress - -A serving v3 store at the soft WAL watermark may perform an internal local -sync from its existing flusher, before snapshotting dirty work. This transition -uses the ordinary A/C physical-sync and final fault gate under one `syncMu` -interval; it takes neither `captureMu` nor `lifecycleMu`. It is ineligible while -BASE is installing or the store is closed. The leader is released before extent, -map and checkpoint publication. Client Flush acknowledgements keep their own -covering durability and observer requirements. Recovery invalidates the existing -snapshot lifetime; local persistence does not bypass it. - -- `INV-WAL-V3-PRESSURE-001`: I1, within a recovery/reset lifetime `wack` advances - only after covering local persistence; I2, checkpoint remains at most `wack` - and the active-session pin floor; I3, record reuse remains below the durable - checkpoint, both-slot floor and dirty-reference retirement; I4, with healthy - local progress and no guest Sync, the reuse floor advances. Enforced by - `syncWALBatchV3Internal`, `persistOwnedMapCheckpointV3` and the existing reclaim - publisher. Tests: `TestWALStoreV3NoClientSyncSixRings`, - `TestWALStoreV3PressureSyncFaultDoesNotPublishFrontiers`, - `TestWALStoreV3PressureSyncSkipsInstalling`, - `TestWALStoreV3PressureProgressWithPendingCutOrClose` and - `TestWALStoreV3PressureWaitBudgetAndPin`. Model correspondence: `WALReclaim.tla` I1/I2/I3 and - `AllWritten`/`NoStuckWaiter` in `REC_safe`/`REC_safe_big`; the no-internal-sync - mutant violates liveness. Prior authored LIGHT receipts are referenced in - `docs/spec/README.md`; this change does not claim a new TLC execution. -- The v3 pressure admission budget is four seconds of cooperative waiting. It - cannot preempt a blocking occupancy/closed callback, lock acquisition or - physical file I/O. An unresolved pin or local stall returns - `ErrWALPressureTimeout`, preserved as `frontend.ErrBackendBusy`; NVMe returns - Generic/Namespace Not Ready (SC0x82), DNR=0. Sticky faults retain their original - non-retryable mapping. This is a local pressure outcome, not a whole-I/O - deadline; the broader budget gap is tracked separately in issue221. -- A flusher cycle sorts native snapshot entries by record offset and reuses at - most one fully validated record (bounded by WALSize). Every block still checks - its LBA/data offset/LSN/nonce; the cache is local to the snapshot recovery - generation and cannot publish or materialize after that lifetime changes. - `TestWALStoreV3FlushBatchCacheIsBoundToRecoveryLifetime` covers one batch decode - and refusal after Recover. Missing map coverage still forbids checkpoint - advancement; the earlier unmapped dark fixture is not a production geometry. - -## Part B. Invariant ledger - -80 rows: 69 ACTIVE, 11 STUB; 15 kept from the internal ledger, 65 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. - -### B.1 Core: storage, durability and the frontend gate - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | -| `INV-WAL-REPLAY-LWW-001` | Replay applies the highest LSN per LBA, independent of the physical scan order. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALStoreRecoverLastWriterWinsAcrossScanOrder` (`core/storage/walstore_recovery_lww_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | -| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the on-disk superblock has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_writer.go` `spaceUsed`, `tailPersisted`; `core/storage/walstore.go` `persistCheckpointReleasing` | `TestWALWriterReuseIsBoundedByTheDurableTail`, `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherSnapshotCutPreservesSyncedWrites` (`core/storage/flusher_snapshot_cut_test.go`); `TestWALStoreCheckpointSIGKILLCrashWindows` (`core/storage/walstore_checkpoint_crash_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-FRONTIER-GAP-001` | Synced entries above an intentional LSN gap (a rebuild's frontier jump) are kept by recovery. | M1 Recovering | `core/storage/recovery.go` `recoverWAL` | `TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump` (`core/storage/walstore_recovery_frontier_gap_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore.go` `persistCheckpointReleasing` | `TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle` (`core/storage/walstore_checkpoint_safety_test.go`) | — | ACTIVE | -| `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent or superblock), the open store refuses every later `Sync`, write and checkpoint without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestWALStoreWALFsyncFailureIsSticky`, `TestWALStoreExtentFsyncFailureIsSticky`, `TestWALStoreCheckpointFsyncFailureIsSticky` (`core/storage/walstore_sticky_fsync_test.go`); `TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | -| `INV-WAL-APPEND-STICKY-001` | A WAL append whose write failed latches the store fault; writers already queued behind it are refused. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteAppendFailure`, `WALStore.Write` | `TestWALStoreWritersQueuedBehindAFailedAppendAreRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | -| `INV-WAL-SYNC-FRONTIER-001` | `Sync` never reports an uncovered write durable: it returns the global synced frontier, which is at least the caller's own write and is covered by a completed `fsync`. It may include later writes whose covering `fsync` completed before the caller resumed. | M1 write lifecycle: Appended → Synced | `core/storage/walstore.go` `WALStore.Sync` | `TestWALStore_SyncDoesNotClaimConcurrentWrite` (`core/storage/walstore_test.go`); `TestWALGenerationFirstCallerReturnOrdering` (`core/storage/walstore_sync_frontier_order_test.go`) | — | ACTIVE | -| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt` (`cmd/blockvolume/durable_startup_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE | -| `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE | -| `INV-WAL-V3-ACTIVATION-001` | Public create produces an owned mapped v3/impl3 volume with the requested chunk geometry and C default/A option. Writable/readonly open validate A/B dependencies, reject actual legacy headers without mutation, and can select a valid fallback when A is damaged. Production provider capture/HEAD restore/status use those selectors. Legacy fixture constructors cannot be called by default production code or enter its transitive storage import closure. | M1 open/create/readonly | `walstore.go` public selectors; `walstore_v3.go` `refuseLegacyWALStore`, `ProbeWALStoreV3`; `provider.go` | `TestWALStoreProductionSelectorCreatesMappedV3`, `TestWALStoreProductionRefusesLegacyWithoutMutation`, `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy`, `TestWALStoreProductionCreateOptions`, `TestLegacyFixtureIsolation`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE | -| `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE | -| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | -| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | -| `INV-WAL-V3-RECORD-001` | An impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | -| `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB | -| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire` | `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | -| `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint releases only complete validated record ends covered by the checkpoint and outside the retention window; an installing BASE retains its install suffix. Physical recovery rebuilds the volatile boundary index only from the trusted kept scan, without restoring a disconnect cursor. Tail/head/map/checkpoint/W publish together, followed by metadata-only rollover; both slot tails still pin reuse. Failure grants no reuse and retains exact dirty retry identity. Checkpoint publication excludes writer admission through both-slot rollover and dirty-reference retirement. Idle, unchanged-checkpoint and admission settle pending rollover; catch-up revalidates tail/checkpoint before delivering its buffered scan. | M1 checkpoint / existing two-slot retirement | `wal_io_v3.go` `reclaimThroughV3`, `rememberReclaimScanV3`; `walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `descriptor_v3.go` `rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse`, `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint`, tagged `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB | -| `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | -| `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | -| `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | -| `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | -| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | -| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | -| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | -| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | -| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | -| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | -| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB | -| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB | -| `INV-WAL-V3-MIGRATE-001` | `sw-block migrate-v3` rewrites only the descriptor of a cleanly closed v2/impl1 volume whose WAL the exhaustive scan proves flushed; the scan and the geometry check run before any write, and a refusal leaves the volume and every sidecar byte-identical. It keeps the extent base (WALSize = old - 4096), writes an atomic operator backup, an all-UNKNOWN initial map (covered = the v2 checkpoint), the prepared slot B, slot A at phase 0 (the commit point), slot B at phase 0, and only then retires the v2 chunk bitmap; each step is durable before the next. A rerun decides from the slot bytes alone: before the commit it restarts with a full rescan; after it, it only finishes the rollover and the retirement; a prepared B with an invalid A refuses with `ErrMigrationIncomplete`, as v3 open does; it never reads or restores the backup. | offline tool | `cmd/sw-block/migrate.go`; `cmd/sw-block/internal/v2legacy`; `core/storage/migrate_v3.go` | `TestMigrateV3CleanVolume`, `TestMigrateV3RefusalsChangeNothing`, `TestMigrateV3CrashAfterEachStepIsResumable`, `TestMigrateV3OldBinaryAfterPreparation`, `TestMigrateV3OldWALOverwritesThePreparedSlot`, `TestMigrateV3NeverRestoresTheBackup` (`cmd/sw-block/migrate_test.go`); tagged `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | none (tool) | STUB | -| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | -| `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | -| `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE | - -Notes: - -- `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged. -- `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. - -- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. Writes invalidate proofs before append and update per-chunk max LSN under store.mu, while Recover rebuilds that volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. - -- `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. Sidecar extents are reused only after neither slot nor a pending or uncertain candidate references them; see `chunk_map_extents_v3.go` and its tests. - -- `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only. -- `INV-FE-FLUSH-SYNC-001`: NVMe/TCP also asserts failed-Sync status and reason logging through the actual session dispatch, and success produces no failure log. -- `INV-WAL-V3-RESET-001`: Format bump v3, plan row 8 (DESIGN 8.6). Dark: no production path calls the reset, and it must not be activated before the reset model (r4.5) passes. No v3 tail release exists yet, so the precondition is CheckpointLSN >= W rather than an empty retained range: retained old-incarnation bytes at or below the checkpoint are preserved in the extent. The map root is unchanged by a reset, so no map page is retired. -- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). Until the chunk layer's side of the v3 install protocol lands (codex03), a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until codex03's v3 FreshFromHead restore lands; since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from (codex01 row 11b P1); it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). -- `INV-WAL-V3-MIGRATE-001`: Format bump v3, plan rows 13a and 13b (DESIGN 10.1). Not yet in this row: the exclusive advisory lock that v3 open will share (precondition 1; it lands with the 12b open path), and raw v2 fixtures committed under testdata (today's controls build v2 volumes with the v2 code that row 14 deletes). The minimum migrated WAL size (64 KiB and two single-block records) is provisional. -- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model (claude05), not by these tests. Installing recovery is row 11. -- `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). It is a STUB until the v3 store is wired in (rows 4 and 5) and activated (row 12b). The v2 checkpoint path (`persistCheckpointReleasing`) is unchanged and is retired in row 14a. The map coverage predicates against the root are added by row 7, and the conditions on BASE edges by rows 9 to 11. -- `INV-WAL-V3-DESCRIPTOR-001`: Format bump v3, plan row 1 (DESIGN r15 section 2). It is a STUB until the activation commit (plan row 12b): no production open or create path reaches the v3 codec before then. The map-dependency checks (root and pages present and hash-valid) are added by plan row 7. The tests decode vectors from an independent generator (`core/storage/testdata/format_v3/slot/gen_slot_vectors.py`). - -### B.2 Core: authority and epochs - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | -| `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that clears the lease is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | -| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | - -Notes: - -- `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, directory sync failed): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. -- `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2). -- `INV-WS-RENEW-NONBLOCKING-001`: The cited tests inject delays or holds before or inside the store write; they show sensitivity to a slow store, not a measured disk trace. - -### B.3 Core: replication and replica roles - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | -| `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | -| `INV-REPL-INGRESS-SLOTS-001` | Replication listeners are open only while the assignment has replica slots. | M3 role → listener lifecycle | `cmd/blockvolume/replication_ingress.go` `roleLocked` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | ACTIVE | -| `INV-REPL-CATCHUP-REBUILD-001` | The engine chooses catch-up when the gap is still in the primary's WAL and rebuild when it is not. | M3 Degraded → CatchingUp \| NeedsRebuild | `core/engine/apply.go` `decide` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | ACTIVE | -| `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE | -| `INV-REPL-DURABILITY-MODE-001` | Under `sync_all` a replicated `Sync` fails if any replica barrier fails; under `sync_quorum` it fails unless a majority of nodes, the primary included, are durable. | M3 barrier evaluation | `core/replication/durability.go` `EvaluateBarrierAcks` | `TestDurabilityCoordinator_Quorum_RF3_OneReplicaFailed`, `TestDurabilityCoordinator_Quorum_RF3_BothReplicasFailed`, `TestDurabilityCoordinator_SyncAll_AnyFailure_Fails` (`core/replication/durability_test.go`) | — | ACTIVE | -| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`) | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive` | ACTIVE | -| `INV-ROLE-STALE-REPLAY-001` | A role call below the host's current desired epoch is refused and cannot clear a newer role-admission failure. | M3 role admission | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `TestG1_StaleReplayDoesNotClearANewerAdmissionFailure`, `TestG1_StaleSupportingReplayDoesNotClearTheLatch` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | -| `INV-ROLE-READINESS-BLOCK-001` | While local recovery blocks readiness, `applyFact` admits neither a primary nor a supporting role, and replays the stored fact once readiness clears. | M3 Unassigned → Primary \| Supporting (guard) | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter`, `TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter`, `TestHost_ApplyFact_Self_ReplaysAfterLocalReadinessClearsWithReplicationFirst` (`core/host/volume/apply_fact_test.go`) | — | ACTIVE | -| `INV-ROLE-SUPERSEDED-001` | A fact naming another replica as primary, with this replica not among its peers, never reaches this host's adapter or replication, and is recorded as the other line. | M3 Primary \| Supporting → Excluded | `core/host/volume/host.go` `applyFact`, `recordOtherLine` | `TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication` (`core/host/volume/apply_fact_test.go`); `TestHost_BuildReport_SupersededReplicaNotReadyForPrimary` (`core/host/volume/frontend_targets_test.go`) | — | ACTIVE | - -Notes: - -- `INV-REPL-INGRESS-SLOTS-001`: Binary test: builds and runs the real `blockvolume`; build tag `subprocess`, not on Windows. -- `INV-REPL-PEER-TRANSITIONS-001`: `ReplicaPeer.Invalidate` uses the same gate as `SetState`; from `NeedsRebuild` it keeps the state and still logs the reason (see Part A, M3; [#182](https://github.com/seaweedfs/seaweed-block/issues/182)). - -### B.4 Workspace: HEAD holder, lease and takeover - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-WS-HEAD-CAS-001` | Every HEAD publish is a conditional update on `{gen, epoch}`, so only one holder can publish each HEAD generation; a holder that sees a superseding HEAD fences itself. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | -| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | -| `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | -| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | -| `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | -| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | -| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | -| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `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`) | — | ACTIVE | - -Notes: - -- `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary. -- `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits). -- `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. - -### B.5 Workspace: the cut pipeline - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | -| `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | -| `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | -| `INV-CUT-STAGED-REUSE-001` | A chunk pre-copied outside the barrier is used only if no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window (legacy fixtures retain the full-copy barrier). | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | -| `INV-CUT-BITMAP-001` | The dirty bitmap never under-reports: it is durable before the checkpoint passes its WAL entries, and it is reset only after a successful CAS, keeping chunks dirtied after the cut. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/chunk_layer.go` `BeforeCheckpointAdvance`, `finishCut` | `TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle`, `TestChunkLayer_C11_RolloverKeepsPostCutDirt` (`core/storage/chunk_layer_c11_test.go`) | `CutCapture` `HeadImage` | ACTIVE | -| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE | -| `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut, an intent naming every new key is durable, and it is removed only after the CAS outcome is known. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | -| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | -| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | - -Notes: - -- `INV-CUT-STAGED-REUSE-001`: `captureLocked` also requires HEAD's generation to be the one the stage was compared against (code reading; not asserted by these tests). - -### B.6 Workspace: chunk lifecycle, GC and delete - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | -| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | -| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | -| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | -| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | -| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | -| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | -| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | -| `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | - -Notes: - -- `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace. - -### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | -| `INV-PROMOTE-FRONTIER-001` | The RF=3 promotion gate promotes only a probed candidate that covers the required acknowledgement frontier, and blocks promotion without a fresh probe. With a known frontier the candidate's durable LSN must be at least the required LSN. With an unknown frontier under `sync_quorum` or `sync_all`, the highest-durable ready candidate is promoted only when at least P-K+1 distinct peers are probed ready and fresh in the same tick (K from `waitForSyncAcks`; RF=3: both peers under `sync_quorum`, one under `sync_all`); otherwise nothing is promoted. An unknown frontier is never read as zero; `best_effort` is unchanged. | M3 Supporting → Primary (RF=3 gate) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/host/master/promotion_probe.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe`, `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe`, `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused`, `TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | -| `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-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 | -| `INV-K8S-REATTACH-001` | A CSI re-stage after failover uses the fresh publish target, and the read model reports recovery by reattach only with CSI reattach observed and a verified reader. | K8s readiness model | `core/csi/node.go` `refreshPublishContext`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestManagedVolumeProjection_NodeLossReattachRecovered` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-MANAGED-VOLUME-READMODEL-001` | Volume explanations in the observation report and explain output are rendered from the `ManagedVolume` projection. | K8s readiness model | `core/ops/managed_volume_model.go` `ProjectManagedVolume` | `TestObservationExplain_IncludesManagedVolumeProjectionAndDryRunActions`, `TestObservationReportSummary_IncludesManagedVolumeStatus` (`core/ops/observation_report_test.go`); `TestProjectManagedVolumeFromEvidence_DualPrimaryInvalid` (`core/ops/managed_volume_evidence_test.go`) | — | ACTIVE | -| `INV-CONTROL-CONTEXT-001` | Cross-layer explanations replayed from a bundle are derived from recorded facts and events. Superseded in scope by `INV-MANAGED-VOLUME-READMODEL-001`; kept for continuity. | K8s readiness model | `core/ops/observation_bundle.go` `BuildObservationFromBundle` | `TestObservationBundle_RendersNodeLossRecoveryStory`, `TestObservationBundle_ManagedVolumeUsesPrimaryFailureArtifactHints` (`core/ops/observation_bundle_test.go`) | — | ACTIVE | -| `INV-K8S-ADAPTOR-FACTS-001` | PVC, pod, node and CSI conditions enter the read model as typed facts and map to distinct blocked reasons before any recovery status is derived. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestManagedVolumeProjection_PVCPendingBlocked`, `TestManagedVolumeProjection_WriterFailedMountBlocked`, `TestManagedVolumeProjection_CSINodeImagePullBlocked`, `TestManagedVolumeProjection_LoopbackCrossNodeBlocked` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-HOSTPATH-FACTS-001` | The read model keeps path facts separate from the recovery claim: missing multipath blocks the transparent claim, and an NVMe ANA seam alone does not infer transparent recovery. | K8s readiness model | `core/ops/managed_volume_model.go` `deriveManagedVolumeStates`, `hasTransparentHostPathEvidence` | `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim`, `TestManagedVolumeProjection_NVMeANASeamDoesNotInferTransparentRecovery` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-FENCE-SELF-ON-PROMOTE-001` | A primary at epoch e applies no inbound replication traffic (ship, recovery lane start, rebuild), and none below e; it still answers probes, and its epoch floor never goes down when it later supports another primary (fencing gap G2). | M3 Supporting → Primary | `core/transport/replica.go` `FenceAsPrimary`, `acceptMutationLineage`; `core/host/volume/host.go` `fenceSelfWithPeers` | `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`); `TestG2_PrimaryListenerRefusesMutationsButAnswersProbes`, `TestG2_FloorStaysWhenThePrimaryLaterSupportsAnother` (`core/transport/g2_self_fence_test.go`) | `ReplicationFailover` `AckedSurvive`, `NoStaleAck` | ACTIVE | -| `INV-FENCE-FLOOR-DURABLE-001` | A replica never accepts mutating traffic below the highest epoch it has acknowledged or taken a role at, across restarts, and accepts none before its assignment is known; a role call whose floor cannot be made durable is not adopted and keeps the frontend unhealthy (fencing gap G1). | M3 Unassigned → Primary \| Supporting | `core/transport/replica.go` `raiseFloor`, `admitMutation`, `AdmitAsReplica`; `core/host/volume/host.go` `latchRoleAdmission` | `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch`, `TestG1_ConcurrentRaisesNeverLowerTheRecord`, `TestG1_RoleCallsPersistBeforeReturning` (`core/transport/g1_durable_floor_test.go`); `TestG1_FailedRoleAdmissionStopsAPreviouslyHealthyFrontend` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | - -Notes: - -- `INV-AUTH-ONE-PRIMARY-001`: Narrowed. The lab evidence field `post_failure_primary_count=1` is not read by any Go test. `IntentBind` is checked per volume: the Publisher refuses a genesis `Bind` (`ErrBindAlreadyBound`) once any slot of the volume holds a present line, also after a restart, when only the current slot is reloaded; `decideVolume` also binds only when the volume has no line ([#183](https://github.com/seaweedfs/seaweed-block/issues/183)). -- `INV-FENCE-STALE-PRIMARY-001`: Narrowed. A primary cut off from blockmaster that has not seen the newer line keeps admitting I/O, and under `best_effort` its local `fsync` still acknowledges (no primary lease on the Kubernetes path; see the Kubernetes known gaps). The lab counter `old_primary_stale_io_success_count=0` is lab evidence only. -- `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`. -- `INV-K8S-NONLOOPBACK-001`: Rejection is opt-in: the chart default for `network.rejectLoopbackPublishTargets` is false; the generator sets it for multi-node values. -- `INV-OBS-PRODUCT-EVENTS-001`: Each event type has a unit test; all four together in one node-loss run is lab evidence only. -- `INV-HOSTPATH-TRANSPARENT-001`: Narrowed to the classifier. It does not compare the host path target with the promoted target, and only the missing-multipath case has a negative test. The mounted-failover run is lab evidence. -- `INV-K8S-REATTACH-001`: The full node-loss run through pod recreate is lab evidence; the classifier does not check that the re-stage target equals the promoted frontend. -- `INV-MANAGED-VOLUME-READMODEL-001`: Partial. No guard test shows that other surfaces never build their own status, and `core/ops/observation_bundle.go` `applyPrimaryFailureSummary` sets a recovered status from summary keys without the classifier. -- `INV-K8S-ADAPTOR-FACTS-001`: Narrowed. The fact metadata the internal row names (source, time, generation, confidence) is neither filled in nor read by the classifier. -- `INV-HOSTPATH-FACTS-001`: Narrowed. There is no session-reachability fact, the classifier does not read the ALUA state, and the artifact path derives the multipath and Active/Optimized facts from one `transparent_failover_claimed` hint. - -**Not in the ledger.** Known gaps where the code does not yet hold the property are tracked as known issues, not as rows: the [core known issues](block-design.md#24-known-issues-and-work-in-progress), the [agent workspace known gaps](agent-workspace-design.md#14-known-gaps) and the [Kubernetes known gaps](kubernetes-block-design.md#12-known-gaps). A fix that closes one adds its row here. - ---- - - -### B.8 NVMe/TCP receive bounds - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | - -## Part C. Change rules - -How a fix or a feature is calibrated against this model: - -1. **Name the touched IDs.** The pull request lists every Part B ID whose statement, enforcing function or test it touches, and the Part A machine and transition. A change on a protocol path that touches no ID says why. -2. **States and transitions move together.** A new or changed state, transition or guard updates, in the same pull request: the Part A table, its diagram (in the design document, or here when the design document has none), the Part B rows, and the TLA+ specification if one models that machine (with its configurations re-run and the results in `docs/spec/README.md`). -3. **An ACTIVE row never loses its test.** Renaming or moving a test updates the row. Deleting a test, or weakening it so it no longer asserts the statement, needs a replacement test in the same pull request. -4. **Every bug becomes a test and a row.** A bug found by a unit test, a review, a soak or chaos run, or a TLA+ counterexample becomes a regression test that fails before the fix and passes after it, and a new or updated Part B row naming that test. -5. **Rows are stable.** IDs are never reused or renumbered. A retired row stays with status `ARCHIVED` and a reason. A narrowed statement says what was dropped in a note. -6. **STUB rows block claims.** A release note or a design document must not claim a property backed only by a `STUB` row. Turning a `STUB` into `ACTIVE` is the test plus the status change. - -Format v3 row 4 remains dark. Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The later W/BASE/fence owner must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. - -### Dark v3 offline reader (row12a) - -- `INV-WAL-V3-READONLY-001` (ACTIVE for the explicit dark selector only): the explicit dark reader opens store and map read-only, validates both live slot dependencies and the trusted WAL prefix, merges WAL winners above the checkpoint with extents, and never runs recovery, a fence, a worker, or publication. Installing images, corrupt acknowledged WAL/map dependencies and unfinished fresh restores refuse. WAL records are checked again at read. An absent remote chunk returns `ErrReadOnlyNotResident`, even with a local hint; offline reading does not perform remote fills. The public selector remains legacy until row12b. -- Controls: `TestWALStoreV3_ReadOnlyMergesWALAndExtentWithoutWrites`, `TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies`, `TestWALStoreV3_ReadOnlyNeverReturnsUnfilledExtentZeros`, `TestWALStoreV3_ReadOnlyRevalidatesWALAndBindsReadonlyMetadata`, and the actual endpoint snapshot caller `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture`. Reader mutex covers the descriptor read and Close; no new lock edge or durability state transition. - -### Dark v3 chunk/BASE integration (row12a) - -- `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for dark mapped v3): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu. -- The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging/reconciliation generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission. -- Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Both installed local presence and the provider durable attach point are required before retirement. The provider removes its fresh marker and fsyncs its directory under the store installMu-exclusive commit, then records per-open owner readiness; the callback never re-enters the store. Layer attach alone never allows retirement. Later completed transitions require owner readiness plus saved full presence before allowing; the next ordinary publication still checks existing retirement coverage. The provider keeps the constructed layer private as chunkPending until this commit succeeds; explicit publication cannot resolve it and the scheduler starts only after commit. Failed commits retain the private layer for retry without reattaching. Held pre-marker controls require Capture/Cut/MakeRemoteDurable to return ErrNotChunkVolume with no new remote writes, intents or HEAD changes, then crash/reopen exact local bytes. Actual subprocess controls crash after presence but before marker removal (both pre-existing installed BASE and attached completion), retaining the installed discriminator and recovering exact local data. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam. From b99e081cf2caee4b1e5b1c433f1de56196cbda54 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 13:47:38 -0800 Subject: [PATCH 121/150] docs: restore UTF-8 invariant ledger with cut birth rule --- seaweed-block/docs/design/invariants.md | 536 ++++++++++++++++++++++++ 1 file changed, 536 insertions(+) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e69de29bb2..198dddd3ed 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -0,0 +1,536 @@ +# Seaweed Block invariants and state machines + +This is the protocol contract of Seaweed Block: the state machines the code implements, the invariants each transition must keep, where each invariant is enforced, which test asserts it, and which TLA+ property models it. It is written for people and for coding agents. Before changing a protocol path, find the machine in Part A and the rows in Part B, and follow the change rules in Part C. + +This document supersedes the internal ledger [`internal/docs/protocol/invariant-ledger.md`](../../internal/docs/protocol/invariant-ledger.md). Every ID from that ledger is kept here and was re-checked against the code; some statements were narrowed to what the tests in this repository actually assert, and each narrowing is noted under its table. The internal file stays for history; new rows go here. + +The design is described in three documents, and this one collects their machines and invariants in one place: the [core design](block-design.md), the [agent workspace design](agent-workspace-design.md) and the [Kubernetes block design](kubernetes-block-design.md). + +**Conventions.** These are the same as in the design documents. + +- Code references name a file and a function, not a line number. Test references name the test function and its file. +- A TLA+ entry names a specification in [`docs/spec/`](../spec/README.md) and an invariant or property defined in it. The models check designs at small scale and are mapped to the code by reading (see the [limits](../spec/README.md#limits)). +- Status: + - `ACTIVE`: a Go test in this repository asserts the statement. + - `STUB`: the code enforces the statement (by reading), but no test asserts it yet. A release note must not claim behaviour backed only by a `STUB` row. + - `ARCHIVED`: a retired row, kept with its reason. There are none yet. +- The rule carried over from the internal ledger still applies: an invariant without a test is a wish, not an invariant. + +## Contents + +- [Part A. State machines](#part-a-state-machines) + - [M1 walstore: open, recover, serve, fault](#m1-walstore-open-recover-serve-fault) + - [M2 Authority: assignment, epoch, lease](#m2-authority-assignment-epoch-lease) + - [M3 Replica role and peer state](#m3-replica-role-and-peer-state) + - [M4 Workspace HEAD holder and takeover](#m4-workspace-head-holder-and-takeover) + - [M5 The cut pipeline](#m5-the-cut-pipeline) + - [M6 Chunk lifecycle](#m6-chunk-lifecycle) +- [Part B. Invariant ledger](#part-b-invariant-ledger) +- [Part C. Change rules](#part-c-change-rules) + +--- + +## Part A. State machines + +Each machine lists its states, the allowed transitions, the guard that must hold for each transition, where the guard is enforced, and the IDs of the Part B rows that protect it. A state name in `code font` is a value in the code; the other names describe a condition and are not code types. + +### M1 walstore: open, recover, serve, fault + +The local storage engine and the durable backend in front of it. Diagrams in the core design: the per-I/O gate in [§1.1](block-design.md#11-frontends-and-the-backend-contract), and the life of one write (appended, synced, in the extent, checkpointed, reusable) in [§1.2](block-design.md#12-walstore-wal-plus-extent). + +```mermaid +stateDiagram-v2 + [*] --> Opened: OpenWALStore / CreateWALStore + Opened --> Recovering: RecoverVolume + Recovering --> Serving: Recover ok, backend operational + Recovering --> RecoveryFailed: Recover error (typed reason) + Serving --> FaultLatched: fsync or WAL append fails + FaultLatched --> Closed: Close + RecoveryFailed --> Closed: Close + Serving --> Closed: Close + Closed --> Opened: reopen +``` + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | +| Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | +| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | +| Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | +| Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001` | +| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse (C11 bitmap/superblock path remains legacy-fixture-only) | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001` | +| Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `noteAppendFailure`, `syncFile` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | +| FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | +| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | + +Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. + +Public walstore Create now selects mapped format v3/impl3 (mode C by default, mode A by create option). Open and offline readonly use A/B slot and owned-map validation; valid legacy formats are refused with `ErrUnsupportedLegacyFormat`, rather than silently retrofitted. The temporary old-engine/raw-codec test scope and every named native replacement are recorded in [the legacy inventory](format-v3-legacy-test-inventory.md). Native recovery validates nonce/cursor binding and a contiguous physical LSN prefix before applying the mode-specific W rule; an acknowledged-range integrity failure blocks startup. The provider's create geometry, auto probe, capture, HEAD restore and readonly/status controls exercise the public selector (`INV-WAL-V3-ACTIVATION-001`). Before reading v3 slots, both read/write and offline read-only open acquire an exclusive nonblocking file lock; the offline migration CLI acquires the same lock before any descriptor read or mutation (`INV-WAL-V3-OWNER-001`). Contention refuses open/migration without changing bytes; descriptor close or process exit releases ownership. This implements the existing offline-migration precondition, not a new serving state. The mapped v3 checkpoint also carries a complete-record physical tail through the covered LSN minus the configured retention window; partial batches remain retained. The existing sole publisher then performs metadata-only rollover when the fallback still pins that prefix. Reuse still requires both valid same-nonce slot tails and retirement of checkpointed dirty references under writer exclusion; idle, unchanged-checkpoint and admission paths also settle a pinned fallback. An unlocked catch-up scan revalidates the coherent checkpoint and tail before emitting anything. A failed rollover latches and grants no reuse (`INV-WAL-V3-RECLAIM-001`). + +Recovery warnings such as `wal_hole_suspected` are recorded in Serving without changing health (`INV-WAL-WARN-NO-HEALTH-001`). The open gaps of this machine (a corrupted synced record mid-history only warns; forged records in user data) are listed in the [core known issues](block-design.md#24-known-issues-and-work-in-progress) and are not ledger rows. + +### M2 Authority: assignment, epoch, lease + +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). + +**Assignment line, per volume.** + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| Unbound | Bound (epoch 1, endpoint version 1) | `IntentBind`; no slot of this volume holds a present line (checked per volume, also after a restart); to move to another slot use `IntentReassign` | `core/authority/authority.go` `applyWithWorkspaceMove`, `boundReplicaForVolume`; `core/authority/controller.go` `decideVolume` (binds only a volume with no line) | `INV-AUTH-ONE-PRIMARY-001`, `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | +| Bound | Bound (endpoint version + 1) | `IntentRefreshEndpoint`; same epoch; a no-op when the addresses are unchanged | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | +| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` | +| any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing, but its durable outcome may be unknown | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | +| any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` | +| Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | + +**Workspace lease and move, in blockmaster.** + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | +| Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | +| Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | +| Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | +| Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | +| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding; each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001` | +| Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | +| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | +| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` | + +### M3 Replica role and peer state + +The role a blockvolume takes from each assignment, its replica listener's admission, and the primary's view of each replica. This is the replication engine of [core §1.6](block-design.md#16-replication-and-failover) (which has the peer-state diagram) as the Kubernetes line uses it; promotion is in [Kubernetes §6](kubernetes-block-design.md#6-authority-promotion) (diagram) and the failover sequence in [Kubernetes §4](kubernetes-block-design.md#4-replication-and-failover). + +```mermaid +stateDiagram-v2 + [*] --> Unassigned: listener with a floor record, no role yet + Unassigned --> Primary: fact names self, listener fenced at e + Unassigned --> Supporting: fact names another primary, self in peers + Supporting --> Primary: promotion, fact names self at a higher epoch + Primary --> Supporting: fact names another primary, self in peers + Primary --> Excluded: fact names another primary, self not in peers + Supporting --> Excluded: fact names another primary, self not in peers + Excluded --> Supporting: later fact lists self as a peer +``` + +**Host role and listener admission.** + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| any | (no change) | local readiness blocked (recovery pending or failed): the fact is stored and replayed when readiness clears | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `INV-ROLE-READINESS-BLOCK-001` | +| any | (no change) | a role call below the current desired epoch is refused and does not clear a newer admission failure | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `INV-ROLE-STALE-REPLAY-001` | +| Unassigned, Supporting | Primary at e | the fact names this replica; the replica set is installed; the listener is fenced as primary and its floor e is persisted before the adapter is told | `core/host/volume/host.go` `applyFact`, `fenceSelfWithPeers`; `core/transport/replica.go` `FenceAsPrimary`, `raiseFloor` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001` | +| Unassigned, Primary | Supporting at e | the fact names another primary and lists this replica as a peer; the floor e is persisted first; the frontend stays gated | `core/host/volume/host.go` `applyFact`; `core/transport/replica.go` `AdmitAsReplica` | `INV-FENCE-FLOOR-DURABLE-001` | +| Primary, Supporting | Excluded | the fact names another primary and does not list this replica; ingress is closed, the other line is recorded and the frontend is unhealthy | `core/host/volume/host.go` `applyFact`, `recordOtherLine`; `core/host/volume/projection_bridge.go` `projectionWithSupersede` | `INV-ROLE-SUPERSEDED-001`, `INV-FENCE-STALE-PRIMARY-001` | +| any | role admission failed | the listener cannot be fenced or its floor cannot be persisted; the role is not adopted and the projection is not healthy | `core/host/volume/host.go` `latchRoleAdmission` | `INV-FENCE-FLOOR-DURABLE-001` | +| (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | +| Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | + +**Peer state, as the primary sees each replica** (type `ReplicaState` in `core/replication/peer.go`). A new peer starts `Healthy` (`NewReplicaPeer`). + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| `Healthy`, `Unknown` | `Degraded` or `CatchingUp` | ship, barrier or fence failure; or a probe that needs catch-up | `core/replication/peer.go` `ReplicaPeer.SetState`, `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | +| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001` | +| `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | +| any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | +| `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | + +`ReplicaPeer.Invalidate`, called on a ship, barrier or fence error, goes through the same gate as `SetState` (`replicaStateTransitionAllowed`): `Healthy`, `Degraded` and `CatchingUp` move to `Degraded`; from `NeedsRebuild` the state is kept and the reason is still logged ([#182](https://github.com/seaweedfs/seaweed-block/issues/182)). A replicated `Sync` is judged per durability mode (`core/replication/durability.go` `EvaluateBarrierAcks`; `INV-REPL-DURABILITY-MODE-001`). + +### M4 Workspace HEAD holder and takeover + +One host at a time holds a workspace volume's HEAD in SeaweedFS. The sequence diagram of a clean and a forced move is in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves); blockmaster's side of the lease is in M2. + +```mermaid +stateDiagram-v2 + state "Lease guard (host)" as G { + [*] --> NoLease + NoLease --> Valid: renewal reply for this volume, replica and epoch + Valid --> Valid: renewal before the local deadline + Valid --> Fenced: deadline passed, invalid reply, or revoking + Fenced --> Drained: frontend and cuts stopped + Drained --> Acked: revocation acknowledged with the HEAD gen + } + state "HEAD holder" as H { + [*] --> Attaching + Attaching --> Claiming: fresh local root + Attaching --> Holder: existing root, HEAD is this holder's + Attaching --> Refused: existing root, HEAD published by another holder + Claiming --> Holder: CAS to this epoch and holder, state active + Claiming --> HolderFenced: HEAD epoch higher, or another holder at this epoch + Holder --> Detached: Detach final cut, state detached + Holder --> HolderFenced: a superseding HEAD is seen + } +``` + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| NoLease, Valid | Valid | the reply names this `{volume, replica, epoch}`, its validity is positive and at most 30 s, and it arrives before the old deadline; the new deadline is anchored to the request start | `core/host/volume/workspace_lease.go` `Refresh` | `INV-WS-LEASE-001`, `INV-WS-FORCED-MOVE-001` | +| Valid | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` | +| Fenced | Drained, Acked | the stop callback succeeded; only then, and only when revoked, the acknowledgement is sent | `core/host/volume/workspace_lease.go` `drain` | `INV-WS-REVOKE-ACK-001` | +| Attaching | Refused | an existing local root whose HEAD another holder has published (`ErrChunkStaleLocalRoot`) | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-STALE-LOCAL-ROOT-001` | +| Claiming | Holder | HEAD epoch not above the master-issued epoch, no other holder at the same epoch; the local frontier is seeded from HEAD before the CAS; I/O opens only after the claim | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-WS-HEAD-CAS-001` | +| Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | +| Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | +| Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | +| Holder | HolderFenced | a HEAD with a higher epoch, or another holder at the same epoch | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | +| Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | + +### M5 The cut pipeline + +A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. The steps are described in [agent workspace §5](agent-workspace-design.md#5-the-cut), and the figure in [§3](agent-workspace-design.md#3-remote-layout) shows them against the remote layout. All steps are in `core/storage/chunk_layer.go` `captureLocked` unless stated. + +```mermaid +stateDiagram-v2 + [*] --> Admit + Admit --> Refused: closed, fenced, detached, base install, reconciling, or lineage or lease invalid + Admit --> Stage: earlier unknown CAS settled + Stage --> Quiesce: at most 3 pre-copy rounds + Quiesce --> OpenWindow: Sync H and D fixed under barrier + OpenWindow --> Copy: release barrier + Copy --> Closed: all candidates done + Copy --> Aborted: error, cancellation, observed fence, recovery or close + Aborted --> Refused: drain owners, cleanup, merge candidates + Copy --> Refused: H below HEAD RemoteLSN + Closed --> Upload: drain and cleanup; intent durable first + Upload --> Manifest + Manifest --> Readmit + Readmit --> Fenced: superseding HEAD + Readmit --> CAS + CAS --> Settled: CAS ok, or a re-read shows the proposal + CAS --> Pending: outcome unknown and HEAD unchanged + CAS --> Fenced: HEAD moved to a superseding holder + CAS --> Refused: HEAD moved otherwise (conflict) + Pending --> Admit: next cut settles it first +``` + +| Step | Guard | Enforced in | Protects | +|---|---|---|---| +| Admit | not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease); no cut while reconciling | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-CUT-RECONCILING-001`, `INV-WS-LEASE-001` | +| Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | +| Stage | while more than the barrier bound would be copied, pre-copy outside the barrier; new keys are covered by an intent first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001` | +| Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | +| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read into buffers; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | +| LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | +| Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after a durable intent names them | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | +| Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | +| No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001` | +| Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-WS-HEAD-CAS-001` | +| CAS | conditional update on `{gen, epoch}`, with `RemoteLSN = H`; refused for a lower epoch, a lower `RemoteLSN`, or a HEAD in a delete state | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001`, `INV-HEAD-DELETE-FROZEN-001` | +| Settled | drop the intents; reset the bitmap to the cut, keeping chunks dirtied after it | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | +| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` | + +### M6 Chunk lifecycle + +HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete). + +**HEAD states** (`active`, `detached`, `deleting`, `purging`, `deleted`, `aborted`). + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | +| `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | +| `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | +| `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | +| `active`, `detached` | `deleting` | a blockmaster deletion reservation exists and HEAD is not held | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `markHeadDeleting` | `INV-VOLDEL-HELD-HEAD-001`, `INV-VOL-ID-NO-REUSE-001` | +| `deleting` | previous state | a snapshot name record exists: the delete is refused and reverted | `core/frontend/chunkstore/volume_delete.go` `snapshotsBlock`, `revertHeadDeleting` | `INV-VOLDEL-COMMIT-001` | +| `deleting` | `purging` | commit point, bound to the same delete incarnation | `core/frontend/chunkstore/volume_delete.go` `commitHeadPurging` | `INV-VOLDEL-COMMIT-001` | +| `purging` | `deleted` | chunks dropped and `VOLUME` marked deleted | `core/frontend/chunkstore/volume_delete.go` `finishHeadDeleted`, `markVolumeDeleted` | `INV-VOL-ID-NO-REUSE-001` | +| `deleting`, `purging`, `deleted` | — | no claim or cut moves HEAD; only the delete's own transitions | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-HEAD-DELETE-FROZEN-001` | +| — | `aborted` | a GC copy sweep settles a dead fork by an exclusive create of an aborted HEAD tombstone, so the fork can never publish | `core/frontend/chunkstore/catalog.go` `AbortFork`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies` | — | + +**Snapshots and forks.** + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | +| name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | +| published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | +| published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001` | + +**Intents and key bindings.** + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | +| intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` | +| intent live | expired | older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001` | +| — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | +| bound | tombstoned, needle deleted | unrooted in two complete marks at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001` | +| tombstoned | (never rebound) | bindings are never removed | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | + +--- + +### Local WAL-pressure durability progress + +A serving v3 store at the soft WAL watermark may perform an internal local +sync from its existing flusher, before snapshotting dirty work. This transition +uses the ordinary A/C physical-sync and final fault gate under one `syncMu` +interval; it takes neither `captureMu` nor `lifecycleMu`. It is ineligible while +BASE is installing or the store is closed. The leader is released before extent, +map and checkpoint publication. Client Flush acknowledgements keep their own +covering durability and observer requirements. Recovery invalidates the existing +snapshot lifetime; local persistence does not bypass it. + +- `INV-WAL-V3-PRESSURE-001`: I1, within a recovery/reset lifetime `wack` advances + only after covering local persistence; I2, checkpoint remains at most `wack` + and the active-session pin floor; I3, record reuse remains below the durable + checkpoint, both-slot floor and dirty-reference retirement; I4, with healthy + local progress and no guest Sync, the reuse floor advances. Enforced by + `syncWALBatchV3Internal`, `persistOwnedMapCheckpointV3` and the existing reclaim + publisher. Tests: `TestWALStoreV3NoClientSyncSixRings`, + `TestWALStoreV3PressureSyncFaultDoesNotPublishFrontiers`, + `TestWALStoreV3PressureSyncSkipsInstalling`, + `TestWALStoreV3PressureProgressWithPendingCutOrClose` and + `TestWALStoreV3PressureWaitBudgetAndPin`. Model correspondence: `WALReclaim.tla` I1/I2/I3 and + `AllWritten`/`NoStuckWaiter` in `REC_safe`/`REC_safe_big`; the no-internal-sync + mutant violates liveness. Prior authored LIGHT receipts are referenced in + `docs/spec/README.md`; this change does not claim a new TLC execution. +- The v3 pressure admission budget is four seconds of cooperative waiting. It + cannot preempt a blocking occupancy/closed callback, lock acquisition or + physical file I/O. An unresolved pin or local stall returns + `ErrWALPressureTimeout`, preserved as `frontend.ErrBackendBusy`; NVMe returns + Generic/Namespace Not Ready (SC0x82), DNR=0. Sticky faults retain their original + non-retryable mapping. This is a local pressure outcome, not a whole-I/O + deadline; the broader budget gap is tracked separately in issue221. +- A flusher cycle sorts native snapshot entries by record offset and reuses at + most one fully validated record (bounded by WALSize). Every block still checks + its LBA/data offset/LSN/nonce; the cache is local to the snapshot recovery + generation and cannot publish or materialize after that lifetime changes. + `TestWALStoreV3FlushBatchCacheIsBoundToRecoveryLifetime` covers one batch decode + and refusal after Recover. Missing map coverage still forbids checkpoint + advancement; the earlier unmapped dark fixture is not a production geometry. + +## Part B. Invariant ledger + +80 rows: 69 ACTIVE, 11 STUB; 15 kept from the internal ledger, 65 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. + +### B.1 Core: storage, durability and the frontend gate + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | +| `INV-WAL-REPLAY-LWW-001` | Replay applies the highest LSN per LBA, independent of the physical scan order. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALStoreRecoverLastWriterWinsAcrossScanOrder` (`core/storage/walstore_recovery_lww_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | +| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the on-disk superblock has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_writer.go` `spaceUsed`, `tailPersisted`; `core/storage/walstore.go` `persistCheckpointReleasing` | `TestWALWriterReuseIsBoundedByTheDurableTail`, `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherSnapshotCutPreservesSyncedWrites` (`core/storage/flusher_snapshot_cut_test.go`); `TestWALStoreCheckpointSIGKILLCrashWindows` (`core/storage/walstore_checkpoint_crash_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-FRONTIER-GAP-001` | Synced entries above an intentional LSN gap (a rebuild's frontier jump) are kept by recovery. | M1 Recovering | `core/storage/recovery.go` `recoverWAL` | `TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump` (`core/storage/walstore_recovery_frontier_gap_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore.go` `persistCheckpointReleasing` | `TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle` (`core/storage/walstore_checkpoint_safety_test.go`) | — | ACTIVE | +| `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent or superblock), the open store refuses every later `Sync`, write and checkpoint without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestWALStoreWALFsyncFailureIsSticky`, `TestWALStoreExtentFsyncFailureIsSticky`, `TestWALStoreCheckpointFsyncFailureIsSticky` (`core/storage/walstore_sticky_fsync_test.go`); `TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | +| `INV-WAL-APPEND-STICKY-001` | A WAL append whose write failed latches the store fault; writers already queued behind it are refused. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteAppendFailure`, `WALStore.Write` | `TestWALStoreWritersQueuedBehindAFailedAppendAreRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | +| `INV-WAL-SYNC-FRONTIER-001` | `Sync` never reports an uncovered write durable: it returns the global synced frontier, which is at least the caller's own write and is covered by a completed `fsync`. It may include later writes whose covering `fsync` completed before the caller resumed. | M1 write lifecycle: Appended → Synced | `core/storage/walstore.go` `WALStore.Sync` | `TestWALStore_SyncDoesNotClaimConcurrentWrite` (`core/storage/walstore_test.go`); `TestWALGenerationFirstCallerReturnOrdering` (`core/storage/walstore_sync_frontier_order_test.go`) | — | ACTIVE | +| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt` (`cmd/blockvolume/durable_startup_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE | +| `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE | +| `INV-WAL-V3-ACTIVATION-001` | Public create produces an owned mapped v3/impl3 volume with the requested chunk geometry and C default/A option. Writable/readonly open validate A/B dependencies, reject actual legacy headers without mutation, and can select a valid fallback when A is damaged. Production provider capture/HEAD restore/status use those selectors. Legacy fixture constructors cannot be called by default production code or enter its transitive storage import closure. | M1 open/create/readonly | `walstore.go` public selectors; `walstore_v3.go` `refuseLegacyWALStore`, `ProbeWALStoreV3`; `provider.go` | `TestWALStoreProductionSelectorCreatesMappedV3`, `TestWALStoreProductionRefusesLegacyWithoutMutation`, `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy`, `TestWALStoreProductionCreateOptions`, `TestLegacyFixtureIsolation`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE | +| `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE | +| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | +| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | +| `INV-WAL-V3-RECORD-001` | An impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | +| `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB | +| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire` | `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | +| `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint releases only complete validated record ends covered by the checkpoint and outside the retention window; an installing BASE retains its install suffix. Physical recovery rebuilds the volatile boundary index only from the trusted kept scan, without restoring a disconnect cursor. Tail/head/map/checkpoint/W publish together, followed by metadata-only rollover; both slot tails still pin reuse. Failure grants no reuse and retains exact dirty retry identity. Checkpoint publication excludes writer admission through both-slot rollover and dirty-reference retirement. Idle, unchanged-checkpoint and admission settle pending rollover; catch-up revalidates tail/checkpoint before delivering its buffered scan. | M1 checkpoint / existing two-slot retirement | `wal_io_v3.go` `reclaimThroughV3`, `rememberReclaimScanV3`; `walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `descriptor_v3.go` `rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse`, `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint`, tagged `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB | +| `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | +| `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | +| `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | +| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | +| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | +| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | +| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | +| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | +| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | +| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB | +| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB | +| `INV-WAL-V3-MIGRATE-001` | `sw-block migrate-v3` rewrites only the descriptor of a cleanly closed v2/impl1 volume whose WAL the exhaustive scan proves flushed; the scan and the geometry check run before any write, and a refusal leaves the volume and every sidecar byte-identical. It keeps the extent base (WALSize = old - 4096), writes an atomic operator backup, an all-UNKNOWN initial map (covered = the v2 checkpoint), the prepared slot B, slot A at phase 0 (the commit point), slot B at phase 0, and only then retires the v2 chunk bitmap; each step is durable before the next. A rerun decides from the slot bytes alone: before the commit it restarts with a full rescan; after it, it only finishes the rollover and the retirement; a prepared B with an invalid A refuses with `ErrMigrationIncomplete`, as v3 open does; it never reads or restores the backup. | offline tool | `cmd/sw-block/migrate.go`; `cmd/sw-block/internal/v2legacy`; `core/storage/migrate_v3.go` | `TestMigrateV3CleanVolume`, `TestMigrateV3RefusalsChangeNothing`, `TestMigrateV3CrashAfterEachStepIsResumable`, `TestMigrateV3OldBinaryAfterPreparation`, `TestMigrateV3OldWALOverwritesThePreparedSlot`, `TestMigrateV3NeverRestoresTheBackup` (`cmd/sw-block/migrate_test.go`); tagged `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | none (tool) | STUB | +| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | +| `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | +| `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE | + +Notes: + +- `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged. +- `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. + +- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. Writes invalidate proofs before append and update per-chunk max LSN under store.mu, while Recover rebuilds that volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. + +- `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. Sidecar extents are reused only after neither slot nor a pending or uncertain candidate references them; see `chunk_map_extents_v3.go` and its tests. + +- `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only. +- `INV-FE-FLUSH-SYNC-001`: NVMe/TCP also asserts failed-Sync status and reason logging through the actual session dispatch, and success produces no failure log. +- `INV-WAL-V3-RESET-001`: Format bump v3, plan row 8 (DESIGN 8.6). Dark: no production path calls the reset, and it must not be activated before the reset model (r4.5) passes. No v3 tail release exists yet, so the precondition is CheckpointLSN >= W rather than an empty retained range: retained old-incarnation bytes at or below the checkpoint are preserved in the extent. The map root is unchanged by a reset, so no map page is retired. +- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). Until the chunk layer's side of the v3 install protocol lands (codex03), a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until codex03's v3 FreshFromHead restore lands; since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from (codex01 row 11b P1); it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). +- `INV-WAL-V3-MIGRATE-001`: Format bump v3, plan rows 13a and 13b (DESIGN 10.1). Not yet in this row: the exclusive advisory lock that v3 open will share (precondition 1; it lands with the 12b open path), and raw v2 fixtures committed under testdata (today's controls build v2 volumes with the v2 code that row 14 deletes). The minimum migrated WAL size (64 KiB and two single-block records) is provisional. +- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model (claude05), not by these tests. Installing recovery is row 11. +- `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). It is a STUB until the v3 store is wired in (rows 4 and 5) and activated (row 12b). The v2 checkpoint path (`persistCheckpointReleasing`) is unchanged and is retired in row 14a. The map coverage predicates against the root are added by row 7, and the conditions on BASE edges by rows 9 to 11. +- `INV-WAL-V3-DESCRIPTOR-001`: Format bump v3, plan row 1 (DESIGN r15 section 2). It is a STUB until the activation commit (plan row 12b): no production open or create path reaches the v3 codec before then. The map-dependency checks (root and pages present and hash-valid) are added by plan row 7. The tests decode vectors from an independent generator (`core/storage/testdata/format_v3/slot/gen_slot_vectors.py`). + +### B.2 Core: authority and epochs + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | +| `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that clears the lease is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | +| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | + +Notes: + +- `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, directory sync failed): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. +- `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2). +- `INV-WS-RENEW-NONBLOCKING-001`: The cited tests inject delays or holds before or inside the store write; they show sensitivity to a slow store, not a measured disk trace. + +### B.3 Core: replication and replica roles + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | +| `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | +| `INV-REPL-INGRESS-SLOTS-001` | Replication listeners are open only while the assignment has replica slots. | M3 role → listener lifecycle | `cmd/blockvolume/replication_ingress.go` `roleLocked` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | ACTIVE | +| `INV-REPL-CATCHUP-REBUILD-001` | The engine chooses catch-up when the gap is still in the primary's WAL and rebuild when it is not. | M3 Degraded → CatchingUp \| NeedsRebuild | `core/engine/apply.go` `decide` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | ACTIVE | +| `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE | +| `INV-REPL-DURABILITY-MODE-001` | Under `sync_all` a replicated `Sync` fails if any replica barrier fails; under `sync_quorum` it fails unless a majority of nodes, the primary included, are durable. | M3 barrier evaluation | `core/replication/durability.go` `EvaluateBarrierAcks` | `TestDurabilityCoordinator_Quorum_RF3_OneReplicaFailed`, `TestDurabilityCoordinator_Quorum_RF3_BothReplicasFailed`, `TestDurabilityCoordinator_SyncAll_AnyFailure_Fails` (`core/replication/durability_test.go`) | — | ACTIVE | +| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`) | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive` | ACTIVE | +| `INV-ROLE-STALE-REPLAY-001` | A role call below the host's current desired epoch is refused and cannot clear a newer role-admission failure. | M3 role admission | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `TestG1_StaleReplayDoesNotClearANewerAdmissionFailure`, `TestG1_StaleSupportingReplayDoesNotClearTheLatch` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | +| `INV-ROLE-READINESS-BLOCK-001` | While local recovery blocks readiness, `applyFact` admits neither a primary nor a supporting role, and replays the stored fact once readiness clears. | M3 Unassigned → Primary \| Supporting (guard) | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter`, `TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter`, `TestHost_ApplyFact_Self_ReplaysAfterLocalReadinessClearsWithReplicationFirst` (`core/host/volume/apply_fact_test.go`) | — | ACTIVE | +| `INV-ROLE-SUPERSEDED-001` | A fact naming another replica as primary, with this replica not among its peers, never reaches this host's adapter or replication, and is recorded as the other line. | M3 Primary \| Supporting → Excluded | `core/host/volume/host.go` `applyFact`, `recordOtherLine` | `TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication` (`core/host/volume/apply_fact_test.go`); `TestHost_BuildReport_SupersededReplicaNotReadyForPrimary` (`core/host/volume/frontend_targets_test.go`) | — | ACTIVE | + +Notes: + +- `INV-REPL-INGRESS-SLOTS-001`: Binary test: builds and runs the real `blockvolume`; build tag `subprocess`, not on Windows. +- `INV-REPL-PEER-TRANSITIONS-001`: `ReplicaPeer.Invalidate` uses the same gate as `SetState`; from `NeedsRebuild` it keeps the state and still logs the reason (see Part A, M3; [#182](https://github.com/seaweedfs/seaweed-block/issues/182)). + +### B.4 Workspace: HEAD holder, lease and takeover + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-WS-HEAD-CAS-001` | Every HEAD publish is a conditional update on `{gen, epoch}`, so only one holder can publish each HEAD generation; a holder that sees a superseding HEAD fences itself. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | +| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | +| `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | +| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | +| `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | +| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | +| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `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`) | — | ACTIVE | + +Notes: + +- `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary. +- `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits). +- `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. + +### B.5 Workspace: the cut pipeline + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | +| `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | +| `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | +| `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-STAGED-REUSE-001` | A chunk pre-copied outside the barrier is used only if no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window (legacy fixtures retain the full-copy barrier). | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-BITMAP-001` | The dirty bitmap never under-reports: it is durable before the checkpoint passes its WAL entries, and it is reset only after a successful CAS, keeping chunks dirtied after the cut. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/chunk_layer.go` `BeforeCheckpointAdvance`, `finishCut` | `TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle`, `TestChunkLayer_C11_RolloverKeepsPostCutDirt` (`core/storage/chunk_layer_c11_test.go`) | `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE | +| `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut, an intent naming every new key is durable, and it is removed only after the CAS outcome is known. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | +| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | +| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | + +Notes: + +- `INV-CUT-STAGED-REUSE-001`: `captureLocked` also requires HEAD's generation to be the one the stage was compared against (code reading; not asserted by these tests). + +### B.6 Workspace: chunk lifecycle, GC and delete + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | +| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | +| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | +| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | +| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | +| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | +| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | +| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | +| `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | + +Notes: + +- `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace. + +### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | +| `INV-PROMOTE-FRONTIER-001` | The RF=3 promotion gate promotes only a probed candidate that covers the required acknowledgement frontier, and blocks promotion without a fresh probe. With a known frontier the candidate's durable LSN must be at least the required LSN. With an unknown frontier under `sync_quorum` or `sync_all`, the highest-durable ready candidate is promoted only when at least P-K+1 distinct peers are probed ready and fresh in the same tick (K from `waitForSyncAcks`; RF=3: both peers under `sync_quorum`, one under `sync_all`); otherwise nothing is promoted. An unknown frontier is never read as zero; `best_effort` is unchanged. | M3 Supporting → Primary (RF=3 gate) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/host/master/promotion_probe.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe`, `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe`, `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused`, `TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | +| `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-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 | +| `INV-K8S-REATTACH-001` | A CSI re-stage after failover uses the fresh publish target, and the read model reports recovery by reattach only with CSI reattach observed and a verified reader. | K8s readiness model | `core/csi/node.go` `refreshPublishContext`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestManagedVolumeProjection_NodeLossReattachRecovered` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-MANAGED-VOLUME-READMODEL-001` | Volume explanations in the observation report and explain output are rendered from the `ManagedVolume` projection. | K8s readiness model | `core/ops/managed_volume_model.go` `ProjectManagedVolume` | `TestObservationExplain_IncludesManagedVolumeProjectionAndDryRunActions`, `TestObservationReportSummary_IncludesManagedVolumeStatus` (`core/ops/observation_report_test.go`); `TestProjectManagedVolumeFromEvidence_DualPrimaryInvalid` (`core/ops/managed_volume_evidence_test.go`) | — | ACTIVE | +| `INV-CONTROL-CONTEXT-001` | Cross-layer explanations replayed from a bundle are derived from recorded facts and events. Superseded in scope by `INV-MANAGED-VOLUME-READMODEL-001`; kept for continuity. | K8s readiness model | `core/ops/observation_bundle.go` `BuildObservationFromBundle` | `TestObservationBundle_RendersNodeLossRecoveryStory`, `TestObservationBundle_ManagedVolumeUsesPrimaryFailureArtifactHints` (`core/ops/observation_bundle_test.go`) | — | ACTIVE | +| `INV-K8S-ADAPTOR-FACTS-001` | PVC, pod, node and CSI conditions enter the read model as typed facts and map to distinct blocked reasons before any recovery status is derived. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestManagedVolumeProjection_PVCPendingBlocked`, `TestManagedVolumeProjection_WriterFailedMountBlocked`, `TestManagedVolumeProjection_CSINodeImagePullBlocked`, `TestManagedVolumeProjection_LoopbackCrossNodeBlocked` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-HOSTPATH-FACTS-001` | The read model keeps path facts separate from the recovery claim: missing multipath blocks the transparent claim, and an NVMe ANA seam alone does not infer transparent recovery. | K8s readiness model | `core/ops/managed_volume_model.go` `deriveManagedVolumeStates`, `hasTransparentHostPathEvidence` | `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim`, `TestManagedVolumeProjection_NVMeANASeamDoesNotInferTransparentRecovery` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-FENCE-SELF-ON-PROMOTE-001` | A primary at epoch e applies no inbound replication traffic (ship, recovery lane start, rebuild), and none below e; it still answers probes, and its epoch floor never goes down when it later supports another primary (fencing gap G2). | M3 Supporting → Primary | `core/transport/replica.go` `FenceAsPrimary`, `acceptMutationLineage`; `core/host/volume/host.go` `fenceSelfWithPeers` | `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`); `TestG2_PrimaryListenerRefusesMutationsButAnswersProbes`, `TestG2_FloorStaysWhenThePrimaryLaterSupportsAnother` (`core/transport/g2_self_fence_test.go`) | `ReplicationFailover` `AckedSurvive`, `NoStaleAck` | ACTIVE | +| `INV-FENCE-FLOOR-DURABLE-001` | A replica never accepts mutating traffic below the highest epoch it has acknowledged or taken a role at, across restarts, and accepts none before its assignment is known; a role call whose floor cannot be made durable is not adopted and keeps the frontend unhealthy (fencing gap G1). | M3 Unassigned → Primary \| Supporting | `core/transport/replica.go` `raiseFloor`, `admitMutation`, `AdmitAsReplica`; `core/host/volume/host.go` `latchRoleAdmission` | `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch`, `TestG1_ConcurrentRaisesNeverLowerTheRecord`, `TestG1_RoleCallsPersistBeforeReturning` (`core/transport/g1_durable_floor_test.go`); `TestG1_FailedRoleAdmissionStopsAPreviouslyHealthyFrontend` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | + +Notes: + +- `INV-AUTH-ONE-PRIMARY-001`: Narrowed. The lab evidence field `post_failure_primary_count=1` is not read by any Go test. `IntentBind` is checked per volume: the Publisher refuses a genesis `Bind` (`ErrBindAlreadyBound`) once any slot of the volume holds a present line, also after a restart, when only the current slot is reloaded; `decideVolume` also binds only when the volume has no line ([#183](https://github.com/seaweedfs/seaweed-block/issues/183)). +- `INV-FENCE-STALE-PRIMARY-001`: Narrowed. A primary cut off from blockmaster that has not seen the newer line keeps admitting I/O, and under `best_effort` its local `fsync` still acknowledges (no primary lease on the Kubernetes path; see the Kubernetes known gaps). The lab counter `old_primary_stale_io_success_count=0` is lab evidence only. +- `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`. +- `INV-K8S-NONLOOPBACK-001`: Rejection is opt-in: the chart default for `network.rejectLoopbackPublishTargets` is false; the generator sets it for multi-node values. +- `INV-OBS-PRODUCT-EVENTS-001`: Each event type has a unit test; all four together in one node-loss run is lab evidence only. +- `INV-HOSTPATH-TRANSPARENT-001`: Narrowed to the classifier. It does not compare the host path target with the promoted target, and only the missing-multipath case has a negative test. The mounted-failover run is lab evidence. +- `INV-K8S-REATTACH-001`: The full node-loss run through pod recreate is lab evidence; the classifier does not check that the re-stage target equals the promoted frontend. +- `INV-MANAGED-VOLUME-READMODEL-001`: Partial. No guard test shows that other surfaces never build their own status, and `core/ops/observation_bundle.go` `applyPrimaryFailureSummary` sets a recovered status from summary keys without the classifier. +- `INV-K8S-ADAPTOR-FACTS-001`: Narrowed. The fact metadata the internal row names (source, time, generation, confidence) is neither filled in nor read by the classifier. +- `INV-HOSTPATH-FACTS-001`: Narrowed. There is no session-reachability fact, the classifier does not read the ALUA state, and the artifact path derives the multipath and Active/Optimized facts from one `transparent_failover_claimed` hint. + +**Not in the ledger.** Known gaps where the code does not yet hold the property are tracked as known issues, not as rows: the [core known issues](block-design.md#24-known-issues-and-work-in-progress), the [agent workspace known gaps](agent-workspace-design.md#14-known-gaps) and the [Kubernetes known gaps](kubernetes-block-design.md#12-known-gaps). A fix that closes one adds its row here. + +--- + + +### B.8 NVMe/TCP receive bounds + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | + +## Part C. Change rules + +How a fix or a feature is calibrated against this model: + +1. **Name the touched IDs.** The pull request lists every Part B ID whose statement, enforcing function or test it touches, and the Part A machine and transition. A change on a protocol path that touches no ID says why. +2. **States and transitions move together.** A new or changed state, transition or guard updates, in the same pull request: the Part A table, its diagram (in the design document, or here when the design document has none), the Part B rows, and the TLA+ specification if one models that machine (with its configurations re-run and the results in `docs/spec/README.md`). +3. **An ACTIVE row never loses its test.** Renaming or moving a test updates the row. Deleting a test, or weakening it so it no longer asserts the statement, needs a replacement test in the same pull request. +4. **Every bug becomes a test and a row.** A bug found by a unit test, a review, a soak or chaos run, or a TLA+ counterexample becomes a regression test that fails before the fix and passes after it, and a new or updated Part B row naming that test. +5. **Rows are stable.** IDs are never reused or renumbered. A retired row stays with status `ARCHIVED` and a reason. A narrowed statement says what was dropped in a note. +6. **STUB rows block claims.** A release note or a design document must not claim a property backed only by a `STUB` row. Turning a `STUB` into `ACTIVE` is the test plus the status change. + +Format v3 row 4 remains dark. Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The later W/BASE/fence owner must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. + +### Dark v3 offline reader (row12a) + +- `INV-WAL-V3-READONLY-001` (ACTIVE for the explicit dark selector only): the explicit dark reader opens store and map read-only, validates both live slot dependencies and the trusted WAL prefix, merges WAL winners above the checkpoint with extents, and never runs recovery, a fence, a worker, or publication. Installing images, corrupt acknowledged WAL/map dependencies and unfinished fresh restores refuse. WAL records are checked again at read. An absent remote chunk returns `ErrReadOnlyNotResident`, even with a local hint; offline reading does not perform remote fills. The public selector remains legacy until row12b. +- Controls: `TestWALStoreV3_ReadOnlyMergesWALAndExtentWithoutWrites`, `TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies`, `TestWALStoreV3_ReadOnlyNeverReturnsUnfilledExtentZeros`, `TestWALStoreV3_ReadOnlyRevalidatesWALAndBindsReadonlyMetadata`, and the actual endpoint snapshot caller `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture`. Reader mutex covers the descriptor read and Close; no new lock edge or durability state transition. + +### Dark v3 chunk/BASE integration (row12a) + +- `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for dark mapped v3): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu. +- The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging/reconciliation generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission. +- Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Both installed local presence and the provider durable attach point are required before retirement. The provider removes its fresh marker and fsyncs its directory under the store installMu-exclusive commit, then records per-open owner readiness; the callback never re-enters the store. Layer attach alone never allows retirement. Later completed transitions require owner readiness plus saved full presence before allowing; the next ordinary publication still checks existing retirement coverage. The provider keeps the constructed layer private as chunkPending until this commit succeeds; explicit publication cannot resolve it and the scheduler starts only after commit. Failed commits retain the private layer for retry without reattaching. Held pre-marker controls require Capture/Cut/MakeRemoteDurable to return ErrNotChunkVolume with no new remote writes, intents or HEAD changes, then crash/reopen exact local bytes. Actual subprocess controls crash after presence but before marker removal (both pre-existing installed BASE and attached completion), retaining the installed discriminator and recovering exact local data. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam. From e789af251551e9dcc5633f91a920cf913c2b2eef Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 09:49:56 -0800 Subject: [PATCH 122/150] test: require read deadlines to detach from owned chunk hydration --- .../storage/chunk_hydration_budget_test.go | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_hydration_budget_test.go diff --git a/seaweed-block/core/storage/chunk_hydration_budget_test.go b/seaweed-block/core/storage/chunk_hydration_budget_test.go new file mode 100644 index 0000000000..1d217458de --- /dev/null +++ b/seaweed-block/core/storage/chunk_hydration_budget_test.go @@ -0,0 +1,58 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "testing" + "time" +) + +func hydrationReadContext(s *WALStore, ctx context.Context, lba uint32) ([]byte, error) { + if r, ok := any(s).(interface { + ReadContext(context.Context, uint32) ([]byte, error) + }); ok { + return r.ReadContext(ctx, lba) + } + return s.Read(lba) +} + +func TestChunkHydration_DeadlineDetachesWithoutCancellingFill(t *testing.T) { + src := make([]byte, ctNumBlocks*ctBlockSize) + copy(src[8*ctBlockSize:], makeBlock(ctBlockSize, 0x88)) + remote := newFakeChunkRemote() + remote.seedHead(t, src, 50, 1) + s, _ := newChunkTestStore(t) + cfg := ctConfig(2) + cfg.FreshFromHead = true + mustAttach(t, s, remote, cfg) + _, release := holdNextGet(t, remote) + fired := make(chan struct{}) + timer := time.AfterFunc(500*time.Millisecond, func() { defer close(fired); release() }) + t.Cleanup(func() { + release() + if !timer.Stop() { + <-fired + } + }) + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + start := time.Now() + got, err := hydrationReadContext(s, ctx, 8) + elapsed := time.Since(start) + if len(got) != 0 || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("deadline must detach before fill: bytes=%d err=%v elapsed=%s", len(got), err, elapsed) + } + if elapsed >= 350*time.Millisecond { + t.Fatalf("hydration ignored caller budget: %s", elapsed) + } + retry, cancelRetry := context.WithTimeout(context.Background(), 2*time.Second) + defer cancelRetry() + got, err = hydrationReadContext(s, retry, 8) + if err != nil || !bytes.Equal(got, makeBlock(ctBlockSize, 0x88)) { + t.Fatalf("retry did not get exact bytes: %v", err) + } + if n := remote.stats().gets; n != 1 { + t.Fatalf("retry cancelled/restarted shared fetch: Gets=%d want1", n) + } +} From 18f28d480b32e8e9240dfeb4bd0aae2213d503be Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 09:53:25 -0800 Subject: [PATCH 123/150] storage: detach read waiters from bounded owned hydration flights --- seaweed-block/core/storage/chunk_hydration.go | 181 ++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 55 ++---- seaweed-block/core/storage/chunk_seam.go | 4 + seaweed-block/core/storage/logical_storage.go | 6 + seaweed-block/core/storage/walstore.go | 30 ++- 5 files changed, 233 insertions(+), 43 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_hydration.go diff --git a/seaweed-block/core/storage/chunk_hydration.go b/seaweed-block/core/storage/chunk_hydration.go new file mode 100644 index 0000000000..9d462e5baf --- /dev/null +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -0,0 +1,181 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "time" +) + +// ErrChunkHydrationPending means no guest bytes were admitted: hydration +// is queued/in flight or the caller's wait expired. Owned work may continue. +var ErrChunkHydrationPending = errors.New("storage: chunk hydration pending") + +const defaultHydrationWorkers = 2 +const defaultHydrationQueueDepth = 64 +const defaultHydrationWait = 4 * time.Second + +type chunkHydrationFlight struct { + idx, gen uint64 + ref chunkRef + ctx context.Context + cancel context.CancelFunc + done chan struct{} + running bool + waiters int + err error +} + +func hydrationPending(cause error) error { + if cause == nil { + return ErrChunkHydrationPending + } + return fmt.Errorf("%w: %w", ErrChunkHydrationPending, cause) +} + +// The promise and worker lifetime belong to the layer, not any one caller. +// stMu protects admission, queue membership and waiter counts. Nobody holds +// it (or a store/capture/lifecycle lock) while awaiting or fetching bytes. +func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]byte, error) { + idx := l.chunkOf(lba) + for { + l.stMu.Lock() + if l.closed { + l.stMu.Unlock() + return nil, errChunkLayerClosed + } + if l.fenced { + l.stMu.Unlock() + return nil, errChunkLayerFenced + } + if !l.absent[idx] || l.localBlocks[lba] { + l.stMu.Unlock() + return nil, nil + } + ref, ok := l.head.Chunks[idx] + if !ok { + l.stMu.Unlock() + return make([]byte, l.blockSize), nil + } + if err := ctx.Err(); err != nil { + l.stMu.Unlock() + return nil, hydrationPending(err) + } + gen := l.absentGen[idx] + f := l.hydration[idx] + stale := f != nil && (f.gen != gen || f.ref != ref) + if stale { + f.cancel() + } + if f == nil { + if len(l.hydration) >= l.cfg.HydrationQueueDepth { + l.stMu.Unlock() + return nil, hydrationPending(nil) + } + if !l.hydrationStarted { + l.hydration = make(map[uint64]*chunkHydrationFlight) + l.hydrationWake = make(chan struct{}, 1) + l.hydrationStarted = true + l.wg.Add(l.cfg.HydrationWorkers) + for i := 0; i < l.cfg.HydrationWorkers; i++ { + go l.hydrationWorker() + } + } + work, cancel := context.WithCancel(l.ctx) + f = &chunkHydrationFlight{idx: idx, gen: gen, ref: ref, ctx: work, cancel: cancel, done: make(chan struct{})} + l.hydration[idx] = f + } + f.waiters++ + l.wakeHydrationLocked() + l.stMu.Unlock() + select { + case <-f.done: + case <-ctx.Done(): + // A completed fault wins a simultaneous caller deadline. + select { + case <-f.done: + default: + l.stMu.Lock() + f.waiters-- + l.stMu.Unlock() + return nil, hydrationPending(ctx.Err()) + } + } + l.stMu.Lock() + f.waiters-- + closed := l.closed + changed := l.absentGen[idx] != f.gen || l.head.Chunks[idx] != f.ref + err := f.err + l.stMu.Unlock() + if closed { + return nil, errChunkLayerClosed + } + if changed { + continue + } + if err != nil { + return nil, err + } + // A local override or an intervening HEAD/absence change is resolved + // through the normal path, under the same original caller deadline. + } +} + +func (l *chunkLayerImpl) wakeHydrationLocked() { + select { + case l.hydrationWake <- struct{}{}: + default: + } +} + +func (l *chunkLayerImpl) hydrationWorker() { + defer l.wg.Done() + for { + l.stMu.Lock() + if l.closed { + l.stMu.Unlock() + return + } + var next *chunkHydrationFlight + for _, f := range l.hydration { + if !f.running && (next == nil || (f.waiters > 0 && next.waiters == 0)) { + next = f + } + } + if next == nil { + l.stMu.Unlock() + select { + case <-l.hydrationWake: + continue + case <-l.ctx.Done(): + return + } + } + next.running = true + l.wakeHydrationLocked() + l.stMu.Unlock() + fetch, cancel := context.WithTimeout(next.ctx, l.cfg.ReadMissTimeout) + _, err := l.fillOnce(fetch, next.idx, next.gen, next.ref) + cancel() + next.cancel() + l.stMu.Lock() + next.err = err + delete(l.hydration, next.idx) + close(next.done) + l.wakeHydrationLocked() + l.stMu.Unlock() + } +} + +// Caller holds stMu, before Close begins joining wg. Running fills remain +// owned until their worker finishes; queued promises settle without I/O. +func (l *chunkLayerImpl) closeHydrationLocked() { + for idx, f := range l.hydration { + f.cancel() + if !f.running { + f.err = errChunkLayerClosed + delete(l.hydration, idx) + close(f.done) + } + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 8736b52936..3ee7508783 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -74,7 +74,10 @@ type chunkLayerImpl struct { bmMu sync.Mutex // serializes bitmap store calls presMu sync.Mutex // serializes a whole presence save: snapshot, fsync, replace, version - closeDone chan struct{} // closed when Close has finished + hydration map[uint64]*chunkHydrationFlight // under stMu + hydrationWake chan struct{} + hydrationStarted bool + closeDone chan struct{} // closed when Close has finished stMu sync.Mutex closed bool @@ -178,6 +181,15 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) if cfg.UploadConcurrency == 0 { cfg.UploadConcurrency = 8 } + if cfg.HydrationWorkers < 0 || cfg.HydrationWorkers > 64 || cfg.HydrationQueueDepth < 0 || cfg.HydrationQueueDepth > 65536 { + return nil, errors.New("storage: hydration workers must be 1..64 and queue depth 1..65536 (0 uses defaults)") + } + if cfg.HydrationWorkers == 0 { + cfg.HydrationWorkers = defaultHydrationWorkers + } + if cfg.HydrationQueueDepth == 0 { + cfg.HydrationQueueDepth = defaultHydrationQueueDepth + } if cfg.ReadMissTimeout <= 0 { cfg.ReadMissTimeout = defaultReadMissTimeout } @@ -534,45 +546,9 @@ func sortedKeys(m map[uint64]bool) []uint64 { // block that has no newer local version, then lets the store read its // extent. It runs with no walstore lock held. func (l *chunkLayerImpl) OnReadMiss(lba uint64) ([]byte, error) { - idx := l.chunkOf(lba) - l.stMu.Lock() - if l.closed || !l.absent[idx] || l.localBlocks[lba] { - l.stMu.Unlock() - return nil, nil - } - l.wg.Add(1) - l.stMu.Unlock() - defer l.wg.Done() - // One deadline covers every attempt. Each attempt fetches the chunk as - // the current HEAD names it; a fill that went stale (eviction generation - // or HEAD ref changed meanwhile) installs nothing and the read retries, - // so the extent is read only once the block is resolved: the chunk is no - // longer absent, or the block has a local version. - ctx, cancel := context.WithTimeout(l.ctx, l.cfg.ReadMissTimeout) + ctx, cancel := context.WithTimeout(context.Background(), defaultHydrationWait) defer cancel() - for { - l.stMu.Lock() - if !l.absent[idx] || l.localBlocks[lba] { - l.stMu.Unlock() - return nil, nil - } - ref, ok := l.head.Chunks[idx] - gen := l.absentGen[idx] - l.stMu.Unlock() - if !ok { // ZERO in the current HEAD - return make([]byte, l.blockSize), nil - } - resolved, err := l.fillOnce(ctx, idx, gen, ref) - if err != nil { - return nil, err - } - if resolved { - return nil, nil - } - if err := ctx.Err(); err != nil { - return nil, fmt.Errorf("storage: chunk %d fetch: fill kept going stale: %w", idx, err) - } - } + return l.OnReadMissContext(ctx, lba) } // fillOnce fetches one chunk version and installs every block that has no @@ -2011,6 +1987,7 @@ func (l *chunkLayerImpl) Close() error { return nil } l.closed = true + l.closeHydrationLocked() l.stMu.Unlock() l.cowMu.Lock() l.cowClosed = true diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 617a88ad7d..9985dcf8fb 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -347,6 +347,10 @@ type chunkLayerConfig struct { CaptureAllowed func() error // ReadMissTimeout bounds one OnReadMiss remote fetch. ReadMissTimeout time.Duration + // HydrationWorkers bounds layer-owned fetches (0 defaults to 2). + HydrationWorkers int + // HydrationQueueDepth bounds distinct queued/in-flight chunks (0 defaults to 64). + HydrationQueueDepth int // Bitmap persists the legacy dirty-since-HEAD bitmap. Required for v2; // impl3 uses its owned LSN map and never calls this optional legacy object. Bitmap chunkBitmapStore diff --git a/seaweed-block/core/storage/logical_storage.go b/seaweed-block/core/storage/logical_storage.go index bf0cf6df6a..ae87a4bdc8 100644 --- a/seaweed-block/core/storage/logical_storage.go +++ b/seaweed-block/core/storage/logical_storage.go @@ -5,6 +5,12 @@ import ( "fmt" ) +// ContextReader is an optional request-aware read seam. One caller context +// may cover several blocks, so implementations must not reset its deadline. +type ContextReader interface { + ReadContext(context.Context, uint32) ([]byte, error) +} + // LogicalStorage is the V3 persistence-seam contract. It separates the // "what data exists, what frontier is durable" question (storage) from // the "what does the engine decide" question (semantic core). The diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 99a79cbfa9..f2b6d3efa4 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -1046,7 +1046,14 @@ func (s *WALStore) WriteInstrumentation() WriteInstrumentationStatus { // Read returns the current bytes at lba. Dirty entries are served // from the WAL; clean LBAs are served from the extent. -func (s *WALStore) Read(lba uint32) ([]byte, error) { +func (s *WALStore) Read(lba uint32) ([]byte, error) { return s.ReadContext(context.Background(), lba) } + +func (s *WALStore) ReadContext(ctx context.Context, lba uint32) ([]byte, error) { + ctx, cancel := context.WithTimeout(ctx, defaultHydrationWait) + defer cancel() + if err := ctx.Err(); err != nil { + return nil, hydrationPending(err) + } maxLBA := uint32(s.sb.VolumeSize / uint64(s.sb.BlockSize)) if lba >= maxLBA { return nil, fmt.Errorf("storage: LBA %d out of range", lba) @@ -1062,12 +1069,12 @@ func (s *WALStore) Read(lba uint32) ([]byte, error) { if data, handled, err := s.readDirtyV3(lba); handled { return data, err } - return s.readFromExtent(lba) + return s.readFromExtentContext(ctx, lba) } if walRelOff, dataOffset, _, _, ok := s.dm.get(uint64(lba)); ok { return s.readFromWAL(walRelOff, dataOffset) } - return s.readFromExtent(lba) + return s.readFromExtentContext(ctx, lba) } // readFromWAL pulls a single block out of a WAL Write/Trim entry @@ -1129,10 +1136,22 @@ func (s *WALStore) DisableAutoFlushForRecoveryTest() { } func (s *WALStore) readFromExtent(lba uint32) ([]byte, error) { + return s.readFromExtentContext(context.Background(), lba) +} + +func (s *WALStore) readFromExtentContext(ctx context.Context, lba uint32) ([]byte, error) { // An attached chunk layer resolves blocks that are absent locally // before the extent lock is taken; nil data means read the extent. if h := s.chunk.Load(); h != nil { - data, err := h.sink.OnReadMiss(uint64(lba)) + var data []byte + var err error + if r, ok := h.sink.(interface { + OnReadMissContext(context.Context, uint64) ([]byte, error) + }); ok { + data, err = r.OnReadMissContext(ctx, uint64(lba)) + } else { + data, err = h.sink.OnReadMiss(uint64(lba)) + } if err != nil { return nil, err } @@ -1150,6 +1169,9 @@ func (s *WALStore) readFromExtent(lba uint32) ([]byte, error) { return s.readFromWAL(walRelOff, dataOffset) } } + if err := ctx.Err(); err != nil { + return nil, hydrationPending(err) + } return s.readExtentBlock(lba) } From 86744d405c278d9e2acf70e2b5faddb1f0785ab7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 09:57:30 -0800 Subject: [PATCH 124/150] test: carry caller deadlines through durable reads and partial writes --- .../frontend/durable/hydration_budget_test.go | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/hydration_budget_test.go diff --git a/seaweed-block/core/frontend/durable/hydration_budget_test.go b/seaweed-block/core/frontend/durable/hydration_budget_test.go new file mode 100644 index 0000000000..6d4850ae84 --- /dev/null +++ b/seaweed-block/core/frontend/durable/hydration_budget_test.go @@ -0,0 +1,83 @@ +package durable_test + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type heldHydrationRemote struct { + storage.ChunkRemote + gate chan struct{} + once sync.Once + gets atomic.Int64 +} + +func (r *heldHydrationRemote) release() { r.once.Do(func() { close(r.gate) }) } +func (r *heldHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) { + r.gets.Add(1) + select { + case <-r.gate: + return r.ChunkRemote.Get(ctx, key) + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func TestDurableHydration_ReadAndRMWPreserveCallerBudget(t *testing.T) { + for _, rmw := range []bool{false, true} { + name := "read" + if rmw { + name = "rmw" + } + t.Run(name, func(t *testing.T) { + r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{})} + p := chunkProvider(t, t.TempDir(), r, v1View(), 0) + t.Cleanup(r.release) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + before := s.NextLSN() + fired := make(chan struct{}) + timer := time.AfterFunc(500*time.Millisecond, func() { defer close(fired); r.release() }) + t.Cleanup(func() { + r.release() + if !timer.Stop() { + <-fired + } + }) + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + start := time.Now() + var n int + if rmw { + n, err = b.Write(ctx, 33*4096+1, []byte{0x74}) + } else { + n, err = b.Read(ctx, 33*4096, make([]byte, 4096)) + } + if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("request deadline: n=%d err=%v elapsed=%s", n, err, time.Since(start)) + } + if time.Since(start) >= 350*time.Millisecond { + t.Fatal("read/RMW did not share caller budget") + } + if s.NextLSN() != before { + t.Fatal("refused RMW appended data") + } + }) + } +} From 3c7cef087dd8a907cc47c3da1c6eb8b57aeb6eec Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 09:58:21 -0800 Subject: [PATCH 125/150] frontend: preserve one arrival deadline through reads and hydration RMW --- .../core/frontend/durable/storage_adapter.go | 63 +++++++++++++++++-- seaweed-block/core/frontend/nvme/session.go | 6 ++ seaweed-block/core/frontend/read_budget.go | 14 +++++ 3 files changed, 78 insertions(+), 5 deletions(-) create mode 100644 seaweed-block/core/frontend/read_budget.go diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index b607073763..70c049839b 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -554,6 +554,8 @@ func (b *StorageBackend) Sync(ctx context.Context) error { // Read copies up to len(p) bytes starting at offset. Reads past // end-of-volume return zero bytes (no error). Every read is gated. func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, error) { + ctx, cancel := frontend.WithReadBudget(ctx, time.Time{}) + defer cancel() release, err := b.admitAfterAttach(ctx) if err != nil { return 0, err @@ -565,7 +567,14 @@ func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, if ctx.Err() != nil { return 0, b.attachReadyTimeout(ctx.Err()) } - return b.readBytes(offset, p) + n, err := b.readBytes(ctx, offset, p) + if hydrationPendingOnly(err) { + if gateErr := b.gate(); gateErr != nil { + return 0, gateErr + } + return n, fmt.Errorf("%w: %w", frontend.ErrBackendBusy, err) + } + return n, err } // setChunkAttachPending is used only after successful local recovery. @@ -679,7 +688,7 @@ func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int b.profile.recordBackendWriteRequest(len(p)) start := time.Now() n, err := b.writeBytes(ctx, offset, p) - if errors.Is(err, storage.ErrWALPressureTimeout) { + if errors.Is(err, storage.ErrWALPressureTimeout) || hydrationPendingOnly(err) { err = fmt.Errorf("%w: %w", frontend.ErrBackendBusy, err) } if n > 0 { @@ -772,6 +781,50 @@ func (b *StorageBackend) lineageCheck() error { return nil } +// readStorageBlock shares the request deadline across blocks and partial-write +// RMW. Legacy engines may still perform contextless local I/O (#221). +func (b *StorageBackend) readStorageBlock(ctx context.Context, lba uint32) ([]byte, error) { + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf("%w: %w", storage.ErrChunkHydrationPending, err) + } + var data []byte + var err error + if r, ok := b.storage.(storage.ContextReader); ok { + data, err = r.ReadContext(ctx, lba) + } else { + data, err = b.storage.Read(lba) + } + if err != nil { + return nil, err + } // a known substrate failure wins expiry + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf("%w: %w", storage.ErrChunkHydrationPending, err) + } + return data, nil +} + +func hydrationPendingOnly(err error) bool { + if err == storage.ErrChunkHydrationPending || err == context.DeadlineExceeded || err == context.Canceled { + return true + } + if err == nil { + return false + } + if j, ok := err.(interface{ Unwrap() []error }); ok { + causes := j.Unwrap() + if len(causes) == 0 { + return false + } + for _, cause := range causes { + if !hydrationPendingOnly(cause) { + return false + } + } + return true + } + return hydrationPendingOnly(errors.Unwrap(err)) +} + // readBytes performs the byte-range → LBA-range fanout for Read. // Reads block-at-a-time, copying the sub-slice covered by the // current byte range. Handles three cases: @@ -779,7 +832,7 @@ func (b *StorageBackend) lineageCheck() error { // - offset aligned, len >= block: copy full block, advance. // - offset misaligned: copy tail of first block only. // - final block, len < available: copy prefix only. -func (b *StorageBackend) readBytes(offset int64, p []byte) (int, error) { +func (b *StorageBackend) readBytes(ctx context.Context, offset int64, p []byte) (int, error) { if offset < 0 { return 0, errInvalidOffset } @@ -789,7 +842,7 @@ func (b *StorageBackend) readBytes(offset int64, p []byte) (int, error) { pos := offset for len(buf) > 0 { lba := uint32(pos / bs) - block, err := b.storage.Read(lba) + block, err := b.readStorageBlock(ctx, lba) if err != nil { return total, fmt.Errorf("durable: read lba=%d: %w", lba, err) } @@ -866,7 +919,7 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte) block = buf[:chunkLen] } else { // Partial-block: RMW. - existing, err := b.storage.Read(lba) + existing, err := b.readStorageBlock(ctx, lba) if err != nil { writeLock.Unlock() return total, fmt.Errorf("durable: RMW read lba=%d: %w", lba, err) diff --git a/seaweed-block/core/frontend/nvme/session.go b/seaweed-block/core/frontend/nvme/session.go index 950b7a0124..48f76d5210 100644 --- a/seaweed-block/core/frontend/nvme/session.go +++ b/seaweed-block/core/frontend/nvme/session.go @@ -574,6 +574,12 @@ func (s *Session) enqueueResponse(resp *response) { // ---------- IO handlers (run in goroutines) ---------- func (s *Session) handleRead(ctx context.Context, req *Request) { + arrival := req.receivedAt + if arrival.IsZero() { + arrival = req.dispatchReadyAt + } + ctx, cancel := frontend.WithReadBudget(ctx, arrival) + defer cancel() s.recordReadCommand() res := s.handler.Handle(ctx, IOCommand{ Opcode: req.capsule.OpCode, diff --git a/seaweed-block/core/frontend/read_budget.go b/seaweed-block/core/frontend/read_budget.go new file mode 100644 index 0000000000..38685a03c4 --- /dev/null +++ b/seaweed-block/core/frontend/read_budget.go @@ -0,0 +1,14 @@ +package frontend + +import ( + "context" + "time" +) + +const ReadCommandBudget = WriteCommandBudget + +// WithReadBudget includes queue residence and all cooperative attachment and +// hydration waits. A previously established, earlier deadline is never reset. +func WithReadBudget(ctx context.Context, arrival time.Time) (context.Context, context.CancelFunc) { + return WithWriteBudget(ctx, arrival) +} From 2b2ac682eeac586e3cb335d32951637f1cb35a19 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 09:58:56 -0800 Subject: [PATCH 126/150] fix: keep physical causes terminal when hydration deadlines expire --- .../core/frontend/durable/storage_adapter.go | 8 ++++-- seaweed-block/core/storage/chunk_hydration.go | 27 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 70c049839b..10f156e3fb 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -804,6 +804,10 @@ func (b *StorageBackend) readStorageBlock(ctx context.Context, lba uint32) ([]by } func hydrationPendingOnly(err error) bool { + return errors.Is(err, storage.ErrChunkHydrationPending) && hydrationPendingCauseOnly(err) +} + +func hydrationPendingCauseOnly(err error) bool { if err == storage.ErrChunkHydrationPending || err == context.DeadlineExceeded || err == context.Canceled { return true } @@ -816,13 +820,13 @@ func hydrationPendingOnly(err error) bool { return false } for _, cause := range causes { - if !hydrationPendingOnly(cause) { + if !hydrationPendingCauseOnly(cause) { return false } } return true } - return hydrationPendingOnly(errors.Unwrap(err)) + return hydrationPendingCauseOnly(errors.Unwrap(err)) } // readBytes performs the byte-range → LBA-range fanout for Read. diff --git a/seaweed-block/core/storage/chunk_hydration.go b/seaweed-block/core/storage/chunk_hydration.go index 9d462e5baf..01cd469c4e 100644 --- a/seaweed-block/core/storage/chunk_hydration.go +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -159,6 +159,9 @@ func (l *chunkLayerImpl) hydrationWorker() { cancel() next.cancel() l.stMu.Lock() + if hydrationContextCauseOnly(err) { + err = hydrationPending(err) + } next.err = err delete(l.hydration, next.idx) close(next.done) @@ -179,3 +182,27 @@ func (l *chunkLayerImpl) closeHydrationLocked() { } } } + +// Joined physical/unknown errors must not become retryable just because they +// also contain a context cause. +func hydrationContextCauseOnly(err error) bool { + if err == context.DeadlineExceeded || err == context.Canceled { + return true + } + if err == nil { + return false + } + if j, ok := err.(interface{ Unwrap() []error }); ok { + causes := j.Unwrap() + if len(causes) == 0 { + return false + } + for _, cause := range causes { + if !hydrationContextCauseOnly(cause) { + return false + } + } + return true + } + return hydrationContextCauseOnly(errors.Unwrap(err)) +} From 19572f01da0b2f0c82caad8736844a80e5dae590 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 10:01:06 -0800 Subject: [PATCH 127/150] test: exercise hydration sharing, capacity, demand priority and close --- seaweed-block/core/storage/chunk_hydration.go | 3 + .../chunk_hydration_concurrency_test.go | 180 ++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 1 + 3 files changed, 184 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_hydration_concurrency_test.go diff --git a/seaweed-block/core/storage/chunk_hydration.go b/seaweed-block/core/storage/chunk_hydration.go index 01cd469c4e..cc36098cf2 100644 --- a/seaweed-block/core/storage/chunk_hydration.go +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -88,6 +88,9 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b f.waiters++ l.wakeHydrationLocked() l.stMu.Unlock() + if hook := l.testHydrationWait; hook != nil { + hook(idx) + } select { case <-f.done: case <-ctx.Done(): diff --git a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go new file mode 100644 index 0000000000..c47b439c3f --- /dev/null +++ b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go @@ -0,0 +1,180 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "testing" + "time" +) + +type hydrationResult struct { + data []byte + err error +} + +func hydrationFixture(t *testing.T, workers, depth int) (*WALStore, *chunkLayerImpl, *fakeChunkRemote, <-chan uint64) { + t.Helper() + image := make([]byte, ctNumBlocks*ctBlockSize) + for i := uint32(0); i < ctNumBlocks; i++ { + copy(image[int(i)*ctBlockSize:], makeBlock(ctBlockSize, byte(0x40+i))) + } + remote := newFakeChunkRemote() + remote.seedHead(t, image, 50, 1) + s, _ := newChunkTestStore(t) + if err := s.SeedChunkFrontier(50); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + cfg.HydrationWorkers = workers + cfg.HydrationQueueDepth = depth + layer := mustAttach(t, s, remote, cfg).(*chunkLayerImpl) + registered := make(chan uint64, 128) + layer.testHydrationWait = func(idx uint64) { registered <- idx } + return s, layer, remote, registered +} + +func startHydrationRead(t *testing.T, s *WALStore, parent context.Context, lba uint32) <-chan hydrationResult { + t.Helper() + ctx, cancel := context.WithCancel(parent) + result := make(chan hydrationResult, 1) + joined := make(chan struct{}) + t.Cleanup(func() { + cancel() + select { + case <-joined: + case <-time.After(ctLocalBound): + t.Error("hydration reader failed to settle") + } + }) + go func() { + defer close(joined) + data, err := hydrationReadContext(s, ctx, lba) + result <- hydrationResult{data, err} + }() + return result +} +func waitHydrationRegistration(t *testing.T, c <-chan uint64, n int) { + t.Helper() + for i := 0; i < n; i++ { + select { + case <-c: + case <-time.After(ctLocalBound): + t.Fatal("hydration waiter was not registered") + } + } +} +func hydrationOutcome(t *testing.T, c <-chan hydrationResult) hydrationResult { + t.Helper() + select { + case r := <-c: + return r + case <-time.After(ctLocalBound): + t.Fatal("hydration read did not finish") + return hydrationResult{} + } +} + +func TestChunkHydration_ConcurrentReadersShareOneGet(t *testing.T) { + s, _, remote, registered := hydrationFixture(t, 2, 64) + entered, release := holdGets(t, remote) + defer release() + const readers = 12 + results := make([]<-chan hydrationResult, readers) + for i := range results { + results[i] = startHydrationRead(t, s, context.Background(), 8) + } + waitHydrationRegistration(t, registered, readers) + waitKey(t, entered, "shared hydration") + if got := remote.stats().gets; got != 1 { + t.Fatalf("same-chunk readers started %d Gets", got) + } + release() + for _, c := range results { + r := hydrationOutcome(t, c) + if r.err != nil || !bytes.Equal(r.data, makeBlock(ctBlockSize, 0x48)) { + t.Fatalf("shared fill bytes: %v", r.err) + } + } + if got := remote.stats().gets; got != 1 { + t.Fatalf("shared fill restarted: Gets=%d", got) + } +} + +func TestChunkHydration_QueueAndWorkerLimitsAreBounded(t *testing.T) { + s, _, remote, registered := hydrationFixture(t, 1, 2) + entered, release := holdGets(t, remote) + defer release() + first := startHydrationRead(t, s, context.Background(), 8) + waitKey(t, entered, "first worker") + waitHydrationRegistration(t, registered, 1) + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond) + defer cancel() + second := startHydrationRead(t, s, ctx, 12) + waitHydrationRegistration(t, registered, 1) + if r := hydrationOutcome(t, second); !errors.Is(r.err, ErrChunkHydrationPending) { + t.Fatalf("queued timeout: %v", r.err) + } + _, err := hydrationReadContext(s, context.Background(), 16) + if !errors.Is(err, ErrChunkHydrationPending) { + t.Fatalf("full queue did not refuse: %v", err) + } + if got := remote.stats().gets; got != 1 { + t.Fatalf("worker bound exceeded: Gets=%d", got) + } + release() + if r := hydrationOutcome(t, first); r.err != nil { + t.Fatal(r.err) + } +} + +func TestChunkHydration_ActiveDemandPrecedesExpiredWaiter(t *testing.T) { + s, _, remote, registered := hydrationFixture(t, 1, 3) + entered, release := holdGets(t, remote) + defer release() + first := startHydrationRead(t, s, context.Background(), 8) + waitKey(t, entered, "occupied worker") + waitHydrationRegistration(t, registered, 1) + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond) + defer cancel() + expired := startHydrationRead(t, s, ctx, 12) + waitHydrationRegistration(t, registered, 1) + if r := hydrationOutcome(t, expired); !errors.Is(r.err, ErrChunkHydrationPending) { + t.Fatalf("expired queued read: %v", r.err) + } + demand := startHydrationRead(t, s, context.Background(), 16) + waitHydrationRegistration(t, registered, 1) + release() + next := waitKey(t, entered, "next fetch") + if want := remote.stats().head.Chunks[4].Key; next != want { + t.Fatalf("fetch %q ran before demand %q", next, want) + } + if r := hydrationOutcome(t, first); r.err != nil { + t.Fatal(r.err) + } + if r := hydrationOutcome(t, demand); r.err != nil || !bytes.Equal(r.data, makeBlock(ctBlockSize, 0x50)) { + t.Fatalf("demand: %v", r.err) + } +} + +func TestChunkHydration_CloseSettlesQueuedAndRunningReaders(t *testing.T) { + s, layer, remote, registered := hydrationFixture(t, 1, 2) + entered, release := holdGets(t, remote) + defer release() + first := startHydrationRead(t, s, context.Background(), 8) + waitKey(t, entered, "running Get") + second := startHydrationRead(t, s, context.Background(), 12) + waitHydrationRegistration(t, registered, 2) + if err := layer.Close(); err != nil { + t.Fatal(err) + } + for _, c := range []<-chan hydrationResult{first, second} { + if r := hydrationOutcome(t, c); !errors.Is(r.err, errChunkLayerClosed) { + t.Fatalf("close outcome: %v", r.err) + } + } + if got := remote.stats().gets; got != 1 { + t.Fatalf("queued work started after Close: Gets=%d", got) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 3ee7508783..e039e1cbc3 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -126,6 +126,7 @@ type chunkLayerImpl struct { keySeq uint64 // Test-only scheduling hooks; nil in production. + testHydrationWait func(uint64) // after promise registration, outside locks testCOWWait func() testCOWRead func(idx uint64, saved bool) testCOWSave func() error From d2d9ce4ac943242d3fd026d794b50a2d45707e36 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 10:03:53 -0800 Subject: [PATCH 128/150] test: distinguish caller close wake from owned hydration I/O joins --- seaweed-block/core/storage/chunk_hydration.go | 4 - .../chunk_hydration_concurrency_test.go | 104 +++++++++++++++++- 2 files changed, 100 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/storage/chunk_hydration.go b/seaweed-block/core/storage/chunk_hydration.go index cc36098cf2..b895b81857 100644 --- a/seaweed-block/core/storage/chunk_hydration.go +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -44,10 +44,6 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b l.stMu.Unlock() return nil, errChunkLayerClosed } - if l.fenced { - l.stMu.Unlock() - return nil, errChunkLayerFenced - } if !l.absent[idx] || l.localBlocks[lba] { l.stMu.Unlock() return nil, nil diff --git a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go index c47b439c3f..220c4073b7 100644 --- a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go +++ b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go @@ -4,6 +4,8 @@ import ( "bytes" "context" "errors" + "strings" + "sync" "testing" "time" ) @@ -146,16 +148,21 @@ func TestChunkHydration_ActiveDemandPrecedesExpiredWaiter(t *testing.T) { demand := startHydrationRead(t, s, context.Background(), 16) waitHydrationRegistration(t, registered, 1) release() - next := waitKey(t, entered, "next fetch") - if want := remote.stats().head.Chunks[4].Key; next != want { - t.Fatalf("fetch %q ran before demand %q", next, want) - } if r := hydrationOutcome(t, first); r.err != nil { t.Fatal(r.err) } if r := hydrationOutcome(t, demand); r.err != nil || !bytes.Equal(r.data, makeBlock(ctBlockSize, 0x50)) { t.Fatalf("demand: %v", r.err) } + var gets []string + for _, op := range remote.stats().ops { + if strings.HasPrefix(op, "get:") { + gets = append(gets, strings.TrimPrefix(op, "get:")) + } + } + if want := remote.stats().head.Chunks[4].Key; len(gets) < 2 || gets[1] != want { + t.Fatalf("fetch order %v, want demand %q second", gets, want) + } } func TestChunkHydration_CloseSettlesQueuedAndRunningReaders(t *testing.T) { @@ -178,3 +185,92 @@ func TestChunkHydration_CloseSettlesQueuedAndRunningReaders(t *testing.T) { t.Fatalf("queued work started after Close: Gets=%d", got) } } + +func TestChunkHydration_ConfiguredWorkersBoundConcurrentGets(t *testing.T) { + s, _, remote, registered := hydrationFixture(t, 2, 3) + entered, release := holdGets(t, remote) + defer release() + a := startHydrationRead(t, s, context.Background(), 8) + b := startHydrationRead(t, s, context.Background(), 12) + waitKey(t, entered, "worker1") + waitKey(t, entered, "worker2") + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + c := startHydrationRead(t, s, ctx, 16) + waitHydrationRegistration(t, registered, 3) + if r := hydrationOutcome(t, c); !errors.Is(r.err, ErrChunkHydrationPending) { + t.Fatalf("queued read: %v", r.err) + } + if got := remote.stats().gets; got != 2 { + t.Fatalf("configured2 workers started%d Gets", got) + } + release() + if r := hydrationOutcome(t, a); r.err != nil { + t.Fatal(r.err) + } + if r := hydrationOutcome(t, b); r.err != nil { + t.Fatal(r.err) + } +} + +type uninterruptibleHydrationRemote struct { + *fakeChunkRemote + entered, release chan struct{} + once sync.Once +} + +func (r *uninterruptibleHydrationRemote) Get(_ context.Context, key string) ([]byte, error) { + r.once.Do(func() { close(r.entered) }) + <-r.release + return r.fakeChunkRemote.Get(context.Background(), key) +} + +func TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet(t *testing.T) { + image := make([]byte, ctNumBlocks*ctBlockSize) + copy(image[8*ctBlockSize:], makeBlock(ctBlockSize, 0x88)) + f := newFakeChunkRemote() + f.seedHead(t, image, 50, 1) + r := &uninterruptibleHydrationRemote{fakeChunkRemote: f, entered: make(chan struct{}), release: make(chan struct{})} + var once sync.Once + release := func() { once.Do(func() { close(r.release) }) } + s, _ := newChunkTestStore(t) + cfg := ctConfig(2) + cfg.FreshFromHead = true + layer := mustAttach(t, s, r, cfg) + t.Cleanup(release) + result := startHydrationRead(t, s, context.Background(), 8) + select { + case <-r.entered: + case <-time.After(ctLocalBound): + t.Fatal("Get not entered") + } + closed := make(chan struct{}) + t.Cleanup(func() { + release() + select { + case <-closed: + case <-time.After(ctLocalBound): + t.Error("Close did not join Get") + } + }) + go func() { _ = layer.Close(); close(closed) }() + select { + case got := <-result: + if !errors.Is(got.err, errChunkLayerClosed) { + t.Fatalf("Close lost closed cause: %v", got.err) + } + case <-time.After(500 * time.Millisecond): + t.Fatal("Close did not wake hydration caller") + } + select { + case <-closed: + t.Fatal("Close abandoned uninterruptible Get") + case <-time.After(50 * time.Millisecond): + } + release() + select { + case <-closed: + case <-time.After(ctLocalBound): + t.Fatal("Close did not settle after Get release") + } +} From 074b7cc0ea6594377201a9c8ba2b74da2daafa5c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 10:04:35 -0800 Subject: [PATCH 129/150] fix: wake hydration callers on close while retaining physical I/O ownership --- seaweed-block/core/storage/chunk_hydration.go | 5 +++++ seaweed-block/core/storage/walstore.go | 8 +++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_hydration.go b/seaweed-block/core/storage/chunk_hydration.go index b895b81857..f8261fa58e 100644 --- a/seaweed-block/core/storage/chunk_hydration.go +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -88,6 +88,11 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b hook(idx) } select { + case <-l.ctx.Done(): + l.stMu.Lock() + f.waiters-- + l.stMu.Unlock() + return nil, errChunkLayerClosed case <-f.done: case <-ctx.Done(): // A completed fault wins a simultaneous caller deadline. diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index f2b6d3efa4..9b96bcbc6d 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -1048,9 +1048,15 @@ func (s *WALStore) WriteInstrumentation() WriteInstrumentationStatus { // from the WAL; clean LBAs are served from the extent. func (s *WALStore) Read(lba uint32) ([]byte, error) { return s.ReadContext(context.Background(), lba) } -func (s *WALStore) ReadContext(ctx context.Context, lba uint32) ([]byte, error) { +func (s *WALStore) ReadContext(ctx context.Context, lba uint32) (data []byte, err error) { ctx, cancel := context.WithTimeout(ctx, defaultHydrationWait) defer cancel() + defer func() { + if err == nil && ctx.Err() != nil { + data = nil + err = hydrationPending(ctx.Err()) + } + }() if err := ctx.Err(); err != nil { return nil, hydrationPending(err) } From 13281568ef483fa6ebf111905b909d971d947b47 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 10:06:08 -0800 Subject: [PATCH 130/150] test: require configurable hydration worker and queue limits --- .../cmd/blockvolume/hydration_flags_test.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/hydration_flags_test.go diff --git a/seaweed-block/cmd/blockvolume/hydration_flags_test.go b/seaweed-block/cmd/blockvolume/hydration_flags_test.go new file mode 100644 index 0000000000..a7cd51d2fd --- /dev/null +++ b/seaweed-block/cmd/blockvolume/hydration_flags_test.go @@ -0,0 +1,15 @@ +package main + +import "testing" + +func TestChunkHydrationFlagsAreConfigurable(t *testing.T) { + base := append(phase150RequiredBlockvolumeArgs(), "--durable-root=hydration-test", "--durable-impl=walstore-chunk", "--chunk-filer=x:1") + if _, err := parseFlags(append(base, "--chunk-hydration-workers=3", "--chunk-hydration-queue-depth=17")); err != nil { + t.Fatalf("valid hydration limits refused: %v", err) + } + for _, flag := range []string{"--chunk-hydration-workers=0", "--chunk-hydration-workers=65", "--chunk-hydration-queue-depth=0", "--chunk-hydration-queue-depth=65537"} { + if _, err := parseFlags(append(base, flag)); err == nil { + t.Fatalf("invalid hydration limit accepted: %s", flag) + } + } +} From 39aca2daee6ff9be84d4436e9c60ac7296ecbac6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 10:07:05 -0800 Subject: [PATCH 131/150] storage: expose configurable hydration limits and wait/fetch counters --- seaweed-block/cmd/blockvolume/chunk_remote.go | 24 ++++++++---- .../cmd/blockvolume/hydration_flags_test.go | 5 ++- seaweed-block/cmd/blockvolume/main.go | 4 ++ .../core/frontend/durable/provider.go | 3 ++ .../core/frontend/durable/provider_chunk.go | 18 +++++---- seaweed-block/core/storage/chunk_hydration.go | 37 ++++++++++++++++++- seaweed-block/core/storage/chunk_layer.go | 9 +++++ seaweed-block/core/storage/chunk_seam.go | 1 + 8 files changed, 82 insertions(+), 19 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index 48015840f1..c8b7ce0c1c 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -29,13 +29,15 @@ const ( ) type chunkFlags struct { - filer string - path string - collection string - replication string - captureInterval time.Duration - dirtyThreshold int - uploadConcurrency int + filer string + path string + collection string + replication string + captureInterval time.Duration + dirtyThreshold int + uploadConcurrency int + hydrationWorkers int + hydrationQueueDepth int // controlEndpoint mounts the /chunk/* routes on the status listener. controlEndpoint bool } @@ -45,7 +47,7 @@ func validateChunkFlags(f flags) error { if f.durableImpl != "walstore-chunk" { if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath || c.captureInterval != defaultChunkCaptureInterval || c.dirtyThreshold != defaultChunkDirtyThreshold || - c.uploadConcurrency != 8 || c.controlEndpoint { + c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint { return errors.New("--chunk-* flags require --durable-impl=walstore-chunk") } return nil @@ -71,6 +73,12 @@ func validateChunkFlags(f flags) error { if c.uploadConcurrency < 1 || c.uploadConcurrency > 64 { return errors.New("--chunk-upload-concurrency must be between 1 and 64") } + if c.hydrationWorkers < 1 || c.hydrationWorkers > 64 { + return errors.New("--chunk-hydration-workers must be between 1 and 64") + } + if c.hydrationQueueDepth < 1 || c.hydrationQueueDepth > 65536 { + return errors.New("--chunk-hydration-queue-depth must be between 1 and 65536") + } if c.dirtyThreshold < 0 { return fmt.Errorf("--chunk-dirty-threshold=%d must not be negative", c.dirtyThreshold) } diff --git a/seaweed-block/cmd/blockvolume/hydration_flags_test.go b/seaweed-block/cmd/blockvolume/hydration_flags_test.go index a7cd51d2fd..6d37a85eb7 100644 --- a/seaweed-block/cmd/blockvolume/hydration_flags_test.go +++ b/seaweed-block/cmd/blockvolume/hydration_flags_test.go @@ -4,8 +4,9 @@ import "testing" func TestChunkHydrationFlagsAreConfigurable(t *testing.T) { base := append(phase150RequiredBlockvolumeArgs(), "--durable-root=hydration-test", "--durable-impl=walstore-chunk", "--chunk-filer=x:1") - if _, err := parseFlags(append(base, "--chunk-hydration-workers=3", "--chunk-hydration-queue-depth=17")); err != nil { - t.Fatalf("valid hydration limits refused: %v", err) + f, err := parseFlags(append(base, "--chunk-hydration-workers=3", "--chunk-hydration-queue-depth=17")) + if err != nil || f.chunk.hydrationWorkers != 3 || f.chunk.hydrationQueueDepth != 17 { + t.Fatalf("hydration limits: %+v err=%v", f.chunk, err) } for _, flag := range []string{"--chunk-hydration-workers=0", "--chunk-hydration-workers=65", "--chunk-hydration-queue-depth=0", "--chunk-hydration-queue-depth=65537"} { if _, err := parseFlags(append(base, flag)); err == nil { diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 62a2f09d92..2516140cb2 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -194,6 +194,8 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)") fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: automatic cut once this long has passed since the last successful cut; 0 (default) disables the timer, e.g. 15m as a host-loss safety net") fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)") + fs.IntVar(&f.chunk.hydrationWorkers, "chunk-hydration-workers", 2, "walstore-chunk: concurrent lazy chunk fetches per volume (1..64)") + fs.IntVar(&f.chunk.hydrationQueueDepth, "chunk-hydration-queue-depth", 64, "walstore-chunk: distinct queued/in-flight hydration chunks per volume (1..65536)") fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", defaultChunkDirtyThreshold, "walstore-chunk: number of candidate chunks above which a cut pre-copies (stages) chunks before its barrier, in rounds of this size; copy-before-write copies the rest outside the barrier; never triggers a cut; 0 = no pre-copy") fs.BoolVar(&f.chunk.controlEndpoint, "chunk-control-endpoint", false, "walstore-chunk: expose the /chunk/* control routes (cut, snapshot, snapshots, snapshot/delete, detach) on the status HTTP listener; off by default; loopback-only like the listener") fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)") @@ -618,6 +620,8 @@ func run(f flags) int { cfg.ChunkCaptureInterval = f.chunk.captureInterval cfg.ChunkDirtyThreshold = f.chunk.dirtyThreshold cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency + cfg.ChunkHydrationWorkers = f.chunk.hydrationWorkers + cfg.ChunkHydrationQueueDepth = f.chunk.hydrationQueueDepth cfg.ChunkHolder = chunkHolder(f) if chunkErr == nil { cfg.ChunkRemoteFor = chunk.remoteFor diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 72ba48299c..6174905117 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -162,6 +162,9 @@ type ProviderConfig struct { // ChunkReadMissTimeout bounds one remote fetch of an absent block. // Zero: the storage default. ChunkReadMissTimeout time.Duration + // Per-volume hydration bounds; zero selects 2 workers and 64 distinct chunks. + ChunkHydrationWorkers int + ChunkHydrationQueueDepth int // ChunkCaptureInterval: an automatic cut is due once this long has // passed since the volume's last successful cut (of any kind). Zero // disables the timer. diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index dc5a1cca97..4af44da113 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -364,14 +364,16 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h remote = &manifestBoundRemote{closeBoundRemote: bound, builder: builder} } cfg := storage.ChunkLayerConfig{ - ChunkBlocks: p.cfg.ChunkBlocks, - RestoreChunkBytes: uint64(ws.BlockSize()) * uint64(p.cfg.ChunkBlocks), - Epoch: lin.epoch, - Holder: holder, - FreshFromHead: h.fresh, - ReadMissTimeout: p.cfg.ChunkReadMissTimeout, - BarrierBound: p.cfg.ChunkDirtyThreshold, - UploadConcurrency: p.cfg.ChunkUploadConcurrency, + ChunkBlocks: p.cfg.ChunkBlocks, + RestoreChunkBytes: uint64(ws.BlockSize()) * uint64(p.cfg.ChunkBlocks), + Epoch: lin.epoch, + Holder: holder, + FreshFromHead: h.fresh, + ReadMissTimeout: p.cfg.ChunkReadMissTimeout, + HydrationWorkers: p.cfg.ChunkHydrationWorkers, + HydrationQueueDepth: p.cfg.ChunkHydrationQueueDepth, + BarrierBound: p.cfg.ChunkDirtyThreshold, + UploadConcurrency: p.cfg.ChunkUploadConcurrency, CaptureAllowed: func() error { cur := p.view.Projection() if !cur.Healthy || cur.VolumeID != volumeID || lin.volumeID != volumeID { diff --git a/seaweed-block/core/storage/chunk_hydration.go b/seaweed-block/core/storage/chunk_hydration.go index f8261fa58e..01e5d97821 100644 --- a/seaweed-block/core/storage/chunk_hydration.go +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -15,6 +15,21 @@ const defaultHydrationWorkers = 2 const defaultHydrationQueueDepth = 64 const defaultHydrationWait = 4 * time.Second +// ChunkHydrationStats separates wait refusals from owned fetch outcomes. +// A wait refusal is not necessarily a wire completion (a caller may cancel). +type ChunkHydrationStats struct { + WorkerLimit int + QueueDepth int + Active int + Queued int + WaitCalls uint64 + Joined uint64 + WaitRefusals uint64 + Fetches uint64 + Completed uint64 + FetchErrors uint64 +} + type chunkHydrationFlight struct { idx, gen uint64 ref chunkRef @@ -38,6 +53,7 @@ func hydrationPending(cause error) error { // it (or a store/capture/lifecycle lock) while awaiting or fetching bytes. func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]byte, error) { idx := l.chunkOf(lba) + counted := false for { l.stMu.Lock() if l.closed { @@ -53,7 +69,12 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b l.stMu.Unlock() return make([]byte, l.blockSize), nil } + if !counted { + l.stats.Hydration.WaitCalls++ + counted = true + } if err := ctx.Err(); err != nil { + l.stats.Hydration.WaitRefusals++ l.stMu.Unlock() return nil, hydrationPending(err) } @@ -63,8 +84,12 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b if stale { f.cancel() } + if f != nil && !stale { + l.stats.Hydration.Joined++ + } if f == nil { if len(l.hydration) >= l.cfg.HydrationQueueDepth { + l.stats.Hydration.WaitRefusals++ l.stMu.Unlock() return nil, hydrationPending(nil) } @@ -101,6 +126,7 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b default: l.stMu.Lock() f.waiters-- + l.stats.Hydration.WaitRefusals++ l.stMu.Unlock() return nil, hydrationPending(ctx.Err()) } @@ -110,6 +136,9 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b closed := l.closed changed := l.absentGen[idx] != f.gen || l.head.Chunks[idx] != f.ref err := f.err + if !closed && !changed && errors.Is(err, ErrChunkHydrationPending) { + l.stats.Hydration.WaitRefusals++ + } l.stMu.Unlock() if closed { return nil, errChunkLayerClosed @@ -156,16 +185,22 @@ func (l *chunkLayerImpl) hydrationWorker() { } } next.running = true + l.stats.Hydration.Fetches++ l.wakeHydrationLocked() l.stMu.Unlock() fetch, cancel := context.WithTimeout(next.ctx, l.cfg.ReadMissTimeout) - _, err := l.fillOnce(fetch, next.idx, next.gen, next.ref) + resolved, err := l.fillOnce(fetch, next.idx, next.gen, next.ref) cancel() next.cancel() l.stMu.Lock() if hydrationContextCauseOnly(err) { err = hydrationPending(err) } + if err != nil { + l.stats.Hydration.FetchErrors++ + } else if resolved { + l.stats.Hydration.Completed++ + } next.err = err delete(l.hydration, next.idx) close(next.done) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index e039e1cbc3..38fd56c042 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1379,6 +1379,15 @@ func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error func (l *chunkLayerImpl) Stats() chunkLayerStats { l.stMu.Lock() out := l.stats + out.Hydration.WorkerLimit = l.cfg.HydrationWorkers + out.Hydration.QueueDepth = l.cfg.HydrationQueueDepth + for _, f := range l.hydration { + if f.running { + out.Hydration.Active++ + } else { + out.Hydration.Queued++ + } + } out.CutsRefused = make(map[string]uint64, len(l.stats.CutsRefused)) for k, v := range l.stats.CutsRefused { out.CutsRefused[k] = v diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 9985dcf8fb..c1cc2888f2 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -435,6 +435,7 @@ type chunkCutStats struct { // - LastCut, LastCutH and LastCutNs (wall clock, Unix ns) describe the // last successful cut, whatever triggered it. type chunkLayerStats struct { + Hydration ChunkHydrationStats CutsOK uint64 CutsNoop uint64 CutsFailed uint64 From 5aea1eaf8b5543d5e44cd75c2c2f2b919063c1a5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 10:14:56 -0800 Subject: [PATCH 132/150] test read command arrival and shared hydration lifetime --- .../frontend/durable/hydration_budget_test.go | 63 +++++++++++++++++++ .../frontend/nvme/read_command_budget_test.go | 45 +++++++++++++ .../core/storage/chunk_layer_races_test.go | 8 ++- 3 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/frontend/nvme/read_command_budget_test.go diff --git a/seaweed-block/core/frontend/durable/hydration_budget_test.go b/seaweed-block/core/frontend/durable/hydration_budget_test.go index 6d4850ae84..cd3bae1973 100644 --- a/seaweed-block/core/frontend/durable/hydration_budget_test.go +++ b/seaweed-block/core/frontend/durable/hydration_budget_test.go @@ -1,6 +1,7 @@ package durable_test import ( + "bytes" "context" "errors" "sync" @@ -12,6 +13,68 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) +type pacedHydrationRemote struct { + storage.ChunkRemote + gets atomic.Int64 + second chan struct{} + once sync.Once +} + +func (r *pacedHydrationRemote) release() { r.once.Do(func() { close(r.second) }) } +func (r *pacedHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) { + if r.gets.Add(1) == 1 { + timer := time.NewTimer(120 * time.Millisecond) + defer timer.Stop() + select { + case <-timer.C: + case <-ctx.Done(): + return nil, ctx.Err() + } + } else { + select { + case <-r.second: + case <-ctx.Done(): + return nil, ctx.Err() + } + } + return r.ChunkRemote.Get(ctx, key) +} + +func TestDurableHydration_MultipleChunksShareOneDeadline(t *testing.T) { + r := &pacedHydrationRemote{ChunkRemote: seededRemote(t), second: make(chan struct{})} + p := chunkProvider(t, t.TempDir(), r, v1View(), 0) + t.Cleanup(r.release) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 220*time.Millisecond) + defer cancel() + start := time.Now() + buf := make([]byte, (101-33)*4096) + n, err := b.Read(ctx, 33*4096, buf) + if !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) || n != (96-33)*4096 { + t.Fatalf("shared deadline n=%d err=%v gets=%d", n, err, r.gets.Load()) + } + if elapsed := time.Since(start); elapsed >= 450*time.Millisecond { + t.Fatalf("read budget renewed: %s", elapsed) + } + if !bytes.Equal(buf[:4096], block(0x33)) { + t.Fatal("first chunk prefix changed") + } + r.release() + ctx2, cancel2 := context.WithTimeout(context.Background(), time.Second) + defer cancel2() + last := make([]byte, 4096) + if n, err := b.Read(ctx2, 100*4096, last); n != 4096 || err != nil || !bytes.Equal(last, block(0x64)) { + t.Fatalf("shared work after timeout: n=%d err=%v", n, err) + } + if r.gets.Load() != 2 { + t.Fatalf("retry restarted shared fetch: %d", r.gets.Load()) + } +} + type heldHydrationRemote struct { storage.ChunkRemote gate chan struct{} diff --git a/seaweed-block/core/frontend/nvme/read_command_budget_test.go b/seaweed-block/core/frontend/nvme/read_command_budget_test.go new file mode 100644 index 0000000000..5ff7456770 --- /dev/null +++ b/seaweed-block/core/frontend/nvme/read_command_budget_test.go @@ -0,0 +1,45 @@ +package nvme + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" +) + +type budgetReadBackend struct { + frontend.Backend + deadline time.Time + physical bool +} + +func (b *budgetReadBackend) Read(ctx context.Context, _ int64, p []byte) (int, error) { + b.deadline, _ = ctx.Deadline() + <-ctx.Done() + if b.physical { + return 0, errors.Join(ctx.Err(), errors.New("physical read failure")) + } + return 0, frontend.ErrBackendBusy +} + +func TestSessionReadBudgetIncludesQueueResidence(t *testing.T) { + for _, physical := range []bool{false, true} { + b := &budgetReadBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), physical: physical} + s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), respCh: make(chan *response, 1), done: make(chan struct{})} + arrival := time.Now().Add(-5 * time.Second) + req := &Request{receivedAt: arrival, dispatchReadyAt: time.Now()} + req.capsule.OpCode, req.capsule.NSID = ioRead, 1 + s.handleRead(context.Background(), req) + resp := <-s.respCh + want := MakeStatusField(SCTGeneric, SCNamespaceNotReady, false) + if physical { + want = MakeStatusField(SCTGeneric, SCInternalError, true) + } + if !b.deadline.Equal(arrival.Add(frontend.ReadCommandBudget)) || resp.resp.Status != want || len(resp.c2hData) != 0 { + t.Fatalf("physical=%t deadline=%v status=%#x data=%d", physical, b.deadline, resp.resp.Status, len(resp.c2hData)) + } + } +} diff --git a/seaweed-block/core/storage/chunk_layer_races_test.go b/seaweed-block/core/storage/chunk_layer_races_test.go index 8ef33cc2e6..f85348c581 100644 --- a/seaweed-block/core/storage/chunk_layer_races_test.go +++ b/seaweed-block/core/storage/chunk_layer_races_test.go @@ -129,6 +129,12 @@ func TestChunkLayer_StaleFillCannotInstallAfterReEviction(t *testing.T) { } held, releaseA := holdNextGet(t, f) + // Schedule an old-generation physical fill directly. Guest readers now + // share one flight, so two guest reads cannot create this overlap. + impl := layer.(*chunkLayerImpl) + impl.stMu.Lock() + oldGen, oldRef := impl.absentGen[2], impl.head.Chunks[2] + impl.stMu.Unlock() readA := make(chan error, 1) joinedA := make(chan struct{}) t.Cleanup(func() { @@ -141,7 +147,7 @@ func TestChunkLayer_StaleFillCannotInstallAfterReEviction(t *testing.T) { }) go func() { defer close(joinedA) - _, err := s.Read(8) + _, err := impl.fillOnce(ctTimeout(t), 2, oldGen, oldRef) readA <- err }() waitKey(t, held, "fetch A") From 33b85df283017e46c66bac319b253dbaa90e04fb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 10:16:44 -0800 Subject: [PATCH 133/150] test terminal hydration failures and queue status --- .../frontend/durable/hydration_budget_test.go | 41 +++++++++++++++++++ .../chunk_hydration_concurrency_test.go | 6 ++- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/durable/hydration_budget_test.go b/seaweed-block/core/frontend/durable/hydration_budget_test.go index cd3bae1973..178a4cf3de 100644 --- a/seaweed-block/core/frontend/durable/hydration_budget_test.go +++ b/seaweed-block/core/frontend/durable/hydration_budget_test.go @@ -10,9 +10,50 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" "github.com/seaweedfs/seaweed-block/core/storage" ) +type faultyHydrationRemote struct { + storage.ChunkRemote + fault error + corrupt bool +} + +func (r *faultyHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) { + if r.fault != nil { + return nil, r.fault + } + b, err := r.ChunkRemote.Get(ctx, key) + if err == nil && r.corrupt && len(b) > 0 { + b = append([]byte(nil), b...) + b[0] ^= 0xff + } + return b, err +} + +func TestDurableHydration_NVMePreservesPhysicalAndHashErrors(t *testing.T) { + for _, corrupt := range []bool{false, true} { + t.Run(map[bool]string{false: "joined physical", true: "hash"}[corrupt], func(t *testing.T) { + r := &faultyHydrationRemote{ChunkRemote: seededRemote(t), corrupt: corrupt} + if !corrupt { + r.fault = errors.Join(context.DeadlineExceeded, errors.New("physical remote read failure")) + } + p := chunkProvider(t, t.TempDir(), r, v1View(), 0) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: b, BlockSize: 4096, VolumeSize: pcBlocks * 4096}) + res := h.Handle(context.Background(), nvme.IOCommand{Opcode: 2, NSID: 1, SLBA: 33, NLB: 1}) + if res.SC != nvme.SCInternalError || len(res.Data) != 0 { + t.Fatalf("terminal hydration failure: %+v", res) + } + }) + } +} + type pacedHydrationRemote struct { storage.ChunkRemote gets atomic.Int64 diff --git a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go index 220c4073b7..46f5742189 100644 --- a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go +++ b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go @@ -105,7 +105,7 @@ func TestChunkHydration_ConcurrentReadersShareOneGet(t *testing.T) { } func TestChunkHydration_QueueAndWorkerLimitsAreBounded(t *testing.T) { - s, _, remote, registered := hydrationFixture(t, 1, 2) + s, layer, remote, registered := hydrationFixture(t, 1, 2) entered, release := holdGets(t, remote) defer release() first := startHydrationRead(t, s, context.Background(), 8) @@ -125,6 +125,10 @@ func TestChunkHydration_QueueAndWorkerLimitsAreBounded(t *testing.T) { if got := remote.stats().gets; got != 1 { t.Fatalf("worker bound exceeded: Gets=%d", got) } + stats := layer.Stats().Hydration + if stats.WorkerLimit != 1 || stats.QueueDepth != 2 || stats.Active != 1 || stats.Queued != 1 || stats.WaitRefusals != 2 || stats.Fetches != 1 { + t.Fatalf("hydration status does not reflect bounded pressure: %+v", stats) + } release() if r := hydrationOutcome(t, first); r.err != nil { t.Fatal(r.err) From cf917925f745593378d682c476fada6fbaeef5e9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 10:17:55 -0800 Subject: [PATCH 134/150] record shared hydration wait and close invariants --- seaweed-block/docs/design/invariants.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 35a961d925..46d9626ee7 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -177,6 +177,8 @@ stateDiagram-v2 | Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | | Holder | HolderFenced | a HEAD with a higher epoch, or another holder at the same epoch | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | +| `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet` | — | ACTIVE | +| Holder | (hydration wait) | one request deadline covers all missing chunks; callers may detach, but bounded per-layer workers retain and join each shared fill; HEAD/generation/local-write checks still govern installation | `core/storage/chunk_hydration.go`; `core/frontend/durable/storage_adapter.go` `readStorageBlock` | `INV-CUT-HYDRATION-WAIT-001`, `INV-CUT-READMISS-001` | ### M5 The cut pipeline From 925c5969631a63f510bd9e4cfd57bb727361bf9b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 10:21:28 -0800 Subject: [PATCH 135/150] test host retries retain the same hydration fetch --- .../frontend/durable/hydration_budget_test.go | 62 ++++++++++++++++++- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/frontend/durable/hydration_budget_test.go b/seaweed-block/core/frontend/durable/hydration_budget_test.go index 178a4cf3de..a53de4ae90 100644 --- a/seaweed-block/core/frontend/durable/hydration_budget_test.go +++ b/seaweed-block/core/frontend/durable/hydration_budget_test.go @@ -118,14 +118,21 @@ func TestDurableHydration_MultipleChunksShareOneDeadline(t *testing.T) { type heldHydrationRemote struct { storage.ChunkRemote - gate chan struct{} - once sync.Once - gets atomic.Int64 + gate chan struct{} + once sync.Once + gets atomic.Int64 + entered chan struct{} } func (r *heldHydrationRemote) release() { r.once.Do(func() { close(r.gate) }) } func (r *heldHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) { r.gets.Add(1) + if r.entered != nil { + select { + case r.entered <- struct{}{}: + default: + } + } select { case <-r.gate: return r.ChunkRemote.Get(ctx, key) @@ -134,6 +141,55 @@ func (r *heldHydrationRemote) Get(ctx context.Context, key string) ([]byte, erro } } +func TestDurableHydration_HostRetriesJoinOwnedFetch(t *testing.T) { + r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)} + p := chunkProvider(t, t.TempDir(), r, v1View(), 0) + t.Cleanup(r.release) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: b, BlockSize: 4096, VolumeSize: pcBlocks * 4096}) + // Start the hold only after the first actual Get. No setup time counts + // toward the delay that the host's retry sequence must bridge. + joined := make(chan struct{}) + stop := make(chan struct{}) + t.Cleanup(func() { close(stop); r.release(); <-joined }) + go func() { + defer close(joined) + select { + case <-r.entered: + case <-stop: + return + } + timer := time.NewTimer(120 * time.Millisecond) + defer timer.Stop() + select { + case <-timer.C: + r.release() + case <-stop: + } + }() + busy := 0 + for attempt := 0; attempt < 6; attempt++ { + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + res := h.Handle(ctx, nvme.IOCommand{Opcode: 2, NSID: 1, SLBA: 33, NLB: 1}) + cancel() + if res.SC == nvme.SCSuccess { + if busy == 0 || !bytes.Equal(res.Data, block(0x33)) || r.gets.Load() != 1 { + t.Fatalf("busy=%d Gets=%d bytes=%d", busy, r.gets.Load(), len(res.Data)) + } + return + } + if res.SC != nvme.SCNamespaceNotReady || len(res.Data) != 0 { + t.Fatalf("attempt %d: %+v", attempt, res) + } + busy++ + } + t.Fatal("six immediate host attempts exhausted despite surviving shared fill") +} + func TestDurableHydration_ReadAndRMWPreserveCallerBudget(t *testing.T) { for _, rmw := range []bool{false, true} { name := "read" From 89b60a1b938668258d7c068d07eeb814c586195c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 10:26:17 -0800 Subject: [PATCH 136/150] test provider hydration configuration in durable status --- .../frontend/durable/hydration_budget_test.go | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/seaweed-block/core/frontend/durable/hydration_budget_test.go b/seaweed-block/core/frontend/durable/hydration_budget_test.go index a53de4ae90..2d488a9df3 100644 --- a/seaweed-block/core/frontend/durable/hydration_budget_test.go +++ b/seaweed-block/core/frontend/durable/hydration_budget_test.go @@ -10,10 +10,38 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" "github.com/seaweedfs/seaweed-block/core/storage" ) +func TestDurableHydration_ConfiguredLimitsReachStatus(t *testing.T) { + for _, configured := range []bool{false, true} { + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks} + r := storage.NewMemChunkRemote() + cfg.ChunkRemoteFor = func(string) (storage.ChunkRemote, error) { return r, nil } + wantWorkers, wantDepth := 2, 64 + if configured { + cfg.ChunkHydrationWorkers, cfg.ChunkHydrationQueueDepth = 3, 17 + wantWorkers, wantDepth = 3, 17 + } + p, err := durable.NewDurableProvider(cfg, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + openRecovered(t, p) + st := p.DurableStatuses() + if len(st) != 1 || st[0].Chunk == nil { + t.Fatalf("missing chunk status: %+v", st) + } + h := st[0].Chunk.Stats.Hydration + if h.WorkerLimit != wantWorkers || h.QueueDepth != wantDepth { + t.Fatalf("configured=%t hydration=%+v", configured, h) + } + } +} + type faultyHydrationRemote struct { storage.ChunkRemote fault error From 8b30c2050f356a9a96c3cb81261d541bb65daa6b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 10:45:43 -0800 Subject: [PATCH 137/150] test lineage fencing during a hydration wait --- .../frontend/durable/hydration_budget_test.go | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/seaweed-block/core/frontend/durable/hydration_budget_test.go b/seaweed-block/core/frontend/durable/hydration_budget_test.go index 2d488a9df3..4d97ab545d 100644 --- a/seaweed-block/core/frontend/durable/hydration_budget_test.go +++ b/seaweed-block/core/frontend/durable/hydration_budget_test.go @@ -218,6 +218,51 @@ func TestDurableHydration_HostRetriesJoinOwnedFetch(t *testing.T) { t.Fatal("six immediate host attempts exhausted despite surviving shared fill") } +func TestDurableHydration_FenceWinsCallerExpiry(t *testing.T) { + r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)} + view := v1View() + p := chunkProvider(t, t.TempDir(), r, view, 0) + t.Cleanup(r.release) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + joined := make(chan struct{}) + result := make(chan error, 1) + t.Cleanup(func() { + cancel() + r.release() + select { + case <-joined: + case <-time.After(time.Second): + t.Error("fenced hydration waiter not joined") + } + }) + go func() { + defer close(joined) + _, err := b.Read(ctx, 33*4096, make([]byte, 4096)) + result <- err + }() + select { + case <-r.entered: + case <-time.After(time.Second): + t.Fatal("cold read never reached Get") + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 1})) + cancel() + select { + case err := <-result: + if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("expiry hid fencing: %v", err) + } + case <-time.After(time.Second): + t.Fatal("fenced waiter did not detach") + } +} + func TestDurableHydration_ReadAndRMWPreserveCallerBudget(t *testing.T) { for _, rmw := range []bool{false, true} { name := "read" From 0311d807269feb195e6216d688aa6813049275b2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 11:11:13 -0800 Subject: [PATCH 138/150] test: retain slow hydration for internal reads --- .../storage/chunk_hydration_budget_test.go | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/seaweed-block/core/storage/chunk_hydration_budget_test.go b/seaweed-block/core/storage/chunk_hydration_budget_test.go index 1d217458de..891ff9931a 100644 --- a/seaweed-block/core/storage/chunk_hydration_budget_test.go +++ b/seaweed-block/core/storage/chunk_hydration_budget_test.go @@ -56,3 +56,25 @@ func TestChunkHydration_DeadlineDetachesWithoutCancellingFill(t *testing.T) { t.Fatalf("retry cancelled/restarted shared fetch: Gets=%d want1", n) } } + +// Internal readers have no frontend command budget: the remote fill owns its timeout. +func TestChunkHydration_ContextlessReadAllowsSlowFill(t *testing.T) { + s, _, remote, _ := hydrationFixture(t, 2, 64) + entered, release := holdGets(t, remote) + defer release() + result := make(chan hydrationResult, 1) + go func() { data, err := s.Read(8); result <- hydrationResult{data, err} }() + waitKey(t, entered, "contextless slow fill") + timer := time.NewTimer(6 * time.Second) + defer timer.Stop() + <-timer.C + release() + select { + case got := <-result: + if got.err != nil || !bytes.Equal(got.data, makeBlock(ctBlockSize, 0x48)) { + t.Fatalf("contextless reader lost slow fill: %v", got.err) + } + case <-time.After(ctLocalBound): + t.Fatal("contextless reader did not settle after release") + } +} From 8ff814ac8b0c7397dc61a8f5d361294cd7fef9b2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 11:12:26 -0800 Subject: [PATCH 139/150] test: isolate stale hydration from new generation reads --- .../chunk_hydration_concurrency_test.go | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go index 46f5742189..6b0c8f8866 100644 --- a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go +++ b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go @@ -278,3 +278,59 @@ func TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet(t *testing.T) t.Fatal("Close did not settle after Get release") } } + +// Only the old generation ignores cancellation; a spare worker can serve the new one. +type staleHydrationRemote struct { + *fakeChunkRemote + oldKey string + entered, release chan struct{} + once sync.Once +} + +func (r *staleHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) { + if key == r.oldKey { + r.once.Do(func() { close(r.entered) }) + <-r.release + return r.fakeChunkRemote.Get(context.Background(), key) + } + return r.fakeChunkRemote.Get(ctx, key) +} +func TestChunkHydration_NewGenerationDoesNotJoinStaleGet(t *testing.T) { + s, layer, remote, registered := hydrationFixture(t, 2, 64) + layer.stMu.Lock() + oldRef, newRef := layer.head.Chunks[2], layer.head.Chunks[3] + layer.stMu.Unlock() + r := &staleHydrationRemote{fakeChunkRemote: remote, oldKey: oldRef.Key, entered: make(chan struct{}), release: make(chan struct{})} + layer.remote = r + var once sync.Once + release := func() { once.Do(func() { close(r.release) }) } + t.Cleanup(release) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + old := startHydrationRead(t, s, ctx, 8) + waitHydrationRegistration(t, registered, 1) + select { + case <-r.entered: + case <-time.After(ctLocalBound): + t.Fatal("old Get not entered") + } + layer.stMu.Lock() + layer.head.Chunks[2] = newRef + layer.absentGen[2]++ + layer.stMu.Unlock() + newer := startHydrationRead(t, s, ctx, 8) + waitHydrationRegistration(t, registered, 1) + select { + case got := <-newer: + if got.err != nil || !bytes.Equal(got.data, makeBlock(ctBlockSize, 0x4c)) { + t.Fatalf("new generation blocked by stale Get or wrong bytes: %v", got.err) + } + case <-time.After(500 * time.Millisecond): + release() + t.Fatal("new generation joined cancellation-ignoring old Get") + } + release() + if got := hydrationOutcome(t, old); got.err != nil || !bytes.Equal(got.data, makeBlock(ctBlockSize, 0x4c)) { + t.Fatalf("old waiter failed to follow new generation: %v", got.err) + } +} From eb177aed834702966601a5b64caeb9578f481b95 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 11:13:35 -0800 Subject: [PATCH 140/150] storage: preserve internal read waits and replace stale hydration --- seaweed-block/core/storage/chunk_hydration.go | 15 +++++++++++---- seaweed-block/core/storage/chunk_layer.go | 8 ++------ seaweed-block/core/storage/walstore.go | 2 -- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/storage/chunk_hydration.go b/seaweed-block/core/storage/chunk_hydration.go index 01e5d97821..2291ea22cc 100644 --- a/seaweed-block/core/storage/chunk_hydration.go +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "time" ) // ErrChunkHydrationPending means no guest bytes were admitted: hydration @@ -13,7 +12,6 @@ var ErrChunkHydrationPending = errors.New("storage: chunk hydration pending") const defaultHydrationWorkers = 2 const defaultHydrationQueueDepth = 64 -const defaultHydrationWait = 4 * time.Second // ChunkHydrationStats separates wait refusals from owned fetch outcomes. // A wait refusal is not necessarily a wire completion (a caller may cancel). @@ -83,6 +81,11 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b stale := f != nil && (f.gen != gen || f.ref != ref) if stale { f.cancel() + // The old worker remains owned and joined, but cannot delay a + // new generation or remove its replacement when it finishes. + delete(l.hydration, idx) + close(f.done) + f = nil } if f != nil && !stale { l.stats.Hydration.Joined++ @@ -185,6 +188,7 @@ func (l *chunkLayerImpl) hydrationWorker() { } } next.running = true + l.stats.Hydration.Active++ l.stats.Hydration.Fetches++ l.wakeHydrationLocked() l.stMu.Unlock() @@ -201,9 +205,12 @@ func (l *chunkLayerImpl) hydrationWorker() { } else if resolved { l.stats.Hydration.Completed++ } + l.stats.Hydration.Active-- next.err = err - delete(l.hydration, next.idx) - close(next.done) + if l.hydration[next.idx] == next { + delete(l.hydration, next.idx) + close(next.done) + } l.wakeHydrationLocked() l.stMu.Unlock() } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 38fd56c042..a2e6c10709 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -547,9 +547,7 @@ func sortedKeys(m map[uint64]bool) []uint64 { // block that has no newer local version, then lets the store read its // extent. It runs with no walstore lock held. func (l *chunkLayerImpl) OnReadMiss(lba uint64) ([]byte, error) { - ctx, cancel := context.WithTimeout(context.Background(), defaultHydrationWait) - defer cancel() - return l.OnReadMissContext(ctx, lba) + return l.OnReadMissContext(context.Background(), lba) } // fillOnce fetches one chunk version and installs every block that has no @@ -1382,9 +1380,7 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats { out.Hydration.WorkerLimit = l.cfg.HydrationWorkers out.Hydration.QueueDepth = l.cfg.HydrationQueueDepth for _, f := range l.hydration { - if f.running { - out.Hydration.Active++ - } else { + if !f.running { out.Hydration.Queued++ } } diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 9b96bcbc6d..12b694b12a 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -1049,8 +1049,6 @@ func (s *WALStore) WriteInstrumentation() WriteInstrumentationStatus { func (s *WALStore) Read(lba uint32) ([]byte, error) { return s.ReadContext(context.Background(), lba) } func (s *WALStore) ReadContext(ctx context.Context, lba uint32) (data []byte, err error) { - ctx, cancel := context.WithTimeout(ctx, defaultHydrationWait) - defer cancel() defer func() { if err == nil && ctx.Err() != nil { data = nil From 10cc4fa495e5aadf68262d55e3996877103e5ab6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 11:14:59 -0800 Subject: [PATCH 141/150] test: use production fill timeout for slow internal read --- seaweed-block/core/storage/chunk_hydration_budget_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_hydration_budget_test.go b/seaweed-block/core/storage/chunk_hydration_budget_test.go index 891ff9931a..4f8ba00980 100644 --- a/seaweed-block/core/storage/chunk_hydration_budget_test.go +++ b/seaweed-block/core/storage/chunk_hydration_budget_test.go @@ -59,7 +59,8 @@ func TestChunkHydration_DeadlineDetachesWithoutCancellingFill(t *testing.T) { // Internal readers have no frontend command budget: the remote fill owns its timeout. func TestChunkHydration_ContextlessReadAllowsSlowFill(t *testing.T) { - s, _, remote, _ := hydrationFixture(t, 2, 64) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + layer.cfg.ReadMissTimeout = 30 * time.Second entered, release := holdGets(t, remote) defer release() result := make(chan hydrationResult, 1) From 0832f07d22dcf389b05c4e3488e6a589ffc2fcd5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 11:16:46 -0800 Subject: [PATCH 142/150] test: expose fencing during cold partial write --- .../frontend/durable/hydration_budget_test.go | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/seaweed-block/core/frontend/durable/hydration_budget_test.go b/seaweed-block/core/frontend/durable/hydration_budget_test.go index 4d97ab545d..08f505b7a0 100644 --- a/seaweed-block/core/frontend/durable/hydration_budget_test.go +++ b/seaweed-block/core/frontend/durable/hydration_budget_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "fmt" "sync" "sync/atomic" "testing" @@ -314,3 +315,59 @@ func TestDurableHydration_ReadAndRMWPreserveCallerBudget(t *testing.T) { }) } } + +func TestDurableHydration_RMWFenceWinsCallerExpiry(t *testing.T) { + r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)} + view := v1View() + p := chunkProvider(t, t.TempDir(), r, view, 0) + t.Cleanup(r.release) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + store, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + before := store.NextLSN() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + joined := make(chan struct{}) + result := make(chan error, 1) + t.Cleanup(func() { + cancel() + r.release() + select { + case <-joined: + case <-time.After(time.Second): + t.Error("fenced hydration waiter not joined") + } + }) + go func() { + defer close(joined) + n, err := b.Write(ctx, 33*4096+1, []byte{0x74}) + if n != 0 { + err = fmt.Errorf("unexpected RMW prefix %d: %w", n, err) + } + result <- err + }() + select { + case <-r.entered: + case <-time.After(time.Second): + t.Fatal("cold read never reached Get") + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 1})) + cancel() + select { + case err := <-result: + if store.NextLSN() != before { + t.Fatal("fenced RMW appended data") + } + if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("expiry hid fencing: %v", err) + } + case <-time.After(time.Second): + t.Fatal("fenced waiter did not detach") + } +} From 731f2785422a91de53c532eed062009a48910eba Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 11:19:53 -0800 Subject: [PATCH 143/150] storage: fail rebuild snapshots on read faults and preserve RMW fencing --- seaweed-block/cmd/sparrow/main.go | 17 ++++--- seaweed-block/core/adapter/handoff_test.go | 5 ++- seaweed-block/core/calibration/harness.go | 10 ++++- .../core/frontend/durable/storage_adapter.go | 5 +++ .../core/recovery/receiver_base_pin_test.go | 2 +- .../core/replication/component/cluster.go | 10 ++++- .../storage/chunk_hydration_budget_test.go | 15 +++++++ seaweed-block/core/storage/contract_test.go | 5 ++- seaweed-block/core/storage/flusher_test.go | 5 ++- seaweed-block/core/storage/logical_storage.go | 5 ++- seaweed-block/core/storage/memorywal/store.go | 4 +- .../core/storage/memorywal/store_test.go | 8 +++- .../core/storage/parallelwal/store.go | 9 ++-- .../storage/smartwal/recovery_scan_test.go | 11 ++++- seaweed-block/core/storage/smartwal/store.go | 6 +-- seaweed-block/core/storage/store.go | 4 +- seaweed-block/core/storage/walstore.go | 6 +-- .../core/storage/walstore_recovery_test.go | 11 ++++- .../core/transport/rebuild_sender.go | 5 ++- .../transport/rebuild_snapshot_error_test.go | 45 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 4 +- 21 files changed, 154 insertions(+), 38 deletions(-) create mode 100644 seaweed-block/core/transport/rebuild_snapshot_error_test.go diff --git a/seaweed-block/cmd/sparrow/main.go b/seaweed-block/cmd/sparrow/main.go index cb1dc80d1d..bdcad2a099 100644 --- a/seaweed-block/cmd/sparrow/main.go +++ b/seaweed-block/cmd/sparrow/main.go @@ -26,15 +26,15 @@ type options struct { calibrate bool persistDemo bool persistDir string - authorityStore string - s5Bootstrap bool - s7RestartSmoke bool + authorityStore string + s5Bootstrap bool + s7RestartSmoke bool } type demoResult struct { - Demo string `json:"demo"` - Pass bool `json:"pass"` - Reason string `json:"reason,omitempty"` + Demo string `json:"demo"` + Pass bool `json:"pass"` + Reason string `json:"reason,omitempty"` Projection engine.ReplicaProjection `json:"projection"` } @@ -221,7 +221,10 @@ func runValidationPass(state *ops.State, volumeID string, pubOpts ...authority.P _, _ = primaryStore.Write(i, data) } _, _ = primaryStore.Sync() - blocks := primaryStore.AllBlocks() + blocks, err := primaryStore.AllBlocks() + if err != nil { + return nil, fmt.Errorf("snapshot primary: %w", err) + } _, _, pH := primaryStore.Boundaries() for lba, data := range blocks { _ = replicaStore.ApplyEntry(lba, data, pH) diff --git a/seaweed-block/core/adapter/handoff_test.go b/seaweed-block/core/adapter/handoff_test.go index 83bd09acc3..f7f8187fc5 100644 --- a/seaweed-block/core/adapter/handoff_test.go +++ b/seaweed-block/core/adapter/handoff_test.go @@ -263,7 +263,10 @@ func TestHandoff_RejoinAfterNewPrimary_DataConsistent(t *testing.T) { waitRecoveredHealthy(t, adapterB, "r1", 3*time.Second) // Every LBA that B wrote must match on the replica. - allB := primaryB.AllBlocks() + allB, snapshotErr := primaryB.AllBlocks() + if snapshotErr != nil { + t.Fatal(snapshotErr) + } for lba, expected := range allB { got, err := replica.Read(lba) if err != nil { diff --git a/seaweed-block/core/calibration/harness.go b/seaweed-block/core/calibration/harness.go index 500fdada44..b7b2e8d4af 100644 --- a/seaweed-block/core/calibration/harness.go +++ b/seaweed-block/core/calibration/harness.go @@ -67,7 +67,10 @@ func (h *harness) writeBlocks(n uint32) { // and marks the replica's synced frontier at the primary's head. Used // by C1 setup where the replica is already caught up. func (h *harness) mirrorToReplica() { - blocks := h.primaryStore.AllBlocks() + blocks, err := h.primaryStore.AllBlocks() + if err != nil { + panic(fmt.Errorf("calibration snapshot: %w", err)) + } _, _, pH := h.primaryStore.Boundaries() for lba, data := range blocks { _ = h.replicaStore.ApplyEntry(lba, data, pH) @@ -120,7 +123,10 @@ func (h *harness) commandLog() []string { // dataMatches returns true iff every LBA that exists on the primary is // byte-identical on the replica. Used for C2/C3 data-integrity evidence. func (h *harness) dataMatches() bool { - primary := h.primaryStore.AllBlocks() + primary, err := h.primaryStore.AllBlocks() + if err != nil { + return false + } for lba, want := range primary { got, err := h.replicaStore.Read(lba) if err != nil { diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 10f156e3fb..e8f388bc46 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -688,6 +688,11 @@ func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int b.profile.recordBackendWriteRequest(len(p)) start := time.Now() n, err := b.writeBytes(ctx, offset, p) + if hydrationPendingOnly(err) { + if gateErr := b.gate(); gateErr != nil { + return 0, gateErr + } + } if errors.Is(err, storage.ErrWALPressureTimeout) || hydrationPendingOnly(err) { err = fmt.Errorf("%w: %w", frontend.ErrBackendBusy, err) } diff --git a/seaweed-block/core/recovery/receiver_base_pin_test.go b/seaweed-block/core/recovery/receiver_base_pin_test.go index 9608f3b1e3..0a305db5f5 100644 --- a/seaweed-block/core/recovery/receiver_base_pin_test.go +++ b/seaweed-block/core/recovery/receiver_base_pin_test.go @@ -196,7 +196,7 @@ func (s *receiverAckStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error func (s *receiverAckStore) WriteExtentDirect(lba uint32, data []byte) error { return nil } -func (s *receiverAckStore) AllBlocks() map[uint32][]byte { return nil } +func (s *receiverAckStore) AllBlocks() (map[uint32][]byte, error) { return nil, nil } func (s *receiverAckStore) ScanLBAs(fromLSN uint64, fn func(storage.RecoveryEntry) error) error { return nil diff --git a/seaweed-block/core/replication/component/cluster.go b/seaweed-block/core/replication/component/cluster.go index 9310f8eb69..d1ce45f6d8 100644 --- a/seaweed-block/core/replication/component/cluster.go +++ b/seaweed-block/core/replication/component/cluster.go @@ -793,7 +793,10 @@ func (c *Cluster) allConverged() bool { } func (c *Cluster) replicaConverged(r *ReplicaNode) bool { - pBlocks := c.primary.Store.AllBlocks() + pBlocks, err := c.primary.Store.AllBlocks() + if err != nil { + return false + } for lba, pData := range pBlocks { rData, _ := r.Store.Read(lba) if !bytes.Equal(pData, rData) { @@ -816,7 +819,10 @@ func (c *Cluster) divergenceReport() string { func (c *Cluster) divergenceReportFor(r *ReplicaNode) string { var diffs []string - pBlocks := c.primary.Store.AllBlocks() + pBlocks, err := c.primary.Store.AllBlocks() + if err != nil { + return fmt.Sprintf("primary snapshot failed: %v", err) + } for lba, pData := range pBlocks { rData, _ := r.Store.Read(lba) if !bytes.Equal(pData, rData) { diff --git a/seaweed-block/core/storage/chunk_hydration_budget_test.go b/seaweed-block/core/storage/chunk_hydration_budget_test.go index 4f8ba00980..1f224970e3 100644 --- a/seaweed-block/core/storage/chunk_hydration_budget_test.go +++ b/seaweed-block/core/storage/chunk_hydration_budget_test.go @@ -79,3 +79,18 @@ func TestChunkHydration_ContextlessReadAllowsSlowFill(t *testing.T) { t.Fatal("contextless reader did not settle after release") } } + +func TestChunkHydration_SnapshotFailsOnReadError(t *testing.T) { + s, _, remote, _ := hydrationFixture(t, 2, 64) + if _, err := s.Write(0, makeBlock(ctBlockSize, 0x77)); err != nil { + t.Fatal(err) + } + fault := errors.New("remote snapshot read fault") + remote.mu.Lock() + remote.failGet = fault + remote.mu.Unlock() + got, err := s.AllBlocks() + if !errors.Is(err, fault) || got != nil { + t.Fatalf("snapshot silently lost unreadable blocks: entries=%d err=%v", len(got), err) + } +} diff --git a/seaweed-block/core/storage/contract_test.go b/seaweed-block/core/storage/contract_test.go index 9e63b2e04c..8c1fccbc09 100644 --- a/seaweed-block/core/storage/contract_test.go +++ b/seaweed-block/core/storage/contract_test.go @@ -316,7 +316,10 @@ func TestContract_AllBlocksReturnsCurrentSnapshot(t *testing.T) { _, _ = store.Write(0, makeBlock(store.BlockSize(), 0x01)) _, _ = store.Write(2, makeBlock(store.BlockSize(), 0x02)) _, _ = store.Write(5, makeBlock(store.BlockSize(), 0x05)) - all := store.AllBlocks() + all, snapshotErr := store.AllBlocks() + if snapshotErr != nil { + t.Fatal(snapshotErr) + } if len(all) != 3 { t.Fatalf("AllBlocks: got %d entries, want 3", len(all)) } diff --git a/seaweed-block/core/storage/flusher_test.go b/seaweed-block/core/storage/flusher_test.go index 9155b34594..3ff75ea1d2 100644 --- a/seaweed-block/core/storage/flusher_test.go +++ b/seaweed-block/core/storage/flusher_test.go @@ -533,7 +533,10 @@ func TestAllBlocks_ReturnsBlocksAfterFlush(t *testing.T) { // AllBlocks must still return both written LBAs even though // they're no longer in the dirty map. - all := s.AllBlocks() + all, snapshotErr := s.AllBlocks() + if snapshotErr != nil { + t.Fatal(snapshotErr) + } if len(all) != 2 { t.Fatalf("AllBlocks after flush returned %d entries, want 2", len(all)) } diff --git a/seaweed-block/core/storage/logical_storage.go b/seaweed-block/core/storage/logical_storage.go index ae87a4bdc8..9fb9a4176d 100644 --- a/seaweed-block/core/storage/logical_storage.go +++ b/seaweed-block/core/storage/logical_storage.go @@ -154,8 +154,9 @@ type LogicalStorage interface { WriteExtentDirect(lba uint32, data []byte) error // AllBlocks snapshots every written LBA's current bytes. Used by - // the rebuild server to enumerate what to ship. - AllBlocks() map[uint32][]byte + // the rebuild server to enumerate what to ship. Any read error fails + // the whole snapshot; callers must not ship a partial image. + AllBlocks() (map[uint32][]byte, error) // ScanLBAs is the T4c-2 tier-1 recovery contract. Emits a // RecoveryEntry callback for each modification the substrate diff --git a/seaweed-block/core/storage/memorywal/store.go b/seaweed-block/core/storage/memorywal/store.go index 58d23617c2..4651dc8999 100644 --- a/seaweed-block/core/storage/memorywal/store.go +++ b/seaweed-block/core/storage/memorywal/store.go @@ -303,7 +303,7 @@ func (s *Store) WriteExtentDirect(lba uint32, data []byte) error { // AllBlocks returns last-writer-wins per LBA across retained records, // filtering out all-zero blocks (matches the LogicalStorage contract). -func (s *Store) AllBlocks() map[uint32][]byte { +func (s *Store) AllBlocks() (map[uint32][]byte, error) { s.mu.RLock() defer s.mu.RUnlock() latest := make(map[uint32][]byte) @@ -329,7 +329,7 @@ func (s *Store) AllBlocks() map[uint32][]byte { delete(latest, lba) } } - return latest + return latest, nil } // ScanLBAs is V2-faithful: emits each retained WAL record with its diff --git a/seaweed-block/core/storage/memorywal/store_test.go b/seaweed-block/core/storage/memorywal/store_test.go index 1cbeffa22d..4f97e3d6b6 100644 --- a/seaweed-block/core/storage/memorywal/store_test.go +++ b/seaweed-block/core/storage/memorywal/store_test.go @@ -316,10 +316,14 @@ func TestAllBlocks_LastWriterWins_FiltersZeros(t *testing.T) { s := NewStore(numBlocks, blockSize) _, _ = s.Write(0, mkBlock(0xAA)) _, _ = s.Write(1, mkBlock(0xBB)) - _, _ = s.Write(0, mkBlock(0xCC)) // overwrites lba 0 + _, _ = s.Write(0, mkBlock(0xCC)) // overwrites lba 0 _, _ = s.Write(2, make([]byte, blockSize)) // zero block — should be filtered - all := s.AllBlocks() + all, snapshotErr := s.AllBlocks() + + if snapshotErr != nil { + t.Fatal(snapshotErr) + } if len(all) != 2 { t.Fatalf("AllBlocks: got %d want 2 (lba 2 should be filtered as zero)", len(all)) } diff --git a/seaweed-block/core/storage/parallelwal/store.go b/seaweed-block/core/storage/parallelwal/store.go index 863b8795ac..7c3139a956 100644 --- a/seaweed-block/core/storage/parallelwal/store.go +++ b/seaweed-block/core/storage/parallelwal/store.go @@ -1330,16 +1330,19 @@ func (s *Store) resetBaseStageUnderSync() error { return nil } -func (s *Store) AllBlocks() map[uint32][]byte { +func (s *Store) AllBlocks() (map[uint32][]byte, error) { out := make(map[uint32][]byte) zero := make([]byte, s.blockSize) for lba := uint32(0); lba < s.numBlocks; lba++ { data, err := s.Read(lba) - if err == nil && !bytes.Equal(data, zero) { + if err != nil { + return nil, fmt.Errorf("snapshot LBA %d: %w", lba, err) + } + if !bytes.Equal(data, zero) { out[lba] = data } } - return out + return out, nil } func (s *Store) ScanLBAs(fromLSN uint64, fn func(storage.RecoveryEntry) error) error { diff --git a/seaweed-block/core/storage/smartwal/recovery_scan_test.go b/seaweed-block/core/storage/smartwal/recovery_scan_test.go index b5c0c3c899..2449bcd935 100644 --- a/seaweed-block/core/storage/smartwal/recovery_scan_test.go +++ b/seaweed-block/core/storage/smartwal/recovery_scan_test.go @@ -230,7 +230,11 @@ func TestSmartwalRecovery_AllBlocks_DeterministicOrdering(t *testing.T) { t.Fatalf("Sync: %v", err) } - got := s.AllBlocks() + got, snapshotErr := s.AllBlocks() + + if snapshotErr != nil { + t.Fatal(snapshotErr) + } if len(got) != len(expected) { t.Fatalf("AllBlocks size: got %d want %d", len(got), len(expected)) } @@ -420,7 +424,10 @@ func TestSmartwalRecovery_Sanity_ExistingAPIsUnchanged(t *testing.T) { } // AllBlocks still works. - all := s.AllBlocks() + all, snapshotErr := s.AllBlocks() + if snapshotErr != nil { + t.Fatal(snapshotErr) + } if len(all) != 1 { t.Fatalf("AllBlocks: got %d want 1", len(all)) } diff --git a/seaweed-block/core/storage/smartwal/store.go b/seaweed-block/core/storage/smartwal/store.go index e054fa170e..b51d3f9bc9 100644 --- a/seaweed-block/core/storage/smartwal/store.go +++ b/seaweed-block/core/storage/smartwal/store.go @@ -502,12 +502,12 @@ func (s *Store) AppliedLSNs() (map[uint32]uint64, error) { // AllBlocks snapshots every LBA's current bytes by reading directly // from the extent. Linear scan — N reads — but in practice the // rebuild server is the only caller and runs once per session. -func (s *Store) AllBlocks() map[uint32][]byte { +func (s *Store) AllBlocks() (map[uint32][]byte, error) { out := make(map[uint32][]byte, s.hdr.NumBlocks) for lba := uint32(0); lba < s.hdr.NumBlocks; lba++ { data, err := s.Read(lba) if err != nil { - continue + return nil, fmt.Errorf("snapshot LBA %d: %w", lba, err) } // Only include LBAs with non-zero content — preserves the // "snapshot of dirty bits" semantics callers expect. @@ -522,7 +522,7 @@ func (s *Store) AllBlocks() map[uint32][]byte { out[lba] = data } } - return out + return out, nil } // Close fsyncs and releases the file. Idempotent. diff --git a/seaweed-block/core/storage/store.go b/seaweed-block/core/storage/store.go index aba2b02013..fc901ce3b3 100644 --- a/seaweed-block/core/storage/store.go +++ b/seaweed-block/core/storage/store.go @@ -316,7 +316,7 @@ func (s *BlockStore) WriteExtentDirect(lba uint32, data []byte) error { } // AllBlocks returns all written LBAs and their data (for rebuild serving). -func (s *BlockStore) AllBlocks() map[uint32][]byte { +func (s *BlockStore) AllBlocks() (map[uint32][]byte, error) { s.mu.RLock() defer s.mu.RUnlock() result := make(map[uint32][]byte, len(s.blocks)) @@ -325,5 +325,5 @@ func (s *BlockStore) AllBlocks() map[uint32][]byte { copy(cp, data) result[lba] = cp } - return result + return result, nil } diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 12b694b12a..754caec8d4 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -1597,14 +1597,14 @@ func (s *WALStore) AppliedLSNs() (map[uint32]uint64, error) { // Linear scan over numBlocks. Acceptable for the rebuild path // (one-shot, off the hot read/write loop). Not appropriate for // a hot-path scan. -func (s *WALStore) AllBlocks() map[uint32][]byte { +func (s *WALStore) AllBlocks() (map[uint32][]byte, error) { n := s.NumBlocks() out := make(map[uint32][]byte) zero := make([]byte, s.sb.BlockSize) for lba := uint32(0); lba < n; lba++ { data, err := s.Read(lba) if err != nil { - continue + return nil, fmt.Errorf("snapshot LBA %d: %w", lba, err) } // Skip never-written / trimmed LBAs. if bytesAllZero(data, zero) { @@ -1612,7 +1612,7 @@ func (s *WALStore) AllBlocks() map[uint32][]byte { } out[lba] = data } - return out + return out, nil } // bytesAllZero is a fast tight-loop equality against a zero slice. diff --git a/seaweed-block/core/storage/walstore_recovery_test.go b/seaweed-block/core/storage/walstore_recovery_test.go index 5d70171d6f..3f30633e4f 100644 --- a/seaweed-block/core/storage/walstore_recovery_test.go +++ b/seaweed-block/core/storage/walstore_recovery_test.go @@ -245,7 +245,11 @@ func TestWalstoreRecovery_AllBlocks_DeterministicOrdering(t *testing.T) { t.Fatalf("Sync: %v", err) } - got := s.AllBlocks() + got, snapshotErr := s.AllBlocks() + + if snapshotErr != nil { + t.Fatal(snapshotErr) + } if len(got) != len(expected) { t.Fatalf("AllBlocks size: got %d want %d", len(got), len(expected)) } @@ -418,7 +422,10 @@ func TestWalstoreRecovery_Sanity_ExistingAPIsUnchanged(t *testing.T) { if got[0] != 0x42 { t.Fatalf("Read[0]=%02x want 42", got[0]) } - all := s.AllBlocks() + all, snapshotErr := s.AllBlocks() + if snapshotErr != nil { + t.Fatal(snapshotErr) + } if len(all) != 1 { t.Fatalf("AllBlocks: got %d want 1", len(all)) } diff --git a/seaweed-block/core/transport/rebuild_sender.go b/seaweed-block/core/transport/rebuild_sender.go index a1515e6bdb..90f776d387 100644 --- a/seaweed-block/core/transport/rebuild_sender.go +++ b/seaweed-block/core/transport/rebuild_sender.go @@ -110,7 +110,10 @@ func (e *BlockExecutor) doRebuild(replicaID string, session *activeSession, fron }() e.signalSessionStart(replicaID, session.lineage.SessionID) - blocks := e.primaryStore.AllBlocks() + blocks, err := e.primaryStore.AllBlocks() + if err != nil { + return 0, fmt.Errorf("rebuild snapshot: %w", err) + } lbas := make([]int, 0, len(blocks)) for lba := range blocks { lbas = append(lbas, int(lba)) diff --git a/seaweed-block/core/transport/rebuild_snapshot_error_test.go b/seaweed-block/core/transport/rebuild_snapshot_error_test.go new file mode 100644 index 0000000000..0206108a57 --- /dev/null +++ b/seaweed-block/core/transport/rebuild_snapshot_error_test.go @@ -0,0 +1,45 @@ +package transport + +import ( + "errors" + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/storage" + "strings" + "testing" + "time" +) + +type failedRebuildSnapshot struct{ storage.LogicalStorage } + +func (*failedRebuildSnapshot) AllBlocks() (map[uint32][]byte, error) { + return map[uint32][]byte{0: makeData(0x77)}, errors.New("snapshot read fault") +} +func TestRebuildSnapshotErrorNeverShipsPartialImage(t *testing.T) { + replica := storage.NewBlockStore(64, 4096) + listener, err := NewReplicaListener("127.0.0.1:0", replica) + if err != nil { + t.Fatal(err) + } + listener.Serve() + defer listener.Stop() + primary := &failedRebuildSnapshot{storage.NewBlockStore(64, 4096)} + exec := NewBlockExecutor(primary, listener.Addr()) + defer exec.Stop() + closed := make(chan adapter.SessionCloseResult, 1) + exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closed <- r }) + before := replica.NextLSN() + if err := exec.StartRebuild("r1", 1, 1, 1, 1); err != nil { + t.Fatal(err) + } + select { + case got := <-closed: + if got.Success || !strings.Contains(got.FailReason, "snapshot read fault") { + t.Fatalf("snapshot error lost: %+v", got) + } + case <-time.After(3 * time.Second): + t.Fatal("snapshot failure did not settle rebuild") + } + if replica.NextLSN() != before { + t.Fatal("failed snapshot shipped a partial image") + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 46d9626ee7..7958791883 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -177,7 +177,6 @@ stateDiagram-v2 | Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | | Holder | HolderFenced | a HEAD with a higher epoch, or another holder at the same epoch | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | -| `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet` | — | ACTIVE | | Holder | (hydration wait) | one request deadline covers all missing chunks; callers may detach, but bounded per-layer workers retain and join each shared fill; HEAD/generation/local-write checks still govern installation | `core/storage/chunk_hydration.go`; `core/frontend/durable/storage_adapter.go` `readStorageBlock` | `INV-CUT-HYDRATION-WAIT-001`, `INV-CUT-READMISS-001` | ### M5 The cut pipeline @@ -448,7 +447,10 @@ Notes: | `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE | | `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut, an intent naming every new key is durable, and it is removed only after the CAS outcome is known. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | | `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | +| `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet` | — | ACTIVE | | `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | +A guest read has a cooperative arrival budget; internal contextless readers keep the owned fill timeout (default 30 s). With five immediate host retries, cold fills slower than roughly 20–24 s can still end in guest EIO despite shared work; retry-delay advertisement remains separate. A changed generation replaces its promise without abandoning the old worker. `AllBlocks` returns an error and no partial image on a failed read; the rebuild sender propagates it before sending blocks. + Notes: From a3bc6aa51f0e3c5b1a4dc33fb2188c6c71054e41 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 11:20:14 -0800 Subject: [PATCH 144/150] docs: align hydration diagram with caller and worker lifetimes --- seaweed-block/docs/design/agent-workspace-design.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 48b9ca7a58..cbf8413016 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -51,6 +51,8 @@ flowchart LR H -->|"snapshot / fork = copy the root"| H2["snapshot or forked volume"] M["blockmaster: epoch + lease"] -->|"higher epoch"| T["another host: claim HEAD, lazy-load chunks"] T --> H + F -->|"one arrival deadline"| Q["bounded per-chunk shared hydration"] + Q -->|"owned fetch, caller may detach"| S ``` - **Frontend:** the same ublk and NVMe/TCP code as the Kubernetes line ([core §1.1](block-design.md#11-frontends-and-the-backend-contract)). NVMe/TCP binds to loopback (`cmd/blockvolume/main.go` `enforceFrontendLoopbackBind`); ublk serves `/dev/ublkbN` on the same host (`--ublk-device`). The guest sees a plain virtio block device that the hypervisor attaches. @@ -133,7 +135,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto `ChunkRemote.CASHead` (`core/frontend/chunkstore/chunk_remote.go`) refuses a lower epoch, any move of a `deleting`, `purging` or `deleted` HEAD, a `{gen, epoch}` mismatch and a lower `RemoteLSN`, then issues the filer's conditional `UpdateEntry` with `expected_extended = {swb.gen, swb.epoch}`. Only a definite refusal is a precondition failure; any other error is an unknown outcome. -**Reads after a move.** A block absent locally is fetched from the chunk named in HEAD, bounded by `ReadMissTimeout` (default 30 s), and installed only if it does not overwrite a newer local extent version; the dirty map is consulted again after the fetch, so a newer WAL-only write still wins on reads, and HEAD's value may sit beneath it as the backing value, which is correct if a crash loses that unsynced write (`OnReadMiss`; walstore `readFromExtent`). +**Reads after a move.** A block absent locally is fetched from the chunk named in HEAD, by a bounded per-chunk shared worker. Frontend callers share their arrival deadline across attach and all missing chunks; contextless internal readers retain `ReadMissTimeout` (default 30 s). Fetched bytes are installed only if it does not overwrite a newer local extent version; the dirty map is consulted again after the fetch, so a newer WAL-only write still wins on reads, and HEAD's value may sit beneath it as the backing value, which is correct if a crash loses that unsynced write (`OnReadMiss`; walstore `readFromExtent`). ### Copy-before-write in the cut window (native v3 implementation) From 518f8d14058778f3d9f0e9c74a97efdcaa410a9d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 11:21:56 -0800 Subject: [PATCH 145/150] test: keep replacement flight when stale worker settles --- .../chunk_hydration_concurrency_test.go | 77 ++++++++++++++++++- 1 file changed, 74 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go index 6b0c8f8866..575e90b035 100644 --- a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go +++ b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go @@ -282,9 +282,10 @@ func TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet(t *testing.T) // Only the old generation ignores cancellation; a spare worker can serve the new one. type staleHydrationRemote struct { *fakeChunkRemote - oldKey string - entered, release chan struct{} - once sync.Once + oldKey string + newEntered, newRelease chan struct{} + entered, release chan struct{} + once sync.Once } func (r *staleHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) { @@ -293,6 +294,17 @@ func (r *staleHydrationRemote) Get(ctx context.Context, key string) ([]byte, err <-r.release return r.fakeChunkRemote.Get(context.Background(), key) } + if r.newRelease != nil { + select { + case r.newEntered <- struct{}{}: + default: + } + select { + case <-r.newRelease: + case <-ctx.Done(): + return nil, ctx.Err() + } + } return r.fakeChunkRemote.Get(ctx, key) } func TestChunkHydration_NewGenerationDoesNotJoinStaleGet(t *testing.T) { @@ -334,3 +346,62 @@ func TestChunkHydration_NewGenerationDoesNotJoinStaleGet(t *testing.T) { t.Fatalf("old waiter failed to follow new generation: %v", got.err) } } + +func TestChunkHydration_StaleCompletionKeepsReplacement(t *testing.T) { + s, layer, remote, registered := hydrationFixture(t, 2, 64) + layer.stMu.Lock() + oldRef, newRef := layer.head.Chunks[2], layer.head.Chunks[3] + layer.stMu.Unlock() + r := &staleHydrationRemote{fakeChunkRemote: remote, oldKey: oldRef.Key, entered: make(chan struct{}), release: make(chan struct{}), newEntered: make(chan struct{}, 1), newRelease: make(chan struct{})} + layer.remote = r + var oldOnce, newOnce sync.Once + releaseOld := func() { oldOnce.Do(func() { close(r.release) }) } + releaseNew := func() { newOnce.Do(func() { close(r.newRelease) }) } + t.Cleanup(func() { releaseOld(); releaseNew() }) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + old := startHydrationRead(t, s, ctx, 8) + waitHydrationRegistration(t, registered, 1) + select { + case <-r.entered: + case <-time.After(ctLocalBound): + t.Fatal("old Get not entered") + } + layer.stMu.Lock() + layer.head.Chunks[2] = newRef + layer.absentGen[2]++ + layer.stMu.Unlock() + newer := startHydrationRead(t, s, ctx, 8) + select { + case <-r.newEntered: + case <-time.After(ctLocalBound): + t.Fatal("replacement Get not entered") + } + layer.stMu.Lock() + replacement := layer.hydration[2] + layer.stMu.Unlock() + releaseOld() + deadline := time.NewTimer(time.Second) + defer deadline.Stop() + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for layer.Stats().Hydration.Active != 1 { + select { + case <-tick.C: + case <-deadline.C: + t.Fatal("stale worker did not settle") + } + } + layer.stMu.Lock() + kept := layer.hydration[2] == replacement + layer.stMu.Unlock() + if !kept { + t.Fatal("stale completion removed replacement promise") + } + releaseNew() + for _, result := range []<-chan hydrationResult{old, newer} { + if got := hydrationOutcome(t, result); got.err != nil || !bytes.Equal(got.data, makeBlock(ctBlockSize, 0x4c)) { + t.Fatalf("replacement data: %v", got.err) + } + } +} From add6fc6e3d143a1bc6af4c2a59d7dbb615bae416 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 11:24:44 -0800 Subject: [PATCH 146/150] docs: bind hydration and rebuild error regressions in ledger --- 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 7958791883..30b2ec535b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -316,6 +316,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| +| `INV-REBUILD-SNAPSHOT-COMPLETE-001` | A rebuild snapshot returns all readable nonzero blocks or an error, never a partial success. The sender propagates snapshot failure before shipping blocks or RebuildDone. | M1 Recovering (base enumeration) | `core/storage/logical_storage.go` `AllBlocks`; storage implementations; `core/transport/rebuild_sender.go` `doRebuild` | `TestChunkHydration_SnapshotFailsOnReadError`, `TestRebuildSnapshotErrorNeverShipsPartialImage` | Existing fail-closed recovery contract; error propagation only | ACTIVE | | `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | | `INV-FE-NVME-READY-001` | Reads and writes on successfully recovered chunk volumes awaiting attachment wait up to 3s (or an earlier caller deadline) for attachment readiness before storage admission; NVMe readiness timeout/refusal returns Namespace Not Ready (SC0x82), DNR=0, without reading or mutating storage; closed/stale lineage retain their ANA errors and physical I/O faults retain Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable`; `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` | — | ACTIVE | @@ -447,7 +448,7 @@ Notes: | `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE | | `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut, an intent naming every new key is durable, and it is removed only after the CAS outcome is known. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | | `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | -| `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet` | — | ACTIVE | +| `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE | | `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | A guest read has a cooperative arrival budget; internal contextless readers keep the owned fill timeout (default 30 s). With five immediate host retries, cold fills slower than roughly 20–24 s can still end in guest EIO despite shared work; retry-delay advertisement remains separate. A changed generation replaces its promise without abandoning the old worker. `AllBlocks` returns an error and no partial image on a failed read; the rebuild sender propagates it before sending blocks. From 590337c058a1555b8e7bdc81b94b7195d3a424a4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 11:29:32 -0800 Subject: [PATCH 147/150] test: witness the RMW fence before actual caller expiry --- seaweed-block/core/frontend/durable/hydration_budget_test.go | 3 +-- seaweed-block/docs/design/agent-workspace-design.md | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/frontend/durable/hydration_budget_test.go b/seaweed-block/core/frontend/durable/hydration_budget_test.go index 08f505b7a0..4332142ec0 100644 --- a/seaweed-block/core/frontend/durable/hydration_budget_test.go +++ b/seaweed-block/core/frontend/durable/hydration_budget_test.go @@ -331,7 +331,7 @@ func TestDurableHydration_RMWFenceWinsCallerExpiry(t *testing.T) { t.Fatal(err) } before := store.NextLSN() - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) defer cancel() joined := make(chan struct{}) result := make(chan error, 1) @@ -358,7 +358,6 @@ func TestDurableHydration_RMWFenceWinsCallerExpiry(t *testing.T) { t.Fatal("cold read never reached Get") } view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 1})) - cancel() select { case err := <-result: if store.NextLSN() != before { diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index cbf8413016..1b8b2a9554 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -135,7 +135,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto `ChunkRemote.CASHead` (`core/frontend/chunkstore/chunk_remote.go`) refuses a lower epoch, any move of a `deleting`, `purging` or `deleted` HEAD, a `{gen, epoch}` mismatch and a lower `RemoteLSN`, then issues the filer's conditional `UpdateEntry` with `expected_extended = {swb.gen, swb.epoch}`. Only a definite refusal is a precondition failure; any other error is an unknown outcome. -**Reads after a move.** A block absent locally is fetched from the chunk named in HEAD, by a bounded per-chunk shared worker. Frontend callers share their arrival deadline across attach and all missing chunks; contextless internal readers retain `ReadMissTimeout` (default 30 s). Fetched bytes are installed only if it does not overwrite a newer local extent version; the dirty map is consulted again after the fetch, so a newer WAL-only write still wins on reads, and HEAD's value may sit beneath it as the backing value, which is correct if a crash loses that unsynced write (`OnReadMiss`; walstore `readFromExtent`). +**Reads after a move.** A block absent locally is fetched from the chunk named in HEAD, by a bounded per-chunk shared worker. Frontend callers share their arrival deadline across attach and all missing chunks; contextless internal readers retain `ReadMissTimeout` (default 30 s). Fetched bytes are installed only if they do not overwrite a newer local extent version; the dirty map is consulted again after the fetch, so a newer WAL-only write still wins on reads, and HEAD's value may sit beneath it as the backing value, which is correct if a crash loses that unsynced write (`OnReadMiss`; walstore `readFromExtent`). ### Copy-before-write in the cut window (native v3 implementation) From 2ac398fdd64da75c5552beead6e71c1f6752150c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 11:37:01 -0800 Subject: [PATCH 148/150] docs: tie snapshot refusal to the rebuild machine --- 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 30b2ec535b..0f0bc7958d 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -316,7 +316,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-REBUILD-SNAPSHOT-COMPLETE-001` | A rebuild snapshot returns all readable nonzero blocks or an error, never a partial success. The sender propagates snapshot failure before shipping blocks or RebuildDone. | M1 Recovering (base enumeration) | `core/storage/logical_storage.go` `AllBlocks`; storage implementations; `core/transport/rebuild_sender.go` `doRebuild` | `TestChunkHydration_SnapshotFailsOnReadError`, `TestRebuildSnapshotErrorNeverShipsPartialImage` | Existing fail-closed recovery contract; error propagation only | ACTIVE | +| `INV-REBUILD-SNAPSHOT-COMPLETE-001` | A rebuild snapshot returns all readable nonzero blocks or an error, never a partial success. The sender propagates snapshot failure before shipping blocks or RebuildDone. | M3 NeedsRebuild (base enumeration) | `core/storage/logical_storage.go` `AllBlocks`; storage implementations; `core/transport/rebuild_sender.go` `doRebuild` | `TestChunkHydration_SnapshotFailsOnReadError`, `TestRebuildSnapshotErrorNeverShipsPartialImage` | Existing fail-closed recovery contract; error propagation only | ACTIVE | | `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | | `INV-FE-NVME-READY-001` | Reads and writes on successfully recovered chunk volumes awaiting attachment wait up to 3s (or an earlier caller deadline) for attachment readiness before storage admission; NVMe readiness timeout/refusal returns Namespace Not Ready (SC0x82), DNR=0, without reading or mutating storage; closed/stale lineage retain their ANA errors and physical I/O faults retain Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable`; `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` | — | ACTIVE | From 7fd4c8491aab836360f22c59fabcd2d0e918e550 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 11:38:41 -0800 Subject: [PATCH 149/150] durable: keep any committed prefix when RMW observes fencing --- .../frontend/durable/hydration_budget_test.go | 58 ++++++++++++++++++- .../core/frontend/durable/storage_adapter.go | 2 +- 2 files changed, 57 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/frontend/durable/hydration_budget_test.go b/seaweed-block/core/frontend/durable/hydration_budget_test.go index 4332142ec0..f19d4f49c6 100644 --- a/seaweed-block/core/frontend/durable/hydration_budget_test.go +++ b/seaweed-block/core/frontend/durable/hydration_budget_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "errors" - "fmt" "sync" "sync/atomic" "testing" @@ -348,7 +347,7 @@ func TestDurableHydration_RMWFenceWinsCallerExpiry(t *testing.T) { defer close(joined) n, err := b.Write(ctx, 33*4096+1, []byte{0x74}) if n != 0 { - err = fmt.Errorf("unexpected RMW prefix %d: %w", n, err) + t.Errorf("unexpected RMW prefix %d: %v", n, err) } result <- err }() @@ -370,3 +369,58 @@ func TestDurableHydration_RMWFenceWinsCallerExpiry(t *testing.T) { t.Fatal("fenced waiter did not detach") } } + +func TestDurableHydration_RMWFenceKeepsCommittedPrefix(t *testing.T) { + r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)} + view := v1View() + p := chunkProvider(t, t.TempDir(), r, view, 0) + t.Cleanup(r.release) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + store, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + before := store.NextLSN() + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + joined := make(chan struct{}) + result := make(chan error, 1) + t.Cleanup(func() { + cancel() + r.release() + select { + case <-joined: + case <-time.After(time.Second): + t.Error("fenced hydration waiter not joined") + } + }) + go func() { + defer close(joined) + n, err := b.Write(ctx, 32*4096, bytes.Repeat([]byte{0x74}, 4097)) + if n != 4096 { + t.Errorf("unexpected RMW prefix %d: %v", n, err) + } + result <- err + }() + select { + case <-r.entered: + case <-time.After(time.Second): + t.Fatal("cold read never reached Get") + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 1})) + select { + case err := <-result: + if store.NextLSN() != before+1 { + t.Fatal("fenced RMW lost its exact committed prefix") + } + if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("expiry hid fencing: %v", err) + } + case <-time.After(time.Second): + t.Fatal("fenced waiter did not detach") + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index e8f388bc46..83545e2a54 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -690,7 +690,7 @@ func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int n, err := b.writeBytes(ctx, offset, p) if hydrationPendingOnly(err) { if gateErr := b.gate(); gateErr != nil { - return 0, gateErr + err = gateErr } } if errors.Is(err, storage.ErrWALPressureTimeout) || hydrationPendingOnly(err) { From c25331967889d3f8888995fbcbe67616d774fab4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 13:17:54 -0800 Subject: [PATCH 150/150] test: retain one deadline across attachment and hydration --- .../durable/attach_hydration_composed_test.go | 161 ++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/attach_hydration_composed_test.go diff --git a/seaweed-block/core/frontend/durable/attach_hydration_composed_test.go b/seaweed-block/core/frontend/durable/attach_hydration_composed_test.go new file mode 100644 index 0000000000..7f56987580 --- /dev/null +++ b/seaweed-block/core/frontend/durable/attach_hydration_composed_test.go @@ -0,0 +1,161 @@ +package durable + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" + "sync" + "sync/atomic" + "testing" + "time" +) + +type cumulativeReadStorage struct { + storage.LogicalStorage + remaining time.Duration +} + +func (s *cumulativeReadStorage) Read(uint32) ([]byte, error) { + time.Sleep(2750 * time.Millisecond) + return make([]byte, 4096), nil +} +func (s *cumulativeReadStorage) ReadContext(ctx context.Context, _ uint32) ([]byte, error) { + deadline, _ := ctx.Deadline() + s.remaining = time.Until(deadline) + timer := time.NewTimer(2750 * time.Millisecond) + defer timer.Stop() + select { + case <-timer.C: + return make([]byte, 4096), nil + case <-ctx.Done(): + return nil, errors.Join(storage.ErrChunkHydrationPending, ctx.Err()) + } +} +func TestAttachAndHydrationUseOneArrivalDeadline(t *testing.T) { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + store := &cumulativeReadStorage{} + b := &StorageBackend{storage: store, blockSize: 4096, id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}} + b.setChunkAttachPending("pending") + var once sync.Once + var timer *time.Timer + fired := make(chan struct{}) + b.testBeforeReadReadyWait = func() { + once.Do(func() { + timer = time.AfterFunc(2500*time.Millisecond, func() { defer close(fired); b.SetOperational(true, "attached") }) + }) + } + defer func() { + if timer != nil && !timer.Stop() { + <-fired + } + }() + start := time.Now() + n, err := b.Read(context.Background(), 0, make([]byte, 4096)) + elapsed := time.Since(start) + if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) || elapsed >= 5*time.Second || store.remaining > 2*time.Second { + t.Fatalf("n=%d err=%v elapsed=%s hydration remaining=%s", n, err, elapsed, store.remaining) + } + t.Logf("combined attach+hydration: %s; remaining at hydration: %s", elapsed, store.remaining) +} + +// Both the command context and the capped attach context use this same +// absolute deadline. Hold the registered wait until it has expired so +// notification selection cannot accidentally make the oracle pass. +type combinedReadProbe struct { + storage.LogicalStorage + calls atomic.Int32 +} + +func (s *combinedReadProbe) Read(uint32) ([]byte, error) { + s.calls.Add(1) + return make([]byte, 4096), nil +} +func (s *combinedReadProbe) ReadContext(context.Context, uint32) ([]byte, error) { + s.calls.Add(1) + return make([]byte, 4096), nil +} +func TestCombinedRead_TiedAttachAndCommandDeadline(t *testing.T) { + for _, state := range []string{"pending", "published", "fenced"} { + t.Run(state, func(t *testing.T) { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + probe := &combinedReadProbe{} + b := &StorageBackend{storage: probe, blockSize: 4096, id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}} + b.setChunkAttachPending("pending") + // Queue residence consumes three seconds of the original four-second + // allowance. The attach child's three-second limit is capped by it. + ctx, cancel := frontend.WithReadBudget(context.Background(), time.Now().Add(-3*time.Second)) + defer cancel() + registered, resume, joined := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once, releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(resume) }) } + b.testBeforeReadReadyWait = func() { once.Do(func() { close(registered) }); <-resume } + result := make(chan error, 1) + t.Cleanup(func() { + cancel() + release() + select { + case <-joined: + case <-time.After(time.Second): + t.Error("combined read did not settle") + } + }) + start := time.Now() + go func() { + defer close(joined) + n, err := b.Read(ctx, 0, make([]byte, 4096)) + if n != 0 { + t.Errorf("expired read returned %d bytes", n) + } + result <- err + }() + select { + case <-registered: + case <-ctx.Done(): + t.Fatal("attach waiter not registered before deadline") + } + <-ctx.Done() + switch state { + case "published": + b.SetOperational(true, "attached at expiry") + case "fenced": + b.mu.Lock() + b.chunkFenced = func() bool { return true } + b.mu.Unlock() + b.SetOperational(false, "fenced at expiry") + } + release() + select { + case err := <-result: + if state == "fenced" { + if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("deadline hid fence: %v", err) + } + } else if !errors.Is(err, frontend.ErrNotReady) || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) || errors.Is(err, storage.ErrChunkHydrationPending) { + t.Fatalf("attach classification must win before hydration: %v", err) + } + case <-time.After(time.Second): + t.Fatal("expired combined read did not return") + } + if probe.calls.Load() != 0 { + t.Fatal("expired command entered storage") + } + if time.Since(start) >= 5*time.Second { + t.Fatal("cooperative combined deadline exceeded command budget") + } + }) + } +} +func TestCombinedRead_ExpiryAfterAdmissionKeepsAttachClassification(t *testing.T) { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + probe := &combinedReadProbe{} + b := &StorageBackend{storage: probe, blockSize: 4096, id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}} + b.SetOperational(true, "attached") + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + b.testBeforeIOLock = func() { <-ctx.Done() } + n, err := b.Read(ctx, 0, make([]byte, 4096)) + if n != 0 || probe.calls.Load() != 0 || !errors.Is(err, frontend.ErrNotReady) || !errors.Is(err, frontend.ErrBackendBusy) || errors.Is(err, storage.ErrChunkHydrationPending) { + t.Fatalf("post-admission expiry: n=%d calls=%d err=%v", n, probe.calls.Load(), err) + } +}