From 089373518abfffb10627b5a2920ba2ab221e92df Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 16:25:22 -0800 Subject: [PATCH 01/57] durable: test: a detach logs when its I/O stop began Red on main: only 'StopIO returned at' is logged, so a test measuring guest errors cannot tell a refusal after the operational flip (by contract) from an admitted I/O that failed. Co-Authored-By: Claude Opus 5.5 --- .../frontend/durable/stopio_began_log_test.go | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/stopio_began_log_test.go diff --git a/seaweed-block/core/frontend/durable/stopio_began_log_test.go b/seaweed-block/core/frontend/durable/stopio_began_log_test.go new file mode 100644 index 0000000000..74b74af80c --- /dev/null +++ b/seaweed-block/core/frontend/durable/stopio_began_log_test.go @@ -0,0 +1,58 @@ +package durable_test + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A detach logs when its I/O stop began (the operational flip, from which +// the backend refuses new I/O) as well as when StopIO returned, both with +// RFC 3339 nanoseconds, so a test measuring guest errors can tell a refusal +// by contract (after the flip) from an admitted I/O that failed. +func TestLiveDetachLogsWhenTheIOStopBegan(t *testing.T) { + p := chunkProvider(t, t.TempDir(), storage.NewMemChunkRemote(), v1View(), time.Hour) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 4096, block(0x51)); err != nil { + t.Fatal(err) + } + logs := &lockedLog{} + captureWriteLogs(t, logs) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + started := time.Now() + if _, _, err := p.DetachVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + ended := time.Now() + + stamp := func(marker string) time.Time { + t.Helper() + var found []time.Time + for _, line := range strings.Split(logs.String(), "\n") { + if _, s, ok := strings.Cut(line, marker); ok { + at, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(s)) + if err != nil { + t.Fatalf("%q: %v", line, err) + } + found = append(found, at) + } + } + if len(found) != 1 { + t.Fatalf("%d lines with %q, want 1:\n%s", len(found), marker, logs.String()) + } + return found[0] + } + began := stamp("volume=v1 I/O stop began at ") + returned := stamp("volume=v1 StopIO returned at ") + if began.Before(started) || returned.Before(began) || ended.Before(returned) { + t.Fatalf("began %s, returned %s: want started %s <= began <= returned <= ended %s", began, returned, started, ended) + } +} From 76e56fc6cdba9d0e3d7be40442dbe58b6afc38f4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 16:25:45 -0800 Subject: [PATCH 02/57] durable: log when a detach's I/O stop began (the operational flip), next to when StopIO returned A guest error after the flip is a refusal by contract; only an error on I/O admitted before the flip is a data-path failure. The detach now logs 'I/O stop began at' (taken just before the flip: plain stop, live StopIO, or the pre-copy TryStopIO) beside 'StopIO returned at', both RFC 3339 nanoseconds, so a measurement can count from the flip (#375). Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider_chunk.go | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index e7a877d293..118aaab786 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -1121,10 +1121,17 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla // the cut gets three quarters, the settlement what is left. The bound is // cooperative (contexts): a syscall that never returns is not bounded here. var start time.Time - var stopIOReturned time.Time + // stopIOBegan is taken just before the operational flip (from then on new + // I/O is refused by contract), stopIOReturned when the admitted I/O has + // drained; both are logged so a measurement can tell a refusal after the + // flip from an admitted I/O that failed. + var stopIOBegan, stopIOReturned time.Time defer func() { if !stopIOReturned.IsZero() { - // Emit after the cut releases its barrier, using the actual return time. + // Emit after the cut releases its barrier, using the actual times. + if !stopIOBegan.IsZero() { + log.Printf("durable: volume=%s I/O stop began at %s", volumeID, stopIOBegan.UTC().Format(time.RFC3339Nano)) + } log.Printf("durable: volume=%s StopIO returned at %s", volumeID, stopIOReturned.UTC().Format(time.RFC3339Nano)) } }() @@ -1194,10 +1201,11 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla // Cancel/join the periodic owner before any final freeze, while serving. p.stopChunkLoop(h) r, err = owner.PrecopyDetachWithAdmission(hostlimit.WithClass(cutCtx, hostlimit.Urgent), h.backend.BeginPrecopyPause, func() bool { + began := time.Now() if !h.backend.TryStopIO("chunk pre-copy: final detached cut") { return false } - stopIOReturned = time.Now() + stopIOBegan, stopIOReturned = began, time.Now() h.chunkDetach = true beginFreeze() return true @@ -1238,6 +1246,7 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla } } else { beginFreeze() + stopIOBegan = time.Now() if plain { if err := h.backend.stopPlainDetachIfIdle(); err != nil { return r, 0, err From 705656010bd028b1e588a7d27929caec0c0bc282 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 16:49:29 -0800 Subject: [PATCH 03/57] docs(invariants): one property per row, third batch (local WAL store) Seventeen over-long rows of the local WAL store (format v3) become 92 rows that state one property each, every statement at most 300 characters. Clauses that only repeated a Part A transition guard point to that transition; the write-admission wait gets its line in the table of bounded waits. The long-statement list shrinks from 18 to 1. Co-Authored-By: Claude Fable 5.2 --- seaweed-block/docs/design/invariants.md | 149 ++++++++++++++---- .../internal/invcheck/invariants_test.go | 2 +- .../invcheck/testdata/long-statements.txt | 17 -- 3 files changed, 123 insertions(+), 45 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 97a87e09e3..f9bc63ebf1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -56,19 +56,19 @@ 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`, `INV-WAL-V3-ACTIVATION-001`, `INV-WAL-V3-DESCRIPTOR-001`, `INV-WAL-V3-MAP-PUBLISH-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 | `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 | `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`, `INV-WAL-FLUSH-SYNC-COVERS-WAL-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 | `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`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-MAP-PUBLISH-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`, `INV-WAL-V3-W-RECOVERY-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`, `INV-WAL-V3-W-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 | `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`, `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`, `INV-WAL-V3-RECLAIM-001`, `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001` | | Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`; `core/storage/walstore_v3.go` `appendWriteV3` | `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` | — | The v2 writer, scanner, checkpoint path, C11 codec/reconciler and in-place converter are retired. Native map and descriptor rules remain enforced; v2 inputs refuse open without mutation. `TestNativeReplacementLegacyBytesRefusedWithoutMutation` and `TestChunkAttachRefusesAnUnmappedNativeStore` cover these admission boundaries. The receiver session bitmap 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 (`INV-WAL-V3-OWNER-001`). Contention refuses open without changing bytes; descriptor close or process exit releases ownership. The offline converter is retired; legacy volumes refuse open unchanged. 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`). +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 (`INV-WAL-V3-OWNER-001`). Contention refuses open without changing bytes; descriptor close or process exit releases ownership. The offline converter is retired; legacy volumes refuse open unchanged. 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-FAIL-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. @@ -403,7 +403,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -216 rows: 193 ACTIVE, 20 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 201 new. +291 rows: 205 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 276 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. @@ -414,38 +414,113 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `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/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `TestNativeReplacementTornWrapKeepsAcknowledgedSuffix` (`core/storage/legacy_replacement_v3_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-FE-NVME-READY-001` | A read or write on a successfully recovered chunk volume awaiting attachment waits for attachment readiness, before storage admission, for at most 3 s or until an earlier caller deadline, on the local monotonic clock. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `admitAfterAttachUnqueued`, `awaitAttachAdmission`, `readyCheck` | `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE | +| `INV-FE-NVME-READY-STATUS-001` | An NVMe read or write whose attachment-readiness wait times out or is refused completes with Namespace Not Ready (SC 0x82), DNR=0, without reading or mutating storage. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` (`core/frontend/durable/takeover_read_ready_test.go`) | — | ACTIVE | +| `INV-FE-NVME-READY-ANA-001` | An I/O that ends during the attachment-readiness wait because the backend closed or its lineage went stale keeps its ANA error, and a physical I/O fault keeps Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE | | `INV-WAL-REPLAY-LWW-001` | Replay of the validated native prefix retains the highest admitted LSN per LBA; invalid cursor, nonce or LSN order is refused. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALLSNOrderV3_RefusesDuplicateAndLower` (`core/storage/wal_lsn_order_v3_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | | `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the both durable descriptor slots has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_io_v3.go` `append`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_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` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`); `TestNativeReplacementCheckpointSIGKILL` (`core/storage/legacy_checkpoint_replacement_v3_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-FRONTIER-GAP-001` | A durable BASE anchor and its contiguous synced install-lane suffix survive recovery; an unpersisted frontier jump is not admitted. | M1 Recovering | `core/storage/walstore_v3.go` `recoverV3` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_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_map_checkpoint_v3.go` `publishCheckpointV3` | `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_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` | `TestNativeReplacementDataFsyncFailureIsSticky` (`core/storage/legacy_replacement_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_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_v3.go` `latchV3`, `appendWriteV3` | `TestNativeReplacementQueuedApplyAfterFailedAppend` (`core/storage/legacy_replacement_v3_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_v3.go` `latchV3`, `appendWriteV3` | `TestNativeReplacementQueuedApplyAfterFailedAppend` (`core/storage/legacy_replacement_v3_test.go`); `TestWALStoreV3AppendWriteErrorLatchesTheStore` (`core/storage/walstore_v3_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`); `TestNativeReplacementSyncCallerReturnOrdering` (`core/storage/legacy_sync_replacement_v3_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` (`core/storage/walstore_activation_test.go`); `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy` (`core/storage/walstore_activation_test.go`); `TestWALStoreProductionCreateOptions` (`core/storage/walstore_activation_test.go`); `TestLegacyFixtureIsolation` (`core/storage/legacy_fixture_isolation_test.go`); `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN` (`core/frontend/durable/provider_format_v3_test.go`); `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` (`core/frontend/durable/provider_format_v3_test.go`); `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE | +| `INV-WAL-V3-ACTIVATION-001` | Public create produces an owned-map v3/impl3 volume with the requested chunk geometry, in mode C unless mode A is requested. | M1 open/create/readonly | `core/storage/walstore.go` `CreateWALStoreWithOptions`; `core/storage/walstore_v3.go` `createWALStoreV3Configured` | `TestWALStoreProductionSelectorCreatesMappedV3`, `TestWALStoreProductionCreateOptions` (`core/storage/walstore_activation_test.go`) | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE | +| `INV-WAL-V3-ACTIVATION-FALLBACK-001` | When descriptor slot A is damaged without being a valid legacy superblock and slot B is valid, writable and read-only open select slot B. | M1 open/create/readonly | `core/storage/walstore_v3.go` `refuseLegacyWALStore`, `openWALStoreV3File`; `core/storage/walstore_readonly_v3.go` `openReadOnlyV3`; `core/storage/superblock_v3.go` `selectSlotV3` | `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy` (`core/storage/walstore_activation_test.go`) | — | ACTIVE | +| `INV-WAL-V3-ACTIVATION-PROVIDER-001` | The durable provider's capture, HEAD restore and status paths probe, open and create volumes through the public v3 selectors (`ProbeWALStoreV3`, `OpenWALStore`, `CreateWALStoreWithOptions`). | M1 open/create/readonly | `core/frontend/durable/provider.go` `openOrCreate` | `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` (`core/frontend/durable/provider_format_v3_test.go`) | — | ACTIVE | +| `INV-WAL-V3-LEGACY-FIXTURE-ISOLATION-001` | No default-build production code calls a legacy fixture constructor, and no legacy fixture is in the transitive import closure of the production storage packages. | M1 open/create/readonly | build layout: legacy fixtures outside the default production import closure | `TestLegacyFixtureIsolation` (`core/storage/legacy_fixture_isolation_test.go`) | — | 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-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB | +| `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | +| `INV-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | STUB | +| `INV-WAL-V3-DESCRIPTOR-CONFLICT-001` | Open is refused when both v3 descriptor slots are valid but carry the same slotGen with different bytes, or disagree on the UUID or the geometry. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3`, `sameGeometryV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`) | — | STUB | +| `INV-WAL-V3-RECORD-001` | An impl-3 WAL record has a fixed 62-byte prefix, 70 bytes of overhead in all, a CRC32C (Castagnoli) and an explicit EntrySize. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `encodeWALEntryV3`, `payloadSizeV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | +| `INV-WAL-V3-RECORD-REFUSE-001` | The impl-3 record codec refuses unknown types or flags, a zero nonce, invalid per-type geometry, overflowing count, LSN, cursor or LBA spans, nonzero padding, a bad CRC or footer, and truncation, before allocating a payload. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `decodeWALEntryV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | — | 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 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-ADMISSION-001` | v3 write admission measures WAL pressure from the active v3 writer's physical head minus the both-slot reuse floor, as a fraction of WALSize. | M1 Serving (write admission) | `core/storage/walstore.go` `openInitializedV3`, `WALStore.walUsedFraction`; `core/storage/write_command_budget.go` `WALStore.writePressureSample` | `TestWALStoreV3AdmissionUsesNativeOccupancy` (`core/storage/walstore_admission_v3_test.go`); `TestWALStoreV3WritePressureSampleMatchesOccupancy` (`core/storage/write_command_budget_test.go`); liveness under pressure: `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback), `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) (`core/frontend/durable/provider_chunk_burst_test.go`) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | +| `INV-WAL-V3-ADMISSION-FAULT-001` | A terminal I/O fault latched while a v3 write waits on WAL pressure or for an admission slot ends that wait with the fault's original typed cause, also when the deadline has expired at the same check. | M1 Serving (write admission) | `core/storage/wal_admission.go` `walAdmission.acquireContext`, `walAdmission.terminalFault`; `core/storage/write_command_budget.go` `WALStore.writeBudgetError` | `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreV3WriteBudgetKeepsTerminalFault` (`core/storage/write_command_budget_test.go`) | — | ACTIVE | +| `INV-WAL-V3-ADMISSION-DEADLINE-001` | One command deadline, the earlier of the caller's deadline and the command's arrival plus `WriteCommandBudget`, bounds every adapter batch of a write and its store waits for the capture and lifecycle locks, on the local clock. | M1 Serving (write admission) | `core/frontend/write_budget.go` `WithWriteBudget`; `core/frontend/durable/storage_adapter.go` `StorageBackend.Write`, `writeBytes`; `core/storage/write_command_budget.go` `WALStore.writeAdmissionDeadline`, `WALStore.acquireWriteLock`; `core/storage/walstore.go` `WALStore.WriteContext`, `WALStore.WriteBatchContext` | `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestSessionWriteBudgetIncludesDispatchQueue` | — | ACTIVE | +| `INV-WAL-V3-ADMISSION-SHORTLOCK-001` | A v3 write takes the store, descriptor and WAL writer locks blocking, never by polling, so RWMutex writer preference holds, and its command deadline is checked once they are held. | M1 Serving (write admission) | `core/storage/walstore.go` `WALStore.WriteContext`, `WALStore.WriteBatchContext`; `core/storage/write_command_budget.go` `WALStore.writePressureSample`; `core/storage/wal_io_v3.go` `walWriterV3.append` | `TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait`, `TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders`, `TestWALStoreV3WriteBudgetRefusesAfterDescriptorWaitBehindSync` | — | ACTIVE | +| `INV-WAL-V3-ADMISSION-NOPAYLOAD-001` | A v3 write whose command deadline has passed starts no new payload WAL write: 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. | M1 Serving (write admission) | `core/storage/walstore_v3.go` `WALStore.appendWriteV3`, `WALStore.writeBatchV3Locked`, `WALStore.v3BudgetAfterRollover`; `core/storage/wal_io_v3.go` `walWriterV3.append` | `TestWALStoreV3WriteBudgetRefusesNewPayloadAfterRollover`, `TestWALStoreV3WriteBudgetRechecksAfterRollover` | — | ACTIVE | +| `INV-WAL-V3-ADMISSION-EXPIRY-STATE-001` | A v3 write refused for an expired deadline before its append leaves the WAL bytes, nextLSN and the dirty map unchanged. | M1 Serving (write admission) | `core/storage/walstore.go` `WALStore.WriteContext`, `WALStore.WriteBatchContext` | `TestStorageBackendExpiredWriteDoesNotAppend` | — | ACTIVE | +| `INV-WAL-V3-ADMISSION-PREFIX-ERR-001` | A write batch that returns a committed prefix with a storage error keeps that error in the error set the frontend classifies. | M1 Serving (write admission) | `core/frontend/durable/storage_adapter.go` `writeFullBlockBatch`, `withStorageCause`, `observeWriteCause` | `TestStorageBackendPartialBatchPhysicalFaultSurvivesObserverDeadline` | — | ACTIVE | +| `INV-WAL-V3-ADMISSION-RETRYABLE-001` | A write that fails only because the caller's deadline expired is reported retryable, also through a required write observer and on NVMe; a write whose error carries a physical cause is reported terminal. | M1 Serving (write admission) | `core/frontend/write_budget.go` `IsWriteDeadline`; `core/frontend/durable/storage_adapter.go` `StorageBackend.Write`, `replicationWriteError`; `core/frontend/nvme/io.go` `mapBackendError`; `core/frontend/nvme/session.go` `Session.handleWrite` | `TestStorageBackendRequiredObserverDeadlineStaysRetryable`, `TestStorageBackendPartialBatchPhysicalFaultSurvivesObserverDeadline`; `TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA` (`core/frontend/nvme/write_command_budget_test.go`) | — | ACTIVE | +| `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint at cp moves retainedTail only to the end of a complete validated record whose last LSN is at most cp minus the retention window, and, while a BASE is installing, never past BaseCursor. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.publishCheckpointV3`; `core/storage/wal_io_v3.go` `walWriterV3.reclaimThroughV3` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB | +| `INV-WAL-V3-RECLAIM-INDEX-001` | A physical v3 recovery rebuilds the writer's volatile record-boundary index only from trusted write records of the kept scan; an installing reopen indexes them without moving the writer's cursor. | M1 checkpoint / existing two-slot retirement | `core/storage/wal_io_v3.go` `walWriterV3.restoreScanV3`, `walWriterV3.rememberReclaimScanV3`, `walWriterV3.indexReclaimScanLockedV3`; `core/storage/walstore_v3.go` `WALStore.recoverV3` | `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen` | — | STUB | +| `INV-WAL-V3-RECLAIM-PUBLISH-001` | A mapped v3 checkpoint publishes retainedTail, retainedHead, the map root, CheckpointLSN and W in one slot publication, followed by a metadata-only rollover when the fallback slot still pins a lower tail. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.publishCheckpointV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin` | — | STUB | +| `INV-WAL-V3-RECLAIM-FAIL-001` | When a v3 checkpoint publication or its rollover fails, no WAL byte is released for reuse and the dirty entries at or below the checkpoint stay unchanged for retry. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.publishCheckpointV3`, `WALStore.rolloverCheckpointV3Locked`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3` | `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin` | — | STUB | +| `INV-WAL-V3-RECLAIM-EXCL-001` | No v3 writer is admitted between a checkpoint's slot publication and the end of both its rollover and its retirement of the dirty entries at or below the checkpoint. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.publishCheckpointV3`, `WALStore.retireCheckpointDirtyV3Locked` | `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse` | — | STUB | +| `INV-WAL-V3-RECLAIM-SETTLE-001` | A pending v3 rollover (the fallback slot pinning a lower tail) is settled without a new checkpoint by the idle refresh, by a flusher cycle whose checkpoint does not advance, and by write admission. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.rolloverCheckpointV3Locked`, `WALStore.persistOwnedMapCheckpointV3`; `core/storage/walstore_v3.go` `WALStore.refreshW`, `WALStore.appendWriteV3` | `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint` | — | STUB | | `INV-WAL-V3-OWNER-001` | v3 read/write open and offline readonly open acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go` | `TestWALStoreV3CreatorKeepsOwnershipThroughPublication` (`core/storage/volume_lock_v3_test.go`); `TestWALStoreV3OwnerExcludesOpenAndReadOnly` (`core/storage/volume_lock_v3_test.go`); `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | -| `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | -| `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `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-CATCHUP-001` | A v3 catch-up source that is installing refuses with `ErrBaseInstalling` and emits nothing, also for an empty request at the head. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `WALStore.ScanLBAs`, `WALStore.scanLBAsV3` | `TestCatchUpV3InstallingAtHeadRefuses` (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-CATCHUP-BASE-001` | A v3 catch-up request covered by an installed BASE (fromLSN at or below BaseLSN) fails with typed `WALRecycled`: the peer needs a rebuild. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `WALStore.scanLBAsV3` | `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`) | — | STUB | +| `INV-WAL-V3-CATCHUP-DAMAGE-001` | Damage in the retained v3 WAL makes a catch-up fail with a typed WAL integrity error and emit nothing. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `v3CatchUpEntries` | `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails` (tag `swblock_format_v3_test`) | — | STUB | +| `INV-WAL-V3-CATCHUP-REVALIDATE-001` | A v3 catch-up emits entries only from a scan whose recovery generation, nonce, BASE state and ID, install epoch, retainedTail and CheckpointLSN are unchanged after the scan. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `WALStore.scanLBAsV3` | `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` (tag `swblock_format_v3_test`) | — | STUB | +| `INV-WAL-V3-BINDING-001` | Every record and padding the v3 writer emits carries the selected nonce and its own absolute logical cursor and fits within WALSize of the both-slot reuse floor; an append that does not fit is refused. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `walWriterV3.append`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`) | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | +| `INV-WAL-V3-SCAN-BINDING-001` | The v3 scanner checks a record's nonce and exact expected cursor before it uses the record's Length or count, and trusts the record only after the whole record validates again. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned` (`core/storage/wal_io_v3_test.go`) | — | STUB | +| `INV-WAL-V3-SCAN-STOP-001` | The v3 scanner skips only geometric end-of-ring slack and stops at the first untrusted record, never searching inside a payload for a later record. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord` (`core/storage/wal_io_v3_test.go`) | — | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | Once a v3 store has bound a validated map, every descriptor publication carries the bound map tuple or a prepared candidate's, with merged CheckpointLSN ≤ map coverage C ≤ merged W. | M1 Serving (v3 map publication) | `core/storage/chunk_map_publication_v3.go` `validateMapPublicationV3`, `sameMapTupleV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedWithMapV3` | `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-MAP-PUBLISH-REPLACE-001` | A prepared v3 map candidate is published only with a higher map generation, coverage not below the bound map's, and the same sidecar and proof domain with its epoch and mutation token unchanged since preparation; a stale candidate writes no slot. | M1 Serving (v3 map publication) | `core/storage/chunk_map_publication_v3.go` `validateMapPublicationV3`, `prepareMapPublicationV3`, `mapPublicationProofV3.validV3` | `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend` | — | STUB | +| `INV-WAL-V3-MAP-PUBLISH-ROLLOVER-001` | A v3 publication without a prepared map candidate (a W-only publication or a rollover) carries the bound map root unchanged. | M1 Serving (v3 map publication) | `core/storage/chunk_map_publication_v3.go` `validateMapPublicationV3` | `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix` | — | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | -| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | -| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | -| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshAndSetWModeCloseTheWindow` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3AppendWriteErrorLatchesTheStore` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeWaitsForAHeldBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3InstallingScanErrorIsTypedNotReady` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision` (`core/storage/recovery_v3_test.go`); `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model | STUB | -| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` | STUB | -| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB | -| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | -| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack | STUB | -| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records | STUB | +| `INV-WAL-V3-MAP-BYTES-001` | A v3 map candidate names immutable pages and root in the store's owned sidecar, checked against the descriptor's identity and geometry. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3`, `encodeMapPageV3`, `encodeMapRootV3` | `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | +| `INV-WAL-V3-MAP-VALIDATE-001` | A v3 map read returns no entry before the root and every page pass their domain-separated body digests, zero reserved and unused bytes, exact page counts, file bounds and non-aliasing page intervals. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `readChunkLSNMapV3`, `mapReadAtV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest` | — | STUB | +| `INV-WAL-V3-MAP-PERSIST-ORDER-001` | A v3 map candidate exists only after its new pages are written and fsynced, then its root is written and fsynced, then the sidecar's directory is fsynced. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage` | — | STUB | +| `INV-WAL-V3-MAP-PERSIST-FAIL-001` | An error inside a v3 map persistence transaction yields no candidate and latches the store against later I/O; a preflight or Stat error latches nothing. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore` | — | STUB | +| `INV-WAL-V3-MAP-EXTENT-REUSE-001` | A v3 sidecar extent is reused only when no live root references it: neither slot's root, no in-flight candidate, and, until reopen, no candidate whose publication outcome is uncertain. | M1 (dark map preparation only) | `core/storage/chunk_map_extents_v3.go` `slotsPublishedV3`, `abandonCandidateV3`, `liveSnapshotV3`, `registerRootV3`; `core/storage/chunk_map_publication_v3.go` `publishMapV3`, `openDescriptorMapV3` | `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot` (`core/storage/chunk_map_extents_v3_test.go`); `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies` | — | STUB | +| `INV-WAL-V3-MAP-TRUNCATE-001` | When the v3 sidecar exceeds four times its live bytes, its free tail is truncated to the end of the highest live page and no lower. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3StatsAfterReopen` (`core/storage/chunk_map_extents_v3_test.go`) | — | STUB | +| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor slot write after create's initial slot A goes through the one publisher, which writes the fallback slot with slotGen + 1 while holding `descMu`. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publish`, `descriptorPublisherV3.publishLockedCoreV3`; create: `core/storage/walstore_v3.go` `createWALStoreV3Configured` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3ConcurrentPublishersNeverRegress` (`core/storage/descriptor_v3_test.go`) | — | STUB | +| `INV-WAL-V3-PUBLISH-LOCKORDER-001` | The v3 publisher holds `WALStore.mu` only to take its snapshot and releases it before any slot I/O; the slot write and its fsync run in the store's fsync leaf. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishWithMapV3`; `core/storage/walstore.go` `WALStore.syncFile` | `TestDescriptorV3LockOrderRecorder` (`core/storage/descriptor_v3_test.go`) | — | STUB | +| `INV-WAL-V3-PUBLISH-MERGE-001` | A v3 publication rebases onto the authoritative descriptor: W and CheckpointLSN are max-merged, and a change of identity, geometry or (outside a reset) nonce, a retainedTail regression, or a map root change without a higher map generation is refused. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `mergeDescriptorV3`, `mergeDescriptorV3Mode` | `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress` (`core/storage/descriptor_v3_test.go`); `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`) | — | STUB | +| `INV-WAL-V3-PUBLISH-BASE-EDGE-001` | A v3 publication whose BASE state change is not a DESIGN 8.5 edge (none → installing, installing → installing under a new ID, installing → installed under the same ID and BaseLSN, installed → none) is refused; installed → installing is refused. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `baseTransitionAllowedV3` | `TestDescriptorV3BaseTransitionTable` (`core/storage/descriptor_v3_test.go`) | — | STUB | +| `INV-WAL-V3-PUBLISH-FAIL-001` | A failed slot write (full or partial) or slot fsync publishes nothing: the authoritative descriptor stays, the store fault is latched, the candidate stays pinned as uncertain, and every later publication, rollover and WAL reuse is refused until reopen. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3`, `descriptorPublisherV3.rolloverIfPinned`, `descriptorPublisherV3.reuseFloorLocked` | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned` (`core/storage/descriptor_v3_test.go`); `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate` | — | STUB | +| `INV-WAL-V3-PUBLISH-LATCH-LEAF-001` | A descriptor slot write error latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a store Sync queued on `fileSyncMu` cannot acknowledge through the uncertain slot. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3`; `core/storage/walstore.go` `WALStore.syncFile`, `noteFsyncFailure` | `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | +| `INV-WAL-V3-PUBLISH-SUCCESS-BOUNDARY-001` | A store fault latched while a v3 publication is in flight makes that publication fail at its success boundary, without advancing the authoritative descriptor. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3` | `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary` (`core/storage/descriptor_v3_test.go`) | — | STUB | +| `INV-WAL-V3-PUBLISH-COUNTER-001` | A v3 publication whose slotGen, W, CheckpointLSN, retainedTail, retainedHead, map generation, map coverage, BaseLSN or BaseCursor would exceed 2^64-2 is refused with `ErrCounterExhausted` before any write. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `checkCountersV3`; `core/storage/superblock_v3.go` `nextSlotGenV3` | `TestDescriptorV3PublicationCounterExhaustion` (`core/storage/descriptor_v3_test.go`) | — | STUB | +| `INV-WAL-V3-PUBLISH-ROLLOVER-001` | When the fallback slot's retainedTail is below the selected slot's under the same nonce, a metadata-only rollover republishes the current descriptor unchanged into it, so the reuse floor rises to the selected tail. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.rolloverIfPinned` | `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange` (`core/storage/descriptor_v3_test.go`) | — | STUB | +| `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001` | No v3 WAL reuse floor is computed across nonces: while the two descriptor slots carry different nonces there is no floor, and no WAL byte is reused. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.reuseFloor`, `descriptorPublisherV3.reuseFloorLocked` | `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor` (`core/storage/descriptor_v3_test.go`) | — | STUB | +| `INV-WAL-V3-W-001` | A v3 Sync acknowledges a write only after an fsync that covers the write's WAL record has completed. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `WALStore.syncWALBatchV3Internal`; `core/storage/walstore.go` `WALStore.Sync` | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` composed model | STUB | +| `INV-WAL-V3-W-MODE-C-001` | In mode C (the default) a Sync batch publishes W = the previous batch's acknowledged W, and that publication's one fsync covers both the batch's WAL records and the slot. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3Internal` | `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch` (`core/storage/walstore_v3_test.go`) | `WALFormat` composed model | STUB | +| `INV-WAL-V3-W-MODE-A-001` | In mode A a Sync batch fsyncs the WAL first and only then publishes the slot with W = H, the highest LSN appended when the batch began. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3Internal` | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`) | `WALFormat` composed model | STUB | +| `INV-WAL-V3-W-RECOVERY-001` | Recovery of a non-installing v3 descriptor fails with `wal_corrupt` when the contiguous LSN prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, highest DurableLSN of a trusted record). | M1 Recovering → Serving \| RecoveryFailed | `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`, `replayFloorV3`; `core/storage/walstore_v3.go` `WALStore.recoverV3` | `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt` (`core/storage/walstore_v3_test.go`) | `WALFormat` composed model | STUB | +| `INV-WAL-V3-W-REFRESH-001` | When the slot W lags the acknowledged W, the flusher's idle refresh and `SetWMode` each publish W = the acknowledged W. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.refreshW`, `WALStore.SetWMode` | `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`) | — | STUB | +| `INV-WAL-V3-W-CHECKPOINT-CLAMP-001` | A v3 checkpoint never exceeds the acknowledged W; entries the flusher wrote to the extent above the published checkpoint stay retry work, so a later Sync and flusher cycle advance the checkpoint and map coverage together. | M1 write lifecycle: InExtent → Checkpointed (v3) | `core/storage/walstore_v3.go` `WALStore.persistCheckpointV3`; `core/storage/walstore_map_checkpoint_v3.go` `WALStore.persistOwnedMapCheckpointV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | — | STUB | +| `INV-WAL-V3-W-SETWMODE-001` | `SetWMode` first syncs every write admitted before it under the old mode, then publishes the new mode while holding the v3 leader role, so no Sync batch acknowledges under a mode other than the descriptor's. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.SetWMode`, `WALStore.syncWALBatchV3Internal` | `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`) | — | STUB | +| `INV-WAL-V3-W-RECOVER-STRADDLE-001` | No v3 W publication or Sync acknowledgement straddles a recovery: a Sync whose completion sees a changed recovery generation is refused, and recovery sets the acknowledged W to its recovered prefix R. | M1 Recovering → Serving | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.refreshW`, `WALStore.syncWALBatchV3Internal`; `core/storage/walstore.go` `WALStore.syncWithPhases` | `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing` (`core/storage/walstore_v3_test.go`) | — | STUB | +| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes the logical WAL interval [E, floor + WALSize), floor being the both-slot same-nonce reuse floor, fsyncs it through the leaf, and only then publishes retainedHead = E. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.fenceV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` `NoResurrection` | STUB | +| `INV-WAL-V3-FENCE-EXACT-001` | The v3 drop fence changes only the bytes of [E, floor + WALSize) mapped modulo WALSize, in at most two ranges split at the physical wrap; no byte before E or outside the interval changes. | M1 Recovering → Serving (v3) | `core/storage/recovery_v3.go` `fenceRangesV3`; `core/storage/walstore_v3.go` `WALStore.fenceV3` | `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | — | STUB | +| `INV-WAL-V3-NO-RESURRECTION-001` | A WAL record dropped by one v3 recovery is never replayed by a later recovery, also after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.fenceV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` `NoResurrection` | STUB | +| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused with `ErrResetNotPreserved`, writing nothing, unless the dirty map is empty and CheckpointLSN is at least every appended LSN (and so equals the acknowledged W). | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB | +| `INV-WAL-V3-RESET-TWO-SLOT-001` | A reset publishes a new nonzero nonce with an empty cursor space into one descriptor slot and then the other, and succeeds only after both publications. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `descriptorPublisherV3.resetIncarnationV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode` | `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3RefusesTheCurrentOrAZeroNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB | +| `INV-WAL-V3-RESET-HALF-001` | After a crash between a reset's two publications, open selects the new incarnation and binds no WAL writer, so every append is refused until Recover's head publication puts the new nonce in both slots. | M1 Serving → Serving (reset, dark) | `core/storage/walstore_v3.go` `openWALStoreV3File`, `WALStore.recoverV3`, `WALStore.appendWriteV3`; `core/storage/reset_v3.go` `descriptorPublisherV3.halfResetV3` | `TestResetV3CrashOutcomes` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB | +| `INV-WAL-V3-RESET-INVARIANT-001` | A reset leaves LSN allocation, W, CheckpointLSN and the map root unchanged. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `descriptorPublisherV3.resetIncarnationV3`, `WALStore.resetIncarnationV3` | `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash` (`core/storage/reset_store_v3_test.go`) | — | STUB | +| `INV-WAL-V3-READ-REVALIDATE-001` | A v3 read served from a dirty entry returns data only from a WAL record that validates whole (CRC, footer, type) and whose LBA and LSN match the resolving entry; on a mismatch it resolves again, so a reused WAL position never serves another block. | M1 Serving → Serving (reset, dark) | `core/storage/walstore_v3.go` `WALStore.readDirtyV3Into`, `WALStore.readRecordIntoV3` | `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock` (`core/storage/reset_store_v3_test.go`) | — | STUB | +| `INV-WAL-V3-READ-DAMAGE-001` | A v3 dirty read reports WAL damage only for a record that fails validation while the resolving entry and the recovery generation are the same before and after the attempt; a failed pread is reported as substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/walstore_v3.go` `WALStore.readDirtyV3Into` | `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | — | STUB | +| `INV-WAL-V3-RECOVER-GEN-001` | The v3 recovery generation is incremented at the start and at the end of every recovery and every reset. | M1 Serving → Serving (reset, dark) | `core/storage/walstore_v3.go` `WALStore.recoverV3`; `core/storage/reset_v3.go` `WALStore.resetIncarnationV3` | `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`); `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only if BaseLSN is at least the acknowledged W (published or not yet), the CheckpointLSN and every appended LSN; otherwise the begin writes nothing and returns `ErrInstallBaseUncovered`, or `ErrInstallSupersedeUncovered` when it supersedes. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3` | `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | +| `INV-WAL-V3-BASE-BEGIN-SLOTS-001` | Before the first BASE mutation of an install, both descriptor slots durably hold installing with its BaseLSN, BaseCursor = the writer head P at begin, and the new install ID. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publish` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots` (`core/storage/base_install_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | +| `INV-WAL-V3-BASE-DRAIN-001` | A BASE write or install-lane apply admitted through an install handle finishes before a later begin proceeds, and after that begin every handle of the earlier install epoch is refused with `ErrInstallSuperseded`. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.admitV3`, `installHandleV3.admissibleV3` | `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession` (`core/storage/base_install_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BASE-HANDLE-001` | On a v3 store, BASE extent writes and install-lane applies go only through an install handle: `WriteExtentDirect` is refused, an ordinary replicated apply is refused while installing, and `WriteBase` needs installing under the handle's ID. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `installHandleV3.WriteBase`, `installHandleV3.admissibleV3`, `WALStore.applyEntryV3`; `core/storage/walstore.go` `WALStore.WriteExtentDirect` | `TestNativeReplacementDirectExtentRefusedPreservesWAL` (`core/storage/legacy_replacement_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BASE-LANE-AFTER-DONE-001` | An install-lane apply through a handle is admitted while the volume is installing under its ID or, once that handle's own complete succeeded, while installed under its ID or retired, until the next begin; otherwise it returns `ErrInstallSuperseded`. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `installHandleV3.admissibleV3`, `installHandleV3.ApplyInstallEntry`, `installHandleV3.MarkBaseComplete` | `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin` (`core/storage/base_install_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BASE-LANE-ORDER-001` | A v3 install-lane apply at or below the highest appended LSN is a no-op if its LBA already holds a higher LSN and fails with `ErrWALLSNOrder` otherwise; one above max(CheckpointLSN, BaseLSN, highest appended) + 1 fails with `ErrInstallLSNGap`. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.applyEntryV3` | `TestBaseInstallV3ApplyInstallEntryOrderAndGap` (`core/storage/base_install_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BASE-COMPLETE-001` | Installed is published only by a complete for the current installing ID, and only after one fsync of the store file covering the BASE extent bytes and the install-lane suffix, followed by the metadata and chunk checkpoint barriers. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`); `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling` (`core/storage/chunk_base_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | +| `INV-WAL-V3-BASE-COMPLETE-MAP-001` | The installed publication sets retainedTail to at least BaseCursor and carries a fresh owned-map candidate in which every chunk a BASE write of the install touched is UNKNOWN. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3`, `installHandleV3.WriteBase`, `WALStore.markMapUnknownV3` | `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BASE-SUPERSEDED-001` | After a successful complete, the open store neither serves nor flushes a WAL record appended before the begin, and recovery from an installed descriptor scans no record behind BaseCursor. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`); `TestWALIOV3_InstalledScanBeginsAtMaxTail` (`core/storage/wal_io_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BASE-RETIRE-001` | A v3 descriptor goes from installed to none only when CheckpointLSN ≥ BaseLSN and both the newly written slot and the slot it leaves as fallback carry retainedTail ≥ BaseCursor; installing never goes to none. | M1 Serving → Installing → Serving (dark) | `core/storage/descriptor_v3.go` `retireBaseV3`, `baseTransitionAllowedV3` | `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3InstallingToNoneIsRefused` (`core/storage/base_install_v3_test.go`); `TestDescriptorV3BaseTransitionTable` (`core/storage/descriptor_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | +| `INV-WAL-V3-BASE-RETIRE-GATE-001` | On a store whose provider deferred BASE retirement at open, retirement of an installed BASE waits for this open's attach commit. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.DeferBaseRetirementV3`, `WALStore.CommitChunkAttachV3`, `WALStore.AllowBaseRetirementV3`; `core/storage/chunk_base_v3.go` `chunkLayerImpl.holdBaseTransitionV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3`; `core/frontend/durable/provider.go` `openOrCreate` | `TestBaseInstallV3CommitChunkAttach`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` (`core/frontend/durable/provider_format_v3_base_test.go`) | — | 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; this is checked again at its completion. | M1 Installing (dark) | `core/storage/walstore.go` `WALStore.Sync`, `WALStore.syncWithPhases` | `TestInstallLogV3SyncIsGatedWhileInstalling` (`core/storage/install_log_v3_test.go`) | `WALFormat` install-log ack | STUB | +| `INV-WAL-V3-INSTALL-LOG-ACK-001` | `SyncInstallLog(id)` returns H, the highest LSN appended when it starts, only after a WAL fsync and then a descriptor publication of W = max(W, H) with BaseState still installing: always mode A. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog` | `TestInstallLogV3IsModeAAndSurvivesACrash` (`core/storage/install_log_v3_test.go`) | `WALFormat` install-log ack | STUB | +| `INV-WAL-V3-INSTALL-LOG-REFUSE-001` | Under `installMu` shared, `SyncInstallLog` is refused with `ErrNotInstalling` outside an install and with `ErrInstallIDMismatch` for another install ID. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`, `installLogTargetV3` | `TestInstallLogV3Refusals` (`core/storage/install_log_v3_test.go`) | — | STUB | +| `INV-WAL-V3-INSTALL-LOG-FAULT-001` | `SyncInstallLog` acknowledges nothing when a store fault has latched by its final check under `WALStore.mu`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog` | `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`) | — | STUB | +| `INV-WAL-V3-INSTALL-LOG-SCOPE-001` | `SyncInstallLog` is on the narrow `InstallLogSyncer`, not on `LogicalStorage`, and no package other than `core/storage` and `core/recovery` names `InstallLogSyncer`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `InstallLogSyncer` | `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`) | — | STUB | +| `INV-WAL-V3-INSTALL-LOG-RECEIVER-001` | The rebuild receiver's durable progress ack is `SyncInstallLog(installID)` until its own session's completion, and the ordinary `Sync` after it. | M1 Installing (dark) | `core/recovery/receiver.go` `Receiver.sendAck` | tagged `swblock_format_v3_test`: `TestReceiverV3ProgressAckIsTheInstallLog` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n > 1 blocks is one record (type 0x04) with LSNs first..first+n-1 under one CRC32C, so a crash keeps all n blocks or none. | M1 Serving (dark) | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`; `core/storage/walstore.go` `WALStore.WriteBatch` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records | STUB | +| `INV-WAL-V3-BATCH-READERS-001` | Each v3 batch block's dirty entry names its data offset in the record, and every reader (store read, flusher, recovery replay, install-path replays, offline reader) uses the block only from a whole valid record whose block has that LBA, LSN and offset. | M1 Serving (dark) | `core/storage/walstore_v3.go` `WALStore.readRecordIntoV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`, `WALStore.replayRecordV3`; `core/storage/walstore_readonly_v3.go` `WALStoreReader.readV3` | `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRoundTripAcrossACrash` (`core/storage/walstore_batch_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BATCH-ACK-001` | A Sync that covers a v3 batch returns a frontier of at least the batch's last LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`, `WALStore.advanceAfterAppendV3` | `TestWALStoreV3BatchAckCoversItsLastLSN` (`core/storage/walstore_batch_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BATCH-MAP-001` | The owned map records every block of a v3 batch at its own LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`; `core/storage/walstore_map_checkpoint_v3.go` `WALStore.recordMapWriteV3` | `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | — | STUB | | `INV-WAL-V3-MIGRATE-001` | ARCHIVED: the in-place v2 converter is removed. Public opens refuse v2 bytes without mutation; no upgrade path is provided. | M1 open refusal | `core/storage/walstore_v3.go` `openWALStoreV3WithOptions` | `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | none (retired tool) | ARCHIVED | | `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA` (expiry and joined physical-fault wire status); `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | | `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | @@ -458,18 +533,35 @@ 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 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-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 now creates and opens mapped v3 too (`INV-WAL-V3-ACTIVATION-001`), 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 create and open select mapped v3 (`INV-WAL-V3-ACTIVATION-001`); the BASE caller and readonly/status controls have dedicated rows below. 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, a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until the v3 FreshFromHead restore lands; since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from; it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). +- `INV-WAL-V3-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`). A v3 begin with an attached chunk layer that has no BASE transition hook is refused (`errV3NotYet`), writing nothing (`TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`; a supported layer is drained as in `INV-WAL-V3-CHUNK-BASE-001`); 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; the provider's former refusal of a HEAD restore onto a v3 store is gone since row 12a (see the `INV-WAL-V3-MAP-PUBLISH-001` note); since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from; it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). - `INV-WAL-V3-MIGRATE-001`: Archived with the converter and its legacy fixtures; v2 inputs refuse open without mutation. - `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model, 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`). +- `INV-WAL-V3-ACTIVATION-001` family: writable and read-only open validate the owned-map dependencies of the selected slot and of every valid fallback slot before the store or reader is returned, and refuse a valid legacy superblock with `ErrUnsupportedLegacyFormat` without changing a byte: see M1 — → Opened (tests `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies` with its fallback-page case, `TestNativeReplacementLegacyBytesRefusedWithoutMutation`). A zero chunk geometry option becomes 1024 blocks per chunk, so every public create is mapped; create persists an all-UNKNOWN initial map before its first slot. +- `INV-WAL-V3-DESCRIPTOR-CONFLICT-001`: the old statement said the two slots must not disagree on identity; of the identity fields, open compares the UUID, together with the geometry. The next publication's slotGen comes from `nextSlotGenV3` (`INV-WAL-V3-PUBLISH-COUNTER-001`). `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` is a store-level control of the selection: a v3 `Close` writes no slot, and reopen selects the newest one. +- `INV-WAL-V3-RECORD-001`: codec success alone is not nonce, cursor or lap replay admission; that belongs to the scanner (`INV-WAL-V3-SCAN-BINDING-001`). +- `INV-WAL-V3-ADMISSION-001` family: at every store call the store derives its own admission deadline from the command deadline, min(command deadline, now + `admissionTimeout`) less a reserve of min(1 s, a quarter of the time left), so the append and its completion keep headroom; the 4 s local admission timeout restarts for each adapter batch, while the command deadline does not. The budget is cooperative: it never interrupts a mutex wait or a WAL write already started, and issued WAL I/O keeps its existing lifecycle ownership. Keeping a committed prefix's storage error in the classified set means a later observer deadline cannot turn a physical fault into a retryable one; on NVMe a retryable deadline is Namespace Not Ready, DNR=0. The WAL-pressure wait and its locks are in Part D. The burst tests are liveness controls: they would stall if a waiter held a lock the flusher needs, but they do not assert the lock state. +- `INV-WAL-V3-RECLAIM-001` family: reuse still needs both valid same-nonce slot tails: see M1 Serving → Serving (checkpoint) and `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001`. A catch-up scan revalidates the tail and checkpoint before it delivers its buffered entries (`INV-WAL-V3-CATCHUP-REVALIDATE-001`). Writer exclusion until the rollover and the dirty retirement end means no write reuses a released position while a dirty entry still names it. The flusher also caps the checkpoint at the lowest active catch-up pin (`persistOwnedMapCheckpointV3`). An installing reopen indexes record boundaries without restoring or rewinding the writer's cursor or LSN (`rememberReclaimScanV3`). +- `INV-WAL-V3-CATCHUP-001` family: the revalidation closes begin/complete/retire ABA, so a superseded prefix is never published; a source that began installing during the scan refuses with `ErrBaseInstalling`, and any other change makes it scan again. A request at or below CheckpointLSN minus the retention window also fails with `WALRecycled`. A scan holds no store lock across its callbacks and emits all of its entries or none. +- `INV-WAL-V3-BINDING-001` family: a writer whose pwrite failed refuses every later append, and the store latches the fault: see M1 Serving → FaultLatched and FaultLatched → FaultLatched (test `TestWALIOV3_FloorAndPwriteFailureRefuse`). A scan result (`walScanResultV3`) is a typed read-only result, never an acknowledgement or serving permission; recovery decides from it (`INV-WAL-V3-W-RECOVERY-001`). The scan start for a BASE descriptor is in `INV-WAL-V3-BASE-SUPERSEDED-001`. +- `INV-WAL-V3-MAP-PUBLISH-001` family: binding validates the map root and pages of the selected slot and of every valid fallback slot before serving: see M1 — → Opened (tests `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`). Recover invalidates the map proof epoch at its start and at its end, on success and on failure: see M1 Recovering → Serving (tests `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`). A candidate whose slot publication outcome is unknown stays pinned until reopen (`INV-WAL-V3-MAP-EXTENT-REUSE-001`, `INV-WAL-V3-PUBLISH-FAIL-001`). Controls of the capture, seed and provider callers described in the next note, not of the publication rule itself: `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_DefaultSelectorCreatesV3`, `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`; `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN` is also a control of `INV-WAL-V3-ACTIVATION-PROVIDER-001`. +- `INV-WAL-V3-MAP-BYTES-001` family: root and pages are addressed by offset and SHA-256; with 4096-byte alignment, distinct page offsets that do not overlap the root rule out a partial overlap. Truncation keeps a root the fallback slot names readable. +- `INV-WAL-V3-PUBLISH-001` family: create writes the initial descriptor into slot A directly (`createWALStoreV3Configured`) before the store opens; every later slot write is the publisher's. The lock graph is metadata callbacks, then `WALStore.mu` (snapshot only), then `descMu`, then `fileSyncMu` (the leaf, inside `syncFile`). An fsync error is latched by the leaf itself (`noteFsyncFailure`); the publisher latches a slot write error because the leaf does not. The success-boundary refusal is the #172 rule. `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate` drives the failure rule through an append's rollover. +- `INV-WAL-V3-W-001` family: because mode C's slot carries the previous batch's W, the acknowledged writes above the slot W are at most those of the newest acknowledged batch, which is unprotected only against media corruption before the next Sync or the idle refresh (`INV-WAL-V3-W-REFRESH-001`; test `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`). For an installing descriptor, recovery reports a short prefix (R < W*) or a scan error as `ErrBaseIncomplete`, not `wal_corrupt` (`installingErrorV3`; test `TestWALStoreV3InstallingScanErrorIsTypedNotReady` covers the scan error). A Sync acknowledges nothing when a store fault has latched by its final check (`INV-WAL-FSYNC-STICKY-001`). +- `INV-WAL-V3-FENCE-001`: with mixed slot nonces (a reset stopped between its two publications) the fence interval is empty, because old-nonce bytes fail the scanner's nonce binding (`fenceRangesV3`). A fence write error latches the store inside the leaf. +- `INV-WAL-V3-RESET-001` family: an empty dirty map means no entry names an old-incarnation WAL position. Between the two reset publications the slots carry different nonces, so there is no reuse floor (`INV-WAL-V3-PUBLISH-NONCE-FLOOR-001`); only a reset changes the nonce (`INV-WAL-V3-PUBLISH-MERGE-001`). A dirty read holds no lock across its WAL read, so the position it resolved may be reused (after a reset the cursor space restarts at 0); LSN allocation runs on across a reset, so a matching LBA and LSN identify the resolved write and no nonce is checked. A reset is also refused during a BASE install and while a previous reset is half published. A BASE resume and a covering supersession bump the recovery generation the same way. +- `INV-WAL-V3-BASE-001` family: begin, complete and the attach commit take `installMu` exclusive; handle mutations take it shared. Begin covers every appended LSN because an unacknowledged record above BaseLSN would leave a hole behind BaseCursor. Begin also refuses a zero install ID, the installing ID itself (`TestBaseInstallV3BeginRefusals`) and a begin while installed (retire first). An install-lane apply stays admitted after the handle's own completion because the session's WAL lane can outlive its BaseDone (DESIGN r17.4). The retirement deferral is meant to keep the installed descriptor as the provider's completed-image evidence while a reopen could still read the volume as fresh from HEAD. It is lifted by the attach commit when the volume is already installed (`CommitChunkAttachV3`), or after a BASE transition once local presence is durably saved and this open's attach is committed (`holdBaseTransitionV3`); a new begin defers it again. Open question: whether the attach commit's removal of the fresh marker and its directory fsync, before the deferral is lifted, is the full safety argument on the non-chunk-managed path where the commit lifts it; the presence-durable form is the stronger, chunk-managed path. Controls of the resume, supersession and same-open Recover rules in the next note: `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`). +- `INV-WAL-V3-INSTALL-ACK-001` family: DESIGN r17.4 section 7. `SyncInstallLog` attests install-log durability only, never a readable image, and never changes BaseState; its final fault check is the #172 acknowledgement boundary. The former clause that a v2 store's `SyncInstallLog` is its `Sync` is dropped: open refuses legacy formats, so every open store is v3. +- `INV-WAL-V3-BATCH-001` family: a single-block `WriteBatch` is an ordinary write record. The writer consumes the whole LSN range of a batch (`INV-WAL-V3-LSN-ORDER-001`). A torn acknowledged batch fails recovery closed (`INV-WAL-V3-W-RECOVERY-001`). A failed batch pwrite latches the store and is never acknowledged: see M1 Serving → FaultLatched (`INV-WAL-APPEND-STICKY-001`). +- Enforced by reading (no test asserts it), M1 rows: `INV-WAL-V3-ADMISSION-001` family, that a WAL-pressure or admission-slot wait wakes the flusher and holds no store, descriptor or WAL writer lock while it sleeps, and that no such wait grants WAL reuse or acknowledges a write (`walAdmission.acquireContext`, `writePressureSample`); `INV-WAL-V3-ACTIVATION-FALLBACK-001`, the read-only half (`openReadOnlyV3` runs the same `refuseLegacyWALStore` and `selectSlotV3`; the test opens writable); `INV-WAL-V3-BASE-HANDLE-001`, the refusal of an ordinary replicated apply while installing (`applyEntryV3`); `INV-WAL-V3-BASE-DRAIN-001`, that a complete also waits for every admitted handle mutation (`markBaseCompleteV3` takes `installMu` exclusive); `INV-WAL-V3-RESET-INVARIANT-001`, that LSN allocation is unchanged (the tests compare W, CheckpointLSN and the map root); `INV-WAL-V3-INSTALL-LOG-RECEIVER-001`, the switch to the ordinary `Sync` after the session's completion (`Receiver.sendAck`); and that a publication refused at its success boundary keeps its written candidate pinned as uncertain until reopen (`publishLockedCoreV3`). ### B.2 Core: authority and epochs @@ -832,6 +924,9 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a |---|---|---|---|---| | Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; positive HTTP timeoutMs. Completed uploads resume only within one blockvolume process and matching owner/HEAD/chunk versions; after restart the seal must fit seal_timeout_ms. | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. | | Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` (not reachable in this release) | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. | +| v3 write WAL-pressure admission: `core/storage/wal_admission.go` `walAdmission.acquireContext`, called by `WALStore.WriteContext` and `WALStore.WriteBatchContext` | M1 Serving (write admission); `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-ADMISSION-DEADLINE-001`, `INV-WAL-V3-ADMISSION-FAULT-001` | The write's store admission deadline, fixed once when the write enters the store: the earlier of the caller's deadline and entry + 4 s (`admissionTimeout`), less a reserve of min(1 s, a quarter of the time then left), so at most entry + 3 s, on the local clock. In the soft band (pressure at least 0.70 and below 0.90) the pressure wait is one sleep of at most 5 ms. | Owner: the flusher. The wait wakes it (`NotifyUrgent`) on entry and at every 2 ms recheck while pressure is at or above the 0.90 hard watermark, and ends once the flusher's progress brings pressure below 0.90; a wait for one of the 64 admission slots ends when another write releases its slot. On expiry the write is refused before its append, with no WAL byte, nextLSN or dirty entry changed: `ErrWALPressureTimeout` (retryable; `frontend.ErrBackendBusy` at the durable backend), or the original fault when a terminal fault has latched, or `context.Canceled` when the caller cancelled. The wait grants no reuse and acknowledges nothing. | Held while waiting: the `captureMu` and `lifecycleMu` read locks, so a capture barrier, a BASE begin or complete, and `Close` wait behind it for at most this bound. Not held while it sleeps: the store, descriptor and WAL writer locks (each pressure sample takes and releases them). Local wait: no remote call. | + +The WAL-pressure admission wait is the one wait here held under store locks (the `captureMu` and `lifecycleMu` read locks). It is a local wait: pressure samples, a timer and the flusher's local progress. No remote call is made while those locks are held, so the rule that no remote call runs under a lock still holds. Frozen estimate reporting: a tail above the existing 60 s estimator ceiling reports the same 60 s rejection sentinel used by admission. It is known but saturated, not a complete fixed-plus-tail duration; quiesce slack is zero. Consumers must not use it as a completion forecast. Drain refusals retain the observation before their reason changes; this reporting does not reclassify refusal causes. diff --git a/seaweed-block/internal/invcheck/invariants_test.go b/seaweed-block/internal/invcheck/invariants_test.go index ddadc2351a..b439593f7f 100644 --- a/seaweed-block/internal/invcheck/invariants_test.go +++ b/seaweed-block/internal/invcheck/invariants_test.go @@ -263,4 +263,4 @@ func TestInvariantStatementsAreShort(t *testing.T) { // longStatementsLeft is the number of rows testdata/long-statements.txt may // name. It only goes down. -const longStatementsLeft = 18 +const longStatementsLeft = 1 diff --git a/seaweed-block/internal/invcheck/testdata/long-statements.txt b/seaweed-block/internal/invcheck/testdata/long-statements.txt index d9a169d951..413b88ad99 100644 --- a/seaweed-block/internal/invcheck/testdata/long-statements.txt +++ b/seaweed-block/internal/invcheck/testdata/long-statements.txt @@ -1,19 +1,2 @@ # Part B rows whose Statement is over 300 characters. This list only shrinks: split a row into rows of one property each, then delete its line; never add one. -INV-FE-NVME-READY-001 INV-WAL-DATA-SYNC-001 -INV-WAL-V3-ACTIVATION-001 -INV-WAL-V3-ADMISSION-001 -INV-WAL-V3-BASE-001 -INV-WAL-V3-BATCH-001 -INV-WAL-V3-BINDING-001 -INV-WAL-V3-CATCHUP-001 -INV-WAL-V3-DESCRIPTOR-001 -INV-WAL-V3-FENCE-001 -INV-WAL-V3-INSTALL-ACK-001 -INV-WAL-V3-MAP-BYTES-001 -INV-WAL-V3-MAP-PUBLISH-001 -INV-WAL-V3-PUBLISH-001 -INV-WAL-V3-RECLAIM-001 -INV-WAL-V3-RECORD-001 -INV-WAL-V3-RESET-001 -INV-WAL-V3-W-001 From e2cc37cfd91d6a57698e1780a252eb33bf72cb21 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 16:41:10 -0800 Subject: [PATCH 04/57] durable: the logged boundary is the backend's admission flip itself (recorded under mu), not a time before the call StorageBackend records stopFlipAt under mu right after operational goes false (setOperationalLocked and both TryStopIO flips); the detach logs it as 'admission closed at' beside 'StopIO returned at'. Admission is unchanged: an I/O whose gate ran before the flip is admitted and drained by StopIO; every gate after it refuses (INV-STOP-FLIP-CUTOFF-001). The stamp is taken after the store (errs toward a false alarm) and logged only on a successful stop. Co-Authored-By: Claude Opus 5.5 --- .../frontend/durable/export_chunk_test.go | 8 + .../core/frontend/durable/provider_chunk.go | 17 +- .../frontend/durable/stopio_began_log_test.go | 145 +++++++++++++++++- .../core/frontend/durable/storage_adapter.go | 26 +++- seaweed-block/docs/design/invariants.md | 3 +- 5 files changed, 181 insertions(+), 18 deletions(-) diff --git a/seaweed-block/core/frontend/durable/export_chunk_test.go b/seaweed-block/core/frontend/durable/export_chunk_test.go index 93158f44c0..5ed81e34c5 100644 --- a/seaweed-block/core/frontend/durable/export_chunk_test.go +++ b/seaweed-block/core/frontend/durable/export_chunk_test.go @@ -36,3 +36,11 @@ func SetTestBeforeIOLock(b frontend.Backend, f func()) { b.(*StorageBackend).tes func SetTestBeforeAttachWait(b frontend.Backend, f func()) { b.(*StorageBackend).testBeforeReadReadyWait = f } + +func SetTestAfterGate(b frontend.Backend, f func()) { b.(*StorageBackend).testAfterGate = f } + +func StopFlipAt(b frontend.Backend) time.Time { return b.(*StorageBackend).StopFlipAt() } + +func StopIOForTest(ctx context.Context, b frontend.Backend, evidence string) error { + return b.(*StorageBackend).StopIO(ctx, evidence) +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 118aaab786..52d74ab8e6 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -1121,16 +1121,17 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla // the cut gets three quarters, the settlement what is left. The bound is // cooperative (contexts): a syscall that never returns is not bounded here. var start time.Time - // stopIOBegan is taken just before the operational flip (from then on new - // I/O is refused by contract), stopIOReturned when the admitted I/O has - // drained; both are logged so a measurement can tell a refusal after the - // flip from an admitted I/O that failed. + // stopIOBegan is the backend's flip (admission closed, under its mu: an + // I/O whose gate runs after it is refused; one gated before it is + // admitted even if it registers later), stopIOReturned when the admitted + // I/O has drained; both are logged so a measurement can tell a refusal + // after the flip from an admitted I/O that failed. var stopIOBegan, stopIOReturned time.Time defer func() { if !stopIOReturned.IsZero() { // Emit after the cut releases its barrier, using the actual times. if !stopIOBegan.IsZero() { - log.Printf("durable: volume=%s I/O stop began at %s", volumeID, stopIOBegan.UTC().Format(time.RFC3339Nano)) + log.Printf("durable: volume=%s admission closed at %s", volumeID, stopIOBegan.UTC().Format(time.RFC3339Nano)) } log.Printf("durable: volume=%s StopIO returned at %s", volumeID, stopIOReturned.UTC().Format(time.RFC3339Nano)) } @@ -1201,11 +1202,11 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla // Cancel/join the periodic owner before any final freeze, while serving. p.stopChunkLoop(h) r, err = owner.PrecopyDetachWithAdmission(hostlimit.WithClass(cutCtx, hostlimit.Urgent), h.backend.BeginPrecopyPause, func() bool { - began := time.Now() if !h.backend.TryStopIO("chunk pre-copy: final detached cut") { return false } - stopIOBegan, stopIOReturned = began, time.Now() + stopIOReturned = time.Now() + stopIOBegan = h.backend.StopFlipAt() h.chunkDetach = true beginFreeze() return true @@ -1246,7 +1247,6 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla } } else { beginFreeze() - stopIOBegan = time.Now() if plain { if err := h.backend.stopPlainDetachIfIdle(); err != nil { return r, 0, err @@ -1268,6 +1268,7 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla } if err == nil { stopIOReturned = time.Now() + stopIOBegan = h.backend.StopFlipAt() } if err == nil { p.stopChunkLoop(h) diff --git a/seaweed-block/core/frontend/durable/stopio_began_log_test.go b/seaweed-block/core/frontend/durable/stopio_began_log_test.go index 74b74af80c..52f272fc34 100644 --- a/seaweed-block/core/frontend/durable/stopio_began_log_test.go +++ b/seaweed-block/core/frontend/durable/stopio_began_log_test.go @@ -2,18 +2,23 @@ package durable_test import ( "context" + "errors" "strings" + "sync" + "sync/atomic" "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" ) -// A detach logs when its I/O stop began (the operational flip, from which -// the backend refuses new I/O) as well as when StopIO returned, both with -// RFC 3339 nanoseconds, so a test measuring guest errors can tell a refusal -// by contract (after the flip) from an admitted I/O that failed. -func TestLiveDetachLogsWhenTheIOStopBegan(t *testing.T) { +// A detach logs when admission closed (the backend's operational flip, +// taken under its lock) as well as when StopIO returned, both with RFC 3339 +// nanoseconds, so a test measuring guest errors can tell a refusal by +// contract (after the flip) from an admitted I/O that failed. +func TestLiveDetachLogsWhenAdmissionClosed(t *testing.T) { p := chunkProvider(t, t.TempDir(), storage.NewMemChunkRemote(), v1View(), time.Hour) openRecovered(t, p) b, err := p.Open(context.Background(), "v1") @@ -50,9 +55,133 @@ func TestLiveDetachLogsWhenTheIOStopBegan(t *testing.T) { } return found[0] } - began := stamp("volume=v1 I/O stop began at ") + closed := stamp("volume=v1 admission closed at ") returned := stamp("volume=v1 StopIO returned at ") - if began.Before(started) || returned.Before(began) || ended.Before(returned) { - t.Fatalf("began %s, returned %s: want started %s <= began <= returned <= ended %s", began, returned, started, ended) + if closed.Before(started) || returned.Before(closed) || ended.Before(returned) { + t.Fatalf("closed %s, returned %s: want started %s <= closed <= returned <= ended %s", closed, returned, started, ended) + } + if got := durable.StopFlipAt(b); !got.Equal(closed) { + t.Fatalf("logged %s, backend flip %s: the log must carry the flip itself", closed, got) + } +} + +// The flip time is the admission cutoff: a write whose gate passed before +// the flip is admitted and completes (StopIO drains it), and a write whose +// gate runs after the flip is refused, so nothing is admitted after the +// logged boundary. +func TestStopFlipIsTheAdmissionCutoff(t *testing.T) { + p := chunkProvider(t, t.TempDir(), storage.NewMemChunkRemote(), v1View(), time.Hour) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + parkedA, releaseA := make(chan struct{}), make(chan struct{}) + parkedB, releaseB := make(chan struct{}), make(chan struct{}) + var onceA, onceB sync.Once + freeA := func() { onceA.Do(func() { close(releaseA) }) } + freeB := func() { onceB.Do(func() { close(releaseB) }) } + errA, errB, stopErr := make(chan error, 1), make(chan error, 1), make(chan error, 1) + var launched struct{ a, b, stop atomic.Bool } + // Registered before anything starts: every parked writer is released and + // every goroutine is joined within a bound, whatever the test hits. + t.Cleanup(func() { + freeA() + freeB() + cancel() + for name, c := range map[string]struct { + on *atomic.Bool + ch chan error + }{"write A": {&launched.a, errA}, "write B": {&launched.b, errB}, "StopIO": {&launched.stop, stopErr}} { + if !c.on.Load() { + continue + } + select { + case <-c.ch: + case <-time.After(5 * time.Second): + t.Errorf("%s did not return", name) + } + } + }) + + // Write A passes the gate, then parks (it registers after the flip and + // still completes: admission is the gate's decision). + var parkA, parkB atomic.Bool + parkA.Store(true) + durable.SetTestAfterGate(b, func() { + if parkA.CompareAndSwap(true, false) { + close(parkedA) + <-releaseA + } + }) + launched.a.Store(true) + go func() { _, err := b.Write(context.Background(), 0, block(0x10)); errA <- err }() + select { + case <-parkedA: + case <-time.After(5 * time.Second): + t.Fatal("write A never passed the gate") + } + // Write B parks before the gate. + parkB.Store(true) + durable.SetTestBeforeIOLock(b, func() { + if parkB.CompareAndSwap(true, false) { + close(parkedB) + <-releaseB + } + }) + launched.b.Store(true) + go func() { _, err := b.Write(context.Background(), 4096, block(0x20)); errB <- err }() + select { + case <-parkedB: + case <-time.After(5 * time.Second): + t.Fatal("write B never reached the gate") + } + + launched.stop.Store(true) + go func() { stopErr <- durable.StopIOForTest(ctx, b, "test stop") }() + deadline := time.Now().Add(5 * time.Second) + for durable.StopFlipAt(b).IsZero() { + if time.Now().After(deadline) { + t.Fatal("the stop never flipped") + } + time.Sleep(time.Millisecond) + } + // B now reaches its gate after the flip (it may first wait behind the + // drain for ioMu); A is admitted and still in flight, so StopIO waits. + freeB() + select { + case err := <-stopErr: + stopErr <- err + t.Fatalf("StopIO returned (%v) while admitted write A was still in flight", err) + case <-time.After(100 * time.Millisecond): + } + freeA() + select { + case err := <-errA: + errA <- err + if err != nil { + t.Fatalf("write A (gate before the flip): %v, want admitted and completed", err) + } + case <-time.After(5 * time.Second): + t.Fatal("write A never returned") + } + select { + case err := <-stopErr: + stopErr <- err + if err != nil { + t.Fatalf("StopIO: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("StopIO never returned after A completed") + } + select { + case err := <-errB: + errB <- err + if !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write B (gate after the flip): %v, want refused (ErrNotReady)", err) + } + case <-time.After(5 * time.Second): + t.Fatal("write B never returned") } } diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index a7641ecd08..98c7023841 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -148,7 +148,15 @@ const maxFullBlockBatchBlocks = 64 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() + testBeforeIOLock func() + // testAfterGate, test-only, runs in admit after the gate passed and + // before the I/O registers under mu. + testAfterGate func() + // stopFlipAt is when admission last closed for a stop, taken under mu + // just after operational went false; guarded by mu. An I/O whose gate + // saw operational before it was admitted (and StopIO drains it); every + // gate after it refuses. + stopFlipAt time.Time testPrecopyQueued func() // after FIFO registration, outside mu testPrecopyGranted func(*precopyWaiter) // FIFO grant under mu; nonblocking test hook testPrecopyStopFallback func() // before fallback lock attempts, outside mu @@ -482,8 +490,12 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) { // The caller owns mu; publication never calls the store or waits for I/O. func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) { + flipped := !ok && b.operational.Load() b.opEvidence.Store(evidence) b.operational.Store(ok) + if flipped { + b.stopFlipAt = time.Now() // after the store: no gate after this instant admits + } b.waitAttachReady = false // A host drain closes storage admission, but is not the old path's // teardown. Keep a final pre-copy queue parked until Close or its budget; @@ -512,6 +524,7 @@ func (b *StorageBackend) TryStopIO(evidence string) bool { } b.opEvidence.Store(evidence) b.operational.Store(false) + b.stopFlipAt = time.Now() b.waitAttachReady = false b.notifyReadReadyLocked() return true @@ -539,6 +552,7 @@ func (b *StorageBackend) TryStopIO(evidence string) bool { b.precopy = p b.opEvidence.Store(evidence) b.operational.Store(false) + b.stopFlipAt = time.Now() b.waitAttachReady = false b.notifyReadReadyLocked() return true @@ -561,6 +575,13 @@ func (b *StorageBackend) stopPlainDetachIfIdle() error { return nil } +// StopFlipAt is when admission last closed for a stop (zero if never). +func (b *StorageBackend) StopFlipAt() time.Time { + b.mu.Lock() + defer b.mu.Unlock() + return b.stopFlipAt +} + // StopIO makes the backend refuse every new Read, Write and Sync with // ErrNotReady (evidence), then waits, bounded by ctx, for the I/O admitted // before the stop to finish. After a nil return no I/O admitted before the @@ -823,6 +844,9 @@ func (b *StorageBackend) admit() (func(), error) { b.ioMu.RUnlock() return nil, err } + if hook := b.testAfterGate; hook != nil { + hook() + } b.mu.Lock() if b.precopy != nil && b.precopy.active { b.mu.Unlock() diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7847a9c0a8..b614f246eb 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -249,6 +249,7 @@ stateDiagram-v2 | Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | | Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001`, `INV-CUT-READ-LOGICAL-001` | | Plain detach | plain=true acquires exclusive idle frontend admission (closed handles allowed), then StopIO and caller-bounded seal. Busy requests mutate nothing; publication and settlement retain authority/HEAD checks. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | +| `INV-STOP-FLIP-CUTOFF-001` | A detach logs 'admission closed at' = the backend's flip, recorded under its mu just after operational goes false: an I/O whose gate ran before it is admitted and drained by StopIO; every gate after it refuses. Logged only on a successful stop. | M5 detach (StopIO / plain stop / pre-copy TryStopIO) | `core/frontend/durable/storage_adapter.go` `setOperationalLocked`, `TryStopIO`, `StopFlipAt`; `provider_chunk.go` detach log | `TestStopFlipIsTheAdmissionCutoff`, `TestLiveDetachLogsWhenAdmissionClosed` (`core/frontend/durable/stopio_began_log_test.go`) | — (no state machine change; the cutoff test is the proof form) | ACTIVE | | Pre-copy admission | (Not reachable in this release; see the note below.) opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | (Not reachable in this release; see the note below.) at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | @@ -403,7 +404,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -185 rows: 163 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 170 new. +186 rows: 164 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 171 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. From 93471b8007adf719f04ffde3acf7381347d760d5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 17:09:31 -0800 Subject: [PATCH 05/57] invariants: INV-STOP-FLIP-CUTOFF-001 in the Part B table beside INV-CUT-PLAIN-DETACH-001 (was in Part A's M5 table) 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 b614f246eb..10cdee99e3 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -249,7 +249,6 @@ stateDiagram-v2 | Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | | Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001`, `INV-CUT-READ-LOGICAL-001` | | Plain detach | plain=true acquires exclusive idle frontend admission (closed handles allowed), then StopIO and caller-bounded seal. Busy requests mutate nothing; publication and settlement retain authority/HEAD checks. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | -| `INV-STOP-FLIP-CUTOFF-001` | A detach logs 'admission closed at' = the backend's flip, recorded under its mu just after operational goes false: an I/O whose gate ran before it is admitted and drained by StopIO; every gate after it refuses. Logged only on a successful stop. | M5 detach (StopIO / plain stop / pre-copy TryStopIO) | `core/frontend/durable/storage_adapter.go` `setOperationalLocked`, `TryStopIO`, `StopFlipAt`; `provider_chunk.go` detach log | `TestStopFlipIsTheAdmissionCutoff`, `TestLiveDetachLogsWhenAdmissionClosed` (`core/frontend/durable/stopio_began_log_test.go`) | — (no state machine change; the cutoff test is the proof form) | ACTIVE | | Pre-copy admission | (Not reachable in this release; see the note below.) opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | (Not reachable in this release; see the note below.) at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | @@ -562,6 +561,7 @@ Notes: | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | | `INV-CUT-PLAIN-DETACH-001` | Plain detach excludes entering/admitted I/O, then seals under the caller context, including a closed idle frontend. Publication and unknown/fenced settlement remain enforced. Closed frontend handles never reopen; absent/false preserves live policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` ; `TestOfflineSealUsesCallerDeadline`, `TestOfflineSealCallerCancelCanRetry` (`core/frontend/durable/provider_offline_seal_test.go`); `TestChunkPlainDetachUsesCallerDeadline`, `TestChunkPlainDetachRequiresExplicitBound` (`core/host/volume/chunk_offline_seal_test.go`) | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | +| `INV-STOP-FLIP-CUTOFF-001` | A detach logs 'admission closed at' = the backend's flip, recorded under its mu just after operational goes false: an I/O whose gate ran before it is admitted and drained by StopIO; every gate after it refuses. Logged only on a successful stop. | M5 detach (StopIO / plain stop / pre-copy TryStopIO) | `core/frontend/durable/storage_adapter.go` `setOperationalLocked`, `TryStopIO`, `StopFlipAt`; `provider_chunk.go` detach log | `TestStopFlipIsTheAdmissionCutoff`, `TestLiveDetachLogsWhenAdmissionClosed` (`core/frontend/durable/stopio_began_log_test.go`) | — (no state machine change; the cutoff test is the proof form) | ACTIVE | | `INV-WS-FREEZE-ACCOUNTING-001` | Frozen detach validates its origin and rechecks elapsed + known estimate against 5 s; override is explicit. Storage reports its admission estimate and quiesce slack using same-host monotonic durations. Stale advice is rechecked before upload; override and actual elapsed remain visible. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess`; `TestCandidateTailReportsCompleteFrozenBudget`, `TestFrozenRefusalRetainsUnknownCompleteEstimate`, `TestChunkFrozenRequestRefusalCarriesNoBudget`, `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation`, `TestFrozenSaturatedTailRemainsKnownButNonActionable` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible`, `ReportSlackSound` | ACTIVE | | `INV-WS-FREEZE-REFUSAL-001` | HTTP400 `invalid_freeze_budget`, retryable=false, is emitted only for frozen-request validation before any provider admission or mutation. Missing/zero/future origin, override without frozen, and frozen+plain preserve that boundary. Generic `bad_request` is not a clean-refusal proof. Terminal and unknown-publication causes retain precedence; no production path emits this typed code after mutation. | G frozen detach: request → refused before admission (M5) | `core/host/volume/chunk_control.go` `handleChunkDetach`, `chunkErrorCode`; `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestChunkFrozenValidationHasDistinctPreMutationCode`, `TestFrozenValidationPrecedesAnyProviderAccess` | — (wire classification; validation/admission guards unchanged) | ACTIVE | | `INV-CUT-PRECOPY-001` | Resume grants waiters FIFO under one lock; gates and completion are independent. Each command keeps its arrival/caller bound. Only pause refusals requeue; stale and terminal errors survive. Detached handoff requires settled publication. See Notes for admission and freeze guards. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestCheckpointTailScanIncludedInTotalAndFixedCosts`, `TestCheckpointTailUsesLiteralLatestThreeConservativeRate`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyResumeReleasesAllWaiters` (FIFO grants under one lock, concurrent outstanding I/O), `TestPrecopyResumedArrivalDoesNotInheritExpiredPause`, `TestPrecopyQueueBoundStartsAtCommandArrival`, `TestPrecopyResumeGrantVersusExpiry`, `TestPrecopyGrantedWaiterFollowsReplacementPause`, `TestPrecopyNewPauseCannotEraseObservedStalePrimary`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); controlled callers and measured latency are not a model proof | ACTIVE | From f8743e62a1d2a99049669ab51bfddfc791b64412 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 17:14:57 -0800 Subject: [PATCH 06/57] blockvolume: the capture-interval floor lives in a build-tagged file The 5-minute --chunk-capture-interval floor moves to capture_floor.go, built unless the swb_enterprise tag is set; a build with the tag supplies its own minChunkCaptureInterval. The OSS build behaves as before: below 5m is refused (60 s now tested), and the refusal and the flag help name the floor from the constant. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/capture_floor.go | 10 ++++++++++ .../cmd/blockvolume/capture_floor_test.go | 20 +++++++++++++++++++ seaweed-block/cmd/blockvolume/chunk_remote.go | 4 ++-- .../cmd/blockvolume/chunk_remote_test.go | 1 + seaweed-block/cmd/blockvolume/main.go | 2 +- 5 files changed, 34 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/capture_floor.go create mode 100644 seaweed-block/cmd/blockvolume/capture_floor_test.go diff --git a/seaweed-block/cmd/blockvolume/capture_floor.go b/seaweed-block/cmd/blockvolume/capture_floor.go new file mode 100644 index 0000000000..c2a37c3c53 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/capture_floor.go @@ -0,0 +1,10 @@ +//go:build !swb_enterprise + +package main + +import "time" + +// minChunkCaptureInterval is the shortest --chunk-capture-interval this +// build accepts; 0 turns the timer off. A build with the swb_enterprise tag +// supplies its own value. +const minChunkCaptureInterval = 5 * time.Minute diff --git a/seaweed-block/cmd/blockvolume/capture_floor_test.go b/seaweed-block/cmd/blockvolume/capture_floor_test.go new file mode 100644 index 0000000000..07366c8f9e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/capture_floor_test.go @@ -0,0 +1,20 @@ +//go:build !swb_enterprise + +package main + +import ( + "strings" + "testing" +) + +// The OSS build keeps the 5-minute capture floor: 60 s is refused, 5m is +// accepted, and the refusal and the flag help name the floor. +func TestOSSCaptureFloor(t *testing.T) { + base := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1") + if _, err := parseFlags(append(base, "--chunk-capture-interval=60s")); err == nil || !strings.Contains(err.Error(), "at least 5m0s") { + t.Fatalf("60 s: %v; want refused below the 5m floor", err) + } + if _, err := parseFlags(append(base, "--chunk-capture-interval=5m")); err != nil { + t.Fatalf("5m refused: %v", err) + } +} diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index e58a93a4e4..e18ea06163 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -88,8 +88,8 @@ func validateChunkFlags(f flags) error { if c.maintenanceInterval < 0 { return errors.New("--chunk-maintenance-interval must not be negative") } - if c.captureInterval > 0 && c.captureInterval < 5*time.Minute { - return errors.New("--chunk-capture-interval must be 0 or at least 5m") + if c.captureInterval > 0 && c.captureInterval < minChunkCaptureInterval { + return fmt.Errorf("--chunk-capture-interval must be 0 or at least %s", minChunkCaptureInterval) } if c.captureInterval < 0 { return fmt.Errorf("--chunk-capture-interval=%s must not be negative", c.captureInterval) diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go index e4ea557d27..8241644545 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -52,6 +52,7 @@ func TestWALStoreChunkFlags(t *testing.T) { "relative path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=swblock"), "root path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=/"), "below OSS capture floor": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=4m59s"), + "60 s in an OSS build": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=60s"), "negative maintenance": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-maintenance-interval=-1s"), "negative interval": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=-1s"), "chunk flag on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-filer=x:1"), diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 689d1a19d9..57fa9a1014 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -203,7 +203,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.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)") fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: not supported in this release; blockvolume refuses to start when it is set") - fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least 5m)") + fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least "+minChunkCaptureInterval.String()+")") f.chunk.snapshotSchedule = defaultSnapshotSchedule fs.Var(&f.chunk.snapshotSchedule, "chunk-snapshot-schedule", "walstore-chunk: scheduled snapshots, daily:N or weekly:N (once per period at a per-volume offset, the newest N kept) or off") fs.DurationVar(&f.chunk.maintenanceInterval, "chunk-maintenance-interval", defaultChunkMaintenanceInterval, "walstore-chunk: retention and optional GC pass interval; 0 disables") From 8fe90ba66d53968bb2773f9ecd1d5033269710d5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 17:23:20 -0800 Subject: [PATCH 07/57] blockvolume: the capture-interval floor is a package variable Replace the build-tagged constant with durable.MinCaptureInterval (default 5 minutes). The flag check and the flag help read it; a program that builds blockvolume with a shorter floor sets it before parsing flags. The OSS binary behaves as before. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/capture_floor.go | 10 ------ .../cmd/blockvolume/capture_floor_test.go | 34 ++++++++++++++----- seaweed-block/cmd/blockvolume/chunk_remote.go | 4 +-- seaweed-block/cmd/blockvolume/main.go | 2 +- .../core/frontend/durable/capture_interval.go | 9 +++++ 5 files changed, 38 insertions(+), 21 deletions(-) delete mode 100644 seaweed-block/cmd/blockvolume/capture_floor.go create mode 100644 seaweed-block/core/frontend/durable/capture_interval.go diff --git a/seaweed-block/cmd/blockvolume/capture_floor.go b/seaweed-block/cmd/blockvolume/capture_floor.go deleted file mode 100644 index c2a37c3c53..0000000000 --- a/seaweed-block/cmd/blockvolume/capture_floor.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build !swb_enterprise - -package main - -import "time" - -// minChunkCaptureInterval is the shortest --chunk-capture-interval this -// build accepts; 0 turns the timer off. A build with the swb_enterprise tag -// supplies its own value. -const minChunkCaptureInterval = 5 * time.Minute diff --git a/seaweed-block/cmd/blockvolume/capture_floor_test.go b/seaweed-block/cmd/blockvolume/capture_floor_test.go index 07366c8f9e..94cf3abfbd 100644 --- a/seaweed-block/cmd/blockvolume/capture_floor_test.go +++ b/seaweed-block/cmd/blockvolume/capture_floor_test.go @@ -1,20 +1,38 @@ -//go:build !swb_enterprise - package main import ( "strings" "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" ) -// The OSS build keeps the 5-minute capture floor: 60 s is refused, 5m is -// accepted, and the refusal and the flag help name the floor. -func TestOSSCaptureFloor(t *testing.T) { +// The capture floor is durable.MinCaptureInterval: 5 minutes by default, +// so 60 s is refused; a program that sets it to 30 s before parsing flags +// accepts 30 s and refuses 29 s. The refusal names the floor in force. +func TestCaptureIntervalFloor(t *testing.T) { base := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1") - if _, err := parseFlags(append(base, "--chunk-capture-interval=60s")); err == nil || !strings.Contains(err.Error(), "at least 5m0s") { - t.Fatalf("60 s: %v; want refused below the 5m floor", err) + parse := func(iv string) error { + _, err := parseFlags(append(append([]string{}, base...), "--chunk-capture-interval="+iv)) + return err } - if _, err := parseFlags(append(base, "--chunk-capture-interval=5m")); err != nil { + if durable.MinCaptureInterval != 5*time.Minute { + t.Fatalf("default floor %s, want 5m", durable.MinCaptureInterval) + } + if err := parse("60s"); err == nil || !strings.Contains(err.Error(), "at least 5m0s") { + t.Fatalf("60 s under the default floor: %v", err) + } + if err := parse("5m"); err != nil { t.Fatalf("5m refused: %v", err) } + old := durable.MinCaptureInterval + durable.MinCaptureInterval = 30 * time.Second + defer func() { durable.MinCaptureInterval = old }() + if err := parse("30s"); err != nil { + t.Fatalf("30 s under a 30 s floor: %v", err) + } + if err := parse("29s"); err == nil || !strings.Contains(err.Error(), "at least 30s") { + t.Fatalf("29 s under a 30 s floor: %v", err) + } } diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index e18ea06163..92b0679e8b 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -88,8 +88,8 @@ func validateChunkFlags(f flags) error { if c.maintenanceInterval < 0 { return errors.New("--chunk-maintenance-interval must not be negative") } - if c.captureInterval > 0 && c.captureInterval < minChunkCaptureInterval { - return fmt.Errorf("--chunk-capture-interval must be 0 or at least %s", minChunkCaptureInterval) + if c.captureInterval > 0 && c.captureInterval < durable.MinCaptureInterval { + return fmt.Errorf("--chunk-capture-interval must be 0 or at least %s", durable.MinCaptureInterval) } if c.captureInterval < 0 { return fmt.Errorf("--chunk-capture-interval=%s must not be negative", c.captureInterval) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 57fa9a1014..73f0176fd2 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -203,7 +203,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.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)") fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: not supported in this release; blockvolume refuses to start when it is set") - fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least "+minChunkCaptureInterval.String()+")") + fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least "+durable.MinCaptureInterval.String()+")") f.chunk.snapshotSchedule = defaultSnapshotSchedule fs.Var(&f.chunk.snapshotSchedule, "chunk-snapshot-schedule", "walstore-chunk: scheduled snapshots, daily:N or weekly:N (once per period at a per-volume offset, the newest N kept) or off") fs.DurationVar(&f.chunk.maintenanceInterval, "chunk-maintenance-interval", defaultChunkMaintenanceInterval, "walstore-chunk: retention and optional GC pass interval; 0 disables") diff --git a/seaweed-block/core/frontend/durable/capture_interval.go b/seaweed-block/core/frontend/durable/capture_interval.go new file mode 100644 index 0000000000..f9bc0525e7 --- /dev/null +++ b/seaweed-block/core/frontend/durable/capture_interval.go @@ -0,0 +1,9 @@ +package durable + +import "time" + +// MinCaptureInterval is the shortest automatic cut interval blockvolume +// accepts (--chunk-capture-interval; 0 turns the timer off). A program +// that builds blockvolume with a shorter floor sets it before parsing +// flags; nothing changes it at run time. +var MinCaptureInterval = 5 * time.Minute From 13b1f154e304c94e165ca2c062517a8c234f525d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 17:36:42 -0800 Subject: [PATCH 08/57] storage: test that a cut revoked mid-upload keeps its uploads A cut whose host budget is revoked after two of five chunk PUTs (the limiter's MaxHold abort) leaves HEAD unchanged; the next cut uploads only the three chunks not yet uploaded, retransmits nothing, and publishes the full image. Co-Authored-By: Claude Opus 5.5 --- .../storage/chunk_cut_revoke_reuse_test.go | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_cut_revoke_reuse_test.go diff --git a/seaweed-block/core/storage/chunk_cut_revoke_reuse_test.go b/seaweed-block/core/storage/chunk_cut_revoke_reuse_test.go new file mode 100644 index 0000000000..6d6f37e3cd --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_revoke_reuse_test.go @@ -0,0 +1,87 @@ +package storage + +import ( + "context" + "errors" + "testing" +) + +// revokingBudget admits every cut and keeps its abort, so the test can +// revoke the cut's host budget the way the limiter does at MaxHold. +type revokingBudget struct{ abort func(error) } + +func (b *revokingBudget) Admit(_ context.Context, _ int64, abort func(error)) (uint64, error) { + b.abort = abort + return 1, nil +} +func (b *revokingBudget) ReserveCOW(uint64, int64) error { return nil } +func (b *revokingBudget) Release(uint64) {} + +// revokeAfterRemote revokes the budget at the PUT after `after` completed +// ones, and counts the bytes each attempt uploads. +type revokeAfterRemote struct { + *fakeChunkRemote + budget *revokingBudget + after int // revoke once this many PUTs completed; < 0: never + completed int + bytes int + keys map[string]bool +} + +func (r *revokeAfterRemote) Put(ctx context.Context, key string, b []byte) error { + if r.after >= 0 && r.completed == r.after { + r.budget.abort(errors.New("test: cut held its host slot past MaxHold")) + <-ctx.Done() + return context.Cause(ctx) + } + if err := r.fakeChunkRemote.Put(ctx, key, b); err != nil { + return err + } + if r.keys[key] { + return errors.New("test: retransmitted a completed upload") + } + r.keys[key] = true + r.completed++ + r.bytes += len(b) + return nil +} + +// A cut whose host budget is revoked mid-upload (MaxHold) keeps the +// chunks it already uploaded: the next cut uploads only the rest, fewer +// bytes than the whole dirty set, and retransmits nothing. +func TestCutRevokedMidUploadKeepsItsUploads(t *testing.T) { + const dirty = 5 + s, f, l, w := precopyLayer(t, 0, dirty) + l.cfg.UploadConcurrency = 1 + budget := &revokingBudget{} + r := &revokeAfterRemote{fakeChunkRemote: f, budget: budget, after: 2, keys: map[string]bool{}} + l.remote = r + l.cfg.Budget = budget + base := f.stats().head.Gen + + if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, errCutBudgetRevoked) { + t.Fatalf("first cut: %v; want the budget revocation", err) + } + if f.stats().head.Gen != base { + t.Fatal("a revoked cut moved HEAD") + } + first := r.bytes + if first != 2*ctChunkBytes { + t.Fatalf("first attempt uploaded %d bytes before the revocation; want %d", first, 2*ctChunkBytes) + } + + r.after, r.bytes = -1, 0 + result, err := l.Cut(ctTimeout(t)) + if err != nil || result.Head.Gen != base+1 { + t.Fatalf("retry: %+v %v", result, err) + } + if result.Stats.StageRounds != 0 { + t.Fatalf("the retry staged (%d rounds); this control is for uploads made after the barrier", result.Stats.StageRounds) + } + if r.bytes >= dirty*ctChunkBytes || r.bytes != (dirty-2)*ctChunkBytes { + t.Fatalf("retry uploaded %d bytes; want only the %d chunks not yet uploaded (%d bytes), less than the dirty set (%d)", + r.bytes, dirty-2, (dirty-2)*ctChunkBytes, dirty*ctChunkBytes) + } + assertImage(t, "published image", f.imageOf(t, result.Head), w.imageAt(s.NextLSN()-1)) + assertNoIntentsLeft(t, f) +} From 14facd11698f75616078f93a96662373009f036f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 17:37:30 -0800 Subject: [PATCH 09/57] test(storage): count retained upload bytes after a mid-cut abort --- .../storage/chunk_abort_upload_bytes_test.go | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_abort_upload_bytes_test.go diff --git a/seaweed-block/core/storage/chunk_abort_upload_bytes_test.go b/seaweed-block/core/storage/chunk_abort_upload_bytes_test.go new file mode 100644 index 0000000000..e18109267b --- /dev/null +++ b/seaweed-block/core/storage/chunk_abort_upload_bytes_test.go @@ -0,0 +1,76 @@ +package storage + +import ( + "context" + "errors" + "testing" +) + +// Abort at a witnessed PUT boundary, after three immutable chunks are stored. +// Count submitted bytes as well as completed PUTs so a retransmission cannot +// hide behind a successful final HEAD. +type abortUploadBytesRemote struct { + *fakeChunkRemote + cancel context.CancelFunc + calls, stored, submittedBytes, storedBytes int +} + +func (r *abortUploadBytesRemote) Put(ctx context.Context, key string, b []byte) error { + r.calls++ + r.submittedBytes += len(b) + if r.stored == 3 && r.cancel != nil { + r.cancel() + return ctx.Err() + } + if err := r.fakeChunkRemote.Put(ctx, key, b); err != nil { + return err + } + r.stored++ + r.storedBytes += len(b) + return nil +} + +// INV-CUT-STAGED-REUSE-001: an interrupted rolling cut retains its completed +// uploads in-process; retrying the unchanged image sends only the remainder. +func TestChunkStageV3_MidUploadAbortReducesRetryBytes(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 5) + l.cfg.COWSpillLimit = ctChunkBytes + l.cfg.UploadConcurrency = 1 + ctx, cancel := context.WithCancel(ctTimeout(t)) + defer cancel() + r := &abortUploadBytesRemote{fakeChunkRemote: f, cancel: cancel} + l.remote = r + before := f.stats().head + frontier := s.NextLSN() - 1 + want := w.imageAt(frontier) + if _, err := l.Cut(ctx); !errors.Is(err, context.Canceled) { + t.Fatalf("mid-upload cut: %v, want cancellation", err) + } + if f.stats().head.Gen != before.Gen { + t.Fatal("aborted cut published HEAD") + } + if r.calls != 4 || r.stored != 3 || r.storedBytes != 3*ctChunkBytes { + t.Fatalf("abort boundary: calls=%d stored=%d bytes=%d", r.calls, r.stored, r.storedBytes) + } + firstCalls, firstStored := r.calls, r.stored + firstSubmitted, firstBytes := r.submittedBytes, r.storedBytes + r.cancel = nil + result, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + retryCalls, retryStored := r.calls-firstCalls, r.stored-firstStored + retrySubmitted, retryBytes := r.submittedBytes-firstSubmitted, r.storedBytes-firstBytes + t.Logf("first: PUTs=%d stored=%d submitted_bytes=%d stored_bytes=%d; retry: PUTs=%d stored=%d submitted_bytes=%d stored_bytes=%d", firstCalls, firstStored, firstSubmitted, firstBytes, retryCalls, retryStored, retrySubmitted, retryBytes) + if retryCalls != 2 || retryStored != 2 || retryBytes != 2*ctChunkBytes || retrySubmitted != retryBytes { + t.Fatalf("retry did not send only the two remaining chunks: PUTs=%d stored=%d submitted=%d stored_bytes=%d", retryCalls, retryStored, retrySubmitted, retryBytes) + } + if retrySubmitted >= firstSubmitted || retryBytes >= firstBytes { + t.Fatal("retry uploaded at least as many bytes as the aborted attempt") + } + if result.Head.RemoteLSN != frontier { + t.Fatalf("retry frontier=%d want%d", result.Head.RemoteLSN, frontier) + } + assertImage(t, "retry image", f.imageOf(t, result.Head), want) + assertNoIntentsLeft(t, f) +} From 7d56ce0324e424bad636c2e65ce5afc039a9476c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 17:40:03 -0800 Subject: [PATCH 10/57] docs(invariants): INV-CUT-STAGED-REUSE-001 lists the MaxHold revocation test 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 2af43683a9..cab8be717d 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -578,7 +578,7 @@ Notes: | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED | -| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | | `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_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. 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` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE | | `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE | From d402aa112b3d85c98c96174b419c636cb4a0f475 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 17:41:20 -0800 Subject: [PATCH 11/57] docs(storage): link mid-upload cancellation regression to reuse invariant --- 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 2af43683a9..00337b142f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -578,7 +578,7 @@ Notes: | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED | -| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | | `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_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. 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` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE | | `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE | From 78d5b5e5f24d3adc6558c4f07b382c94186b443f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 17:43:14 -0800 Subject: [PATCH 12/57] storage: the revoke-reuse test counts every PUT attempt before the fake A re-send of an already completed key is now counted before the fake remote sees it (the real put path reconciles such a re-send), and the test asserts no completed key is re-sent. Co-Authored-By: Claude Opus 5.5 --- .../storage/chunk_cut_revoke_reuse_test.go | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_revoke_reuse_test.go b/seaweed-block/core/storage/chunk_cut_revoke_reuse_test.go index 6d6f37e3cd..5f1d1a5dc6 100644 --- a/seaweed-block/core/storage/chunk_cut_revoke_reuse_test.go +++ b/seaweed-block/core/storage/chunk_cut_revoke_reuse_test.go @@ -18,13 +18,16 @@ func (b *revokingBudget) ReserveCOW(uint64, int64) error { return nil } func (b *revokingBudget) Release(uint64) {} // revokeAfterRemote revokes the budget at the PUT after `after` completed -// ones, and counts the bytes each attempt uploads. +// ones. Every PUT attempt is counted before it reaches the fake, so a +// re-send of a completed key is recorded even if the caller then +// reconciles it. type revokeAfterRemote struct { *fakeChunkRemote budget *revokingBudget after int // revoke once this many PUTs completed; < 0: never completed int - bytes int + bytes int // bytes of every PUT attempt + dups int // attempts for a key that already completed keys map[string]bool } @@ -34,15 +37,15 @@ func (r *revokeAfterRemote) Put(ctx context.Context, key string, b []byte) error <-ctx.Done() return context.Cause(ctx) } + r.bytes += len(b) + if r.keys[key] { + r.dups++ + } if err := r.fakeChunkRemote.Put(ctx, key, b); err != nil { return err } - if r.keys[key] { - return errors.New("test: retransmitted a completed upload") - } r.keys[key] = true r.completed++ - r.bytes += len(b) return nil } @@ -78,6 +81,9 @@ func TestCutRevokedMidUploadKeepsItsUploads(t *testing.T) { if result.Stats.StageRounds != 0 { t.Fatalf("the retry staged (%d rounds); this control is for uploads made after the barrier", result.Stats.StageRounds) } + if r.dups != 0 { + t.Fatalf("%d PUTs re-sent an already completed key", r.dups) + } if r.bytes >= dirty*ctChunkBytes || r.bytes != (dirty-2)*ctChunkBytes { t.Fatalf("retry uploaded %d bytes; want only the %d chunks not yet uploaded (%d bytes), less than the dirty set (%d)", r.bytes, dirty-2, (dirty-2)*ctChunkBytes, dirty*ctChunkBytes) From f83bb48a7a66e41c2e3ba8821fb38e99e59a845e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 17:55:39 -0800 Subject: [PATCH 13/57] docs(invariants): leave INV-CUT-STAGED-REUSE-001 unchanged in this test-only change A TEST change may not touch the ledger; the row's Tests cell is updated in a separate docs change. 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 cab8be717d..2af43683a9 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -578,7 +578,7 @@ Notes: | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED | -| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | | `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_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. 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` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE | | `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE | From fc7d7eb13f3ceda242e9cf89794be1e5e87aea72 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 17:57:26 -0800 Subject: [PATCH 14/57] test(storage): leave ledger update to shared docs follow-up --- 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 00337b142f..2af43683a9 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -578,7 +578,7 @@ Notes: | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED | -| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | | `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_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. 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` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE | | `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE | From 8c154f7de0a55d30d97f8d3eaa64aacaf97d27f8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 18:10:37 -0800 Subject: [PATCH 15/57] docs: SeaweedFS maintenance commands that destroy walstore-chunk volumes A walstore-chunk volume's data is held in needles that no file's chunk list names, so volume.fsck with its delete flags would remove it. The operator document now says which commands must never run on such a cluster, which only report, and which are safe. Co-Authored-By: Claude Fable 5.2 --- seaweed-block/docs/standalone-deployment.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 0413a1c0ab..13196e1293 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -372,6 +372,27 @@ Check the data afterwards. `--depth data` reads every chunk once. sw-block ops chunk verify --volume v1 --chunk-filer FILER --all-snapshots --depth data --timeout 30m ``` +### SeaweedFS maintenance commands that destroy chunk volumes + +A walstore-chunk volume keeps its data in SeaweedFS as needles that **no file's chunk list names**: the volume's +own records in the filer point at them. SeaweedFS tools that decide what is referenced from file chunk lists +therefore see every chunk of every volume and snapshot as unreferenced. + +- **Never run `volume.fsck` with `-reallyDeleteFromVolume`** (alone or with `-forcePurging`) on a SeaweedFS + cluster that stores walstore-chunk volumes. It deletes the needles it considers orphaned, once they are older + than `-cutoffTimeAgo` (5 hours by default): that is the volumes' data, including every snapshot. There is no undo. +- **Never run `volume.fsck -findMissingChunksInFiler` with `-reallyDeleteFilerEntries` or + `-reallyDeleteFromVolume`** on such a cluster either. +- `volume.fsck` **without** those flags only reports. Its orphan list will contain the chunk needles; that is + expected and is not a fault. +- **Give chunk data its own collection** (`--chunk-collection`, `SWB_CHUNK_COLLECTION`) so it is easy to keep + cluster maintenance away from it. Do not put a TTL on that collection and do not delete it: both remove needles + without regard to what refers to them. +- `filer.sync`, `filer.backup` and `filer.replicate` copy file chunk lists. They do **not** copy a walstore-chunk + volume: the copied records would point at needles that do not exist on the target. +- Space is returned only by the two steps above (`sw-block ops chunk gc`, then a SeaweedFS vacuum). `volume.vacuum` + is safe: it compacts needles that were already deleted. + ### Restoring a snapshot into a new volume A restore makes a new, independent volume from a snapshot. The source volume and its snapshot can be deleted afterwards. From 27f8c2967edf9a3eccefbeb563b358fdabe2998b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:05:46 -0800 Subject: [PATCH 16/57] test: require durable expired same-holder lease re-grant --- .../core/authority/workspace_regrant_test.go | 110 ++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 seaweed-block/core/authority/workspace_regrant_test.go diff --git a/seaweed-block/core/authority/workspace_regrant_test.go b/seaweed-block/core/authority/workspace_regrant_test.go new file mode 100644 index 0000000000..4942a0cb76 --- /dev/null +++ b/seaweed-block/core/authority/workspace_regrant_test.go @@ -0,0 +1,110 @@ +package authority + +import ( + "context" + "testing" + "time" +) + +// INV-WS-LEASE-REGRANT-001: expiry alone does not abandon an unchanged owner. +// A new guard may use a durable re-grant; existing fenced guards stay terminal. +func TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable(t *testing.T) { + disk, _ := newTempStore(t) + clock := newTestClock() + store := &hookStore{AuthorityStore: disk} + p := newLeasePublisher(t, store, time.Second, clock) + original := bindAndGrant(t, p, "v", "r") + before := p.WorkspaceState("v").Lease + clock.at(3) + writes := 0 + store.setBefore(func(r DurableRecord) error { writes++; return nil }) + renewed, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1) + if err != nil { + t.Fatalf("unchanged expired holder cannot obtain a durable re-grant: %v", err) + } + if renewed.ReplicaID != "r" || renewed.Epoch != 1 || renewed.Revoking || renewed.ExpiresAtNS <= clock.now().UnixNano() || renewed.ExpiresAtNS <= original.ExpiresAtNS || writes != 1 { + t.Fatalf("bad re-grant %+v writes%d", renewed, writes) + } + records, err := disk.Load() + if err != nil { + t.Fatal(err) + } + found := false + for _, r := range records { + if r.VolumeID == "v" && r.Workspace != nil && r.Workspace.Lease != nil { + l := r.Workspace.Lease + found = true + if l.ExpiresAtNS < renewed.ExpiresAtNS || l.ExpiresAtNS < before.ExpiresAtNS || l.MaxClockSkewNS < before.MaxClockSkewNS { + t.Fatalf("grant ahead of durable horizon/skew: disk%+v reply%+v", l, renewed) + } + } + } + if !found { + t.Fatal("re-grant used without durable lease") + } + line, _ := p.VolumeAuthorityLine("v") + if line.Epoch != 1 || line.ReplicaID != "r" { + t.Fatal("re-grant minted authority", line) + } + // Immediate flapping/repeated requests take the memory path: one durable + // re-grant, no extra writes while its positive grant is outstanding. + for i := 0; i < 10; i++ { + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { + t.Fatal(err) + } + } + if writes != 1 { + t.Fatalf("repeat requests amplified durable writes: %d", writes) + } +} + +func TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight(t *testing.T) { + disk, _ := newTempStore(t) + clock := newTestClock() + p := newLeasePublisher(t, disk, time.Second, clock) + bindAndGrant(t, p, "v", "r") + clock.at(3) + req := WorkspaceMoveRequest{RequestID: "force", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} + if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", req.RequestID, "r", 1); err != nil { + t.Fatal("forced preflight was not actually admitted", err) + } + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { + t.Fatal("same-owner re-grant failed", err) + } + if _, err := p.MoveWorkspace(context.Background(), req, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42}); err == nil { + t.Fatal("force ignored the grant committed after its HEAD preflight") + } + line, _ := p.VolumeAuthorityLine("v") + if line.Epoch != 1 { + t.Fatal("two winning successors", line) + } + if len(p.WorkspaceState("v").Moves) != 0 { + t.Fatal("refused forced move reserved an epoch") + } +} + +func TestWorkspaceLeaseSealedAckNeverRegrants(t *testing.T) { + disk, _ := newTempStore(t) + clock := newTestClock() + store := &hookStore{AuthorityStore: disk} + p := newLeasePublisher(t, store, time.Second, clock) + bindAndGrant(t, p, "v", "r") + ctx := context.Background() + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil { + t.Fatal(err) + } + // ACK is the master's durable evidence for this holder's sealed generation. + clock.at(10) + writes := 0 + store.setBefore(func(DurableRecord) error { writes++; return nil }) + got, err := p.RenewWorkspaceLease(ctx, "v", "r", 1) + if err == nil && (!got.Revoking || got.ExpiresAtNS > clock.now().UnixNano()) { + t.Fatalf("sealed/ACKed owner got usable re-grant: %+v", got) + } + if writes != 0 || p.WorkspaceState("v").Ack.HeadGen != 7 { + t.Fatal("sealed proof mutated by re-grant") + } +} From 81a1dc9b1fba26fa3a1a619f40dc7639799c7217 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:10:32 -0800 Subject: [PATCH 17/57] docs(invariants): split the last over-long row; the long-statement list is empty INV-WAL-DATA-SYNC-001 becomes five rows of one property each (automatic sync choice, explicit override, status, allocation at create, prezero). Three clauses with no test of their own are listed as enforced by reading. Every statement in the ledger is now at most 300 characters. Co-Authored-By: Claude Fable 5.2 --- seaweed-block/docs/design/invariants.md | 9 +++++++-- seaweed-block/internal/invcheck/invariants_test.go | 2 +- .../internal/invcheck/testdata/long-statements.txt | 1 - 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d2f32d4b05..f47ea1f081 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -409,7 +409,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -296 rows: 210 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 281 new. +300 rows: 214 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 285 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. @@ -889,9 +889,14 @@ Notes: | ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status | |---|---|---|---|---|---|---| -| `INV-WAL-DATA-SYNC-001` | `SWBLOCK_SYNC=auto` is the default. Once at volume open, Linux WAL/extent sync selects fdatasync only when every resolved non-partition node, including dm/md nodes and all slaves, advertises write through; write back or unknown/unreadable device policy selects fsync. `SWBLOCK_SYNC=fsync|fdatasync` explicitly overrides detection (other platforms retain fsync). The selected mode and reason are logged and exposed in durable status without mid-life reselection. Descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|prezero` selects allocation at create; sparse is the default and fallocate is refused. `SWBLOCK_PREZERO=1` aliases prezero, which explicitly writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `device_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams; `core/frontend/durable/storage_adapter.go` status | `TestDurableProvider_DataSyncStatus` (`core/frontend/durable/data_sync_status_test.go`), `TestExplicitAutoDataSyncPolicy`, `TestDeviceDataSyncStackNodePolicy`, `TestDeviceDataSyncMalformedTopology`, `TestDeviceDataSyncPolicy`, `TestExplicitDataSyncPolicyDoesNotInspectDevice` (`core/storage/device_sync_linux_test.go`; positive cache fixtures witness empty-stack/cycle guards), `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateAllocationIsRefused`, `TestDefaultCreatedVolumeStaysSparse`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | +| `INV-WAL-DATA-SYNC-001` | `SWBLOCK_SYNC=auto` is the default. Once at volume open, Linux WAL/extent sync selects fdatasync only when every resolved non-partition node, including dm/md nodes and all slaves, advertises write through; write back or an unknown or unreadable device policy selects fsync. | M1 Create / Sync / Checkpoint | `data_sync.go`, `device_sync_linux.go`; `walstore.go` data sync seams | `TestExplicitAutoDataSyncPolicy`, `TestDeviceDataSyncStackNodePolicy`, `TestDeviceDataSyncMalformedTopology`, `TestDeviceDataSyncPolicy` (`core/storage/device_sync_linux_test.go`; positive cache fixtures witness empty-stack/cycle guards), `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | +| `INV-WAL-DATA-SYNC-OVERRIDE-001` | An explicit `SWBLOCK_SYNC=fsync` or `SWBLOCK_SYNC=fdatasync` overrides detection without inspecting the device. Platforms other than Linux keep fsync. | M1 Create / Sync / Checkpoint | `data_sync.go` `configuredDataSyncMode`, `selectedDataSyncMode` | `TestExplicitDataSyncPolicyDoesNotInspectDevice` (`core/storage/device_sync_linux_test.go`) | — | ACTIVE | +| `INV-WAL-DATA-SYNC-STATUS-001` | The data sync mode chosen at open and its reason are logged and exposed in durable status. | M1 Create / Sync / Checkpoint | `data_sync.go` `bindDataFileSync`, `DataSyncPolicy`; `core/frontend/durable/storage_adapter.go` status | `TestDurableProvider_DataSyncStatus` (`core/frontend/durable/data_sync_status_test.go`) | — | ACTIVE | +| `INV-WAL-ALLOCATION-001` | `SWBLOCK_ALLOCATION` selects allocation at create: sparse, the default, or prezero; fallocate is refused. `SWBLOCK_PREZERO=1` is an alias of prezero. | M1 Create / Sync / Checkpoint | `walstore_v3.go` Create | `TestDefaultCreatedVolumeStaysSparse`, `TestFallocateAllocationIsRefused` (`core/storage/data_sync_linux_test.go`) | — | ACTIVE | +| `INV-WAL-PREZERO-001` | Prezero writes every byte at create and fsyncs; a file opened as initialized is refused when it has holes or unwritten extent mappings. | M1 Create / Sync / Checkpoint | `walstore_v3.go` Create | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten` (`core/storage/data_sync_linux_test.go`) | — | ACTIVE | | `INV-WAL-FLUSH-SYNC-COVERS-WAL-001` | WAL and extent data live in one store file, and the WAL sync and the flusher's extent sync are the same whole-file fsync or fdatasync of that one descriptor, never a range sync, so every flusher sync also makes the WAL durable. | M1 Serving → Serving (checkpoint) | `core/storage/walstore.go` `openInitializedV3`; `core/storage/data_sync.go` `bindDataFileSync`; `core/storage/flusher.go` `flushOnceInternal` | — | — | STUB | +- `INV-WAL-DATA-SYNC-001` and the rows split from it: enforced by reading, with no test of their own: the mode is not reselected during the life of an open volume; descriptor, map, create and directory durability always use fsync, whatever the data sync mode; an existing file is never prezeroed. Notes: - `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`: the one-file, one-descriptor, no-range-sync clause is enforced by reading; no test asserts it yet. Fault-injection tests replace the WAL sync and the extent sync separately and do not check that they are the same call. diff --git a/seaweed-block/internal/invcheck/invariants_test.go b/seaweed-block/internal/invcheck/invariants_test.go index b439593f7f..50f22c4ed0 100644 --- a/seaweed-block/internal/invcheck/invariants_test.go +++ b/seaweed-block/internal/invcheck/invariants_test.go @@ -263,4 +263,4 @@ func TestInvariantStatementsAreShort(t *testing.T) { // longStatementsLeft is the number of rows testdata/long-statements.txt may // name. It only goes down. -const longStatementsLeft = 1 +const longStatementsLeft = 0 diff --git a/seaweed-block/internal/invcheck/testdata/long-statements.txt b/seaweed-block/internal/invcheck/testdata/long-statements.txt index 413b88ad99..49c4839b4e 100644 --- a/seaweed-block/internal/invcheck/testdata/long-statements.txt +++ b/seaweed-block/internal/invcheck/testdata/long-statements.txt @@ -1,2 +1 @@ # Part B rows whose Statement is over 300 characters. This list only shrinks: split a row into rows of one property each, then delete its line; never add one. -INV-WAL-DATA-SYNC-001 From fd7b4569d4eb92f4ef72766f741a118dac0acbfd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:38:39 -0800 Subject: [PATCH 18/57] test(cli): specify explicit workspace revocation requests --- .../cmd/sw-block/workspace_revoke_test.go | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 seaweed-block/cmd/sw-block/workspace_revoke_test.go diff --git a/seaweed-block/cmd/sw-block/workspace_revoke_test.go b/seaweed-block/cmd/sw-block/workspace_revoke_test.go new file mode 100644 index 0000000000..0ad5a94bc0 --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_revoke_test.go @@ -0,0 +1,113 @@ +package main + +import ( + "context" + "strings" + "testing" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/wsclient" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// Other RPC methods are deliberately absent: revoke must not orchestrate a +// query, detach, acknowledgement or move on the operator's behalf. +type revokeCLIRecorder struct { + control.WorkspaceServiceClient + requests []*control.WorkspaceIdentity + reply *control.WorkspaceLeaseFact + err error +} + +func (r *revokeCLIRecorder) RevokeWorkspace(_ context.Context, q *control.WorkspaceIdentity, _ ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { + r.requests = append(r.requests, q) + return r.reply, r.err +} + +func installRevokeRecorder(t *testing.T, r *revokeCLIRecorder) *int { + t.Helper() + dials := 0 + old := workspaceDial + workspaceDial = func(string) (*wsclient.Client, error) { + dials++ + return wsclient.New(r), nil + } + t.Cleanup(func() { workspaceDial = old }) + return &dials +} + +func revokeArgs(extra ...string) []string { + return append([]string{"ops", "workspace", "revoke", "--master", "127.0.0.1:19090", "--volume", "vol", "--replica", "r1", "--epoch", "3"}, extra...) +} + +// G1 / existing M2 Granted -> Revoking, INV-WS-CLEAN-MOVE-001. +// A successful request is not a host ACK or proof of a detached HEAD. +func TestWorkspaceRevokeSendsOnlyTheExplicitIdentity(t *testing.T) { + r := &revokeCLIRecorder{reply: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3, ExpiresAtNs: 12345, Revoking: true}} + dials := installRevokeRecorder(t, r) + code, out, errOut := runCLI(revokeArgs()) + if code != wsExitOK || *dials != 1 || len(r.requests) != 1 { + t.Fatalf("exit=%d dials=%d requests=%d stdout=%q stderr=%q", code, *dials, len(r.requests), out, errOut) + } + q := r.requests[0] + if q.GetVolumeId() != "vol" || q.GetReplicaId() != "r1" || q.GetEpoch() != 3 { + t.Fatalf("identity=%+v", q) + } + if !strings.Contains(out, "revocation requested") || !strings.Contains(out, "vol") || !strings.Contains(out, "r1@3") { + t.Fatalf("request outcome must name its identity and remain distinct from ACK: %q", out) + } +} + +func TestWorkspaceRevokeRejectsInvalidInputsBeforeDial(t *testing.T) { + r := &revokeCLIRecorder{} + dials := installRevokeRecorder(t, r) + for _, extra := range [][]string{ + {"--master", ""}, {"--volume", ""}, {"--replica", ""}, {"--epoch", "0"}, {"--epoch", "-1"}, + {"--timeout", "0s"}, {"--timeout", "-1s"}, {"unexpected"}, + } { + code, _, _ := runCLI(revokeArgs(extra...)) + if code != wsExitRefusedLocally || *dials != 0 || len(r.requests) != 0 { + t.Fatalf("%v: exit=%d dials=%d requests=%d", extra, code, *dials, len(r.requests)) + } + } +} + +func TestWorkspaceRevokeDoesNotTrustAnUnmatchedReply(t *testing.T) { + for _, tc := range []struct { + name string + reply *control.WorkspaceLeaseFact + }{ + {"missing", nil}, + {"volume", &control.WorkspaceLeaseFact{VolumeId: "other", ReplicaId: "r1", Epoch: 3, Revoking: true}}, + {"replica", &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r2", Epoch: 3, Revoking: true}}, + {"epoch", &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 4, Revoking: true}}, + {"not_revoking", &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3}}, + } { + t.Run(tc.name, func(t *testing.T) { + r := &revokeCLIRecorder{reply: tc.reply} + installRevokeRecorder(t, r) + code, out, errOut := runCLI(revokeArgs()) + if code != wsExitUnknown || out != "" || len(r.requests) != 1 || !strings.Contains(errOut, "unknown") { + t.Fatalf("exit=%d requests=%d stdout=%q stderr=%q", code, len(r.requests), out, errOut) + } + }) + } +} + +func TestWorkspaceRevokePreservesRPCOutcome(t *testing.T) { + for _, tc := range []struct { + code codes.Code + want int + }{{codes.FailedPrecondition, wsExitRefused}, {codes.Unavailable, wsExitUnknown}, {codes.DeadlineExceeded, wsExitUnknown}} { + t.Run(tc.code.String(), func(t *testing.T) { + r := &revokeCLIRecorder{err: status.Error(tc.code, "recorded revoke result")} + installRevokeRecorder(t, r) + code, out, errOut := runCLI(revokeArgs()) + if code != tc.want || out != "" || len(r.requests) != 1 || !strings.Contains(errOut, "recorded revoke result") { + t.Fatalf("exit=%d want=%d requests=%d stdout=%q stderr=%q", code, tc.want, len(r.requests), out, errOut) + } + }) + } +} From 2c681f3cfd090411b0c7c8684e3a26ed65af8e2c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:40:31 -0800 Subject: [PATCH 19/57] test(cli): require an explicit seal choice before revocation --- .../cmd/sw-block/workspace_revoke_test.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/sw-block/workspace_revoke_test.go b/seaweed-block/cmd/sw-block/workspace_revoke_test.go index 0ad5a94bc0..74a26ecbb0 100644 --- a/seaweed-block/cmd/sw-block/workspace_revoke_test.go +++ b/seaweed-block/cmd/sw-block/workspace_revoke_test.go @@ -39,7 +39,7 @@ func installRevokeRecorder(t *testing.T, r *revokeCLIRecorder) *int { } func revokeArgs(extra ...string) []string { - return append([]string{"ops", "workspace", "revoke", "--master", "127.0.0.1:19090", "--volume", "vol", "--replica", "r1", "--epoch", "3"}, extra...) + return append([]string{"ops", "workspace", "revoke", "--master", "127.0.0.1:19090", "--volume", "vol", "--replica", "r1", "--epoch", "3", "--sealed-gen", "9"}, extra...) } // G1 / existing M2 Granted -> Revoking, INV-WS-CLEAN-MOVE-001. @@ -55,7 +55,7 @@ func TestWorkspaceRevokeSendsOnlyTheExplicitIdentity(t *testing.T) { if q.GetVolumeId() != "vol" || q.GetReplicaId() != "r1" || q.GetEpoch() != 3 { t.Fatalf("identity=%+v", q) } - if !strings.Contains(out, "revocation requested") || !strings.Contains(out, "vol") || !strings.Contains(out, "r1@3") { + if !strings.Contains(out, "revocation requested") || !strings.Contains(out, "vol") || !strings.Contains(out, "r1@3") || !strings.Contains(out, "9") { t.Fatalf("request outcome must name its identity and remain distinct from ACK: %q", out) } } @@ -66,6 +66,7 @@ func TestWorkspaceRevokeRejectsInvalidInputsBeforeDial(t *testing.T) { for _, extra := range [][]string{ {"--master", ""}, {"--volume", ""}, {"--replica", ""}, {"--epoch", "0"}, {"--epoch", "-1"}, {"--timeout", "0s"}, {"--timeout", "-1s"}, {"unexpected"}, + {"--sealed-gen", "0"}, {"--without-seal"}, } { code, _, _ := runCLI(revokeArgs(extra...)) if code != wsExitRefusedLocally || *dials != 0 || len(r.requests) != 0 { @@ -74,6 +75,20 @@ func TestWorkspaceRevokeRejectsInvalidInputsBeforeDial(t *testing.T) { } } +func TestWorkspaceRevokeRequiresAnExplicitSealChoice(t *testing.T) { + r := &revokeCLIRecorder{reply: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3, Revoking: true}} + dials := installRevokeRecorder(t, r) + args := revokeArgs() + args = args[:len(args)-2] // omit --sealed-gen entirely + if code, _, _ := runCLI(args); code != wsExitRefusedLocally || *dials != 0 { + t.Fatalf("missing seal choice: exit=%d dials=%d", code, *dials) + } + code, out, errOut := runCLI(append(args, "--without-seal")) + if code != wsExitOK || !strings.Contains(out, "abandoning unpublished tail") || len(r.requests) != 1 { + t.Fatalf("explicit lossy choice: exit=%d requests=%d out=%q err=%q", code, len(r.requests), out, errOut) + } +} + func TestWorkspaceRevokeDoesNotTrustAnUnmatchedReply(t *testing.T) { for _, tc := range []struct { name string From 5a2fe0c657f9493a8ac9a67e7cdec38c44e4f665 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:40:47 -0800 Subject: [PATCH 20/57] test: witness sealed same-host clean move and binding retirement --- .../workspace_same_host_clean_test.go | 57 ++++++++++++++++++ .../master/workspace_same_host_clean_test.go | 58 +++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100644 seaweed-block/core/authority/workspace_same_host_clean_test.go create mode 100644 seaweed-block/core/host/master/workspace_same_host_clean_test.go diff --git a/seaweed-block/core/authority/workspace_same_host_clean_test.go b/seaweed-block/core/authority/workspace_same_host_clean_test.go new file mode 100644 index 0000000000..de0052305c --- /dev/null +++ b/seaweed-block/core/authority/workspace_same_host_clean_test.go @@ -0,0 +1,57 @@ +package authority + +import ( + "context" + "testing" + "time" +) + +// INV-WS-SAME-HOST-CLEAN-MOVE-001: an unchanged sealed generation and its +// durable ACK remain a clean-move proof after the lease expires overnight. +func TestWorkspaceSameHostCleanMoveUsesOvernightSeal(t *testing.T) { + disk, _ := newTempStore(t) + clock := newTestClock() + p := newLeasePublisher(t, disk, time.Second, clock) + bindAndGrant(t, p, "v", "r") + ctx := context.Background() + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil { + t.Fatal(err) + } + clock.at(86400) + req := WorkspaceMoveRequest{RequestID: "return", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "host", TargetHost: "host", ExpectedEpoch: 1, TargetDataAddr: "d", TargetCtrlAddr: "c", Kind: "clean"} + head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 42, Detached: true} + for _, bad := range []WorkspaceHead{ + {Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 42}, + {Gen: 8, Epoch: 1, Holder: "host/r", RemoteLSN: 42, Detached: true}, + } { + if _, err := p.MoveWorkspace(ctx, req, bad); err == nil { + t.Fatal("same-host move bypassed sealed-generation proof", bad) + } + } + forced := req + forced.Kind, forced.Force = "forced", true + if _, err := p.MoveWorkspace(ctx, forced, head); err == nil { + t.Fatal("same-host forced move accepted") + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 1 || len(p.WorkspaceState("v").Moves) != 0 { + t.Fatal("refusal reserved or published authority", line) + } + grant, err := p.MoveWorkspace(ctx, req, head) + if err != nil { + t.Fatal("sealed same-host clean move refused", err) + } + if !grant.Issued || grant.NewEpoch != 2 || grant.OldHost != "host" || grant.NewHost != "host" || grant.HeadGen != 7 || grant.RemoteLSN != 42 { + t.Fatal("wrong journaled successor", grant) + } + again, err := p.MoveWorkspace(ctx, req, WorkspaceHead{}) + if err != nil || again != grant { + t.Fatal("same-ID replay changed the successor", again, err) + } + loaded := NewPublisher(nil, WithStore(disk)).WorkspaceState("v") + if loaded == nil || len(loaded.Moves) != 1 || loaded.Moves[0] != grant { + t.Fatal("same-host grant not durable", loaded) + } +} diff --git a/seaweed-block/core/host/master/workspace_same_host_clean_test.go b/seaweed-block/core/host/master/workspace_same_host_clean_test.go new file mode 100644 index 0000000000..d45ca68761 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_same_host_clean_test.go @@ -0,0 +1,58 @@ +package master + +import ( + "testing" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// INV-WS-SAME-HOST-CLEAN-MOVE-001: retirement belongs to an epoch, so the +// old epoch's replay cannot retire the re-prepared same-host binding. +func TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding(t *testing.T) { + h, conn, ctx := reviewBindingHost(t) + reviewCreate(t, conn, ctx, "v") + ws := control.NewWorkspaceServiceClient(conn) + b := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"} + if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "v", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + reviewHeartbeat(t, conn, ctx, "v", "node-a", b.DataAddr, b.CtrlAddr) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + if line := waitAuthorityLine(t, h.Publisher(), "v"); line.Epoch != 1 { + t.Fatal(line) + } + id := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1} + 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) + } + if got, ok, err := h.Lifecycle().WorkspaceBindings.Get("v"); err != nil || !ok || !got.Retired { + t.Fatal("ACK did not retire the old binding", got, err) + } + if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal("same-host re-prepare refused", err) + } + req := &control.WorkspaceMove{RequestId: "return", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-a", TargetDataAddr: b.DataAddr, TargetCtrlAddr: b.CtrlAddr, Kind: "clean"} + if _, err := ws.MoveWorkspace(ctx, req); err != nil { + t.Fatal("same-host clean move refused over RPC", err) + } + if _, err := ws.MoveWorkspace(ctx, req); err != nil { + t.Fatal("same-host move replay refused", err) + } + if line, _ := h.Publisher().VolumeAuthorityLine("v"); line.Epoch != 2 || line.DataAddr != b.DataAddr || line.CtrlAddr != b.CtrlAddr { + t.Fatal("same-host move did not publish exactly the next epoch", line) + } + if got, ok, err := h.Lifecycle().WorkspaceBindings.Get("v"); err != nil || !ok || got.Retired { + t.Fatal("old epoch retired the re-prepared binding", got, err) + } +} From 11079b620a7e6bfe24e8085eb08144a0b346e27c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:41:06 -0800 Subject: [PATCH 21/57] test: inspect the volume binding list explicitly --- .../core/host/master/workspace_same_host_clean_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/host/master/workspace_same_host_clean_test.go b/seaweed-block/core/host/master/workspace_same_host_clean_test.go index d45ca68761..74df103b90 100644 --- a/seaweed-block/core/host/master/workspace_same_host_clean_test.go +++ b/seaweed-block/core/host/master/workspace_same_host_clean_test.go @@ -36,7 +36,7 @@ func TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding(t *testing.T) { if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil { t.Fatal(err) } - if got, ok, err := h.Lifecycle().WorkspaceBindings.Get("v"); err != nil || !ok || !got.Retired { + if got, ok, err := h.Lifecycle().WorkspaceBindings.Get("v"); err != nil || !ok || len(got) != 1 || !got[0].Retired { t.Fatal("ACK did not retire the old binding", got, err) } if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { @@ -52,7 +52,7 @@ func TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding(t *testing.T) { if line, _ := h.Publisher().VolumeAuthorityLine("v"); line.Epoch != 2 || line.DataAddr != b.DataAddr || line.CtrlAddr != b.CtrlAddr { t.Fatal("same-host move did not publish exactly the next epoch", line) } - if got, ok, err := h.Lifecycle().WorkspaceBindings.Get("v"); err != nil || !ok || got.Retired { + if got, ok, err := h.Lifecycle().WorkspaceBindings.Get("v"); err != nil || !ok || len(got) != 1 || got[0].Retired { t.Fatal("old epoch retired the re-prepared binding", got, err) } } From b3e98de4a4d58dd7dcf3b82e970ee8eaa6b00706 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:41:14 -0800 Subject: [PATCH 22/57] feat(cli): expose explicit workspace revocation over the existing RPC --- seaweed-block/cmd/sw-block/workspace.go | 2 + .../cmd/sw-block/workspace_revoke.go | 61 +++++++++++++++++++ seaweed-block/core/rpc/wsclient/revoke.go | 25 ++++++++ 3 files changed, 88 insertions(+) create mode 100644 seaweed-block/cmd/sw-block/workspace_revoke.go create mode 100644 seaweed-block/core/rpc/wsclient/revoke.go diff --git a/seaweed-block/cmd/sw-block/workspace.go b/seaweed-block/cmd/sw-block/workspace.go index b1e7d1693f..b16c413470 100644 --- a/seaweed-block/cmd/sw-block/workspace.go +++ b/seaweed-block/cmd/sw-block/workspace.go @@ -65,6 +65,8 @@ func runOpsWorkspace(args []string, stdout, stderr io.Writer) int { return wsExitRefusedLocally } switch args[0] { + case "revoke": + return runWorkspaceRevoke(args[1:], stdout, stderr) case "force-move": return runWorkspaceForceMove(args[1:], stdout, stderr) case "lost-range": diff --git a/seaweed-block/cmd/sw-block/workspace_revoke.go b/seaweed-block/cmd/sw-block/workspace_revoke.go new file mode 100644 index 0000000000..6805e08ac8 --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_revoke.go @@ -0,0 +1,61 @@ +package main + +import ( + "context" + "flag" + "fmt" + "io" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/wsclient" +) + +// M2 Granted -> Revoking, INV-WS-CLEAN-MOVE-001. The seal choice is an +// operator statement only; no HEAD lookup or ACK is synthesized here. +func runWorkspaceRevoke(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops workspace revoke", flag.ContinueOnError) + fs.SetOutput(stderr) + var id control.WorkspaceIdentity + var master string + var sealedGen uint64 + var withoutSeal bool + var timeout time.Duration + fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port") + fs.StringVar(&id.VolumeId, "volume", "", "volume id") + fs.StringVar(&id.ReplicaId, "replica", "", "current logical replica id") + fs.Uint64Var(&id.Epoch, "epoch", 0, "current holder epoch") + fs.Uint64Var(&sealedGen, "sealed-gen", 0, "HEAD generation printed by detach --plain; operator assertion, not verified here") + fs.BoolVar(&withoutSeal, "without-seal", false, "explicitly abandon the unpublished tail; a clean move may not be possible") + fs.DurationVar(&timeout, "timeout", wsDefaultTimeout, "bound for the RPC") + if err := fs.Parse(args); err != nil { + return wsExitRefusedLocally + } + if fs.NArg() != 0 || master == "" || id.VolumeId == "" || id.ReplicaId == "" || id.Epoch == 0 || timeout <= 0 || (sealedGen > 0) == withoutSeal { + fmt.Fprintln(stderr, "workspace revoke: refused locally; require --master, --volume, --replica, positive --epoch/--timeout and exactly one of positive --sealed-gen or --without-seal") + return wsExitRefusedLocally + } + c, err := workspaceDial(master) + if err != nil { + fmt.Fprintf(stderr, "workspace revoke: refused locally, nothing sent: %v\n", err) + return wsExitRefusedLocally + } + defer c.Close() + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + lease, err := c.Revoke(ctx, &id) + if err != nil { + fmt.Fprintf(stderr, "workspace revoke: %v\n", err) + if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown { + fmt.Fprintln(stderr, "workspace revoke: outcome unknown; inspect workspace show before proceeding") + } + return workspaceExit(wsclient.OutcomeOf(err)) + } + fmt.Fprintf(stdout, "revocation requested: volume %s holder %s@%d expiry_ns %d\n", id.VolumeId, id.ReplicaId, id.Epoch, lease.GetExpiresAtNs()) + if withoutSeal { + fmt.Fprintln(stdout, "operator statement: abandoning unpublished tail (--without-seal)") + } else { + fmt.Fprintf(stdout, "operator-stated sealed HEAD generation: %d (not verified); workspace show must report ACK at this generation before move --clean\n", sealedGen) + } + return wsExitOK +} diff --git a/seaweed-block/core/rpc/wsclient/revoke.go b/seaweed-block/core/rpc/wsclient/revoke.go new file mode 100644 index 0000000000..232b0b04ce --- /dev/null +++ b/seaweed-block/core/rpc/wsclient/revoke.go @@ -0,0 +1,25 @@ +package wsclient + +import ( + "context" + "errors" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// Revoke implements M2 Granted -> Revoking (INV-WS-CLEAN-MOVE-001). +// Its reply proves the request was recorded, not that the host has ACKed. +func (c *Client) Revoke(ctx context.Context, id *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) { + const op = "workspace revoke" + if id.GetVolumeId() == "" || id.GetReplicaId() == "" || id.GetEpoch() == 0 { + return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: errors.New("volume, replica and positive epoch are required")} + } + lease, err := c.rpc.RevokeWorkspace(ctx, id) + if err != nil { + return nil, classify(op, err) + } + if lease.GetVolumeId() != id.GetVolumeId() || lease.GetReplicaId() != id.GetReplicaId() || lease.GetEpoch() != id.GetEpoch() || !lease.GetRevoking() { + return nil, &Error{Outcome: OutcomeUnknown, Op: op, Err: errors.New("reply does not match the requested revoking identity")} + } + return lease, nil +} From a1f524e6255cea125604461dd4620a86a89bbf35 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:42:14 -0800 Subject: [PATCH 23/57] test(cli): specify clean move encoding and grant binding --- .../cmd/sw-block/workspace_clean_test.go | 100 ++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 seaweed-block/cmd/sw-block/workspace_clean_test.go diff --git a/seaweed-block/cmd/sw-block/workspace_clean_test.go b/seaweed-block/cmd/sw-block/workspace_clean_test.go new file mode 100644 index 0000000000..0892b69855 --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_clean_test.go @@ -0,0 +1,100 @@ +package main + +import ( + "strings" + "testing" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func cleanMoveArgs(addr string, extra ...string) []string { + return append([]string{"ops", "workspace", "move", "--clean", "--master", addr, "--volume", "vol", "--replica", "r1", "--epoch", "3", "--request-id", "clean-1", "--target-host", "node-b", "--target-data", "10.0.0.2:3260", "--target-ctrl", "10.0.0.2:9100"}, extra...) +} + +func cleanGrant(q *control.WorkspaceMove) *control.WorkspaceGrant { + g := wsGrant(q) + g.Kind, g.LostRange = "clean", nil + return g +} + +// Existing M2 Acked -> Moved (clean), INV-WS-CLEAN-MOVE-001. +func TestWorkspaceCleanMoveSendsOnlyTheExplicitCleanRequest(t *testing.T) { + f := &fakeWorkspace{move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + if q.GetKind() != "clean" || q.GetForce() || q.GetVolumeId() != "vol" || q.GetRequestId() != "clean-1" || q.GetExpectedReplicaId() != "r1" || q.GetExpectedEpoch() != 3 || q.GetTargetReplicaId() != "r1" || q.GetTargetServerId() != "node-b" || q.GetTargetDataAddr() != "10.0.0.2:3260" || q.GetTargetCtrlAddr() != "10.0.0.2:9100" { + t.Errorf("clean request=%+v", q) + } + return cleanGrant(q), nil + }} + addr, _ := startFakeWorkspace(t, f) + for i := 0; i < 2; i++ { + code, out, errOut := runCLI(cleanMoveArgs(addr)) + if code != wsExitOK || !strings.Contains(out, "clean move issued") || !strings.Contains(out, "clean-1") || !strings.Contains(out, "start") || strings.Contains(out, "no loss") { + t.Fatalf("exit=%d out=%q err=%q", code, out, errOut) + } + } + if f.total() != 2 || f.n("MoveWorkspace") != 2 { + t.Fatalf("unexpected orchestration calls=%d", f.total()) + } +} + +func TestWorkspaceCleanMoveRefusesBadInputBeforeDial(t *testing.T) { + f := &fakeWorkspace{} + addr, dials := startFakeWorkspace(t, f) + for _, extra := range [][]string{{"--clean=false"}, {"--master", ""}, {"--volume", ""}, {"--replica", ""}, {"--epoch", "0"}, {"--request-id", ""}, {"--target-host", ""}, {"--target-data", ""}, {"--target-ctrl", ""}, {"--timeout", "0s"}, {"--force"}, {"unexpected"}} { + if code, _, _ := runCLI(cleanMoveArgs(addr, extra...)); code != wsExitRefusedLocally || *dials != 0 || f.total() != 0 { + t.Fatalf("%v: exit=%d dials=%d calls=%d", extra, code, *dials, f.total()) + } + } +} + +func TestWorkspaceCleanMoveRejectsMismatchedGrant(t *testing.T) { + for _, tc := range []struct { + name string + edit func(*control.WorkspaceGrant) + }{ + {"unissued", func(g *control.WorkspaceGrant) { g.Issued = false }}, + {"forced", func(g *control.WorkspaceGrant) { g.Kind = "forced" }}, + {"request", func(g *control.WorkspaceGrant) { g.RequestId = "other" }}, + {"volume", func(g *control.WorkspaceGrant) { g.VolumeId = "other" }}, + {"replica", func(g *control.WorkspaceGrant) { g.OldReplicaId = "other" }}, + {"old_epoch", func(g *control.WorkspaceGrant) { g.OldEpoch++ }}, + {"target_replica", func(g *control.WorkspaceGrant) { g.NewReplicaId = "other" }}, + {"target_host", func(g *control.WorkspaceGrant) { g.NewHost = "other" }}, + {"new_epoch", func(g *control.WorkspaceGrant) { g.NewEpoch = g.OldEpoch }}, + } { + t.Run(tc.name, func(t *testing.T) { + f := &fakeWorkspace{move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + g := cleanGrant(q) + tc.edit(g) + return g, nil + }} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(cleanMoveArgs(addr)) + if code != wsExitUnknown || out != "" || !strings.Contains(errOut, "SAME --request-id clean-1") { + t.Fatalf("exit=%d out=%q err=%q", code, out, errOut) + } + }) + } +} + +func TestWorkspaceCleanMovePreservesRefusalAndUnknown(t *testing.T) { + for _, tc := range []struct { + name string + err error + want int + }{ + {"unsealed_or_no_ack", status.Error(codes.FailedPrecondition, "HEAD not sealed or acknowledgement missing"), wsExitRefused}, + {"lost_reply", status.Error(codes.Unavailable, "reply lost"), wsExitUnknown}, + } { + t.Run(tc.name, func(t *testing.T) { + f := &fakeWorkspace{move: func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) { return nil, tc.err }} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(cleanMoveArgs(addr)) + if code != tc.want || out != "" || (tc.want == wsExitUnknown && !strings.Contains(errOut, "SAME --request-id clean-1")) { + t.Fatalf("exit=%d out=%q err=%q", code, out, errOut) + } + }) + } +} From a20e83872cdb1be536b909a490a4f1832ab08ab7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:43:01 -0800 Subject: [PATCH 24/57] feat(cli): encode clean authority moves without orchestration --- seaweed-block/cmd/sw-block/workspace.go | 2 + seaweed-block/cmd/sw-block/workspace_clean.go | 60 +++++++++++++++++++ seaweed-block/core/rpc/wsclient/clean_move.go | 26 ++++++++ seaweed-block/core/rpc/wsclient/wsclient.go | 4 +- 4 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/cmd/sw-block/workspace_clean.go create mode 100644 seaweed-block/core/rpc/wsclient/clean_move.go diff --git a/seaweed-block/cmd/sw-block/workspace.go b/seaweed-block/cmd/sw-block/workspace.go index b16c413470..d69ff1e587 100644 --- a/seaweed-block/cmd/sw-block/workspace.go +++ b/seaweed-block/cmd/sw-block/workspace.go @@ -65,6 +65,8 @@ func runOpsWorkspace(args []string, stdout, stderr io.Writer) int { return wsExitRefusedLocally } switch args[0] { + case "move": + return runWorkspaceCleanMove(args[1:], stdout, stderr) case "revoke": return runWorkspaceRevoke(args[1:], stdout, stderr) case "force-move": diff --git a/seaweed-block/cmd/sw-block/workspace_clean.go b/seaweed-block/cmd/sw-block/workspace_clean.go new file mode 100644 index 0000000000..1b940489b3 --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_clean.go @@ -0,0 +1,60 @@ +package main + +import ( + "context" + "flag" + "fmt" + "io" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/wsclient" +) + +// M2 Acked -> Moved (clean), INV-WS-CLEAN-MOVE-001: encode only; do not +// synthesize a seal/ACK, release a lease or start the target here. +func runWorkspaceCleanMove(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops workspace move", flag.ContinueOnError) + fs.SetOutput(stderr) + var q control.WorkspaceMove + var master string + var clean bool + var timeout time.Duration + fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port") + fs.StringVar(&q.VolumeId, "volume", "", "volume id") + fs.StringVar(&q.ExpectedReplicaId, "replica", "", "current logical replica id") + fs.Uint64Var(&q.ExpectedEpoch, "epoch", 0, "current holder epoch") + fs.StringVar(&q.RequestId, "request-id", "", "operator-supplied move id; reuse on unknown outcome") + fs.StringVar(&q.TargetServerId, "target-host", "", "target node; may be the source host once sealed (requires server support)") + fs.StringVar(&q.TargetDataAddr, "target-data", "", "target data address host:port") + fs.StringVar(&q.TargetCtrlAddr, "target-ctrl", "", "target control address host:port") + fs.BoolVar(&clean, "clean", false, "required: move using the detached HEAD and matching recorded host ACK") + fs.DurationVar(&timeout, "timeout", wsDefaultTimeout, "bound for the RPC") + if err := fs.Parse(args); err != nil { + return wsExitRefusedLocally + } + if fs.NArg() != 0 || !clean || master == "" || q.VolumeId == "" || q.ExpectedReplicaId == "" || q.ExpectedEpoch == 0 || q.RequestId == "" || q.TargetServerId == "" || q.TargetDataAddr == "" || q.TargetCtrlAddr == "" || timeout <= 0 { + fmt.Fprintln(stderr, "workspace move: refused locally; --clean, --master, --volume, --replica, positive --epoch/--timeout, --request-id and target host/data/ctrl are required") + return wsExitRefusedLocally + } + q.Kind, q.TargetReplicaId = "clean", q.ExpectedReplicaId + c, err := workspaceDial(master) + if err != nil { + fmt.Fprintf(stderr, "workspace move: refused locally, nothing sent: %v\n", err) + return wsExitRefusedLocally + } + defer c.Close() + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + g, err := c.CleanMove(ctx, &q) + if err != nil { + fmt.Fprintf(stderr, "workspace move: %v\n", err) + if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown { + fmt.Fprintf(stderr, "workspace move: outcome unknown; rerun with the SAME --request-id %s\n", q.RequestId) + } + return workspaceExit(wsclient.OutcomeOf(err)) + } + fmt.Fprintf(stdout, "clean move issued: volume %s request %s: %s@%d -> %s@%d on %s (sealed HEAD gen %d, remote LSN %d)\n", g.GetVolumeId(), g.GetRequestId(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewReplicaId(), g.GetNewEpoch(), g.GetNewHost(), g.GetHeadGen(), g.GetRemoteLsn()) + fmt.Fprintf(stdout, "next: start volume %s on %s (this command moved authority only)\n", g.GetVolumeId(), g.GetNewHost()) + return wsExitOK +} diff --git a/seaweed-block/core/rpc/wsclient/clean_move.go b/seaweed-block/core/rpc/wsclient/clean_move.go new file mode 100644 index 0000000000..f7fa8296eb --- /dev/null +++ b/seaweed-block/core/rpc/wsclient/clean_move.go @@ -0,0 +1,26 @@ +package wsclient + +import ( + "context" + "errors" + "fmt" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// CleanMove implements M2 Acked -> Moved (clean), INV-WS-CLEAN-MOVE-001. +// The master checks the actual detached HEAD and recorded ACK. +func (c *Client) CleanMove(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + const op = "clean move" + if q.GetKind() != "clean" || q.GetForce() || q.GetVolumeId() == "" || q.GetRequestId() == "" || q.GetExpectedReplicaId() == "" || q.GetExpectedEpoch() == 0 || q.GetTargetReplicaId() != q.GetExpectedReplicaId() || q.GetTargetServerId() == "" || q.GetTargetDataAddr() == "" || q.GetTargetCtrlAddr() == "" { + return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: errors.New("clean move requires explicit identity, request id and target endpoints; force is not allowed")} + } + g, err := c.rpc.MoveWorkspace(ctx, q) + if err != nil { + return nil, classify(op, err) + } + if err := checkGrant(g, q); err != nil { + return nil, &Error{Outcome: OutcomeUnknown, Op: op, Err: fmt.Errorf("%v; rerun with the same request id", err)} + } + return g, nil +} diff --git a/seaweed-block/core/rpc/wsclient/wsclient.go b/seaweed-block/core/rpc/wsclient/wsclient.go index ec8c868973..78e980abff 100644 --- a/seaweed-block/core/rpc/wsclient/wsclient.go +++ b/seaweed-block/core/rpc/wsclient/wsclient.go @@ -213,11 +213,11 @@ func (c *Client) ForceMove(ctx context.Context, m ForcedMove) (*control.Workspac } // checkGrant binds a successful answer to the request that was sent: an -// issued forced grant for this request id and volume, from the expected +// issued grant of the requested kind for this request id and volume, from the expected // holder at the expected epoch to the requested target, at a higher epoch. // Anything else leaves the outcome unknown. func checkGrant(g *control.WorkspaceGrant, q *control.WorkspaceMove) error { - if !g.GetIssued() || g.GetKind() != "forced" || g.GetRequestId() != q.GetRequestId() || g.GetVolumeId() != q.GetVolumeId() || + if !g.GetIssued() || g.GetKind() != q.GetKind() || g.GetRequestId() != q.GetRequestId() || g.GetVolumeId() != q.GetVolumeId() || g.GetOldReplicaId() != q.GetExpectedReplicaId() || g.GetOldEpoch() != q.GetExpectedEpoch() || g.GetNewReplicaId() != q.GetTargetReplicaId() || g.GetNewHost() != q.GetTargetServerId() || g.GetNewEpoch() <= g.GetOldEpoch() { return fmt.Errorf("the answer does not match the request (issued=%t kind=%q request=%q volume=%q old=%s@%d new=%s@%d on %q)", From 0dde418dfde8726fb30e874f25f5f867d410adfa Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:45:52 -0800 Subject: [PATCH 25/57] test(cli): specify plain detach request and seal readout --- .../cmd/sw-block/chunk_plain_test.go | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 seaweed-block/cmd/sw-block/chunk_plain_test.go diff --git a/seaweed-block/cmd/sw-block/chunk_plain_test.go b/seaweed-block/cmd/sw-block/chunk_plain_test.go new file mode 100644 index 0000000000..875a43414a --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_plain_test.go @@ -0,0 +1,52 @@ +package main + +import ( + "net/http" + "strings" + "testing" +) + +// M5 PlainStop -> Quiesce, INV-CUT-PLAIN-DETACH-001: encode the existing +// idle seal request; preserve JSON stdout for existing operator tooling. +func TestOpsChunkPlainDetachSendsTheExistingRequest(t *testing.T) { + const reply = `{"volumeID":"vol","headGen":11,"headState":"detached"}` + srv, got := chunkServer(t, http.StatusOK, reply) + code, out, errOut := runChunk("detach", "--plain", "--volume", "vol", "--status-addr", srv.URL, "--timeout", "2s") + if code != 0 || out != reply || !strings.Contains(errOut, "sealed HEAD generation: 11\n") { + t.Fatalf("exit=%d stdout=%q stderr=%q", code, out, errOut) + } + if len(*got) != 1 || (*got)[0].path != "/chunk/detach" || (*got)[0].body["plain"] != true || (*got)[0].body["volumeID"] != "vol" || (*got)[0].body["timeoutMs"] != float64(2000) { + t.Fatalf("plain request=%+v", *got) + } + for _, key := range []string{"frozen", "freezeStartedAtNs", "allowOverBudget"} { + if _, ok := (*got)[0].body[key]; ok { + t.Fatalf("plain request contains %s", key) + } + } +} + +func TestOpsChunkPlainDetachRefusesInvalidMixBeforeHTTP(t *testing.T) { + srv, got := chunkServer(t, http.StatusOK, `{}`) + for _, extra := range [][]string{ + {"--frozen", "--freeze-started-at-ns", "1"}, {"--freeze-started-at-ns", "1"}, {"--allow-over-budget"}, + {"--timeout", "0s"}, {"--timeout", "-1s"}, {"unexpected"}, + } { + args := append([]string{"detach", "--plain", "--volume", "vol", "--status-addr", srv.URL}, extra...) + if code, _, _ := runChunk(args...); code != 2 || len(*got) != 0 { + t.Fatalf("%v: exit=%d requests=%d", extra, code, len(*got)) + } + } +} + +func TestOpsChunkPlainDetachPreservesTypedFailure(t *testing.T) { + for _, reason := range []string{"busy", "fenced", "outcome_unknown"} { + t.Run(reason, func(t *testing.T) { + reply := `{"code":"` + reason + `","message":"seal refused","retryable":true}` + srv, got := chunkServer(t, http.StatusConflict, reply) + code, out, errOut := runChunk("detach", "--plain", "--volume", "vol", "--status-addr", srv.URL) + if code != 1 || out != reply+"\n" || len(*got) != 1 || strings.Contains(errOut, "sealed HEAD generation:") { + t.Fatalf("exit=%d stdout=%q stderr=%q requests=%d", code, out, errOut, len(*got)) + } + }) + } +} From dacd9be6ff170185727dc1404069d8f4a29d45e1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:46:24 -0800 Subject: [PATCH 26/57] feat(cli): expose plain detach and print the sealed generation --- seaweed-block/cmd/sw-block/chunk.go | 18 +++++++-- seaweed-block/cmd/sw-block/chunk_plain.go | 37 +++++++++++++++++++ .../cmd/sw-block/chunk_plain_test.go | 2 +- 3 files changed, 52 insertions(+), 5 deletions(-) create mode 100644 seaweed-block/cmd/sw-block/chunk_plain.go diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index b672e3bb9e..d037546ad2 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -259,14 +259,15 @@ func chunkSnapshot(args []string, stdout, stderr io.Writer) int { func chunkDetach(args []string, stdout, stderr io.Writer) int { fs := chunkFlagSet("detach", stderr) var ( - volumeID, statusAddr string - timeout time.Duration - frozen, allowOverBudget bool - freezeStartedAtNs int64 + volumeID, statusAddr string + timeout time.Duration + plain, frozen, allowOverBudget bool + freezeStartedAtNs int64 ) fs.StringVar(&volumeID, "volume", "", "volume id") fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") fs.DurationVar(&timeout, "timeout", 120*time.Second, "operation bound (capped at the server's OpDeadline)") + fs.BoolVar(&plain, "plain", false, "seal an idle volume without pre-copy; prints sealed HEAD generation on stderr") fs.BoolVar(&frozen, "frozen", false, "not supported in this release: the server refuses a frozen detach (frozen_detach_unsupported)") fs.Int64Var(&freezeStartedAtNs, "freeze-started-at-ns", 0, "not supported in this release; only valid with --frozen") fs.BoolVar(&allowOverBudget, "allow-over-budget", false, "not supported in this release; only valid with --frozen") @@ -276,10 +277,19 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int { if volumeID == "" || statusAddr == "" { return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false) } + // M5 PlainStop -> Quiesce, INV-CUT-PLAIN-DETACH-001: an idle seal has + // its own finite caller bound and cannot encode frozen policy fields. + if plain && (timeout <= 0 || frozen || freezeStartedAtNs != 0 || allowOverBudget || fs.NArg() != 0) { + return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--plain requires positive --timeout, no extra arguments and no frozen options", false) + } if (frozen && freezeStartedAtNs <= 0) || (!frozen && (freezeStartedAtNs != 0 || allowOverBudget)) { return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--frozen requires --freeze-started-at-ns; --allow-over-budget requires --frozen", false) } body := map[string]any{"volumeID": volumeID} + if plain { + body["plain"] = true + return chunkPlainDetachPost(statusAddr, volumeID, timeout, body, stdout, stderr) + } if frozen { body["frozen"] = true body["freezeStartedAtNs"] = freezeStartedAtNs diff --git a/seaweed-block/cmd/sw-block/chunk_plain.go b/seaweed-block/cmd/sw-block/chunk_plain.go new file mode 100644 index 0000000000..e558f5e1f1 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_plain.go @@ -0,0 +1,37 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// M5 PlainStop -> Quiesce, INV-CUT-PLAIN-DETACH-001. Keep stdout JSON +// unchanged; the separate human readout identifies the seal to the operator. +func chunkPlainDetachPost(addr, volume string, timeout time.Duration, body map[string]any, stdout, stderr io.Writer) int { + var out bytes.Buffer + code := chunkPost("detach", addr, "/chunk/detach", timeout, body, &out, stderr) + if code != ops.VolumeStatusExitOK { + if err := writeAll(stdout, out.Bytes()); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk detach: write result: %v\n", err) + } + return code + } + var seal struct { + VolumeID string `json:"volumeID"` + HeadGen uint64 `json:"headGen"` + } + if err := json.Unmarshal(out.Bytes(), &seal); err != nil || seal.VolumeID != volume || seal.HeadGen == 0 { + return chunkFail("detach", stdout, stderr, chunkExitFailed, codeInternalCLI, "plain detach outcome unknown: reply has no matching volume and sealed HEAD generation", false) + } + if err := writeAll(stdout, out.Bytes()); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk detach: write result: %v\n", err) + return chunkExitFailed + } + fmt.Fprintf(stderr, "sealed HEAD generation: %d\n", seal.HeadGen) + return ops.VolumeStatusExitOK +} diff --git a/seaweed-block/cmd/sw-block/chunk_plain_test.go b/seaweed-block/cmd/sw-block/chunk_plain_test.go index 875a43414a..57585f858c 100644 --- a/seaweed-block/cmd/sw-block/chunk_plain_test.go +++ b/seaweed-block/cmd/sw-block/chunk_plain_test.go @@ -9,7 +9,7 @@ import ( // M5 PlainStop -> Quiesce, INV-CUT-PLAIN-DETACH-001: encode the existing // idle seal request; preserve JSON stdout for existing operator tooling. func TestOpsChunkPlainDetachSendsTheExistingRequest(t *testing.T) { - const reply = `{"volumeID":"vol","headGen":11,"headState":"detached"}` + const reply = `{"volumeID":"vol","headGen":11}` srv, got := chunkServer(t, http.StatusOK, reply) code, out, errOut := runChunk("detach", "--plain", "--volume", "vol", "--status-addr", srv.URL, "--timeout", "2s") if code != 0 || out != reply || !strings.Contains(errOut, "sealed HEAD generation: 11\n") { From 4d5056090ca28c72a5e87ff86dddfc038e0e5213 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:46:37 -0800 Subject: [PATCH 27/57] test(cli): preserve exact existing HTTP error response bytes --- seaweed-block/cmd/sw-block/chunk_plain_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/cmd/sw-block/chunk_plain_test.go b/seaweed-block/cmd/sw-block/chunk_plain_test.go index 57585f858c..09d9befd25 100644 --- a/seaweed-block/cmd/sw-block/chunk_plain_test.go +++ b/seaweed-block/cmd/sw-block/chunk_plain_test.go @@ -44,7 +44,7 @@ func TestOpsChunkPlainDetachPreservesTypedFailure(t *testing.T) { reply := `{"code":"` + reason + `","message":"seal refused","retryable":true}` srv, got := chunkServer(t, http.StatusConflict, reply) code, out, errOut := runChunk("detach", "--plain", "--volume", "vol", "--status-addr", srv.URL) - if code != 1 || out != reply+"\n" || len(*got) != 1 || strings.Contains(errOut, "sealed HEAD generation:") { + if code != 1 || out != reply || len(*got) != 1 || strings.Contains(errOut, "sealed HEAD generation:") { t.Fatalf("exit=%d stdout=%q stderr=%q requests=%d", code, out, errOut, len(*got)) } }) From f99538eb5da680b72ccb513b46bfef806d37c4fc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:47:31 -0800 Subject: [PATCH 28/57] test(cli): specify the read-only workspace handoff view --- .../cmd/sw-block/workspace_show_test.go | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 seaweed-block/cmd/sw-block/workspace_show_test.go diff --git a/seaweed-block/cmd/sw-block/workspace_show_test.go b/seaweed-block/cmd/sw-block/workspace_show_test.go new file mode 100644 index 0000000000..207657d4c7 --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_show_test.go @@ -0,0 +1,92 @@ +package main + +import ( + "context" + "strings" + "testing" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/wsclient" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type workspaceShowRecorder struct { + control.WorkspaceServiceClient + requests []*control.WorkspaceVolume + reply *control.WorkspaceStatus + err error +} + +func (r *workspaceShowRecorder) QueryWorkspace(_ context.Context, q *control.WorkspaceVolume, _ ...grpc.CallOption) (*control.WorkspaceStatus, error) { + r.requests = append(r.requests, q) + return r.reply, r.err +} + +func installShowRecorder(t *testing.T, r *workspaceShowRecorder) *int { + t.Helper() + dials := 0 + old := workspaceDial + workspaceDial = func(string) (*wsclient.Client, error) { dials++; return wsclient.New(r), nil } + t.Cleanup(func() { workspaceDial = old }) + return &dials +} + +// Query-only view of M2 Granted -> Revoking -> Acked -> Moved (clean), +// INV-WS-CLEAN-MOVE-001. A recorded ACK must remain distinct from a request. +func TestWorkspaceShowPrintsTheRecordedLeaseACKAndMoves(t *testing.T) { + r := &workspaceShowRecorder{reply: &control.WorkspaceStatus{ + Lease: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3, ValidForNs: 1000000000, Revoking: true}, + RevocationAck: &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: "vol", ReplicaId: "r1", Epoch: 3}, HeadGen: 9}, + Moves: []*control.WorkspaceGrant{{VolumeId: "vol", RequestId: "old-move", Kind: "clean", OldEpoch: 2, NewEpoch: 3, OldReplicaId: "r1", NewReplicaId: "r1", OldHost: "node-a", NewHost: "node-b", HeadGen: 8, Issued: true}}, + }} + dials := installShowRecorder(t, r) + code, out, errOut := runCLI([]string{"ops", "workspace", "show", "--master", "master:19090", "--volume", "vol"}) + if code != 0 || *dials != 1 || len(r.requests) != 1 || r.requests[0].GetVolumeId() != "vol" { + t.Fatalf("exit=%d dials=%d requests=%v out=%q err=%q", code, *dials, r.requests, out, errOut) + } + for _, want := range []string{"holder: r1@3", "lease state: revoking", "recorded ACK: r1@3 HEAD generation 9", "old-move", "node-a", "node-b", "issued=true"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in %q", want, out) + } + } +} + +func TestWorkspaceShowUsesTheMastersLeaseValidity(t *testing.T) { + for _, tc := range []struct { + name string + lease *control.WorkspaceLeaseFact + want string + }{ + {"granted", &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3, ValidForNs: 1}, "lease state: granted"}, + {"expired", &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3, ExpiresAtNs: 9223372036854775807}, "lease state: expired"}, + {"absent", nil, "holder: none"}, + } { + t.Run(tc.name, func(t *testing.T) { + r := &workspaceShowRecorder{reply: &control.WorkspaceStatus{Lease: tc.lease}} + installShowRecorder(t, r) + code, out, errOut := runCLI([]string{"ops", "workspace", "show", "--master", "master:19090", "--volume", "vol"}) + if code != 0 || !strings.Contains(out, tc.want) || !strings.Contains(out, "recorded ACK: none") { + t.Fatalf("exit=%d out=%q err=%q", code, out, errOut) + } + }) + } +} + +func TestWorkspaceShowRefusesBadUsageAndClassifiesRPCFailure(t *testing.T) { + r := &workspaceShowRecorder{err: status.Error(codes.Unavailable, "query unavailable")} + dials := installShowRecorder(t, r) + for _, args := range [][]string{ + {"--volume", "vol"}, {"--master", "master:19090"}, + {"--master", "master:19090", "--volume", "vol", "--timeout", "0s"}, + } { + if code, _, _ := runCLI(append([]string{"ops", "workspace", "show"}, args...)); code != wsExitRefusedLocally || *dials != 0 { + t.Fatalf("%v: exit=%d dials=%d", args, code, *dials) + } + } + code, out, errOut := runCLI([]string{"ops", "workspace", "show", "--master", "master:19090", "--volume", "vol"}) + if code != wsExitUnknown || out != "" || !strings.Contains(errOut, "query unavailable") || len(r.requests) != 1 { + t.Fatalf("exit=%d out=%q err=%q requests=%d", code, out, errOut, len(r.requests)) + } +} From 7071b9af72113908fddc2f247f741e197445eab7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:48:12 -0800 Subject: [PATCH 29/57] feat(cli): print existing workspace lease ACK and move facts --- seaweed-block/cmd/sw-block/workspace.go | 2 + seaweed-block/cmd/sw-block/workspace_show.go | 75 ++++++++++++++++++++ seaweed-block/core/rpc/wsclient/show.go | 24 +++++++ 3 files changed, 101 insertions(+) create mode 100644 seaweed-block/cmd/sw-block/workspace_show.go create mode 100644 seaweed-block/core/rpc/wsclient/show.go diff --git a/seaweed-block/cmd/sw-block/workspace.go b/seaweed-block/cmd/sw-block/workspace.go index d69ff1e587..fa5f2bdba7 100644 --- a/seaweed-block/cmd/sw-block/workspace.go +++ b/seaweed-block/cmd/sw-block/workspace.go @@ -65,6 +65,8 @@ func runOpsWorkspace(args []string, stdout, stderr io.Writer) int { return wsExitRefusedLocally } switch args[0] { + case "show": + return runWorkspaceShow(args[1:], stdout, stderr) case "move": return runWorkspaceCleanMove(args[1:], stdout, stderr) case "revoke": diff --git a/seaweed-block/cmd/sw-block/workspace_show.go b/seaweed-block/cmd/sw-block/workspace_show.go new file mode 100644 index 0000000000..996785e6e8 --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_show.go @@ -0,0 +1,75 @@ +package main + +import ( + "context" + "flag" + "fmt" + "io" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/wsclient" +) + +// Read-only M2 Granted -> Revoking -> Acked -> Moved (clean) facts, +// INV-WS-CLEAN-MOVE-001. Do not synthesize an ACK or resolve a physical host. +func runWorkspaceShow(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops workspace show", flag.ContinueOnError) + fs.SetOutput(stderr) + var master, volume string + var timeout time.Duration + fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port") + fs.StringVar(&volume, "volume", "", "volume id") + fs.DurationVar(&timeout, "timeout", wsDefaultTimeout, "bound for the read-only RPC") + if err := fs.Parse(args); err != nil { + return wsExitRefusedLocally + } + if fs.NArg() != 0 || master == "" || volume == "" || timeout <= 0 { + fmt.Fprintln(stderr, "workspace show: --master, --volume and positive --timeout required; nothing sent") + return wsExitRefusedLocally + } + c, err := workspaceDial(master) + if err != nil { + fmt.Fprintf(stderr, "workspace show: refused locally, nothing sent: %v\n", err) + return wsExitRefusedLocally + } + defer c.Close() + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + view, err := c.Show(ctx, volume) + if err != nil { + fmt.Fprintf(stderr, "workspace show: %v\n", err) + return workspaceExit(wsclient.OutcomeOf(err)) + } + printWorkspaceView(stdout, volume, view) + return wsExitOK +} + +func printWorkspaceView(out io.Writer, volume string, view *control.WorkspaceStatus) { + fmt.Fprintf(out, "volume: %s (query snapshot, not authority to serve)\n", volume) + lease := view.GetLease() + if lease == nil { + fmt.Fprintln(out, "holder: none\nlease state: none") + } else { + state := "granted" + if lease.GetValidForNs() <= 0 { + state = "expired" + } else if lease.GetRevoking() { + state = "revoking" + } + fmt.Fprintf(out, "holder: %s@%d (logical replica; server not provided by lease view)\nlease state: %s\nlease expiry_ns: %d; host validity_ns at query: %d\n", lease.GetReplicaId(), lease.GetEpoch(), state, lease.GetExpiresAtNs(), lease.GetValidForNs()) + } + ack := view.GetRevocationAck() + if ack == nil { + fmt.Fprintln(out, "recorded ACK: none") + } else { + id := ack.GetIdentity() + fmt.Fprintf(out, "recorded ACK: %s@%d HEAD generation %d\n", id.GetReplicaId(), id.GetEpoch(), ack.GetHeadGen()) + } + for _, g := range view.GetMoves() { + fmt.Fprintf(out, "move: request=%s kind=%s issued=%t %s/%s@%d -> %s/%s@%d HEAD generation %d remote LSN %d\n", g.GetRequestId(), g.GetKind(), g.GetIssued(), g.GetOldHost(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewHost(), g.GetNewReplicaId(), g.GetNewEpoch(), g.GetHeadGen(), g.GetRemoteLsn()) + } + for _, b := range view.GetBindings() { + fmt.Fprintf(out, "binding: host=%s data=%s ctrl=%s retired=%t\n", b.GetServerId(), b.GetDataAddr(), b.GetCtrlAddr(), b.GetRetired()) + } +} diff --git a/seaweed-block/core/rpc/wsclient/show.go b/seaweed-block/core/rpc/wsclient/show.go new file mode 100644 index 0000000000..3b296827b8 --- /dev/null +++ b/seaweed-block/core/rpc/wsclient/show.go @@ -0,0 +1,24 @@ +package wsclient + +import ( + "context" + "errors" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// Show reads the existing M2 lease/ACK/move view. It grants no authority. +func (c *Client) Show(ctx context.Context, volume string) (*control.WorkspaceStatus, error) { + const op = "workspace show" + if volume == "" { + return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: errors.New("volume is required")} + } + view, err := c.rpc.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: volume}) + if err != nil { + return nil, classify(op, err) + } + if view == nil { + return nil, &Error{Outcome: OutcomeUnknown, Op: op, Err: errors.New("missing workspace reply")} + } + return view, nil +} From 25493cf7aefe240e173758656c813a06498ff939 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:48:31 -0800 Subject: [PATCH 30/57] test(cli): reject a zero seal flag combined with unsealed revocation --- seaweed-block/cmd/sw-block/workspace_revoke_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/seaweed-block/cmd/sw-block/workspace_revoke_test.go b/seaweed-block/cmd/sw-block/workspace_revoke_test.go index 74a26ecbb0..ffb088a877 100644 --- a/seaweed-block/cmd/sw-block/workspace_revoke_test.go +++ b/seaweed-block/cmd/sw-block/workspace_revoke_test.go @@ -67,6 +67,7 @@ func TestWorkspaceRevokeRejectsInvalidInputsBeforeDial(t *testing.T) { {"--master", ""}, {"--volume", ""}, {"--replica", ""}, {"--epoch", "0"}, {"--epoch", "-1"}, {"--timeout", "0s"}, {"--timeout", "-1s"}, {"unexpected"}, {"--sealed-gen", "0"}, {"--without-seal"}, + {"--sealed-gen", "0", "--without-seal"}, } { code, _, _ := runCLI(revokeArgs(extra...)) if code != wsExitRefusedLocally || *dials != 0 || len(r.requests) != 0 { From c5d9a99d3447a5ac2187cbbc4544915e37b822c1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:48:45 -0800 Subject: [PATCH 31/57] fix(cli): validate presence and value of the seal declaration --- seaweed-block/cmd/sw-block/workspace_revoke.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/seaweed-block/cmd/sw-block/workspace_revoke.go b/seaweed-block/cmd/sw-block/workspace_revoke.go index 6805e08ac8..3bd06441d5 100644 --- a/seaweed-block/cmd/sw-block/workspace_revoke.go +++ b/seaweed-block/cmd/sw-block/workspace_revoke.go @@ -31,7 +31,13 @@ func runWorkspaceRevoke(args []string, stdout, stderr io.Writer) int { if err := fs.Parse(args); err != nil { return wsExitRefusedLocally } - if fs.NArg() != 0 || master == "" || id.VolumeId == "" || id.ReplicaId == "" || id.Epoch == 0 || timeout <= 0 || (sealedGen > 0) == withoutSeal { + sealProvided := false + fs.Visit(func(f *flag.Flag) { + if f.Name == "sealed-gen" { + sealProvided = true + } + }) + if fs.NArg() != 0 || master == "" || id.VolumeId == "" || id.ReplicaId == "" || id.Epoch == 0 || timeout <= 0 || sealProvided == withoutSeal || (sealProvided && sealedGen == 0) { fmt.Fprintln(stderr, "workspace revoke: refused locally; require --master, --volume, --replica, positive --epoch/--timeout and exactly one of positive --sealed-gen or --without-seal") return wsExitRefusedLocally } From a6190e59f67dc596636c20bbd11f564086ef08be Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:50:12 -0800 Subject: [PATCH 32/57] docs(cli): document seal-before-revoke planned handoff workflow --- seaweed-block/cmd/sw-block/workspace.go | 18 ++++++- seaweed-block/docs/standalone-deployment.md | 57 +++++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/seaweed-block/cmd/sw-block/workspace.go b/seaweed-block/cmd/sw-block/workspace.go index fa5f2bdba7..c1c5368ef9 100644 --- a/seaweed-block/cmd/sw-block/workspace.go +++ b/seaweed-block/cmd/sw-block/workspace.go @@ -25,6 +25,11 @@ const ( ) const workspaceUsage = `usage: + sw-block ops workspace show --master ADDR --volume V [--timeout 30s] + sw-block ops workspace revoke --master ADDR --volume V --replica R --epoch E + (--sealed-gen G | --without-seal) [--timeout 30s] + sw-block ops workspace move --clean --master ADDR --volume V --replica R --epoch E + --target-host H --target-data A --target-ctrl A --request-id ID [--timeout 30s] sw-block ops workspace force-move --master ADDR --volume V --target-host H --target-data A --target-ctrl A --request-id ID --confirm-forced V@EPOCH [--dry-run] [--timeout 30s] sw-block ops workspace lost-range --master ADDR --volume V [--request-id ID] [--timeout 30s] @@ -35,7 +40,18 @@ starting the volume on the target host is the next step, done separately. The blockmaster admits it only once the holder's lease horizon and its granted or restart deadline, each plus the clock-skew bound, have passed; before that it is refused and this command says when it becomes admissible. There is NO bypass -flag. Clean (detached) moves are not offered here. +flag. + +Planned hand-over order: stop the writer; ops chunk detach --plain; revoke +--sealed-gen G; show until the recorded ACK names the same replica, epoch and +HEAD generation G; move --clean; start blockvolume on the target separately. +Revoke only requests revocation: it does not prove an ACK. --sealed-gen is +an operator assertion, not checked against storage by this CLI. --without-seal +deliberately abandons the unpublished tail and may require a forced move. +The clean target may be the source host once sealed (requires server support). +On an unknown move outcome, rerun with the SAME --request-id. +Show is read-only. Lease state uses the master's reported host validity at +query time, not a comparison with this machine's clock; it is not a grant. --confirm-forced must be exactly @, retyped: the epoch is the holder's epoch the move is sent against, and the master refuses it when diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 13196e1293..d723d58572 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -293,6 +293,63 @@ The script's default engine is `SW_BLOCK_DURABLE_IMPL=smartwal`; the command above sets `walstore`, the engine used by the Kubernetes chart and the workspace path. There is no equivalent script for ublk yet. +## Planned workspace hand-over + +For an RF1 chunk volume with a workspace lease, inspect the current logical +holder with `sw-block ops workspace show --master MASTER --volume V`. Copy the +replica and epoch exactly. The view prints the master's lease state, recorded +revocation ACK (including its HEAD generation), move records and bindings. It +does not infer a physical holder from the binding list; a binding is not proof +of a current assignment. Reported validity is a snapshot, not permission to +serve I/O. + +Perform a clean hand-over in this order: + +1. Stop the application/writer and prevent new I/O to the old attachment. +2. Seal the idle volume while its lease still permits publication: + + ```bash + sw-block ops chunk detach --plain --volume V --status-addr OLD_STATUS --timeout 120s >seal.json + ``` + + Busy admission refuses the operation. Do not proceed on any failure or + unknown outcome. JSON remains on stdout; a successful command also prints + `sealed HEAD generation: G` on its own stderr line. Copy the positive `G`. +3. Request revocation using that seal and the identity from `show`: + + ```bash + sw-block ops workspace revoke --master MASTER --volume V --replica R --epoch E --sealed-gen G + ``` + + Seal **before** revocation: revoking first can prevent the old host from + publishing the final image and leave only a lossy forced move. The CLI + requires exactly one of `--sealed-gen G` or `--without-seal`. The former is + your statement, not a storage check. The latter explicitly abandons the + unpublished tail and does not promise that a clean move is possible. +4. Run `ops workspace show --master MASTER --volume V` until the **recorded + ACK** names the same replica `R`, epoch `E` and HEAD generation `G`. + A successful `revoke` reply alone is not that ACK. +5. Ask for the clean authority move: + + ```bash + sw-block ops workspace move --clean --master MASTER --volume V --replica R --epoch E \ + --target-host NEW_HOST --target-data DATA_ADDR --target-ctrl CTRL_ADDR --request-id MOVE_ID + ``` + + Use registered target endpoints. The master checks the seal and matching + ACK. The target may be the source host once sealed, when the server supports + same-host clean reload. A command refuses rather than bypassing a missing + seal, ACK or current identity. On an **unknown outcome**, rerun with the + **SAME `--request-id MOVE_ID`**; never use a new id to guess whether it ran. +6. Start `blockvolume` on the target separately with the granted replica and + new epoch and the normal workspace-lease options. The move command only + transfers authority; it does not start the target or reconnect clients. + +Workspace commands exit 0 on success, 1 on a definite server refusal, 2 on local +usage refusal, 3 on an unknown outcome, and 4 on an unproven readout. Plain +detach keeps the chunk CLI's existing JSON error and exit policy. Neither CLI +retries or polls automatically. + ## Snapshots, restore and space (walstore-chunk) **Recovery point.** From 96079684fbb7e36b783af06b266224a4bd2a61c3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:53:40 -0800 Subject: [PATCH 33/57] test(cli): exercise planned handoff against the real master RPCs --- .../sw-block/workspace_planned_master_test.go | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 seaweed-block/cmd/sw-block/workspace_planned_master_test.go diff --git a/seaweed-block/cmd/sw-block/workspace_planned_master_test.go b/seaweed-block/cmd/sw-block/workspace_planned_master_test.go new file mode 100644 index 0000000000..b003feeb66 --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_planned_master_test.go @@ -0,0 +1,67 @@ +package main + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/host/master" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +// Existing M2 Granted -> Revoking -> Acked -> Moved (clean), +// INV-WS-CLEAN-MOVE-001: real RPC admission still requires the host ACK. +// HEAD reading is supplied by the existing master seam; no lab is involved. +func TestWorkspacePlannedHandoffAgainstRealMaster(t *testing.T) { + h, stop := startDeleteMaster(t, master.Config{ + Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil + }, + }) + defer stop() + seedForcedVolume(t, h) + show := []string{"ops", "workspace", "show", "--master", h.Addr(), "--volume", "vol-f"} + if code, out, errOut := runCLI(show); code != 0 || !strings.Contains(out, "holder: r1@1") || !strings.Contains(out, "recorded ACK: none") { + t.Fatalf("initial show: exit=%d out=%q err=%q", code, out, errOut) + } + revoke := []string{"ops", "workspace", "revoke", "--master", h.Addr(), "--volume", "vol-f", "--replica", "r1", "--epoch", "1", "--sealed-gen", "9"} + if code, out, errOut := runCLI(revoke); code != 0 { + t.Fatalf("revoke: exit=%d out=%q err=%q", code, out, errOut) + } + move := []string{"ops", "workspace", "move", "--clean", "--master", h.Addr(), "--volume", "vol-f", "--replica", "r1", "--epoch", "1", "--request-id", "clean-actual", "--target-host", "node-b", "--target-data", "127.0.0.1:29200", "--target-ctrl", "127.0.0.1:29100"} + if code, _, errOut := runCLI(move); code != wsExitRefused { + t.Fatalf("move without host ACK: exit=%d err=%q", code, errOut) + } + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + // This is the separate host event, never synthesized by the CLI. + _, err = control.NewWorkspaceServiceClient(conn).AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}, HeadGen: 9}) + if err != nil { + t.Fatal(err) + } + if code, out, errOut := runCLI(show); code != 0 || !strings.Contains(out, "recorded ACK: r1@1 HEAD generation 9") { + t.Fatalf("ACK show: exit=%d out=%q err=%q", code, out, errOut) + } + var first string + for i := 0; i < 2; i++ { + code, out, errOut := runCLI(move) + if code != 0 || !strings.Contains(out, "clean move issued") || !strings.Contains(out, "r1@1 -> r1@2 on node-b") { + t.Fatalf("clean move: exit=%d out=%q err=%q", code, out, errOut) + } + if i == 0 { + first = out + } else if out != first { + t.Fatalf("same-id replay changed grant: %q versus %q", out, first) + } + } +} From 4a58b209b06fe375df0d79c81f8758647c26e1d7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 19:55:06 -0800 Subject: [PATCH 34/57] docs(cli): distinguish host validity from forced-move admission --- seaweed-block/docs/standalone-deployment.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index d723d58572..8301c917fc 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -302,6 +302,9 @@ revocation ACK (including its HEAD generation), move records and bindings. It does not infer a physical holder from the binding list; a binding is not proof of a current assignment. Reported validity is a snapshot, not permission to serve I/O. +`expired` means the master reported no positive **host validity** at query +time; it is not a claim that the master's forced-move horizon has passed. +Only the master admits a move. Perform a clean hand-over in this order: From 26702a36aa7537292359ac5dd51f18b3ba448638 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:00:07 -0800 Subject: [PATCH 35/57] fix: allow sealed clean moves to return to the same host --- seaweed-block/core/authority/workspace.go | 5 +++-- seaweed-block/core/host/master/workspace_service.go | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 9f3046cbb2..adae4867fa 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -153,12 +153,13 @@ func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string, } func validateWorkspaceMoveRequest(req WorkspaceMoveRequest) error { - // v1 moves a replica between hosts without changing its logical slot. + // INV-WS-SAME-HOST-CLEAN-MOVE-001: clean moves may reuse the host, + // but every move preserves its logical replica slot. // Refuse before locking or persisting a reservation/authority epoch. if req.ExpectedReplicaID != req.TargetReplicaID { return fmt.Errorf("workspace move: v1 requires the same logical replica id") } - if req.RequestID == "" || req.VolumeID == "" || req.ExpectedHost == "" || req.TargetHost == "" || req.ExpectedHost == req.TargetHost || req.ExpectedReplicaID == "" || req.ExpectedEpoch == 0 || req.TargetReplicaID == "" || + if req.RequestID == "" || req.VolumeID == "" || req.ExpectedHost == "" || req.TargetHost == "" || (req.ExpectedHost == req.TargetHost && (req.Kind != "clean" || req.Force)) || req.ExpectedReplicaID == "" || req.ExpectedEpoch == 0 || req.TargetReplicaID == "" || req.TargetDataAddr == "" || req.TargetCtrlAddr == "" || (req.Kind != "clean" && req.Kind != "forced") || req.Force != (req.Kind == "forced") { return fmt.Errorf("workspace move: invalid request") } diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index fa363061f0..30ef4387bc 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -323,7 +323,9 @@ func (s *services) workspaceMoveCheckLocked(q *control.WorkspaceMove) (req autho 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: + // INV-WS-SAME-HOST-CLEAN-MOVE-001: the authority clean-proof + // checks still run after these endpoint and binding checks. + case target.ServerID == oldHost && (q.GetKind() != "clean" || q.GetForce()): refusal = fmt.Sprintf("move target %q is the current source host", target.ServerID) case !replay && s.host.colocatedTargetRefused(target.ServerID): refusal = fmt.Sprintf("move target node %q shares the authority store's file system (strict journal isolation)", target.ServerID) From 1f2bcd82bb21c9e624da0706336ff79c08aa1195 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:01:49 -0800 Subject: [PATCH 36/57] test: preserve same-host clean proof and sealed image controls --- .../workspace_same_host_clean_test.go | 9 +++- .../master/workspace_move_refusal_test.go | 4 +- .../master/workspace_same_host_clean_test.go | 10 ++++- .../storage/chunk_same_host_clean_test.go | 41 +++++++++++++++++++ 4 files changed, 60 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_same_host_clean_test.go diff --git a/seaweed-block/core/authority/workspace_same_host_clean_test.go b/seaweed-block/core/authority/workspace_same_host_clean_test.go index de0052305c..4473ebd22f 100644 --- a/seaweed-block/core/authority/workspace_same_host_clean_test.go +++ b/seaweed-block/core/authority/workspace_same_host_clean_test.go @@ -14,6 +14,11 @@ func TestWorkspaceSameHostCleanMoveUsesOvernightSeal(t *testing.T) { p := newLeasePublisher(t, disk, time.Second, clock) bindAndGrant(t, p, "v", "r") ctx := context.Background() + req := WorkspaceMoveRequest{RequestID: "return", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "host", TargetHost: "host", ExpectedEpoch: 1, TargetDataAddr: "d", TargetCtrlAddr: "c", Kind: "clean"} + head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 42, Detached: true} + if _, err := p.MoveWorkspace(ctx, req, head); err == nil { + t.Fatal("same-host move accepted a seal without revocation ACK") + } if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { t.Fatal(err) } @@ -21,11 +26,11 @@ func TestWorkspaceSameHostCleanMoveUsesOvernightSeal(t *testing.T) { t.Fatal(err) } clock.at(86400) - req := WorkspaceMoveRequest{RequestID: "return", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "host", TargetHost: "host", ExpectedEpoch: 1, TargetDataAddr: "d", TargetCtrlAddr: "c", Kind: "clean"} - head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 42, Detached: true} for _, bad := range []WorkspaceHead{ {Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 42}, {Gen: 8, Epoch: 1, Holder: "host/r", RemoteLSN: 42, Detached: true}, + {Gen: 7, Epoch: 1, Holder: "other/r", RemoteLSN: 42, Detached: true}, + {Gen: 7, Epoch: 2, Holder: "host/r", RemoteLSN: 42, Detached: true}, } { if _, err := p.MoveWorkspace(ctx, req, bad); err == nil { t.Fatal("same-host move bypassed sealed-generation proof", bad) 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 9a7e113705..8c3196aa03 100644 --- a/seaweed-block/core/host/master/workspace_move_refusal_test.go +++ b/seaweed-block/core/host/master/workspace_move_refusal_test.go @@ -95,6 +95,8 @@ func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { return &control.WorkspaceMove{RequestId: vol + "-" + server + "-" + data, VolumeId: vol, ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: server, TargetDataAddr: data, TargetCtrlAddr: ctrl, Kind: "clean"} } + forcedSource := move("placed", "node-a", "127.0.0.1:19101", "127.0.0.1:19102") + forcedSource.Kind, forcedSource.Force = "forced", true for _, c := range []struct { name string q *control.WorkspaceMove @@ -102,7 +104,7 @@ 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`}, + {"forced target is the source", forcedSource, `move target "node-a" is the current source host`}, {"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"), diff --git a/seaweed-block/core/host/master/workspace_same_host_clean_test.go b/seaweed-block/core/host/master/workspace_same_host_clean_test.go index 74df103b90..e518160a4c 100644 --- a/seaweed-block/core/host/master/workspace_same_host_clean_test.go +++ b/seaweed-block/core/host/master/workspace_same_host_clean_test.go @@ -39,10 +39,18 @@ func TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding(t *testing.T) { if got, ok, err := h.Lifecycle().WorkspaceBindings.Get("v"); err != nil || !ok || len(got) != 1 || !got[0].Retired { t.Fatal("ACK did not retire the old binding", got, err) } + req := &control.WorkspaceMove{RequestId: "return", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-a", TargetDataAddr: b.DataAddr, TargetCtrlAddr: b.CtrlAddr, Kind: "clean"} + if _, err := ws.MoveWorkspace(ctx, req); err == nil { + t.Fatal("same-host move accepted an unprepared retired binding") + } if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { t.Fatal("same-host re-prepare refused", err) } - req := &control.WorkspaceMove{RequestId: "return", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-a", TargetDataAddr: b.DataAddr, TargetCtrlAddr: b.CtrlAddr, Kind: "clean"} + forced := *req + forced.Kind, forced.Force = "forced", true + if _, err := ws.MoveWorkspace(ctx, &forced); err == nil { + t.Fatal("same-host forced move accepted over RPC") + } if _, err := ws.MoveWorkspace(ctx, req); err != nil { t.Fatal("same-host clean move refused over RPC", err) } diff --git a/seaweed-block/core/storage/chunk_same_host_clean_test.go b/seaweed-block/core/storage/chunk_same_host_clean_test.go new file mode 100644 index 0000000000..1dfb88a699 --- /dev/null +++ b/seaweed-block/core/storage/chunk_same_host_clean_test.go @@ -0,0 +1,41 @@ +package storage + +import ( + "bytes" + "errors" + "testing" +) + +// INV-WS-SAME-HOST-CLEAN-MOVE-001: the returning host consumes its sealed +// image only with a newly issued epoch; same-epoch reopening stays sealed. +func TestClaimChunkHeadSameHostCleanMovePreservesSealedImage(t *testing.T) { + s, _ := newChunkTestStore(t) + r := newFakeChunkRemote() + layer := mustAttach(t, s, r, ctConfig(1)) + want := makeBlock(4096, 0x63) + if _, err := s.Write(0, want); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := layer.Detach(ctTimeout(t)); err != nil { + t.Fatal(err) + } + sealed := copyHead(r.stats().head) + if _, err := ClaimChunkHead(ctTimeout(t), r, ctConfig(1)); !errors.Is(err, ErrChunkLayerDetached) || !sameHead(r.stats().head, sealed) { + t.Fatal("same-epoch reopen consumed the seal", err) + } + claimed, err := ClaimChunkHead(ctTimeout(t), r, ctConfig(2)) + if err != nil { + t.Fatal(err) + } + expected := copyHead(sealed) + expected.Gen++ + expected.Epoch = 2 + expected.State = ChunkHeadActive + expected.DetachedBy = nil + if !sameHead(claimed, expected) || !bytes.Equal(r.imageOf(t, claimed)[:4096], want) { + t.Fatalf("same-host claim changed sealed image/frontier: sealed=%+v claimed=%+v", sealed, claimed) + } +} From 87b92007ddf9d64b47c64bd50bef9cb0889afb68 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:02:07 -0800 Subject: [PATCH 37/57] test(cli): pin operator identity output order --- .../cmd/sw-block/workspace_show_test.go | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/seaweed-block/cmd/sw-block/workspace_show_test.go b/seaweed-block/cmd/sw-block/workspace_show_test.go index 207657d4c7..48b9b41eaa 100644 --- a/seaweed-block/cmd/sw-block/workspace_show_test.go +++ b/seaweed-block/cmd/sw-block/workspace_show_test.go @@ -74,6 +74,28 @@ func TestWorkspaceShowUsesTheMastersLeaseValidity(t *testing.T) { } } +func TestWorkspaceShowOrdersOperatorIdentityWithoutInventingAHost(t *testing.T) { + r := &workspaceShowRecorder{reply: &control.WorkspaceStatus{ + Lease: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3, ValidForNs: 1}, + }} + installShowRecorder(t, r) + code, out, errOut := runCLI([]string{"ops", "workspace", "show", "--master", "master:19090", "--volume", "vol"}) + if code != 0 { + t.Fatalf("exit=%d err=%q", code, errOut) + } + last := -1 + for _, field := range []string{"volume: vol", "replica: r1\n", "epoch: 3\n", "lease state: granted", "recorded ACK: none"} { + at := strings.Index(out, field) + if at <= last { + t.Fatalf("missing or out-of-order %q in %q", field, out) + } + last = at + } + if !strings.Contains(out, "host: unknown (not recorded by the master)") { + t.Fatalf("physical host must remain unknown: %q", out) + } +} + func TestWorkspaceShowRefusesBadUsageAndClassifiesRPCFailure(t *testing.T) { r := &workspaceShowRecorder{err: status.Error(codes.Unavailable, "query unavailable")} dials := installShowRecorder(t, r) From f9177aa249cf7f31750528b0ceb3690087d7a040 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:02:31 -0800 Subject: [PATCH 38/57] docs: trace same-host clean return through the sealed HEAD claim --- .../core/host/master/workspace_move_refusal_test.go | 4 +--- seaweed-block/docs/design/agent-workspace-design.md | 4 +++- seaweed-block/docs/design/invariants.md | 11 ++++++----- seaweed-block/docs/workspace-lease.md | 13 +++++++++++++ 4 files changed, 23 insertions(+), 9 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 8c3196aa03..71d59787ee 100644 --- a/seaweed-block/core/host/master/workspace_move_refusal_test.go +++ b/seaweed-block/core/host/master/workspace_move_refusal_test.go @@ -95,8 +95,6 @@ func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { return &control.WorkspaceMove{RequestId: vol + "-" + server + "-" + data, VolumeId: vol, ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: server, TargetDataAddr: data, TargetCtrlAddr: ctrl, Kind: "clean"} } - forcedSource := move("placed", "node-a", "127.0.0.1:19101", "127.0.0.1:19102") - forcedSource.Kind, forcedSource.Force = "forced", true for _, c := range []struct { name string q *control.WorkspaceMove @@ -104,7 +102,7 @@ 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`}, - {"forced target is the source", forcedSource, `move target "node-a" is the current source host`}, + {"same-host clean still needs authority", move("placed", "node-a", "127.0.0.1:19101", "127.0.0.1:19102"), `workspace move: missing or changed authority/lease`}, {"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"), diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 5c81669a25..a2beb233de 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -359,12 +359,14 @@ stateDiagram-v2 Granted --> Granted: Renew before horizon and deadline (from memory) Granted --> Revoking: BeginWorkspaceRevocation Revoking --> Acked: host acks detached HEAD gen while the lease is valid - Acked --> Moved: CLEAN move + Acked --> Moved: CLEAN move, including same host, new epoch Granted --> Expired: horizon or deadline passes Expired --> Moved: FORCED move after expiry + skew bound, then HEAD read (an older-epoch HEAD is accepted) } ``` +**Same-host planned return.** A sealed volume can be moved cleanly back to its source host after the exact detached-generation ACK was recorded. The move issues a higher epoch even when the host and endpoints are unchanged. The returning process claims the sealed HEAD before serving; a same-epoch reopen remains detached. Forced moves to the source host remain refused. Re-preparing the binding preserves the old retired-epoch tag, so replaying that retirement cannot retire the new binding. + **Moving back to a host with a surviving local file.** A fresh volume claims HEAD before serving. A non-fresh attach reads HEAD first; if another holder published it, the attach fails closed with `ErrChunkStaleLocalRoot` (`core/frontend/durable/provider_chunk.go`): the volume is not served, and one log line and the status evidence name the local root to remove or quarantine, after which the next attach starts fresh from HEAD (#167). ## 8. Security model diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d2f32d4b05..c36bbfb9e1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -96,8 +96,8 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | 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-LEASE-HORIZON-MONO-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-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`, `INV-WS-FORCED-MOVE-REPLY-001` | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | -| Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | -| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` | +| Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation; the target may be the same host, with a newly issued epoch and every binding/collision/isolation check retained | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `validateWorkspaceMoveRequest`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-SAME-HOST-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 (the source itself only for a clean, non-force move), and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | | Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced @`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` | | Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` | @@ -198,7 +198,8 @@ stateDiagram-v2 | Claiming | Detached (non-serving) | same epoch/holder HEAD is already detached: refuse with ErrChunkLayerDetached before restore preparation or CAS; a higher-epoch takeover still consumes the sealed image | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-SEALED-REOPEN-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 | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-SAME-HOST-CLEAN-MOVE-001` | Same-host move: CLEAN only, with HEAD detached by the current holder at its epoch and the matching revocation ACK; it issues a higher epoch to the same host, which claims that sealed HEAD and serves exactly its image. Forced same-host move stays refused; a same-epoch sealed reopen never serves. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | ACTIVE | +| `INV-WS-CLEAN-MOVE-001` | | Holder | HolderFenced | a conflicting HEAD owner (including a regressed epoch) or a displaced publication is observed; local data and unresolved cut intents remain | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | | Holder | (hydration wait) | one request deadline covers all missing chunks; callers may detach, but bounded per-layer workers retain and join each shared fill; HEAD/generation/local-write checks still govern installation | `core/storage/chunk_hydration.go`; `core/frontend/durable/storage_adapter.go` `readStorageBlock` | `INV-CUT-HYDRATION-WAIT-001`, `INV-CUT-READMISS-001` | @@ -289,7 +290,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork or restore HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork`, `Restore` | `INV-WS-HEAD-CAS-001` | | `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | -| `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | +| `detached` | `active` | takeover CAS at a higher issued epoch, including a clean move to the same host | `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` | @@ -409,7 +410,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -296 rows: 210 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 281 new. +297 rows: 211 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 282 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. diff --git a/seaweed-block/docs/workspace-lease.md b/seaweed-block/docs/workspace-lease.md index bb089340fe..70e0b139c6 100644 --- a/seaweed-block/docs/workspace-lease.md +++ b/seaweed-block/docs/workspace-lease.md @@ -70,3 +70,16 @@ defaults). Beyond that, grants shrink and hosts fence: the design fails closed. Blockmaster logs one warning per failure streak, with the write's latency and the remaining horizon, when an extension fails, and one when grants start to be clamped to the horizon, and a line when either recovers. + + +## Planned return on the same host + +After plain detach seals HEAD and revocation records its exact generation, +a clean move may target the source host itself. Prepare the binding again +before requesting the move. The move journals a higher epoch even when its +endpoints are unchanged; start the returning blockvolume at that new epoch. +It claims the sealed HEAD before serving and preserves the sealed image and +remote frontier. The matching seal/ACK remains valid overnight while HEAD +is unchanged. A same-epoch reopen remains detached, and a forced move to the +same host is refused. Every ordinary binding, endpoint collision, journal +isolation and uncertain-outcome check still applies. From dd6fd3c2bbbf7f020f0033375951874398c5ce48 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:02:31 -0800 Subject: [PATCH 39/57] cli: clarify logical holder and sealed generation fields --- seaweed-block/cmd/sw-block/chunk.go | 2 +- seaweed-block/cmd/sw-block/workspace_show.go | 5 +++-- seaweed-block/docs/standalone-deployment.md | 3 ++- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index d037546ad2..793f613a04 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -267,7 +267,7 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int { fs.StringVar(&volumeID, "volume", "", "volume id") fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") fs.DurationVar(&timeout, "timeout", 120*time.Second, "operation bound (capped at the server's OpDeadline)") - fs.BoolVar(&plain, "plain", false, "seal an idle volume without pre-copy; prints sealed HEAD generation on stderr") + fs.BoolVar(&plain, "plain", false, "seal an idle volume without pre-copy; prints JSON headGen as sealed HEAD generation on stderr") fs.BoolVar(&frozen, "frozen", false, "not supported in this release: the server refuses a frozen detach (frozen_detach_unsupported)") fs.Int64Var(&freezeStartedAtNs, "freeze-started-at-ns", 0, "not supported in this release; only valid with --frozen") fs.BoolVar(&allowOverBudget, "allow-over-budget", false, "not supported in this release; only valid with --frozen") diff --git a/seaweed-block/cmd/sw-block/workspace_show.go b/seaweed-block/cmd/sw-block/workspace_show.go index 996785e6e8..add1bb9980 100644 --- a/seaweed-block/cmd/sw-block/workspace_show.go +++ b/seaweed-block/cmd/sw-block/workspace_show.go @@ -49,7 +49,7 @@ func printWorkspaceView(out io.Writer, volume string, view *control.WorkspaceSta fmt.Fprintf(out, "volume: %s (query snapshot, not authority to serve)\n", volume) lease := view.GetLease() if lease == nil { - fmt.Fprintln(out, "holder: none\nlease state: none") + fmt.Fprintln(out, "replica: none\nepoch: none\nlease state: none\nholder: none") } else { state := "granted" if lease.GetValidForNs() <= 0 { @@ -57,7 +57,7 @@ func printWorkspaceView(out io.Writer, volume string, view *control.WorkspaceSta } else if lease.GetRevoking() { state = "revoking" } - fmt.Fprintf(out, "holder: %s@%d (logical replica; server not provided by lease view)\nlease state: %s\nlease expiry_ns: %d; host validity_ns at query: %d\n", lease.GetReplicaId(), lease.GetEpoch(), state, lease.GetExpiresAtNs(), lease.GetValidForNs()) + fmt.Fprintf(out, "replica: %s\nepoch: %d\nlease state: %s\nholder: %s@%d (logical replica)\nlease expiry_ns: %d; host validity_ns at query: %d\n", lease.GetReplicaId(), lease.GetEpoch(), state, lease.GetReplicaId(), lease.GetEpoch(), lease.GetExpiresAtNs(), lease.GetValidForNs()) } ack := view.GetRevocationAck() if ack == nil { @@ -66,6 +66,7 @@ func printWorkspaceView(out io.Writer, volume string, view *control.WorkspaceSta id := ack.GetIdentity() fmt.Fprintf(out, "recorded ACK: %s@%d HEAD generation %d\n", id.GetReplicaId(), id.GetEpoch(), ack.GetHeadGen()) } + fmt.Fprintln(out, "host: unknown (not recorded by the master); issued moves and bindings below are separate facts") for _, g := range view.GetMoves() { fmt.Fprintf(out, "move: request=%s kind=%s issued=%t %s/%s@%d -> %s/%s@%d HEAD generation %d remote LSN %d\n", g.GetRequestId(), g.GetKind(), g.GetIssued(), g.GetOldHost(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewHost(), g.GetNewReplicaId(), g.GetNewEpoch(), g.GetHeadGen(), g.GetRemoteLsn()) } diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 8301c917fc..055c79795b 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -317,7 +317,8 @@ Perform a clean hand-over in this order: Busy admission refuses the operation. Do not proceed on any failure or unknown outcome. JSON remains on stdout; a successful command also prints - `sealed HEAD generation: G` on its own stderr line. Copy the positive `G`. + `sealed HEAD generation: G` on its own stderr line, taken from the same + JSON `headGen` field on stdout. Copy the positive `G`. 3. Request revocation using that seal and the identity from `show`: ```bash From 8120d0102d698cfc4bc75bf4b131d07a2888fcb0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:04:44 -0800 Subject: [PATCH 40/57] test: require the full skew barrier before same-holder regrant --- .../core/authority/workspace_regrant_test.go | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/seaweed-block/core/authority/workspace_regrant_test.go b/seaweed-block/core/authority/workspace_regrant_test.go index 4942a0cb76..73f9cdd248 100644 --- a/seaweed-block/core/authority/workspace_regrant_test.go +++ b/seaweed-block/core/authority/workspace_regrant_test.go @@ -108,3 +108,34 @@ func TestWorkspaceLeaseSealedAckNeverRegrants(t *testing.T) { t.Fatal("sealed proof mutated by re-grant") } } + +// INV-WS-LEASE-REGRANT-001: expiry alone cannot fence a previous process +// whose own clock may lag. The full skew bound must pass before re-grant. +func TestWorkspaceLeaseRegrantWaitsForFullSkew(t *testing.T) { + disk, _ := newTempStore(t) + clock := newTestClock() + store := &hookStore{AuthorityStore: disk} + p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(10*time.Second, clock.now), WithWorkspaceMaxClockSkew(4*time.Second)) + t.Cleanup(p.CloseWorkspaceExtenders) + grant := bindAndGrant(t, p, "v", "r") + if grant.ExpiresAtNS != clock.sec(10).UnixNano() || p.WorkspaceState("v").Lease.ExpiresAtNS != clock.sec(15).UnixNano() { + t.Fatal("fixture did not create the declared grant/horizon", grant) + } + writes := 0 + store.setBefore(func(DurableRecord) error { writes++; return nil }) + // Expired by master time, but still inside expiry + the full 4 s bound. + clock.at(13) + if got, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil { + t.Fatal("re-grant raced the old process's lagging clock", got) + } + if writes != 0 { + t.Fatal("unsafe early re-grant attempted persistence", writes) + } + // Both deadline+skew and horizon+skew have now passed. This positive + // endpoint is independent of the pending min/max barrier clarification. + clock.at(19) + got, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1) + if err != nil || got.ExpiresAtNS <= clock.now().UnixNano() || writes != 1 { + t.Fatalf("safe unchanged owner cannot return: grant=%+v writes=%d err=%v", got, writes, err) + } +} From 7968ea390434c31c92dff211ebdd0786166da5ea Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:06:15 -0800 Subject: [PATCH 41/57] test: connect expired regrant to sealed reopen and local WAL return --- .../workspace_regrant_storage_test.go | 132 ++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 seaweed-block/core/authority/workspace_regrant_storage_test.go diff --git a/seaweed-block/core/authority/workspace_regrant_storage_test.go b/seaweed-block/core/authority/workspace_regrant_storage_test.go new file mode 100644 index 0000000000..489ba80c52 --- /dev/null +++ b/seaweed-block/core/authority/workspace_regrant_storage_test.go @@ -0,0 +1,132 @@ +package authority + +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" +) + +type regrantStorageView struct{} + +func (regrantStorageView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true} +} + +// These component controls obtain the real authority re-grant before opening +// the returning file-backed provider. They do not model a second live process. +func TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut(t *testing.T) { + testWorkspaceRegrantStorage(t, false) +} + +func TestWorkspaceLeaseRegrantCannotUnsealSameEpoch(t *testing.T) { + testWorkspaceRegrantStorage(t, true) +} + +func testWorkspaceRegrantStorage(t *testing.T, sealed bool) { + t.Helper() + ctx := context.Background() + disk, _ := newTempStore(t) + clock := newTestClock() + p := newLeasePublisher(t, disk, time.Second, clock) + bindAndGrant(t, p, "v", "r") + remote := storage.NewMemChunkRemote() + root := t.TempDir() + open := func() *durable.DurableProvider { + t.Helper() + provider, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, + BlockSize: 4096, ChunkBlocks: 4, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, regrantStorageView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = provider.Close() }) + if _, err := provider.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + return provider + } + first := open() + if _, err := first.RecoverVolume(ctx, "v"); err != nil { + t.Fatal(err) + } + backend, err := first.Open(ctx, "v") + if err != nil { + t.Fatal(err) + } + a, b := bytes.Repeat([]byte{0x31}, 4096), bytes.Repeat([]byte{0x42}, 4096) + write := func(offset int64, data []byte) { + t.Helper() + if n, err := backend.Write(ctx, offset, data); err != nil || n != len(data) { + t.Fatal(n, err) + } + if err := backend.Sync(ctx); err != nil { + t.Fatal(err) + } + } + write(0, a) + if _, err := first.CaptureVolume(ctx, "v"); err != nil { + t.Fatal(err) + } + write(4096, b) // completed Sync, deliberately absent from the last HEAD + if sealed { + if _, err := first.DetachVolumePlain(ctx, "v"); err != nil { + t.Fatal(err) + } + } + before, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if err := first.Close(); err != nil { + t.Fatal(err) + } + clock.at(3) // beyond both original expiry/skew endpoints + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal("returning process could not obtain the authority re-grant", err) + } + second := open() + _, err = second.RecoverVolume(ctx, "v") + if sealed { + after, readErr := remote.GetHead(ctx) + if !errors.Is(err, storage.ErrChunkLayerDetached) || readErr != nil || after.Gen != before.Gen || after.Epoch != before.Epoch || after.Holder != before.Holder || after.State != storage.ChunkHeadDetached || after.RemoteLSN != before.RemoteLSN { + t.Fatal("same-epoch re-grant reactivated the seal", after, err, readErr) + } + return + } + if err != nil { + t.Fatal(err) + } + returning, err := second.Open(ctx, "v") + if err != nil { + t.Fatal(err) + } + for i, want := range [][]byte{a, b} { + got := make([]byte, 4096) + if _, err := returning.Read(ctx, int64(i*4096), got); err != nil || !bytes.Equal(got, want) { + t.Fatal("return lost locally acknowledged bytes", i, err) + } + } + claimed, err := remote.GetHead(ctx) + if err != nil || claimed.Gen <= before.Gen || claimed.Epoch != 1 || claimed.Holder != before.Holder || claimed.RemoteLSN != before.RemoteLSN { + t.Fatal("return served without the new generation fence", claimed, err) + } + if _, err := second.CaptureVolume(ctx, "v"); err != nil { + t.Fatal(err) + } + final, err := remote.GetHead(ctx) + if err != nil || final.RemoteLSN <= before.RemoteLSN { + t.Fatal("first returning cut did not cover the local log", final, err) + } + payload, err := remote.Get(ctx, final.Chunks[0].Key) + if err != nil || len(payload) < 8192 || !bytes.Equal(payload[:4096], a) || !bytes.Equal(payload[4096:8192], b) { + t.Fatal("first cut did not publish the full acknowledged image", err) + } +} From b2a28dea397afdbad775a7be375275ac3dd50545 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:06:34 -0800 Subject: [PATCH 42/57] test: match the plain detach result contract --- seaweed-block/core/authority/workspace_regrant_storage_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/authority/workspace_regrant_storage_test.go b/seaweed-block/core/authority/workspace_regrant_storage_test.go index 489ba80c52..21f445ff7d 100644 --- a/seaweed-block/core/authority/workspace_regrant_storage_test.go +++ b/seaweed-block/core/authority/workspace_regrant_storage_test.go @@ -77,7 +77,7 @@ func testWorkspaceRegrantStorage(t *testing.T, sealed bool) { } write(4096, b) // completed Sync, deliberately absent from the last HEAD if sealed { - if _, err := first.DetachVolumePlain(ctx, "v"); err != nil { + if _, _, err := first.DetachVolumePlain(ctx, "v"); err != nil { t.Fatal(err) } } From e6fcfd38b97e7acecac2927cf551a3c37216bd8e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:07:59 -0800 Subject: [PATCH 43/57] test: retain endpoint refusal evidence and place G3 row in ledger --- seaweed-block/core/host/master/workspace_move_refusal_test.go | 2 +- seaweed-block/docs/design/invariants.md | 4 ++-- 2 files changed, 3 insertions(+), 3 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 71d59787ee..3bcf314468 100644 --- a/seaweed-block/core/host/master/workspace_move_refusal_test.go +++ b/seaweed-block/core/host/master/workspace_move_refusal_test.go @@ -102,7 +102,7 @@ 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`}, - {"same-host clean still needs authority", move("placed", "node-a", "127.0.0.1:19101", "127.0.0.1:19102"), `workspace move: missing or changed authority/lease`}, + {"same-host clean still needs prepared endpoints", move("bound", "node-a", "127.0.0.1:19101", "127.0.0.1:19102"), `move target endpoints 127.0.0.1:19101/127.0.0.1:19102 on "node-a" are not registered (live bindings on that node: 127.0.0.1:19121/127.0.0.1:19122)`}, {"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"), diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index c36bbfb9e1..6cad2c7132 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -198,8 +198,7 @@ stateDiagram-v2 | Claiming | Detached (non-serving) | same epoch/holder HEAD is already detached: refuse with ErrChunkLayerDetached before restore preparation or CAS; a higher-epoch takeover still consumes the sealed image | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-SEALED-REOPEN-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-SAME-HOST-CLEAN-MOVE-001` | Same-host move: CLEAN only, with HEAD detached by the current holder at its epoch and the matching revocation ACK; it issues a higher epoch to the same host, which claims that sealed HEAD and serves exactly its image. Forced same-host move stays refused; a same-epoch sealed reopen never serves. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | ACTIVE | -| `INV-WS-CLEAN-MOVE-001` | +| Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | | Holder | HolderFenced | a conflicting HEAD owner (including a regressed epoch) or a displaced publication is observed; local data and unresolved cut intents remain | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | | Holder | (hydration wait) | one request deadline covers all missing chunks; callers may detach, but bounded per-layer workers retain and join each shared fill; HEAD/generation/local-write checks still govern installation | `core/storage/chunk_hydration.go`; `core/frontend/durable/storage_adapter.go` `readStorageBlock` | `INV-CUT-HYDRATION-WAIT-001`, `INV-CUT-READMISS-001` | @@ -651,6 +650,7 @@ Notes: | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | +| `INV-WS-SAME-HOST-CLEAN-MOVE-001` | Same-host move: CLEAN only, with HEAD detached by the current holder at its epoch and the matching revocation ACK; it issues a higher epoch to the same host, which claims that sealed HEAD and serves exactly its image. Forced same-host move stays refused; a same-epoch sealed reopen never serves. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | ACTIVE | | `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-FORCED-MOVE-001` | A forced move is admitted only after the persisted lease horizon and the granted or restart deadline, each plus the clock-skew bound, have passed for the lease the last move issue started (never a predecessor's): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE | | `INV-WS-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry, never the persisted horizon. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE | From a489f4e1f58fec5e269ef7b4d48a507cf38eafab Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:08:15 -0800 Subject: [PATCH 44/57] test: clone protobuf requests without copying lock state --- .../core/host/master/workspace_same_host_clean_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/host/master/workspace_same_host_clean_test.go b/seaweed-block/core/host/master/workspace_same_host_clean_test.go index e518160a4c..6134a2c3d9 100644 --- a/seaweed-block/core/host/master/workspace_same_host_clean_test.go +++ b/seaweed-block/core/host/master/workspace_same_host_clean_test.go @@ -4,6 +4,7 @@ import ( "testing" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/protobuf/proto" ) // INV-WS-SAME-HOST-CLEAN-MOVE-001: retirement belongs to an epoch, so the @@ -46,9 +47,9 @@ func TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding(t *testing.T) { if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { t.Fatal("same-host re-prepare refused", err) } - forced := *req + forced := proto.Clone(req).(*control.WorkspaceMove) forced.Kind, forced.Force = "forced", true - if _, err := ws.MoveWorkspace(ctx, &forced); err == nil { + if _, err := ws.MoveWorkspace(ctx, forced); err == nil { t.Fatal("same-host forced move accepted over RPC") } if _, err := ws.MoveWorkspace(ctx, req); err != nil { From 7ed752eb299ff6bf26ea8ce556e6170e3d900833 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:09:42 -0800 Subject: [PATCH 45/57] docs: use the approved same-host clean move invariant text --- 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 6cad2c7132..8a1759e186 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -650,7 +650,7 @@ Notes: | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | -| `INV-WS-SAME-HOST-CLEAN-MOVE-001` | Same-host move: CLEAN only, with HEAD detached by the current holder at its epoch and the matching revocation ACK; it issues a higher epoch to the same host, which claims that sealed HEAD and serves exactly its image. Forced same-host move stays refused; a same-epoch sealed reopen never serves. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | ACTIVE | +| `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A clean move may name the source host as its target only when HEAD is sealed by the current holder and the revocation ACK is recorded for that HEAD generation; it issues a higher epoch. A forced move to the source host is refused. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | ACTIVE | | `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-FORCED-MOVE-001` | A forced move is admitted only after the persisted lease horizon and the granted or restart deadline, each plus the clock-skew bound, have passed for the lease the last move issue started (never a predecessor's): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE | | `INV-WS-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry, never the persisted horizon. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE | From c1033cb8af9229df88caefd6d7ae5aad26c4d7a2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:10:25 -0800 Subject: [PATCH 46/57] test: pin regrant to the existing later forced-move skew barrier --- .../core/authority/workspace_regrant_test.go | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/seaweed-block/core/authority/workspace_regrant_test.go b/seaweed-block/core/authority/workspace_regrant_test.go index 73f9cdd248..1b5eeb3270 100644 --- a/seaweed-block/core/authority/workspace_regrant_test.go +++ b/seaweed-block/core/authority/workspace_regrant_test.go @@ -123,17 +123,25 @@ func TestWorkspaceLeaseRegrantWaitsForFullSkew(t *testing.T) { } writes := 0 store.setBefore(func(DurableRecord) error { writes++; return nil }) - // Expired by master time, but still inside expiry + the full 4 s bound. - clock.at(13) - if got, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil { - t.Fatal("re-grant raced the old process's lagging clock", got) + // The deadline+skew boundary is 14 s; horizon+skew is 19 s. + // Re-grant uses the same MAX barrier as a forced move, including the + // interval after the shorter deadline has passed and its final ns. + for _, now := range []time.Time{clock.sec(13), clock.sec(14), clock.sec(19).Add(-time.Nanosecond)} { + clock.ns.Store(now.UnixNano()) + if got, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil { + t.Fatal("re-grant crossed the later expiry/skew boundary early", now, got) + } + if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", "force", "r", 1); err == nil { + t.Fatal("forced move crossed the shared boundary early", now) + } + if writes != 0 { + t.Fatal("unsafe early re-grant attempted persistence", writes) + } } - if writes != 0 { - t.Fatal("unsafe early re-grant attempted persistence", writes) - } - // Both deadline+skew and horizon+skew have now passed. This positive - // endpoint is independent of the pending min/max barrier clarification. clock.at(19) + if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", "force", "r", 1); err != nil { + t.Fatal("fixture did not reach the shared forced-move barrier", err) + } got, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1) if err != nil || got.ExpiresAtNS <= clock.now().UnixNano() || writes != 1 { t.Fatalf("safe unchanged owner cannot return: grant=%+v writes=%d err=%v", got, writes, err) From 612b3276c07b113b05ad40fdb317e42e1e9d54f9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:34:04 -0800 Subject: [PATCH 47/57] docs: recount invariant ledger after merging current main --- 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 b0741f542f..f31d0df116 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -409,7 +409,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -297 rows: 211 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 282 new. +298 rows: 212 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 283 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. From 823a7b9e2d1352a5a42e2c5f7f0768c19a39cf56 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:56:09 -0800 Subject: [PATCH 48/57] fix: durably regrant expired unchanged owners after forced-move barrier --- .../core/authority/workspace_lease_view.go | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index b97a30c123..9f701f0abc 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -214,7 +214,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri } if now.UnixNano() >= lv.d.horizon || !now.Before(lv.deadline) { unlock() - return WorkspaceLease{}, fmt.Errorf("workspace lease expired or revoking") + return p.regrantWorkspaceLease(ctx, volume, holder, epoch) } // Where the synchronous write used to refuse (persistWorkspaceLocked): // a renewal never bypasses uncertainty (INV-AUTH-UNCERTAIN-001). @@ -310,6 +310,42 @@ func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder stri return WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lease.MaxClockSkewNS}, nil } +// INV-WS-LEASE-REGRANT-001: serialize an expired re-grant with move issue, +// reusing the forced-move barrier so the old process's validity is past. +// The live renewal path releases leaseMu before entering this writer. +func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { + p.mu.Lock() + defer p.mu.Unlock() + if err := ctx.Err(); err != nil { + return WorkspaceLease{}, err + } + _, line, ok := p.workspaceLineLocked(volume) + s := cloneWorkspace(p.workspace[volume]) + if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch || s == nil || s.Lease == nil || + s.Lease.ReplicaID != holder || s.Lease.Epoch != epoch { + return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority") + } + if s.Lease.Revoking || s.Ack != nil || (len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued) { + return WorkspaceLease{}, fmt.Errorf("workspace lease: revocation or move pending") + } + if p.store == nil || p.workspaceUncertain[volume] { + return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain") + } + _, now, err := p.forcedMoveBarrierLocked(volume, s.Lease) + if err != nil { + return WorkspaceLease{}, err + } + lease, grant := p.newWorkspaceLease(holder, epoch, now) + lease.ExpiresAtNS = max(lease.ExpiresAtNS, s.Lease.ExpiresAtNS) + lease.MaxClockSkewNS = int64(p.workspaceSkew(s.Lease)) + s.Lease = lease + if err := p.persistWorkspaceLocked(volume, s); err != nil { + return WorkspaceLease{}, err + } + p.setLeaseDeadlineLocked(volume, grant, true) + return WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lease.MaxClockSkewNS}, nil +} + // newWorkspaceLease starts a lease at now: the durable horizon is // now+1.5*TTL and the grant (the deadline) now+TTL. Both a first grant and a // move issue start a lease this way. From db9f8ff5f20003088b49f30f36e9335017fede24 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:57:20 -0800 Subject: [PATCH 49/57] test: witness regrant durability force exclusion and empty-root restore --- .../workspace_regrant_storage_test.go | 21 ++++- .../core/authority/workspace_regrant_test.go | 76 +++++++++++++++++++ 2 files changed, 94 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/authority/workspace_regrant_storage_test.go b/seaweed-block/core/authority/workspace_regrant_storage_test.go index 21f445ff7d..7de486198f 100644 --- a/seaweed-block/core/authority/workspace_regrant_storage_test.go +++ b/seaweed-block/core/authority/workspace_regrant_storage_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "reflect" "testing" "time" @@ -21,14 +22,18 @@ func (regrantStorageView) Projection() frontend.Projection { // These component controls obtain the real authority re-grant before opening // the returning file-backed provider. They do not model a second live process. func TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut(t *testing.T) { - testWorkspaceRegrantStorage(t, false) + testWorkspaceRegrantStorage(t, false, false) } func TestWorkspaceLeaseRegrantCannotUnsealSameEpoch(t *testing.T) { - testWorkspaceRegrantStorage(t, true) + testWorkspaceRegrantStorage(t, true, false) } -func testWorkspaceRegrantStorage(t *testing.T, sealed bool) { +func TestWorkspaceLeaseRegrantEmptyRootClaimsOnlyHEAD(t *testing.T) { + testWorkspaceRegrantStorage(t, false, true) +} + +func testWorkspaceRegrantStorage(t *testing.T, sealed, fresh bool) { t.Helper() ctx := context.Background() disk, _ := newTempStore(t) @@ -92,6 +97,10 @@ func testWorkspaceRegrantStorage(t *testing.T, sealed bool) { if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { t.Fatal("returning process could not obtain the authority re-grant", err) } + if fresh { + root = t.TempDir() + b = make([]byte, 4096) // the absent local log cannot be claimed as present + } second := open() _, err = second.RecoverVolume(ctx, "v") if sealed { @@ -122,6 +131,12 @@ func testWorkspaceRegrantStorage(t *testing.T, sealed bool) { t.Fatal(err) } final, err := remote.GetHead(ctx) + if fresh { + if err != nil || !reflect.DeepEqual(final, claimed) { + t.Fatal("empty-root return published bytes/frontier absent from HEAD", final, err) + } + return + } if err != nil || final.RemoteLSN <= before.RemoteLSN { t.Fatal("first returning cut did not cover the local log", final, err) } diff --git a/seaweed-block/core/authority/workspace_regrant_test.go b/seaweed-block/core/authority/workspace_regrant_test.go index 1b5eeb3270..17c029bdbc 100644 --- a/seaweed-block/core/authority/workspace_regrant_test.go +++ b/seaweed-block/core/authority/workspace_regrant_test.go @@ -2,6 +2,7 @@ package authority import ( "context" + "errors" "testing" "time" ) @@ -58,6 +59,81 @@ func TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable(t *testing.T) { } } +func TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure(t *testing.T) { + for _, fail := range []bool{false, true} { + t.Run(map[bool]string{false: "durable", true: "uncertain"}[fail], func(t *testing.T) { + disk, _ := newTempStore(t) + clock := newTestClock() + store := &hookStore{AuthorityStore: disk} + p := newLeasePublisher(t, store, time.Second, clock) + before := bindAndGrant(t, p, "v", "r") + clock.at(3) + entered, release := make(chan struct{}), make(chan struct{}) + // Release even on a failed assertion, before publisher cleanup joins. + defer close(release) + store.setBefore(func(DurableRecord) error { + close(entered) + <-release + return nil + }) + store.setAfter(func(DurableRecord) error { + if fail { + return errors.New("write landed but reply lost") + } + return nil + }) + type answer struct { + lease WorkspaceLease + err error + } + done := make(chan answer, 1) + go func() { + l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1) + done <- answer{l, err} + }() + <-entered + if visible, ok := p.WorkspaceLeaseReply("v"); !ok || visible.ExpiresAtNS != before.ExpiresAtNS { + t.Error("grant published ahead of durable store", visible) + } + // An unbuffered release lets this test join the writer without racing + // a wall-clock delay; its deferred close is harmless after the send. + release <- struct{}{} + got := <-done + if fail { + if got.err == nil || got.lease.ExpiresAtNS != 0 { + t.Fatal("uncertain write produced a usable grant", got) + } + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil { + t.Fatal("renewal bypassed uncertain re-grant") + } + } else if got.err != nil || got.lease.ExpiresAtNS != clock.sec(4).UnixNano() { + t.Fatal("durable re-grant not returned", got) + } + }) + } +} + +func TestWorkspaceLeaseForcedIssueDefeatsOldHolderRegrant(t *testing.T) { + disk, _ := newTempStore(t) + clock := newTestClock() + p := newLeasePublisher(t, disk, time.Second, clock) + bindAndGrant(t, p, "v", "r") + clock.at(3) + req := WorkspaceMoveRequest{RequestID: "force", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} + grant, err := p.MoveWorkspace(context.Background(), req, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42}) + if err != nil || !grant.Issued || grant.NewEpoch != 2 { + t.Fatal("fixture did not issue forced successor", grant, err) + } + clock.at(7) + if got, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil { + t.Fatal("old epoch re-granted after forced issue", got) + } + line, _ := p.VolumeAuthorityLine("v") + if line.Epoch != 2 || p.WorkspaceState("v").Lease.Epoch != 2 { + t.Fatal("re-grant undid forced issue", line) + } +} + func TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight(t *testing.T) { disk, _ := newTempStore(t) clock := newTestClock() From bc43c667861506882ee974aa5dbab3d482b17bc4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 20:59:09 -0800 Subject: [PATCH 50/57] docs: specify expired-holder regrant behind the shared MAX barrier --- .../core/authority/workspace_lease_view.go | 4 ++-- .../core/authority/workspace_regrant_test.go | 6 ++++- .../docs/design/agent-workspace-design.md | 3 +++ seaweed-block/docs/design/invariants.md | 4 +++- seaweed-block/docs/workspace-lease.md | 24 ++++++++++++++++++- 5 files changed, 36 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index 9f701f0abc..ce4ecf1615 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -178,7 +178,7 @@ func (p *Publisher) PublishedAuthorityLines() map[string]PublishedLine { // leaf leaseMu, does no I/O and never waits on p.mu or the store. The grant // is min(now+TTL, durable horizon); a background extender (an ordinary p.mu // writer) pushes the horizon ahead. Only the first grant of a lease writes -// synchronously (firstWorkspaceGrant). +// synchronously, as does an expired re-grant after the shared move barrier. func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { if err := ctx.Err(); err != nil { return WorkspaceLease{}, err @@ -348,7 +348,7 @@ func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder st // newWorkspaceLease starts a lease at now: the durable horizon is // now+1.5*TTL and the grant (the deadline) now+TTL. Both a first grant and a -// move issue start a lease this way. +// expired re-grant and move issue start a lease this way. func (p *Publisher) newWorkspaceLease(holder string, epoch uint64, now time.Time) (*WorkspaceLease, time.Time) { return &WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(nil))}, now.Add(p.workspaceTTL) } diff --git a/seaweed-block/core/authority/workspace_regrant_test.go b/seaweed-block/core/authority/workspace_regrant_test.go index 17c029bdbc..658a97e591 100644 --- a/seaweed-block/core/authority/workspace_regrant_test.go +++ b/seaweed-block/core/authority/workspace_regrant_test.go @@ -91,7 +91,11 @@ func TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure(t *testing.T) l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1) done <- answer{l, err} }() - <-entered + select { + case <-entered: + case got := <-done: + t.Fatal("re-grant returned before the durable write witness", got) + } if visible, ok := p.WorkspaceLeaseReply("v"); !ok || visible.ExpiresAtNS != before.ExpiresAtNS { t.Error("grant published ahead of durable store", visible) } diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 5c81669a25..4d2f1711a4 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -361,10 +361,13 @@ stateDiagram-v2 Revoking --> Acked: host acks detached HEAD gen while the lease is valid Acked --> Moved: CLEAN move Granted --> Expired: horizon or deadline passes + Expired --> Granted: unchanged holder, no move/revocation, MAX expiry + skew passed; durable re-grant Expired --> Moved: FORCED move after expiry + skew bound, then HEAD read (an older-epoch HEAD is accepted) } ``` +**Return after lease expiry.** A new process of the unchanged holder and epoch may obtain one durable re-grant after the existing forced-move barrier: both the persisted horizon and granted/restart deadline plus full skew have passed. Re-grant and forced issue serialize under the publisher lock; the winner prevents the competing operation. Revocation, a pending move or uncertain persistence refuses a usable grant. Existing fenced guards remain terminal. The returning process claims a new HEAD generation before I/O, keeps its local acknowledged WAL, and publishes it on the first cut. An empty local root restores only HEAD; a same-epoch sealed HEAD remains detached. + **Moving back to a host with a surviving local file.** A fresh volume claims HEAD before serving. A non-fresh attach reads HEAD first; if another holder published it, the attach fails closed with `ErrChunkStaleLocalRoot` (`core/frontend/durable/provider_chunk.go`): the volume is not served, and one log line and the status evidence name the local root to remove or quarantine, after which the next attach starts fresh from HEAD (#167). ## 8. Security model diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5954fb6f01..d23961cf6f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -99,6 +99,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | | Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | +| Expired | Granted | Same current holder/epoch, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001` | | Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced @`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` | | Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` | @@ -409,7 +410,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -297 rows: 211 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 282 new. +298 rows: 212 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 283 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. @@ -647,6 +648,7 @@ Notes: | `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`); `TestLocalReopenRejectsForeignClaimImage` (`core/frontend/durable/provider_reopen_belt_test.go`) | — | ACTIVE | | `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | +| `INV-WS-LEASE-REGRANT-001` | Re-grant after expiry: same holder and epoch only, no move pending or issued, not revoking, store certain, one durable write, and only once max(horizon, deadline) + skew bound has passed; the new process claims HEAD with a new generation before any I/O, so no older incarnation writes or CASes after. | M2 lease: Expired → Granted | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable`, `TestWorkspaceLeaseRegrantWaitsForFullSkew`, `TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight`, `TestWorkspaceLeaseForcedIssueDefeatsOldHolderRegrant`, `TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure` (`core/authority/workspace_regrant_test.go`); `TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut`, `TestWorkspaceLeaseRegrantCannotUnsealSameEpoch`, `TestWorkspaceLeaseRegrantEmptyRootClaimsOnlyHEAD` (`core/authority/workspace_regrant_storage_test.go`) | `WorkspaceRegrant` `NoDualServingInc`, `RegrantNoLoss`, `DiskCoversMemory` | ACTIVE | | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/workspace-lease.md b/seaweed-block/docs/workspace-lease.md index bb089340fe..e6fe4fbca2 100644 --- a/seaweed-block/docs/workspace-lease.md +++ b/seaweed-block/docs/workspace-lease.md @@ -17,7 +17,9 @@ the assignment. Blockvolume closes frontend admission, drains and closes the frontend, replication, and provider, reads the stored detached HEAD, and only then ACKs its exact generation. The authority refuses an expired lease's ACK. Revocation does not perform a final cut. Lease expiry or cancellation closes -the host without a CLEAN ACK or cut; recovery uses a FORCED move. +the host without a CLEAN ACK or cut. A new process of the unchanged holder +and epoch may return through a durable re-grant as described below; a move +to a different holder still requires the move protocol. The shared projection loads the guard atomically. Guard operations serialize renewal, drain, and ACK with the operation mutex; the state mutex is held only @@ -70,3 +72,23 @@ defaults). Beyond that, grants shrink and hosts fence: the design fails closed. Blockmaster logs one warning per failure streak, with the write's latency and the remaining horizon, when an extension fails, and one when grants start to be clamped to the horizon, and a line when either recovers. + + +## Returning after an expired lease + +Restarting the same holder at the same epoch can retain its acknowledged +local WAL after a long outage. Re-grant waits for the existing forced-move +barrier: both the durable horizon and the granted or conservative restart +deadline, each plus the full configured/persisted skew bound, must have +passed. The master then persists one new horizon before returning the grant; +neither horizon nor skew is reduced. Immediate repeated renewals use memory, +so they do not add durable re-grant writes while that grant is live. + +The authority record must still name this holder and epoch. A pending move, +revocation/ACK or uncertain store prevents a usable re-grant. Re-grant and +forced issue serialize; whichever commits first makes the other refuse. +An already fenced guard never reopens: start a new process, which claims a +new HEAD generation before serving and retains its local WAL. Its first cut +covers those acknowledged bytes. If the local root is absent, recovery +restores only the sealed/published HEAD image and never claims missing local +bytes. A same-epoch detached HEAD stays detached even after a lease re-grant. From 7e8084c7a482134ba2e9a87021b61f366b2efd97 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 21:02:35 -0800 Subject: [PATCH 51/57] fix: keep expired renewal nonblocking behind held authority writes --- seaweed-block/core/authority/workspace_lease_view.go | 6 +++++- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/workspace-lease.md | 2 ++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index ce4ecf1615..07b5547c6f 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -314,7 +314,11 @@ func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder stri // reusing the forced-move barrier so the old process's validity is past. // The live renewal path releases leaseMu before entering this writer. func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { - p.mu.Lock() + // INV-WS-RENEW-NONBLOCKING-001: a held writer refuses this attempt; + // a returning process can retry after that writer has settled. + if !p.mu.TryLock() { + return WorkspaceLease{}, fmt.Errorf("workspace lease: authority writer busy; retry") + } defer p.mu.Unlock() if err := ctx.Err(); err != nil { return WorkspaceLease{}, err diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d23961cf6f..3b5de3c240 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -99,7 +99,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | | Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | -| Expired | Granted | Same current holder/epoch, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001` | +| Expired | Granted | Same current holder/epoch, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); a busy authority writer refuses this attempt, otherwise persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001` | | Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced @`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` | | Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` | diff --git a/seaweed-block/docs/workspace-lease.md b/seaweed-block/docs/workspace-lease.md index e6fe4fbca2..0ebaf72775 100644 --- a/seaweed-block/docs/workspace-lease.md +++ b/seaweed-block/docs/workspace-lease.md @@ -87,6 +87,8 @@ so they do not add durable re-grant writes while that grant is live. The authority record must still name this holder and epoch. A pending move, revocation/ACK or uncertain store prevents a usable re-grant. Re-grant and forced issue serialize; whichever commits first makes the other refuse. +If an authority writer holds the lock, this renewal attempt refuses +immediately; a returning process may retry after the writer settles. An already fenced guard never reopens: start a new process, which claims a new HEAD generation before serving and retains its local WAL. Its first cut covers those acknowledged bytes. If the local root is absent, recovery From 5af76730c72118436810d34764f2cf0be6b36a39 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 21:05:38 -0800 Subject: [PATCH 52/57] test: require sealed regrant return to preserve proof and refuse guest IO --- seaweed-block/core/authority/workspace_lease_view.go | 8 ++++---- .../core/authority/workspace_regrant_storage_test.go | 9 ++++++++- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index 07b5547c6f..f72ded0815 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -177,8 +177,8 @@ func (p *Publisher) PublishedAuthorityLines() map[string]PublishedLine { // RenewWorkspaceLease answers a live holder from memory: it takes only the // leaf leaseMu, does no I/O and never waits on p.mu or the store. The grant // is min(now+TTL, durable horizon); a background extender (an ordinary p.mu -// writer) pushes the horizon ahead. Only the first grant of a lease writes -// synchronously, as does an expired re-grant after the shared move barrier. +// writer) pushes the horizon ahead. A first grant and an expired re-grant +// after the shared move barrier write synchronously. func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { if err := ctx.Err(); err != nil { return WorkspaceLease{}, err @@ -351,8 +351,8 @@ func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder st } // newWorkspaceLease starts a lease at now: the durable horizon is -// now+1.5*TTL and the grant (the deadline) now+TTL. Both a first grant and a -// expired re-grant and move issue start a lease this way. +// now+1.5*TTL and the grant (the deadline) now+TTL. A first grant, expired +// re-grant and move issue start a lease this way. func (p *Publisher) newWorkspaceLease(holder string, epoch uint64, now time.Time) (*WorkspaceLease, time.Time) { return &WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(nil))}, now.Add(p.workspaceTTL) } diff --git a/seaweed-block/core/authority/workspace_regrant_storage_test.go b/seaweed-block/core/authority/workspace_regrant_storage_test.go index 7de486198f..2f5cf00411 100644 --- a/seaweed-block/core/authority/workspace_regrant_storage_test.go +++ b/seaweed-block/core/authority/workspace_regrant_storage_test.go @@ -105,9 +105,16 @@ func testWorkspaceRegrantStorage(t *testing.T, sealed, fresh bool) { _, err = second.RecoverVolume(ctx, "v") if sealed { after, readErr := remote.GetHead(ctx) - if !errors.Is(err, storage.ErrChunkLayerDetached) || readErr != nil || after.Gen != before.Gen || after.Epoch != before.Epoch || after.Holder != before.Holder || after.State != storage.ChunkHeadDetached || after.RemoteLSN != before.RemoteLSN { + if !errors.Is(err, storage.ErrChunkLayerDetached) || readErr != nil || !reflect.DeepEqual(after, before) { t.Fatal("same-epoch re-grant reactivated the seal", after, err, readErr) } + blocked, openErr := second.Open(ctx, "v") + if openErr != nil { + t.Fatal(openErr) + } + if _, readErr := blocked.Read(ctx, 0, make([]byte, 4096)); !errors.Is(readErr, frontend.ErrNotReady) { + t.Fatal("sealed re-granted process exposed guest I/O", readErr) + } return } if err != nil { From 742d248a783c41c2651090b4016a42f7e1b88b09 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 21:12:08 -0800 Subject: [PATCH 53/57] test: preserve persisted regrant skew across a smaller restart setting --- .../core/authority/workspace_regrant_test.go | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/seaweed-block/core/authority/workspace_regrant_test.go b/seaweed-block/core/authority/workspace_regrant_test.go index 658a97e591..208986b2f5 100644 --- a/seaweed-block/core/authority/workspace_regrant_test.go +++ b/seaweed-block/core/authority/workspace_regrant_test.go @@ -227,3 +227,32 @@ func TestWorkspaceLeaseRegrantWaitsForFullSkew(t *testing.T) { t.Fatalf("safe unchanged owner cannot return: grant=%+v writes=%d err=%v", got, writes, err) } } + +func TestWorkspaceLeaseRegrantRetainsPersistedSkewAfterRestart(t *testing.T) { + disk, _ := newTempStore(t) + clock := newTestClock() + first := newLeasePublisher(t, disk, time.Second, clock) + before := bindAndGrant(t, first, "v", "r") + first.CloseWorkspaceExtenders() + clock.at(3) + returned := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, clock.now), WithWorkspaceMaxClockSkew(time.Millisecond)) + t.Cleanup(returned.CloseWorkspaceExtenders) + // Restart deadline is 4 s. The newly configured 1 ms bound has passed, + // but the original persisted bound still protects the previous process. + clock.at(4.5) + if got, err := returned.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil { + t.Fatal("smaller restart setting shortened the old barrier", got) + } + clock.at(6) + got, err := returned.RenewWorkspaceLease(context.Background(), "v", "r", 1) + if err != nil || got.MaxClockSkewNS != before.MaxClockSkewNS { + t.Fatal("re-grant lowered the persisted skew", got, err) + } + records, err := disk.Load() + if err != nil { + t.Fatal(err) + } + if len(records) != 1 || records[0].Workspace.Lease.MaxClockSkewNS != before.MaxClockSkewNS || records[0].Workspace.Lease.ExpiresAtNS < got.ExpiresAtNS { + t.Fatal("preserved re-grant bound was not durable", records) + } +} From 70fa2dee00d528dbbcc7d77e22e088fd8ff1c7fc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 21:23:41 -0800 Subject: [PATCH 54/57] docs: required setup, make the volume known to blockmaster A blockvolume that blockmaster does not know serves nothing and says little. The standalone document now states the topology file and the matching flags as required steps, how to check before and after, and which log line means which missing step. Co-Authored-By: Claude Fable 5.2 --- seaweed-block/docs/standalone-deployment.md | 83 ++++++++++++++++++++- 1 file changed, 81 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 055c79795b..e7efc685a6 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -65,20 +65,99 @@ sudo install -m 0640 -g sw-block deploy/config/*.env deploy/config/topology.yaml sudo install -m 0644 deploy/systemd/*.service /etc/systemd/system/ sudo systemctl daemon-reload sudo systemctl enable --now sw-blockmaster sw-blockvolume -journalctl -u sw-blockvolume -f # wait for "nvme-listening" +journalctl -u sw-blockvolume -f # wait for "adopted as PRIMARY" (see the required setup below) ``` The binaries take command-line flags. The `SWB_*` variables are read only by the example units, which turn them into flags. blockvolume itself reads only `SW_BLOCK_ISCSI_CHAP_USERNAME` and `SW_BLOCK_ISCSI_CHAP_SECRET`. +## Required setup: make the volume known to blockmaster + +blockmaster gives a blockvolume an assignment only for a volume and replica +slot it already knows. It does not learn volumes from heartbeats. Without an +assignment, blockvolume starts, opens its storage and its listeners, and +serves no I/O. + +Outside Kubernetes, a volume becomes known through the accepted-topology file. +Do these steps before you start blockvolume: + +1. **Write the topology file.** One entry per volume, one slot per replica; + `volume_id`, `replica_id` and `server_id` are required. This is + [`deploy/config/topology.yaml`](../deploy/config/topology.yaml): + + ```yaml + volumes: + - volume_id: v1 + slots: + - replica_id: r1 + server_id: s1 + ``` + +2. **Start blockmaster with the file and the matching slot count.** + `--expected-slots-per-volume` must equal the number of slots of each + volume: `1` here (the default is `3`). + + ```bash + blockmaster --authority-store /var/lib/sw-block-master/authority --listen 127.0.0.1:9180 \ + --topology /etc/sw-block/topology.yaml --expected-slots-per-volume 1 + ``` + + In `blockmaster.env` these are `SWB_MASTER_TOPOLOGY` and + `SWB_MASTER_EXPECTED_SLOTS`. blockmaster reads the file only at start: + after you change it, run `sudo systemctl restart sw-blockmaster`. + +3. **Start blockvolume with the identity of one slot.** `--volume-id`, + `--replica-id` and `--server-id` (`SWB_VOLUME_ID`, `SWB_REPLICA_ID`, + `SWB_SERVER_ID`) must equal one slot of the file: `v1`, `r1`, `s1` here. + +**Check before starting blockvolume.** Without a usable topology, blockmaster +logs this line at start; if `journalctl -u sw-blockmaster` shows it, redo +steps 1 and 2: + +``` +blockmaster: WARNING: --topology not supplied or empty; controller will not mint assignments until topology is provided +``` + +A file that cannot be read or parsed stops blockmaster with +`blockmaster: topology: ...`. + +**Check after.** blockvolume logs `blockvolume: volume v1 adopted as PRIMARY +at r1@`, and its status shows a positive `Epoch`, `"Healthy":true` and +`"AuthorityRole":"primary"`: + +```bash +journalctl -u sw-blockvolume | grep 'adopted as PRIMARY' +curl -s 'http://127.0.0.1:9203/status?volume=v1'; echo +``` + +`nvme-listening` alone does not prove this: blockvolume starts its NVMe/TCP +listener before it has an assignment. Without one, the status shows +`"Epoch":0`, `"Healthy":false` and `"AuthorityRole":"unknown"`. + +| What you see | Missing step | +|---|---| +| blockvolume logs `blockvolume: subscribe stream: rpc error: code = Unknown desc = subscribe: volume "v1" not in accepted topology`, again every few seconds | blockmaster has no topology, or `v1` is not in it (steps 1, 2) | +| `walstore-chunk` only: `durable: chunk layer for volume=v1 waits for master authority (up to 30s): projection lacks healthy=false epoch=0`, and 30 s later `durable: chunk authority wait for volume=v1 ended after ...: assignment unavailable, not serving (projection lacks healthy=false epoch=0)` | The same. This wait runs once per start: after the fix, restart blockvolume too | +| No error in either log, and `"Epoch":0` stays | `--expected-slots-per-volume` differs from the slot count (step 2), or `--server-id` or `--replica-id` differ from the slot (step 3) | +| blockmaster logs `authority: rejected ask ...: workspace publication: no lifecycle VolumeRecord for v1; register it (CreateVolume) before publishing` | blockmaster runs with `--lifecycle-store`: a topology slot is then not enough, the volume also needs a volume record (below) | + +**Workspace lease volumes (`--workspace-lease`).** Besides the steps above, +blockmaster needs `--workspace-rpc`, `--workspace-head-base-url` and +`--lifecycle-store`, and the volume needs a single-replica volume record in +that store. This release has no `sw-block` command that creates that record. Check with `sw-block ops workspace show --master 127.0.0.1:9180 +--volume v1`; it names the first missing piece: `workspace RPC disabled`, +`lifecycle store unavailable`, or `workspace move requires an existing RF1 +volume`. A move target must also be a registered node, or the move is refused +with `move target node "s2" is not registered`. + ## blockmaster settings | Variable | Flag | Default | Meaning | |---|---|---|---| | `SWB_MASTER_AUTHORITY_STORE` | `--authority-store` | required | Durable authority store: assignments, epochs, leases | | `SWB_MASTER_LISTEN` | `--listen` | `127.0.0.1:0` | gRPC address; unauthenticated, keep it on loopback or a trusted network | -| `SWB_MASTER_TOPOLOGY` | `--topology` | empty (no assignments minted) | Accepted-topology YAML: volumes and replica slots | +| `SWB_MASTER_TOPOLOGY` | `--topology` | empty (no assignments minted: no volume serves) | Accepted-topology YAML: volumes and replica slots; required outside Kubernetes, read only at start | | `SWB_MASTER_EXPECTED_SLOTS` | `--expected-slots-per-volume` | `3` | Replica slots per volume; `1` for a single replica | | `SWB_MASTER_FRESHNESS_WINDOW` | `--freshness-window` | `30s` | How long a heartbeat stays fresh | | `SWB_MASTER_PENDING_GRACE` | `--pending-grace` | `1s` | Startup grace before a missing observation is unsupported | From 0d7808c9ad5d58244eed529fd5781c4f41bb5e16 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 21:23:47 -0800 Subject: [PATCH 55/57] test: bound regrant durability handshakes and clarify renewal scope --- .../core/authority/workspace_regrant_test.go | 30 +++++++++++++++---- seaweed-block/docs/design/invariants.md | 6 ++-- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/seaweed-block/core/authority/workspace_regrant_test.go b/seaweed-block/core/authority/workspace_regrant_test.go index 208986b2f5..c191bab314 100644 --- a/seaweed-block/core/authority/workspace_regrant_test.go +++ b/seaweed-block/core/authority/workspace_regrant_test.go @@ -3,6 +3,7 @@ package authority import ( "context" "errors" + "sync" "testing" "time" ) @@ -69,8 +70,8 @@ func TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure(t *testing.T) before := bindAndGrant(t, p, "v", "r") clock.at(3) entered, release := make(chan struct{}), make(chan struct{}) - // Release even on a failed assertion, before publisher cleanup joins. - defer close(release) + var releaseOnce sync.Once + releaseWriter := func() { releaseOnce.Do(func() { close(release) }) } store.setBefore(func(DurableRecord) error { close(entered) <-release @@ -87,7 +88,18 @@ func TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure(t *testing.T) err error } done := make(chan answer, 1) + finished := make(chan struct{}) + // Registered last: release and join before publisher/store cleanup. + t.Cleanup(func() { + releaseWriter() + select { + case <-finished: + case <-time.After(5 * time.Second): + t.Error("re-grant worker did not finish during cleanup") + } + }) go func() { + defer close(finished) l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1) done <- answer{l, err} }() @@ -95,14 +107,20 @@ func TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure(t *testing.T) case <-entered: case got := <-done: t.Fatal("re-grant returned before the durable write witness", got) + case <-time.After(5 * time.Second): + t.Fatal("re-grant did not enter the durable write") } if visible, ok := p.WorkspaceLeaseReply("v"); !ok || visible.ExpiresAtNS != before.ExpiresAtNS { t.Error("grant published ahead of durable store", visible) } - // An unbuffered release lets this test join the writer without racing - // a wall-clock delay; its deferred close is harmless after the send. - release <- struct{}{} - got := <-done + // Events decide success; timers only bound failed handshakes. + releaseWriter() + var got answer + select { + case got = <-done: + case <-time.After(5 * time.Second): + t.Fatal("released re-grant did not return") + } if fail { if got.err == nil || got.lease.ExpiresAtNS != 0 { t.Fatal("uncertain write produced a usable grant", got) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 3b5de3c240..63402cac31 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -582,7 +582,7 @@ Notes: | `INV-LEASE-VIEW-OWNED-001` | The granted deadline and the extender flag exist only in the lease view; refreshing the view from its derive inputs never changes either of them. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`, `setLeaseDeadlineLocked`, `extendWorkspaceLease` | — | — | STUB | | `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch, the `Lease.ExpiresAtNS` persisted in the authority store is at least the published horizon, and the published horizon is at least every grant issued since the last reload. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant`, `newWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked`, `issueWorkspaceMove` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-WS-LEASE-HORIZON-MONO-001` | Within one lease the published horizon never decreases: an extension writes a new horizon only when it is greater than the current one. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/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-WS-RENEW-NONBLOCKING-001` | Live renewals take only the leaf lease lock and lock-free lifecycle snapshots; they never wait on publisher/store locks. First grants and expired re-grants persist synchronously; an expired re-grant refuses immediately if the publisher lock is busy. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | | `INV-MASTER-JOURNAL-ISOLATION-001` | Under strict journal isolation, blockmaster gives no new work to a node whose durable root shares the authority store's file system: it refuses that node's heartbeat while it serves no volume, a new placement on it and a move onto it; work the node already has is kept. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE | @@ -594,9 +594,9 @@ 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. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended: see M2 any (workspace) → Uncertain. A failed move on an uncertain volume is answered as an unknown outcome before any admission refusal, the request's own cancellation or deadline stays typed, and an issued move's replay still returns its stored grant: see M2 Uncertain → Uncertain (move answer). The renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`), not from `persistWorkspaceLocked`. - `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-LEASE-HORIZON-001`, `INV-WS-LEASE-HORIZON-MONO-001`: a move issue that replaces the lease with the new holder's (a clean handoff, or a forced move past the barrier) is its ordered successor and ends the scope of these rows. If that issue write is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further grant at the old epoch is issued (`INV-AUTH-UNCERTAIN-001`), so no disk expiry is claimed for it. -- `INV-LEASE-VIEW-001`, `INV-LEASE-VIEW-OWNED-001`: writers refresh the view under the publisher lock, then the lease lock, at every change of a derive input; the renewal path takes only the lease lock (`INV-WS-RENEW-NONBLOCKING-001`). A move issue publishes the derived view and the new holder's initial deadline in one lease-lock section, never lowering a deadline a renewal raised: see M2 Moved → epoch issued (test `TestWorkspaceIssuePublishNeverLowersARenewedDeadline`, `core/authority/workspace_issue_publish_test.go`). +- `INV-LEASE-VIEW-001`, `INV-LEASE-VIEW-OWNED-001`: writers refresh the view under the publisher lock, then the lease lock, at every change of a derive input; the live renewal path takes only the lease lock (`INV-WS-RENEW-NONBLOCKING-001`). A move issue publishes the derived view and the new holder's initial deadline in one lease-lock section, never lowering a deadline a renewal raised: see M2 Moved → epoch issued (test `TestWorkspaceIssuePublishNeverLowersARenewedDeadline`, `core/authority/workspace_issue_publish_test.go`). - Enforced by reading (no test asserts it): `INV-AUTH-PERSIST-BEFORE-PUBLISH-001`, that no subscriber sees a failed write (`applyWithWorkspaceMove` writes the store before it changes memory and snapshots the subscribers); `INV-AUTH-UNCERTAIN-001`, the drain reply on an uncertain volume (`RenewWorkspaceLease` answers a Revoking lease before it checks uncertainty); `INV-LEASE-VIEW-OWNED-001` (`refreshLeaseViewLocked` assigns only the derived part); the one-section issue publish (`publishIssuedLeaseLocked`); `INV-WS-LEASE-HORIZON-MONO-001`, that an extension writes only a greater horizon (`extendWorkspaceLease`); and the note above on `INV-WS-LEASE-HORIZON-001`, that no old-epoch grant follows an issue write with an unknown outcome (the latch, then the uncertainty check in `RenewWorkspaceLease`). -- `INV-WS-RENEW-NONBLOCKING-001`: The cited tests inject delays or holds before or inside the store write; they show sensitivity to a slow store, not a measured disk trace. +- `INV-WS-RENEW-NONBLOCKING-001`: First grants and expired re-grants are synchronous exceptions (M2 Expired → Granted, `INV-WS-LEASE-REGRANT-001`); the expired path uses TryLock and refuses a busy publisher. The cited live-renewal tests inject delays or holds before or inside the store write; they show sensitivity to a slow store, not a measured disk trace. - `INV-MASTER-JOURNAL-ISOLATION-001`: a refused heartbeat gets FailedPrecondition. A new placement is either a workspace placement or one the product loop plans. Work the node already has means: the node serves by durable state (a placement slot or a current authority line that names it), a repeated identical placement, or the retry of an issued move. Without strict mode, co-location only raises an alarm. ### B.3 Core: replication and replica roles From f287e281c21a645a464bda55baa7ed8103871552 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 22:02:34 -0800 Subject: [PATCH 56/57] docs: NVMe/TCP device lookup needs native NVMe multipath The walkthrough's lookup and the CSI node plugin resolve the namespace under /sys/class/nvme-subsystem, which holds it only with nvme_core multipath=Y. Say so, with the check. Co-Authored-By: Claude Fable 5.2 --- seaweed-block/docs/standalone-deployment.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index e7efc685a6..f3e46a6522 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -233,6 +233,10 @@ group while volumes run. - **On an NVMe root,** and in that disk's other attaches: the fsync took 50-75 microseconds and the publish 2-3 milliseconds. - **Cause:** not yet established. - **Check the device:** `lsblk -d -o NAME,ROTA,TRAN,MODEL`, and the line blockvolume logs at start, `storage: WAL/extent sync=... file=... reason=...`, whose reason names the root's device. +- **NVMe/TCP needs native NVMe multipath on the host (`nvme_core multipath=Y`, the Ubuntu default).** + The device lookup below, and the CSI node plugin's, find the namespace as an `nvmeXnY` entry under + `/sys/class/nvme-subsystem/nvme-subsysN/`; with multipath off that directory holds no namespace entry and + neither finds the device. Check: `cat /sys/module/nvme_core/parameters/multipath` must print `Y`. - ublk needs root. Use `sw-blockvolume-ublk.service` instead of editing the unprivileged unit, and load `ublk_drv` at boot (`echo ublk_drv | sudo tee /etc/modules-load.d/ublk.conf`). From 636bc9874784b3c62ae5a4a57667c56c54f5b776 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 22:36:28 -0800 Subject: [PATCH 57/57] docs: invariants say which v3 paths production reaches Production creates and opens format-v3 stores, so most 'dark', 'not yet wired' and 'until activation' phrases in the contract were false. Each phrase was checked against its production caller and now says what is true: reachable by default, reachable only with a named flag, or no production caller. Row status is unchanged. Also cites two merged tests on INV-CUT-STAGED-REUSE-001. Co-Authored-By: Claude Fable 5.2 --- seaweed-block/docs/design/invariants.md | 118 ++++++++++++------------ 1 file changed, 59 insertions(+), 59 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 10d68e4e95..0c566e3b11 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -149,7 +149,7 @@ RF2 qualification limitation until ordered-live certification is wired (#297). S | `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001`, `INV-REPL-RECOVERY-SESSION-UNIQUE-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 session (single-lane by default, dual-lane with `--recovery-mode=dual-lane`) | `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`). @@ -259,7 +259,7 @@ stateDiagram-v2 | Pre-copy admission | (Not reachable in this release; see the note below.) opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | (Not reachable in this release; see the note below.) at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | -| Guest-frozen detach | (Not reachable in this release; see the note below.) `frozen=true` carries a non-future guest freeze origin; invalid freeze options return HTTP400 `invalid_freeze_budget` before any provider admission or mutation (generic `bad_request` is not that proof); forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001`, `INV-WS-FREEZE-REFUSAL-001`, `INV-WS-FREEZE-REFUSAL-INPUTS-001` | +| Guest-frozen detach | (Not reachable in this release, except the HTTP400 validation; see the note below.) `frozen=true` carries a non-future guest freeze origin; invalid freeze options return HTTP400 `invalid_freeze_budget` before any provider admission or mutation (generic `bad_request` is not that proof); forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001`, `INV-WS-FREEZE-REFUSAL-001`, `INV-WS-FREEZE-REFUSAL-INPUTS-001` | | Checkpoint tail | one cost observation reports remaining bytes, tail cost, frozen admission estimate/known bit, storage limit and quiesce slack after a cut. Same-host duration advice is rechecked at admission before upload. | `chunk_precopy.go` `candidateTail`; `chunk_frozen_budget.go` `frozenBudgetEstimate`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001` | | Pre-copy host drain | (Not reachable in this release; see the note below.) a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` | | Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001`, `INV-CUT-READ-LOGICAL-001`, `INV-CUT-GUEST-BOUNDED-WAIT-001` | @@ -272,7 +272,7 @@ stateDiagram-v2 | Settled | drop the intents; settle native map capture tokens, keeping chunks dirtied after the cut; a refused current-lineage point retains intent-rooted completed uploads until reuse, supersession or clean Close (unresolved CAS roots excluded) | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | | Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` | -Not reachable in this release: the frozen detach and the pre-copy detach. `/chunk/detach` refuses a valid `frozen` request with `frozen_detach_unsupported` before any provider call (`INV-CUT-FROZEN-DETACH-REFUSED-001`), and blockvolume refuses to start with `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`). So the transitions Admit → FrozenForecast, FrozenForecast → Refused, FrozenForecast → Quiesce, Quiesce → Refused (guest-frozen recheck), Quiesce → FinalFreeze and FinalFreeze → OpenWindow, and the rows Pre-copy admission, Pre-copy detach, Guest-frozen detach and Pre-copy host drain, are not reached by a released process. Their code is kept and still tested below the HTTP handler; the text above is unchanged. +Not reachable in this release: the frozen detach and the pre-copy detach. `/chunk/detach` refuses a valid `frozen` request with `frozen_detach_unsupported` before any provider call (`INV-CUT-FROZEN-DETACH-REFUSED-001`), and blockvolume refuses to start with `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`). So the transitions Admit → FrozenForecast, FrozenForecast → Refused, FrozenForecast → Quiesce, Quiesce → Refused (guest-frozen recheck), Quiesce → FinalFreeze and FinalFreeze → OpenWindow, and the rows Pre-copy admission, Pre-copy detach, Guest-frozen detach (apart from its HTTP400 validation) and Pre-copy host drain, are not reached by a released process. Their code is kept and still tested below the HTTP handler; the text above is unchanged. Periodic HEAD cuts default to 15 minutes in blockvolume (OSS minimum 5 minutes; 0 explicitly disables); they do not create named snapshots. One five-minute @@ -462,23 +462,23 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-RECLAIM-EXCL-001` | No v3 writer is admitted between a checkpoint's slot publication and the end of both its rollover and its retirement of the dirty entries at or below the checkpoint. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.publishCheckpointV3`, `WALStore.retireCheckpointDirtyV3Locked` | `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse` | — | STUB | | `INV-WAL-V3-RECLAIM-SETTLE-001` | A pending v3 rollover (the fallback slot pinning a lower tail) is settled without a new checkpoint by the idle refresh, by a flusher cycle whose checkpoint does not advance, and by write admission. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.rolloverCheckpointV3Locked`, `WALStore.persistOwnedMapCheckpointV3`; `core/storage/walstore_v3.go` `WALStore.refreshW`, `WALStore.appendWriteV3` | `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint` | — | STUB | | `INV-WAL-V3-OWNER-001` | v3 read/write open and offline readonly open acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go` | `TestWALStoreV3CreatorKeepsOwnershipThroughPublication` (`core/storage/volume_lock_v3_test.go`); `TestWALStoreV3OwnerExcludesOpenAndReadOnly` (`core/storage/volume_lock_v3_test.go`); `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | -| `INV-WAL-V3-CATCHUP-001` | A v3 catch-up source that is installing refuses with `ErrBaseInstalling` and emits nothing, also for an empty request at the head. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `WALStore.ScanLBAs`, `WALStore.scanLBAsV3` | `TestCatchUpV3InstallingAtHeadRefuses` (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-CATCHUP-BASE-001` | A v3 catch-up request covered by an installed BASE (fromLSN at or below BaseLSN) fails with typed `WALRecycled`: the peer needs a rebuild. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `WALStore.scanLBAsV3` | `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`) | — | STUB | -| `INV-WAL-V3-CATCHUP-DAMAGE-001` | Damage in the retained v3 WAL makes a catch-up fail with a typed WAL integrity error and emit nothing. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `v3CatchUpEntries` | `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails` (tag `swblock_format_v3_test`) | — | STUB | -| `INV-WAL-V3-CATCHUP-REVALIDATE-001` | A v3 catch-up emits entries only from a scan whose recovery generation, nonce, BASE state and ID, install epoch, retainedTail and CheckpointLSN are unchanged after the scan. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `WALStore.scanLBAsV3` | `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` (tag `swblock_format_v3_test`) | — | STUB | -| `INV-WAL-V3-BINDING-001` | Every record and padding the v3 writer emits carries the selected nonce and its own absolute logical cursor and fits within WALSize of the both-slot reuse floor; an append that does not fit is refused. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `walWriterV3.append`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`) | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-SCAN-BINDING-001` | The v3 scanner checks a record's nonce and exact expected cursor before it uses the record's Length or count, and trusts the record only after the whole record validates again. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned` (`core/storage/wal_io_v3_test.go`) | — | STUB | -| `INV-WAL-V3-SCAN-STOP-001` | The v3 scanner skips only geometric end-of-ring slack and stops at the first untrusted record, never searching inside a payload for a later record. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord` (`core/storage/wal_io_v3_test.go`) | — | STUB | +| `INV-WAL-V3-CATCHUP-001` | A v3 catch-up source that is installing refuses with `ErrBaseInstalling` and emits nothing, also for an empty request at the head. | M1 BASE lifecycle / M3 CatchingUp | `core/storage/walstore_recovery.go` `WALStore.ScanLBAs`, `WALStore.scanLBAsV3` | `TestCatchUpV3InstallingAtHeadRefuses` (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-CATCHUP-BASE-001` | A v3 catch-up request covered by an installed BASE (fromLSN at or below BaseLSN) fails with typed `WALRecycled`: the peer needs a rebuild. | M1 BASE lifecycle / M3 CatchingUp | `core/storage/walstore_recovery.go` `WALStore.scanLBAsV3` | `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`) | — | STUB | +| `INV-WAL-V3-CATCHUP-DAMAGE-001` | Damage in the retained v3 WAL makes a catch-up fail with a typed WAL integrity error and emit nothing. | M1 BASE lifecycle / M3 CatchingUp | `core/storage/walstore_recovery.go` `v3CatchUpEntries` | `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails` (tag `swblock_format_v3_test`) | — | STUB | +| `INV-WAL-V3-CATCHUP-REVALIDATE-001` | A v3 catch-up emits entries only from a scan whose recovery generation, nonce, BASE state and ID, install epoch, retainedTail and CheckpointLSN are unchanged after the scan. | M1 BASE lifecycle / M3 CatchingUp | `core/storage/walstore_recovery.go` `WALStore.scanLBAsV3` | `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` (tag `swblock_format_v3_test`) | — | STUB | +| `INV-WAL-V3-BINDING-001` | Every record and padding the v3 writer emits carries the selected nonce and its own absolute logical cursor and fits within WALSize of the both-slot reuse floor; an append that does not fit is refused. | M1 Recovering | `core/storage/wal_io_v3.go` `walWriterV3.append`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`) | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | +| `INV-WAL-V3-SCAN-BINDING-001` | The v3 scanner checks a record's nonce and exact expected cursor before it uses the record's Length or count, and trusts the record only after the whole record validates again. | M1 Recovering | `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned` (`core/storage/wal_io_v3_test.go`) | — | STUB | +| `INV-WAL-V3-SCAN-STOP-001` | The v3 scanner skips only geometric end-of-ring slack and stops at the first untrusted record, never searching inside a payload for a later record. | M1 Recovering | `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord` (`core/storage/wal_io_v3_test.go`) | — | STUB | | `INV-WAL-V3-MAP-PUBLISH-001` | Once a v3 store has bound a validated map, every descriptor publication carries the bound map tuple or a prepared candidate's, with merged CheckpointLSN ≤ map coverage C ≤ merged W. | M1 Serving (v3 map publication) | `core/storage/chunk_map_publication_v3.go` `validateMapPublicationV3`, `sameMapTupleV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedWithMapV3` | `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-MAP-PUBLISH-REPLACE-001` | A prepared v3 map candidate is published only with a higher map generation, coverage not below the bound map's, and the same sidecar and proof domain with its epoch and mutation token unchanged since preparation; a stale candidate writes no slot. | M1 Serving (v3 map publication) | `core/storage/chunk_map_publication_v3.go` `validateMapPublicationV3`, `prepareMapPublicationV3`, `mapPublicationProofV3.validV3` | `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend` | — | STUB | | `INV-WAL-V3-MAP-PUBLISH-ROLLOVER-001` | A v3 publication without a prepared map candidate (a W-only publication or a rollover) carries the bound map root unchanged. | M1 Serving (v3 map publication) | `core/storage/chunk_map_publication_v3.go` `validateMapPublicationV3` | `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix` | — | 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 v3 map candidate names immutable pages and root in the store's owned sidecar, checked against the descriptor's identity and geometry. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3`, `encodeMapPageV3`, `encodeMapRootV3` | `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | -| `INV-WAL-V3-MAP-VALIDATE-001` | A v3 map read returns no entry before the root and every page pass their domain-separated body digests, zero reserved and unused bytes, exact page counts, file bounds and non-aliasing page intervals. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `readChunkLSNMapV3`, `mapReadAtV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest` | — | STUB | -| `INV-WAL-V3-MAP-PERSIST-ORDER-001` | A v3 map candidate exists only after its new pages are written and fsynced, then its root is written and fsynced, then the sidecar's directory is fsynced. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage` | — | STUB | -| `INV-WAL-V3-MAP-PERSIST-FAIL-001` | An error inside a v3 map persistence transaction yields no candidate and latches the store against later I/O; a preflight or Stat error latches nothing. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore` | — | STUB | -| `INV-WAL-V3-MAP-EXTENT-REUSE-001` | A v3 sidecar extent is reused only when no live root references it: neither slot's root, no in-flight candidate, and, until reopen, no candidate whose publication outcome is uncertain. | M1 (dark map preparation only) | `core/storage/chunk_map_extents_v3.go` `slotsPublishedV3`, `abandonCandidateV3`, `liveSnapshotV3`, `registerRootV3`; `core/storage/chunk_map_publication_v3.go` `publishMapV3`, `openDescriptorMapV3` | `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot` (`core/storage/chunk_map_extents_v3_test.go`); `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies` | — | STUB | -| `INV-WAL-V3-MAP-TRUNCATE-001` | When the v3 sidecar exceeds four times its live bytes, its free tail is truncated to the end of the highest live page and no lower. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3StatsAfterReopen` (`core/storage/chunk_map_extents_v3_test.go`) | — | STUB | +| `INV-WAL-V3-FLUSH-LIFETIME-001` | A 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 v3 map candidate names immutable pages and root in the store's owned sidecar, checked against the descriptor's identity and geometry. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3`, `encodeMapPageV3`, `encodeMapRootV3` | `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | +| `INV-WAL-V3-MAP-VALIDATE-001` | A v3 map read returns no entry before the root and every page pass their domain-separated body digests, zero reserved and unused bytes, exact page counts, file bounds and non-aliasing page intervals. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `readChunkLSNMapV3`, `mapReadAtV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest` | — | STUB | +| `INV-WAL-V3-MAP-PERSIST-ORDER-001` | A v3 map candidate exists only after its new pages are written and fsynced, then its root is written and fsynced, then the sidecar's directory is fsynced. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage` | — | STUB | +| `INV-WAL-V3-MAP-PERSIST-FAIL-001` | An error inside a v3 map persistence transaction yields no candidate and latches the store against later I/O; a preflight or Stat error latches nothing. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore` | — | STUB | +| `INV-WAL-V3-MAP-EXTENT-REUSE-001` | A v3 sidecar extent is reused only when no live root references it: neither slot's root, no in-flight candidate, and, until reopen, no candidate whose publication outcome is uncertain. | M1 (map preparation) | `core/storage/chunk_map_extents_v3.go` `slotsPublishedV3`, `abandonCandidateV3`, `liveSnapshotV3`, `registerRootV3`; `core/storage/chunk_map_publication_v3.go` `publishMapV3`, `openDescriptorMapV3` | `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot` (`core/storage/chunk_map_extents_v3_test.go`); `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies` | — | STUB | +| `INV-WAL-V3-MAP-TRUNCATE-001` | When the v3 sidecar exceeds four times its live bytes, its free tail is truncated to the end of the highest live page and no lower. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3StatsAfterReopen` (`core/storage/chunk_map_extents_v3_test.go`) | — | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor slot write after create's initial slot A goes through the one publisher, which writes the fallback slot with slotGen + 1 while holding `descMu`. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publish`, `descriptorPublisherV3.publishLockedCoreV3`; create: `core/storage/walstore_v3.go` `createWALStoreV3Configured` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3ConcurrentPublishersNeverRegress` (`core/storage/descriptor_v3_test.go`) | — | STUB | | `INV-WAL-V3-PUBLISH-LOCKORDER-001` | The v3 publisher holds `WALStore.mu` only to take its snapshot and releases it before any slot I/O; the slot write and its fsync run in the store's fsync leaf. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishWithMapV3`; `core/storage/walstore.go` `WALStore.syncFile` | `TestDescriptorV3LockOrderRecorder` (`core/storage/descriptor_v3_test.go`) | — | STUB | | `INV-WAL-V3-PUBLISH-MERGE-001` | A v3 publication rebases onto the authoritative descriptor: W and CheckpointLSN are max-merged, and a change of identity, geometry or (outside a reset) nonce, a retainedTail regression, or a map root change without a higher map generation is refused. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `mergeDescriptorV3`, `mergeDescriptorV3Mode` | `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress` (`core/storage/descriptor_v3_test.go`); `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`) | — | STUB | @@ -500,34 +500,34 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes the logical WAL interval [E, floor + WALSize), floor being the both-slot same-nonce reuse floor, fsyncs it through the leaf, and only then publishes retainedHead = E. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.fenceV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` `NoResurrection` | STUB | | `INV-WAL-V3-FENCE-EXACT-001` | The v3 drop fence changes only the bytes of [E, floor + WALSize) mapped modulo WALSize, in at most two ranges split at the physical wrap; no byte before E or outside the interval changes. | M1 Recovering → Serving (v3) | `core/storage/recovery_v3.go` `fenceRangesV3`; `core/storage/walstore_v3.go` `WALStore.fenceV3` | `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | — | STUB | | `INV-WAL-V3-NO-RESURRECTION-001` | A WAL record dropped by one v3 recovery is never replayed by a later recovery, also after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.fenceV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` `NoResurrection` | STUB | -| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused with `ErrResetNotPreserved`, writing nothing, unless the dirty map is empty and CheckpointLSN is at least every appended LSN (and so equals the acknowledged W). | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB | -| `INV-WAL-V3-RESET-TWO-SLOT-001` | A reset publishes a new nonzero nonce with an empty cursor space into one descriptor slot and then the other, and succeeds only after both publications. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `descriptorPublisherV3.resetIncarnationV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode` | `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3RefusesTheCurrentOrAZeroNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB | -| `INV-WAL-V3-RESET-HALF-001` | After a crash between a reset's two publications, open selects the new incarnation and binds no WAL writer, so every append is refused until Recover's head publication puts the new nonce in both slots. | M1 Serving → Serving (reset, dark) | `core/storage/walstore_v3.go` `openWALStoreV3File`, `WALStore.recoverV3`, `WALStore.appendWriteV3`; `core/storage/reset_v3.go` `descriptorPublisherV3.halfResetV3` | `TestResetV3CrashOutcomes` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB | -| `INV-WAL-V3-RESET-INVARIANT-001` | A reset leaves LSN allocation, W, CheckpointLSN and the map root unchanged. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `descriptorPublisherV3.resetIncarnationV3`, `WALStore.resetIncarnationV3` | `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash` (`core/storage/reset_store_v3_test.go`) | — | STUB | -| `INV-WAL-V3-READ-REVALIDATE-001` | A v3 read served from a dirty entry returns data only from a WAL record that validates whole (CRC, footer, type) and whose LBA and LSN match the resolving entry; on a mismatch it resolves again, so a reused WAL position never serves another block. | M1 Serving → Serving (reset, dark) | `core/storage/walstore_v3.go` `WALStore.readDirtyV3Into`, `WALStore.readRecordIntoV3` | `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock` (`core/storage/reset_store_v3_test.go`) | — | STUB | -| `INV-WAL-V3-READ-DAMAGE-001` | A v3 dirty read reports WAL damage only for a record that fails validation while the resolving entry and the recovery generation are the same before and after the attempt; a failed pread is reported as substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/walstore_v3.go` `WALStore.readDirtyV3Into` | `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | — | STUB | -| `INV-WAL-V3-RECOVER-GEN-001` | The v3 recovery generation is incremented at the start and at the end of every recovery and every reset. | M1 Serving → Serving (reset, dark) | `core/storage/walstore_v3.go` `WALStore.recoverV3`; `core/storage/reset_v3.go` `WALStore.resetIncarnationV3` | `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`); `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`) | — | STUB | -| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only if BaseLSN is at least the acknowledged W (published or not yet), the CheckpointLSN and every appended LSN; otherwise the begin writes nothing and returns `ErrInstallBaseUncovered`, or `ErrInstallSupersedeUncovered` when it supersedes. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3` | `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | -| `INV-WAL-V3-BASE-BEGIN-SLOTS-001` | Before the first BASE mutation of an install, both descriptor slots durably hold installing with its BaseLSN, BaseCursor = the writer head P at begin, and the new install ID. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publish` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots` (`core/storage/base_install_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | -| `INV-WAL-V3-BASE-DRAIN-001` | A BASE write or install-lane apply admitted through an install handle finishes before a later begin proceeds, and after that begin every handle of the earlier install epoch is refused with `ErrInstallSuperseded`. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.admitV3`, `installHandleV3.admissibleV3` | `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession` (`core/storage/base_install_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB | -| `INV-WAL-V3-BASE-HANDLE-001` | On a v3 store, BASE extent writes and install-lane applies go only through an install handle: `WriteExtentDirect` is refused, an ordinary replicated apply is refused while installing, and `WriteBase` needs installing under the handle's ID. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `installHandleV3.WriteBase`, `installHandleV3.admissibleV3`, `WALStore.applyEntryV3`; `core/storage/walstore.go` `WALStore.WriteExtentDirect` | `TestNativeReplacementDirectExtentRefusedPreservesWAL` (`core/storage/legacy_replacement_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB | -| `INV-WAL-V3-BASE-LANE-AFTER-DONE-001` | An install-lane apply through a handle is admitted while the volume is installing under its ID or, once that handle's own complete succeeded, while installed under its ID or retired, until the next begin; otherwise it returns `ErrInstallSuperseded`. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `installHandleV3.admissibleV3`, `installHandleV3.ApplyInstallEntry`, `installHandleV3.MarkBaseComplete` | `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin` (`core/storage/base_install_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB | -| `INV-WAL-V3-BASE-LANE-ORDER-001` | A v3 install-lane apply at or below the highest appended LSN is a no-op if its LBA already holds a higher LSN and fails with `ErrWALLSNOrder` otherwise; one above max(CheckpointLSN, BaseLSN, highest appended) + 1 fails with `ErrInstallLSNGap`. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.applyEntryV3` | `TestBaseInstallV3ApplyInstallEntryOrderAndGap` (`core/storage/base_install_v3_test.go`) | — | STUB | -| `INV-WAL-V3-BASE-COMPLETE-001` | Installed is published only by a complete for the current installing ID, and only after one fsync of the store file covering the BASE extent bytes and the install-lane suffix, followed by the metadata and chunk checkpoint barriers. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`); `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling` (`core/storage/chunk_base_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | -| `INV-WAL-V3-BASE-COMPLETE-MAP-001` | The installed publication sets retainedTail to at least BaseCursor and carries a fresh owned-map candidate in which every chunk a BASE write of the install touched is UNKNOWN. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3`, `installHandleV3.WriteBase`, `WALStore.markMapUnknownV3` | `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`) | — | STUB | -| `INV-WAL-V3-BASE-SUPERSEDED-001` | After a successful complete, the open store neither serves nor flushes a WAL record appended before the begin, and recovery from an installed descriptor scans no record behind BaseCursor. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`); `TestWALIOV3_InstalledScanBeginsAtMaxTail` (`core/storage/wal_io_v3_test.go`) | — | STUB | -| `INV-WAL-V3-BASE-RETIRE-001` | A v3 descriptor goes from installed to none only when CheckpointLSN ≥ BaseLSN and both the newly written slot and the slot it leaves as fallback carry retainedTail ≥ BaseCursor; installing never goes to none. | M1 Serving → Installing → Serving (dark) | `core/storage/descriptor_v3.go` `retireBaseV3`, `baseTransitionAllowedV3` | `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3InstallingToNoneIsRefused` (`core/storage/base_install_v3_test.go`); `TestDescriptorV3BaseTransitionTable` (`core/storage/descriptor_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | -| `INV-WAL-V3-BASE-RETIRE-GATE-001` | On a store whose provider deferred BASE retirement at open, retirement of an installed BASE waits for this open's attach commit. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.DeferBaseRetirementV3`, `WALStore.CommitChunkAttachV3`, `WALStore.AllowBaseRetirementV3`; `core/storage/chunk_base_v3.go` `chunkLayerImpl.holdBaseTransitionV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3`; `core/frontend/durable/provider.go` `openOrCreate` | `TestBaseInstallV3CommitChunkAttach`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` (`core/frontend/durable/provider_format_v3_base_test.go`) | — | 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; this is checked again at its completion. | M1 Installing (dark) | `core/storage/walstore.go` `WALStore.Sync`, `WALStore.syncWithPhases` | `TestInstallLogV3SyncIsGatedWhileInstalling` (`core/storage/install_log_v3_test.go`) | `WALFormat` install-log ack | STUB | -| `INV-WAL-V3-INSTALL-LOG-ACK-001` | `SyncInstallLog(id)` returns H, the highest LSN appended when it starts, only after a WAL fsync and then a descriptor publication of W = max(W, H) with BaseState still installing: always mode A. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog` | `TestInstallLogV3IsModeAAndSurvivesACrash` (`core/storage/install_log_v3_test.go`) | `WALFormat` install-log ack | STUB | -| `INV-WAL-V3-INSTALL-LOG-REFUSE-001` | Under `installMu` shared, `SyncInstallLog` is refused with `ErrNotInstalling` outside an install and with `ErrInstallIDMismatch` for another install ID. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`, `installLogTargetV3` | `TestInstallLogV3Refusals` (`core/storage/install_log_v3_test.go`) | — | STUB | -| `INV-WAL-V3-INSTALL-LOG-FAULT-001` | `SyncInstallLog` acknowledges nothing when a store fault has latched by its final check under `WALStore.mu`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog` | `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`) | — | STUB | -| `INV-WAL-V3-INSTALL-LOG-SCOPE-001` | `SyncInstallLog` is on the narrow `InstallLogSyncer`, not on `LogicalStorage`, and no package other than `core/storage` and `core/recovery` names `InstallLogSyncer`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `InstallLogSyncer` | `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`) | — | STUB | -| `INV-WAL-V3-INSTALL-LOG-RECEIVER-001` | The rebuild receiver's durable progress ack is `SyncInstallLog(installID)` until its own session's completion, and the ordinary `Sync` after it. | M1 Installing (dark) | `core/recovery/receiver.go` `Receiver.sendAck` | tagged `swblock_format_v3_test`: `TestReceiverV3ProgressAckIsTheInstallLog` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB | -| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n > 1 blocks is one record (type 0x04) with LSNs first..first+n-1 under one CRC32C, so a crash keeps all n blocks or none. | M1 Serving (dark) | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`; `core/storage/walstore.go` `WALStore.WriteBatch` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records | STUB | -| `INV-WAL-V3-BATCH-READERS-001` | Each v3 batch block's dirty entry names its data offset in the record, and every reader (store read, flusher, recovery replay, install-path replays, offline reader) uses the block only from a whole valid record whose block has that LBA, LSN and offset. | M1 Serving (dark) | `core/storage/walstore_v3.go` `WALStore.readRecordIntoV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`, `WALStore.replayRecordV3`; `core/storage/walstore_readonly_v3.go` `WALStoreReader.readV3` | `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRoundTripAcrossACrash` (`core/storage/walstore_batch_v3_test.go`) | — | STUB | -| `INV-WAL-V3-BATCH-ACK-001` | A Sync that covers a v3 batch returns a frontier of at least the batch's last LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`, `WALStore.advanceAfterAppendV3` | `TestWALStoreV3BatchAckCoversItsLastLSN` (`core/storage/walstore_batch_v3_test.go`) | — | STUB | -| `INV-WAL-V3-BATCH-MAP-001` | The owned map records every block of a v3 batch at its own LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`; `core/storage/walstore_map_checkpoint_v3.go` `WALStore.recordMapWriteV3` | `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | — | STUB | +| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused with `ErrResetNotPreserved`, writing nothing, unless the dirty map is empty and CheckpointLSN is at least every appended LSN (and so equals the acknowledged W). | M1 Serving → Serving (reset: no production caller; tests only) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB | +| `INV-WAL-V3-RESET-TWO-SLOT-001` | A reset publishes a new nonzero nonce with an empty cursor space into one descriptor slot and then the other, and succeeds only after both publications. | M1 Serving → Serving (reset: no production caller; tests only) | `core/storage/reset_v3.go` `descriptorPublisherV3.resetIncarnationV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode` | `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3RefusesTheCurrentOrAZeroNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB | +| `INV-WAL-V3-RESET-HALF-001` | After a crash between a reset's two publications, open selects the new incarnation and binds no WAL writer, so every append is refused until Recover's head publication puts the new nonce in both slots. | M1 Serving → Serving (reset: no production caller; tests only) | `core/storage/walstore_v3.go` `openWALStoreV3File`, `WALStore.recoverV3`, `WALStore.appendWriteV3`; `core/storage/reset_v3.go` `descriptorPublisherV3.halfResetV3` | `TestResetV3CrashOutcomes` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB | +| `INV-WAL-V3-RESET-INVARIANT-001` | A reset leaves LSN allocation, W, CheckpointLSN and the map root unchanged. | M1 Serving → Serving (reset: no production caller; tests only) | `core/storage/reset_v3.go` `descriptorPublisherV3.resetIncarnationV3`, `WALStore.resetIncarnationV3` | `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash` (`core/storage/reset_store_v3_test.go`) | — | STUB | +| `INV-WAL-V3-READ-REVALIDATE-001` | A v3 read served from a dirty entry returns data only from a WAL record that validates whole (CRC, footer, type) and whose LBA and LSN match the resolving entry; on a mismatch it resolves again, so a reused WAL position never serves another block. | M1 Serving → Serving (reads; the reset has no production caller) | `core/storage/walstore_v3.go` `WALStore.readDirtyV3Into`, `WALStore.readRecordIntoV3` | `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock` (`core/storage/reset_store_v3_test.go`) | — | STUB | +| `INV-WAL-V3-READ-DAMAGE-001` | A v3 dirty read reports WAL damage only for a record that fails validation while the resolving entry and the recovery generation are the same before and after the attempt; a failed pread is reported as substrate I/O. | M1 Serving → Serving (reads; the reset has no production caller) | `core/storage/walstore_v3.go` `WALStore.readDirtyV3Into` | `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | — | STUB | +| `INV-WAL-V3-RECOVER-GEN-001` | The v3 recovery generation is incremented at the start and at the end of every recovery and every reset. | M1 Serving → Serving (recovery; the reset has no production caller) | `core/storage/walstore_v3.go` `WALStore.recoverV3`; `core/storage/reset_v3.go` `WALStore.resetIncarnationV3` | `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`); `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only if BaseLSN is at least the acknowledged W (published or not yet), the CheckpointLSN and every appended LSN; otherwise the begin writes nothing and returns `ErrInstallBaseUncovered`, or `ErrInstallSupersedeUncovered` when it supersedes. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3` | `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | +| `INV-WAL-V3-BASE-BEGIN-SLOTS-001` | Before the first BASE mutation of an install, both descriptor slots durably hold installing with its BaseLSN, BaseCursor = the writer head P at begin, and the new install ID. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publish` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots` (`core/storage/base_install_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | +| `INV-WAL-V3-BASE-DRAIN-001` | A BASE write or install-lane apply admitted through an install handle finishes before a later begin proceeds, and after that begin every handle of the earlier install epoch is refused with `ErrInstallSuperseded`. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.admitV3`, `installHandleV3.admissibleV3` | `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession` (`core/storage/base_install_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BASE-HANDLE-001` | On a v3 store, BASE extent writes and install-lane applies go only through an install handle: `WriteExtentDirect` is refused, an ordinary replicated apply is refused while installing, and `WriteBase` needs installing under the handle's ID. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `installHandleV3.WriteBase`, `installHandleV3.admissibleV3`, `WALStore.applyEntryV3`; `core/storage/walstore.go` `WALStore.WriteExtentDirect` | `TestNativeReplacementDirectExtentRefusedPreservesWAL` (`core/storage/legacy_replacement_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BASE-LANE-AFTER-DONE-001` | An install-lane apply through a handle is admitted while the volume is installing under its ID or, once that handle's own complete succeeded, while installed under its ID or retired, until the next begin; otherwise it returns `ErrInstallSuperseded`. | M1 Serving → Installing → Serving (install lane only with `--recovery-mode=dual-lane`) | `core/storage/base_install_v3.go` `installHandleV3.admissibleV3`, `installHandleV3.ApplyInstallEntry`, `installHandleV3.MarkBaseComplete` | `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin` (`core/storage/base_install_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BASE-LANE-ORDER-001` | A v3 install-lane apply at or below the highest appended LSN is a no-op if its LBA already holds a higher LSN and fails with `ErrWALLSNOrder` otherwise; one above max(CheckpointLSN, BaseLSN, highest appended) + 1 fails with `ErrInstallLSNGap`. | M1 Serving → Installing → Serving (install lane only with `--recovery-mode=dual-lane`) | `core/storage/base_install_v3.go` `WALStore.applyEntryV3` | `TestBaseInstallV3ApplyInstallEntryOrderAndGap` (`core/storage/base_install_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BASE-COMPLETE-001` | Installed is published only by a complete for the current installing ID, and only after one fsync of the store file covering the BASE extent bytes and the install-lane suffix, followed by the metadata and chunk checkpoint barriers. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`); `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling` (`core/storage/chunk_base_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | +| `INV-WAL-V3-BASE-COMPLETE-MAP-001` | The installed publication sets retainedTail to at least BaseCursor and carries a fresh owned-map candidate in which every chunk a BASE write of the install touched is UNKNOWN. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3`, `installHandleV3.WriteBase`, `WALStore.markMapUnknownV3` | `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BASE-SUPERSEDED-001` | After a successful complete, the open store neither serves nor flushes a WAL record appended before the begin, and recovery from an installed descriptor scans no record behind BaseCursor. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`); `TestWALIOV3_InstalledScanBeginsAtMaxTail` (`core/storage/wal_io_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BASE-RETIRE-001` | A v3 descriptor goes from installed to none only when CheckpointLSN ≥ BaseLSN and both the newly written slot and the slot it leaves as fallback carry retainedTail ≥ BaseCursor; installing never goes to none. | M1 Serving → Installing → Serving | `core/storage/descriptor_v3.go` `retireBaseV3`, `baseTransitionAllowedV3` | `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3InstallingToNoneIsRefused` (`core/storage/base_install_v3_test.go`); `TestDescriptorV3BaseTransitionTable` (`core/storage/descriptor_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB | +| `INV-WAL-V3-BASE-RETIRE-GATE-001` | On a store whose provider deferred BASE retirement at open, retirement of an installed BASE waits for this open's attach commit. | M1 Serving → Installing → Serving (deferral only with `--durable-impl=walstore-chunk`) | `core/storage/base_install_v3.go` `WALStore.DeferBaseRetirementV3`, `WALStore.CommitChunkAttachV3`, `WALStore.AllowBaseRetirementV3`; `core/storage/chunk_base_v3.go` `chunkLayerImpl.holdBaseTransitionV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3`; `core/frontend/durable/provider.go` `openOrCreate` | `TestBaseInstallV3CommitChunkAttach`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` (`core/frontend/durable/provider_format_v3_base_test.go`) | — | 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; this is checked again at its completion. | M1 Installing | `core/storage/walstore.go` `WALStore.Sync`, `WALStore.syncWithPhases` | `TestInstallLogV3SyncIsGatedWhileInstalling` (`core/storage/install_log_v3_test.go`) | `WALFormat` install-log ack | STUB | +| `INV-WAL-V3-INSTALL-LOG-ACK-001` | `SyncInstallLog(id)` returns H, the highest LSN appended when it starts, only after a WAL fsync and then a descriptor publication of W = max(W, H) with BaseState still installing: always mode A. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog` | `TestInstallLogV3IsModeAAndSurvivesACrash` (`core/storage/install_log_v3_test.go`) | `WALFormat` install-log ack | STUB | +| `INV-WAL-V3-INSTALL-LOG-REFUSE-001` | Under `installMu` shared, `SyncInstallLog` is refused with `ErrNotInstalling` outside an install and with `ErrInstallIDMismatch` for another install ID. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`, `installLogTargetV3` | `TestInstallLogV3Refusals` (`core/storage/install_log_v3_test.go`) | — | STUB | +| `INV-WAL-V3-INSTALL-LOG-FAULT-001` | `SyncInstallLog` acknowledges nothing when a store fault has latched by its final check under `WALStore.mu`. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog` | `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`) | — | STUB | +| `INV-WAL-V3-INSTALL-LOG-SCOPE-001` | `SyncInstallLog` is on the narrow `InstallLogSyncer`, not on `LogicalStorage`, and no package other than `core/storage` and `core/recovery` names `InstallLogSyncer`. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/storage/install_log_v3.go` `InstallLogSyncer` | `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`) | — | STUB | +| `INV-WAL-V3-INSTALL-LOG-RECEIVER-001` | The rebuild receiver's durable progress ack is `SyncInstallLog(installID)` until its own session's completion, and the ordinary `Sync` after it. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/recovery/receiver.go` `Receiver.sendAck` | tagged `swblock_format_v3_test`: `TestReceiverV3ProgressAckIsTheInstallLog` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n > 1 blocks is one record (type 0x04) with LSNs first..first+n-1 under one CRC32C, so a crash keeps all n blocks or none. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`; `core/storage/walstore.go` `WALStore.WriteBatch` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records | STUB | +| `INV-WAL-V3-BATCH-READERS-001` | Each v3 batch block's dirty entry names its data offset in the record, and every reader (store read, flusher, recovery replay, install-path replays, offline reader) uses the block only from a whole valid record whose block has that LBA, LSN and offset. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.readRecordIntoV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`, `WALStore.replayRecordV3`; `core/storage/walstore_readonly_v3.go` `WALStoreReader.readV3` | `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRoundTripAcrossACrash` (`core/storage/walstore_batch_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BATCH-ACK-001` | A Sync that covers a v3 batch returns a frontier of at least the batch's last LSN. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`, `WALStore.advanceAfterAppendV3` | `TestWALStoreV3BatchAckCoversItsLastLSN` (`core/storage/walstore_batch_v3_test.go`) | — | STUB | +| `INV-WAL-V3-BATCH-MAP-001` | The owned map records every block of a v3 batch at its own LSN. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`; `core/storage/walstore_map_checkpoint_v3.go` `WALStore.recordMapWriteV3` | `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | — | STUB | | `INV-WAL-V3-MIGRATE-001` | ARCHIVED: the in-place v2 converter is removed. Public opens refuse v2 bytes without mutation; no upgrade path is provided. | M1 open refusal | `core/storage/walstore_v3.go` `openWALStoreV3WithOptions` | `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | none (retired tool) | ARCHIVED | | `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA` (expiry and joined physical-fault wire status); `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | | `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | @@ -540,18 +540,18 @@ 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 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 now creates and opens mapped v3 too (`INV-WAL-V3-ACTIVATION-001`), 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 create and open select mapped v3 (`INV-WAL-V3-ACTIVATION-001`); the BASE caller and readonly/status controls have dedicated rows below. 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. Production create and open run this bind (`openWALStoreV3File`); capture does not. 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 map-requiring actual-store opener (production open) 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 actual chunk capture (production with `--durable-impl=walstore-chunk`) 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 chunk transition drain (no production caller: a BASE install comes only from replication, which `walstore-chunk` refuses) 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 now creates and opens mapped v3 too (`INV-WAL-V3-ACTIVATION-001`), 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 create and open select mapped v3 (`INV-WAL-V3-ACTIVATION-001`); the BASE caller and readonly/status controls have dedicated rows below. WAL tail reclamation is wired (`INV-WAL-V3-RECLAIM-001` family). Existing 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`). A v3 begin with an attached chunk layer that has no BASE transition hook is refused (`errV3NotYet`), writing nothing (`TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`; a supported layer is drained as in `INV-WAL-V3-CHUNK-BASE-001`); 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; the provider's former refusal of a HEAD restore onto a v3 store is gone since row 12a (see the `INV-WAL-V3-MAP-PUBLISH-001` note); since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from; it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). +- `INV-WAL-V3-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. 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). Production reaches it through both callers below: the legacy single-lane caller by default, the dual-lane `Receiver` with `--recovery-mode=dual-lane`. 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`). A v3 begin with an attached chunk layer that has no BASE transition hook is refused (`errV3NotYet`), writing nothing (`TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`; a supported layer is drained as in `INV-WAL-V3-CHUNK-BASE-001`); 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; the provider's former refusal of a HEAD restore onto a v3 store is gone since row 12a (see the `INV-WAL-V3-MAP-PUBLISH-001` note); since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from; it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). - `INV-WAL-V3-MIGRATE-001`: Archived with the converter and its legacy fixtures; v2 inputs refuse open without mutation. -- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model, 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`). +- `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. Since activation (row 12b) production create and open (`CreateWALStoreWithOptions`, `OpenWALStoreWithOptions`) reach it. Without the row-7 map candidate (unmapped test fixtures only) the v3 checkpoint and tail do not advance. They are still STUBs although the path is active; their promotion is pending a per-row check of their tests. The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model, not by these tests. Installing recovery is row 11. +- `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). The v3 store is wired in (rows 4 and 5) and activated (row 12b); the row is still a STUB although the path is active, its promotion pending a per-row check of its tests. The v2 checkpoint path (`persistCheckpointReleasing`) is retired. 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). Since the activation commit (plan row 12b) production walstore open and create reach the v3 codec; the row is still a STUB although the path is active, its promotion pending a per-row check of its tests. 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`). - `INV-WAL-V3-ACTIVATION-001` family: writable and read-only open validate the owned-map dependencies of the selected slot and of every valid fallback slot before the store or reader is returned, and refuse a valid legacy superblock with `ErrUnsupportedLegacyFormat` without changing a byte: see M1 — → Opened (tests `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies` with its fallback-page case, `TestNativeReplacementLegacyBytesRefusedWithoutMutation`). A zero chunk geometry option becomes 1024 blocks per chunk, so every public create is mapped; create persists an all-UNKNOWN initial map before its first slot. - `INV-WAL-V3-DESCRIPTOR-CONFLICT-001`: the old statement said the two slots must not disagree on identity; of the identity fields, open compares the UUID, together with the geometry. The next publication's slotGen comes from `nextSlotGenV3` (`INV-WAL-V3-PUBLISH-COUNTER-001`). `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` is a store-level control of the selection: a v3 `Close` writes no slot, and reopen selects the newest one. - `INV-WAL-V3-RECORD-001`: codec success alone is not nonce, cursor or lap replay admission; that belongs to the scanner (`INV-WAL-V3-SCAN-BINDING-001`). @@ -707,7 +707,7 @@ Notes: | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED | -| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | | `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_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. 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` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE | | `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE | @@ -739,7 +739,7 @@ Notes: | `INV-CUT-INTENT-CLOSE-001` | Close deletes the intents of reusable uploads and leftover intents, but never an intent of a proposal whose CAS outcome is still unresolved. | M5 Close | `core/storage/chunk_layer.go` `Close`, `captureLocked`, `dropIntents` | `TestChunkCloseDropsReusableButKeepsUnknownCASRoots` (`core/storage/chunk_review271_test.go`); `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`, `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`, `TestHeadBeltEmptyBaseForeignPublicationFences` (`core/storage/chunk_head_belt_test.go`) | — | 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`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE | -| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | +| `INV-CUT-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) | — | ACTIVE | | `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestCutPolicy_TimerRunsOnObservationTime`, `TestCutPolicy_StaggerPreservesExplicitTimerReset` (`core/frontend/durable/cut_policy_test.go`) | — | ACTIVE | | `INV-CUT-TIMER-SKIP-001` | A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince`; `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestChunkPeriodicCut_SkipsAfterANewerCut`, `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`); `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | | `INV-CUT-TIMER-SLOT-WAIT-001` | A periodic cut refused because every host cut slot is held is a wait, not a failure: no backoff or minimum spacing; it retries after a random delay under 200 ms that shrinks with lateness, and status reports the wait until any later cut succeeds. Other errors keep the backoff. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `cutPolicy.after`, `chunkLoop`; `core/hostlimit/limiter.go` `ErrSlotsHeld` | `TestCutPolicy_HostSlotBusyIsAWaitNotAFailure`, `TestCutPolicy_SuccessDuringSlotWaitDropsTheSlotRetry`, `TestCutWaitSlot_StatusEndsTheWaitAfterALaterCut`, `TestNewSlotDelay_ShrinksWithLateness`, `TestCutPolicy_OneSlotWaitBound` (`core/frontend/durable/cut_policy_test.go`); `TestTimerCutRunsSoonAfterHostSlotFrees`, `TestSlotWaitEndsWithASuccessfulDetachSeal` (`core/frontend/durable/host_slot_wait_test.go`); `TestAdmitClosedDuringPoolAcquisitionIsRevoked` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | @@ -749,7 +749,7 @@ A guest read has a cooperative arrival budget; internal contextless readers keep Notes: - `INV-CUT-TIMER-RESTART-001`, `INV-CUT-TIMER-SKIP-001`: cuts are identified and ordered by the layer's in-process `CutSeq`, never by the `LastCutNs` wall stamp: a `CutSeq` not seen before is a success at the moment it is observed, and a periodic decision is skipped once `CutSeq` has moved; at start the existing value is not new, so a restart keeps the startup phase. The scheduled-snapshot worker (`INV-SNAP-SCHEDULED-KEEP-001`) runs on the same monotonic time: slots are the loop start plus the volume's offset plus whole periods; a re-armed loop on the same handle keeps its schedule (failures, retry time); a restart starts a fresh one. Tests: `TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime`, `_RearmKeepsTheSchedule`, `_OverdueWithNoSuccess`, `TestSnapshotSchedule_SlotsAreOffsetPerVolume`. -- Not reachable in this release: `INV-WS-FREEZE-ACCOUNTING-001` and `INV-CUT-PRECOPY-001`. `/chunk/detach` refuses `frozen` (`INV-CUT-FROZEN-DETACH-REFUSED-001`) and blockvolume refuses `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`), so neither the frozen admission nor the pre-copy admission runs in a released process. Their code is kept and their tests below the HTTP handler still assert them, so their status stays ACTIVE. For the same reason the pre-copy policy that `INV-CUT-PLAIN-DETACH-001` keeps for an absent or false `plain` field is always off. `INV-WS-FREEZE-REFUSAL-001` stays reachable: its HTTP400 validation runs before the refusal. So do `INV-WS-FREEZE-REFUSAL-INPUTS-001` and `INV-WS-FREEZE-REFUSAL-PRECEDENCE-001`. +- Not reachable in this release: `INV-WS-FREEZE-ACCOUNTING-001` (except its estimate and quiesce-slack report, which every successful cut returns) and `INV-CUT-PRECOPY-001`. `/chunk/detach` refuses `frozen` (`INV-CUT-FROZEN-DETACH-REFUSED-001`) and blockvolume refuses `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`), so neither the frozen admission nor the pre-copy admission runs in a released process. Their code is kept and their tests below the HTTP handler still assert them, so their status stays ACTIVE. For the same reason the pre-copy policy that `INV-CUT-PLAIN-DETACH-001` keeps for an absent or false `plain` field is always off. `INV-WS-FREEZE-REFUSAL-001` stays reachable: its HTTP400 validation runs before the refusal. So do `INV-WS-FREEZE-REFUSAL-INPUTS-001` and `INV-WS-FREEZE-REFUSAL-PRECEDENCE-001`. - `INV-WS-FREEZE-REFUSAL-001`: a generic `bad_request` is not proof of a clean refusal. The validation also refuses a non-frozen request that carries a freeze origin (`handleChunkDetach`). `INV-WS-FREEZE-REFUSAL-INPUTS-001` compares the caller's Unix-nanosecond origin with blockvolume's `time.Now`, with no skew bound. - `INV-HOST-CUT-BUDGET-001`: an unavailable pool skips normal, fill and idle work with an alarm: see M7 (test `TestUnusablePoolClassPolicy`). Coordinated reservations do not account retained crash spill, fallback leases or process RSS (`HostBudget` excludes fallback). Guest I/O and WAL reclamation never take a slot (M7). Hold expiry (`MaxHold`, `INV-HOST-CUT-BUDGET-SETTLE-001`) and upload pacing (`INV-HOST-CUT-BUDGET-PACING-001`) run on the process's local clock. - Enforced by reading (no test asserts it): the refusal of a non-frozen request that carries a freeze origin; and an explicit zero freeze origin, which the test sends only as a missing origin (both decode to zero). @@ -924,16 +924,16 @@ One row per wait in the data and control paths. Guest-visible rows on one path m |---|---|---|---|---|---|---| | `core/storage/chunk_publish_settled.go` `runPublishSettled` (from `unlockCap`, on the cut or detach caller's goroutine) | the `OnPublishSettled` hook to return | the hook's duration: the hook must return without blocking and without remote calls, enqueueing its work to its own worker | the hook implementer | none: a stalled hook stalls its caller, and later reports queue without a bound (a nil hook queues nothing) | none (`capMu` and `stMu` released) | yes on detach (the detach caller delivers before returning) | -Format v3 row 4 remains dark. Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The later W/BASE/fence owner must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. +Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The W/BASE/fence owner (`WALStore.recoverV3`) 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) +### 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. +- `INV-WAL-V3-READONLY-001` (ACTIVE; the public selector `OpenReadOnly` opens this reader): the 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. Its production caller is `cmd/m01verify`. - 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) +### 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. +- `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for mapped v3; no production caller of begin/complete with a layer attached: a layer attaches only with `--durable-impl=walstore-chunk`, which refuses replica roles): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu. - The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission. - Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Both installed local presence and the provider durable attach point are required before retirement. The provider removes its fresh marker and fsyncs its directory under the store installMu-exclusive commit, then records per-open owner readiness; the callback never re-enters the store. Layer attach alone never allows retirement. Later completed transitions require owner readiness plus saved full presence before allowing; the next ordinary publication still checks existing retirement coverage. The provider keeps the constructed layer private as chunkPending until this commit succeeds; explicit publication cannot resolve it and the scheduler starts only after commit. Failed commits retain the private layer for retry without reattaching. Held pre-marker controls require Capture/Cut/MakeRemoteDurable to return ErrNotChunkVolume with no new remote writes, intents or HEAD changes, then crash/reopen exact local bytes. Actual subprocess controls crash after presence but before marker removal (both pre-existing installed BASE and attached completion), retaining the installed discriminator and recovering exact local data. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam.