- The provider refuses the removed names and, under every selector and
before any selector comparison, a volume carrying their magic (SWAW;
SWPW in either header slot), reading the file read-only and never
modifying it. blockvolume --durable-impl and the launcher refuse the
names with the same advice; the chart schema allows walstore only.
- core/storage/smartwal, core/storage/parallelwal and
cmd/sw-block-testutil (whose one command corrupted smartwal records)
are deleted, with the helm smartwal-corruption scenario and the
parallel-walstore gate script.
- The replication harness runs on walstore; tests that ran on a removed
engine only because a stub needed some store move to walstore, and the
state_convergence label test moves to the in-memory BlockStore.
- sw-block cluster.check drops the removed engines' cases.
- Ledger: INV-OPEN-REMOVED-ENGINE-REFUSED-001 and
INV-OPEN-REMOVED-ENGINE-NAME-REFUSED-001, an OpenRefused edge in M1, and
the rows citing the removed tests updated. Docs: block-design 1.3 now
describes the removal, the smartwal deep-dive and figure are gone, the
scripts default to walstore, and the v1.1 notes carry the removal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Live-ship and recovery session ids came from two process-wide counters;
once the live counter ran ahead, the replica refused every recovery as
older. Each replica now has one order, kept by the volume across its
peers and executors, and every session toward it takes the next id.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The recovery begins with BeginEpochRecovery, so the primary's live
session stays admissible and only the invalid epoch table can refuse its
frames; a recovery begun and ended is the control. The test is its own
package so its sessions do not reorder another test's.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
While a recovery owns a replica's store its epoch table is invalid and its
end may sit above a gap. Such a replica is never a fencing round's target,
also with the highest end, and never completes a sync_all or sync_quorum
write.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Priming and the adapter lookup were keyed by ReplicaID. A dispatch the loop
admitted for an old degraded peer, delayed while a lineage bump replaced the
peer under the same ReplicaID, then primed the new healthy peer's adapter,
whose probe raced the volume's live session again. The registry now keeps
the exact peer each adapter was added for; PrimePendingFor and
AdapterForPeer compare it under the registry lock, and a mismatch primes
nothing and sends no wire probe.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test waited for its registry adapter to probe the new peer right after
the add, which is the adapter acting on a healthy peer the volume's live
session owns. It now checks the adapter has issued nothing at the add and
wires the probe loop as the binary does (priming on the first dispatch for
a degraded peer); its degrade, recover and replay assertions are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The frontier-0 store barriers run in parallel after UpdateReplicaSet
releases v.mu. A replica refused for an unrecorded store stays Healthy with
its learned store, so the next attestation records it with no operator.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A peer counts toward write ACKs only while its barrier store equals the
store the master recorded for it from a primary's attestation, carried in
the replica descriptor; empty never matches, and the peer's own word never
changes it. A record change re-sends the assignment at the same
generation and the primary updates expected stores in place.
A volume's first bind records its initial replicas: until each has an
attested store the fact carries the awaited count, the primary serves no
frontend I/O and reports "creating: waiting for replica attestations
(n of N)"; the primary learns new peers' stores with a barrier at LSN 0.
Replica rows show store_attested/store_id.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An unacknowledged replica's ack does not complete a sync_quorum flush
(it does once its store is acknowledged). The first-heartbeat window's
defect is pinned by a skipped red test: a fresh primary with healthy
replicas must fail no flush before its first acknowledged heartbeat.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- .github/workflows/test.yml, job 'go test (linux)': on pull_request and on
push to main; Go from go.mod; go build ./..., go vet ./..., and
go test -short -count=1 -timeout 10m ./... with CGO_ENABLED=0. Actions are
pinned by commit SHA, permissions are contents: read, and a new push to a
PR cancels the older run.
- core/ops/surface_test.go: fix the two go vet warnings (resp used before
the error check), so vet covers the whole module.
- cmd/blockvolume: a withdrawn port no longer has to answer ECONNREFUSED.
A successful connect still fails; any other dial error passes only if the
address can be bound again.
- core/host/volume: probe tests dial a listener they opened and closed,
not the fixed 127.0.0.1:1.
- core/replication/component: on failure, the G5-5C and G9A catch-up tests
log frontiers, peer status and the engine trace. Assertions and timeouts
are unchanged.
Test files and the workflow only; no product code.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-up: the release was a t.Cleanup registered before Start, and
cleanups run LIFO, so the executor shutdown Start registers ran first; a
t.Fatal while the base frame was held would deadlock StopAndWait. A defer
inside the scenario runs before every t.Cleanup, including on t.Fatal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-up. The pre-barrier hold proved in-session delivery and
convergence but no longer the test's point: a newer WAL write for an LBA must
win over an OLDER base frame for that LBA that arrives later.
Drop the production SetPreBarrierHook seam (core/recovery is back to main)
and hold the base lane instead, through the existing WithPrimaryStorageWrap:
staleBaseHold captures the base read of LBA 5 (old value A) and holds it; the
test pushes the same-LBA overwrites (the session cannot seal its recovery cut
while base is held, so they ship in-session: this is also what fixes the
flake), waits until the replica holds B at LBA 5, then releases the stale A
frame. Convergence requires LBA 5 == B: RebuildSession.ApplyBaseBlock must
skip a base frame for an LBA the WAL lane already applied (bitmap).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TestPillar3Slice2_EngineDriven_SameLBAArbitration was flaky (on main baca5fd,
-race -count=40: 25/40 failures at -cpu 1, 6/40 at -cpu 2, 1/40 at -cpu 4).
Root cause is a timing assumption in the test, not a product race: with a
12-LBA backlog, base copy and DrainBacklog finish in microseconds and
Sender.Run seals the recovery cut (SealBeforeBarrier) before the test pushes
its same-LBA overwrites. PushLiveWrite then returns ErrSinkBarrierSealed,
the documented 'retain the WAL entry for replay' outcome that production
FeedLiveWrite maps to LiveWriteRetained, and the test treated it as fatal.
Once in a while the whole session also finished inside waitBridgeLiveReady's
1 ms poll gap.
Tolerating the error would defeat the test (the overwrites would never ship
in-session, so convergence could not be checked), and a larger backlog would
only shift the timing. Instead add a test-only hook,
PrimaryBridge.SetPreBarrierHook: each sender runs it after base + backlog
drain and before SealBeforeBarrier. The test installs it before the probe
that starts the rebuild, waits until the sender reaches it (session live,
cut not made), pushes the overwrites, releases, and asserts convergence.
With no hook installed the sender path is unchanged.
The now-unused waitBridgeLiveReady helper in this package is removed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A push between HasActiveSession and live-ready returns
ErrSessionNotLiveReady (2 of 200 runs on Linux). ship_sender treats
it, ErrSinkBarrierSealed, ErrSinkSealed and ErrNoActiveSession as
retained or handed back to the steady path; the test now accepts the
same set, and the replica byte check still pins arrival.
Refs #94
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TestDualLane_EngineDrivenRebuild_WithPushLiveDuringSession pushed its
live write straight into PrimaryBridge and failed on any error. Since
the dual-lane sink seals at the pre-barrier cut (8682e15), a push after
the cut returns ErrSinkBarrierSealed and the entry stays in the WAL for
replay; the production live-write path treats that as retained. A
12-entry rebuild usually reaches its cut before the push, and sometimes
closes before the test sees it live, so the test failed on most runs.
The test now accepts both: ErrSinkBarrierSealed from the push, or a
session that already closed (no push). The existing byte check that
the live LBA matches on the replica still pins that the write arrived.
Refs #94
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* storage: bound flusher snapshot to published LSN cut
* storage: make checkpoint snapshot atomic with write publication
* transport: close the replica connection when ApplyEntry fails (#89)
The production replica listener (no apply hook) only logged a failed
store.ApplyEntry and kept reading. Later entries on the same connection
were still applied, so the next barrier acked a frontier past the LSN
that was never applied. walstore's ApplyEntry can fail when its WAL is
full, and the primary only checks that AchievedLSN reaches the target,
so the gap went unnoticed.
A failed apply now ends the connection, as the apply-gate path already
does. Nothing after the failed LSN is applied on that connection, and
the primary sees the close, marks the peer degraded and recovers it
from the replica's real frontier.
The new test ships LSNs 1, 2 and 3 with LSN 2 failing and checks that
no barrier, on the same connection or a fresh one, acks LSN 2 or later.
It fails before this change (the barrier acks 3) and passes after.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test: prove the failed apply, the close and the primary's recovery (#89)
The replica test now waits for the injected ApplyEntry(2) failure, requires
the failed connection to end with EOF or a reset (a timeout fails), and
checks that LSN 3 never reaches the store.
A new component test runs the production primary path with the host's
PeerAdapterRegistry and probe loop: a transient replica apply failure
degrades the peer, recovery replays from the replica's frontier starting
exactly at the failed LSN with exact bytes, the peer returns to healthy,
and a later write and barrier succeed. Without the fix the peer is never
degraded and the failed block stays missing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Strip T4a/T4b/T4c/T4d, G3+/G5-5/G5-5A/G5-5C/G6/G7-redo, P14/P15, and
"architect round-NN" prose from godoc and in-body comments across the
core/ tree. Preserve stable invariant identifiers (INV-* names) since
they're searchable across the codebase.
Files: core/engine/apply.go, core/host/master/services.go,
core/replication/component/cluster.go, core/replication/probe_loop.go,
core/storage/walstore.go, core/storage/walstore_recovery.go,
core/transport/executor.go, core/transport/replica.go.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The component harness (cluster.go) constructed dual-lane executors
with rid="r-%d" while the engine driver in dual_lane_engine_test.go
sent AssignmentInfo / ProbeResult under "replica-%d". Pre-Phase-0-
Fix-#1 this silently diverged: bridge keyed coord.PinFloor under
"r-N", sink keyed WalShipper writeMu + post-emit RecordShipped under
"replica-N". The rebuild barrier completed despite the keying
mismatch (replica-driven BarrierResp), so the bug stayed invisible.
Now that startRebuildDualLane fail-closes on a mismatched non-empty
construction RID (commit 11392ba), this drift surfaces as a hard
error in TestDualLane_EngineDrivenRebuild_HappyPath / _WithPushLive
DuringSession. Aligning the harness to the engine driver's
"replica-%d" convention restores the invariant: construction RID ==
engine arg, coord/sink/bridge all keyed identically.
Test assertions that probed the stale "r-0" key (lines 110, 197, 251
region) updated to "replica-0".
Refs: INV-RID-UNIFIED-PER-SESSION (commit 11392ba);
v3-recovery-execution-institution.md Phase 0.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Architect review (offline against §6.8 / §IV / §V) flagged two
correctness gaps in C1+C2+C3:
1. NotifyAppend Realtime missing the §6.8 #9 sequence invariant
(lsn == cursor + 1). Without it, a caller that drops a
notification or races would silently emit out-of-order LSNs
leaving permanent gaps on replica (T4a no-replay carve-out
means no self-healing in Realtime).
2. drainOpportunity TOCTOU: mode/cursor read under shipMu, then
shipMu released before head.Head(). A concurrent NotifyAppend
(Backlog lag-only) could shift state between the unlock and
the head read.
Also two architect-derived doc tightenings:
3. DisableTimerDrain inline doc now states production MUST leave
false (§6.8 #4 forbids primary-idle starvation); test-only
invariant: shipper MUST NOT linger in cursor < head without
alternative drain source.
4. walShipperEntry.writeMu lock hierarchy doc: shipMu → writeMu,
never reverse.
Fixes:
- WalShipperConfig.StrictRealtimeOrdering (default false): tier
selector per architect's "production fail-close vs minimum log
+ monitor" guidance. Default mode logs WALSHIPPER-OUT-OF-ORDER
warning + emits anyway (preserves pre-guard test compatibility);
strict mode returns explicit error (production opt-in once
engine drives rebuild-on-gap).
- drainOpportunity now reads mode + cursor + head under one
shipMu hold (consistent snapshot), then releases for the heavy
ScanLBAs call. Eliminates the TOCTOU window.
Tests:
+ TestC1_Realtime_OutOfOrder_StrictFailsClosed — strict mode
rejects lsn != cursor+1 with explicit error. Banned regression
anchor: the old `if lsn > cursor + 1 ... drain` check (the
dense-edge counterexample architect flagged).
- Existing tests preserved by non-strict default mode. Engine-
driven dual-lane PushLiveWrite test + T4a6 reassign test now
log warning during the brief race window but emit + pass.
Existing test renamed:
- TestC1_WriteMu_NoInterleave → TestC1_WriteMu_FramesWellFormed
(concurrent-NotifyAppend was unrealistic; production callers
serialize per-replica via volume.mu; real concurrent-writer
coverage lives in TestDualLane_LiveWritesDuringSession_AtomicSeal).
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component}
— all PASS.
Production migration path (separate work):
- Engine wires StrictRealtimeOrdering=true once peer churn /
UpdateReplicaSet drives rebuild-on-gap (re-anchors WalShipper
cursor for the new endpoint).
- Fix replicaID consistency in startRebuildDualLane (engine
replicaID vs dl.ReplicaID — currently sink uses one, bridge
coord uses the other).
Closes architect priority 2.5 per docs/recovery-wiring-plan.md §6.
Pinned by INV-RECYCLE-GATED-BY-MIN-ACTIVE-PIN. Depends on wiring
(stack-on-wiring per architect Option A 2026-04-29).
Substrate gate (`core/storage`):
+ RecycleFloorSource interface — externally-supplied
`MinPinAcrossActiveSessions() (uint64, bool)`. Substrate stays
orthogonal to engine: structural typing means
`core/recovery.PeerShipCoordinator` satisfies it without import.
+ RecycleFloorGate optional interface — substrate impl that
accepts a source via `SetRecycleFloorSource`. Cmd / wiring
type-asserts on it; smartwal can opt in later.
walstore (`core/storage/walstore.go`):
+ recycleFloorSrc field, mu-guarded.
+ persistCheckpoint clamps proposed `highestLSN` to floor when
source reports active session. Existing no-regress guard
(`if highestLSN <= s.checkpointLSN`) handles transient
floor-below-checkpoint races.
+ SetRecycleFloorSource setter.
memorywal (`core/storage/memorywal/store.go`):
+ recycleFloorSrc field, mu-guarded.
+ AdvanceWALTail clamps proposed `newTail` to floor when source
reports active session. Same shape as walstore.
+ SetRecycleFloorSource setter.
Coordinator assertion (`core/recovery/peer_ship_coordinator.go`):
+ `var _ storage.RecycleFloorSource = (*PeerShipCoordinator)(nil)`
— compile-time pin so future signature drift breaks the build,
not the runtime gate.
Daemon wiring (`cmd/blockvolume/main.go`):
+ In dual-lane mode, install gate via `RecycleFloorGate` type
assertion. Skipped silently when substrate doesn't support it
(BlockStore today). Diagnostic stderr line for operators.
Component fixture (`core/replication/component/cluster.go`):
+ Cluster.Start installs the gate when dualLane is set, so
component-level dual-lane tests exercise the recycle path
against the same coordinator they install on executors.
Tests (12 new):
+ walstore_recycle_pin_test.go (6) — nil source / inactive /
active clamp / floor-above-proposed (no clamp) / no-regress
when floor < current checkpoint / disable via Set(nil).
+ memorywal/store_recycle_pin_test.go (6) — nil source / inactive
/ active clamp + scan-gate inequality / floor-above-proposed /
disable / RecycleFloorGate interface satisfaction.
Verified: `go test ./core/... ./cmd/... -count=1` all green
(transport, host, recovery, storage{,/memorywal,/smartwal},
replication{,/component}, blockvolume).
inv-test-map.md updated: row flips from "logic only; recycle
integration is next milestone" to "coord + walstore + memorywal
substrate integration" with the 12 new tests cited.
* docs: wiring plan for core/recovery → core/transport + cmd
Strategy doc for the next PR (g7-redo/wiring): how to land the
dual-lane recovery package alongside (NOT replacing) the existing
single-lane core/transport path per architect ruling.
Sections:
- Strategy: --recovery-mode flag (legacy / dual-lane); default
legacy until one milestone of dual-lane GREEN observed.
- Surface inventory: 6 files in core/transport, 1-2 in cmd, 0 in
core/recovery (it stays untouched).
- Lifecycle alignment: PeerShipCoordinator is the single source of
truth for "is replica P in a rebuild session" when dual-lane
active; legacy's BlockExecutor.activeSession is internal to the
legacy path. Mode is exclusive.
- Wire-format collision (frameSessionStart=0x01 vs MsgShipEntry=
0x01): three options analyzed; recommend separate ports per mode.
- Coordinator scope: per-volume, NOT per-replica (so MinPin sees
all replicas for a meaningful min).
- Priority 2.5 (WAL recycle consumes MinPin): new RecycleFloorSource
interface in core/storage; coordinator already implements it
exactly; recommend split into g7-redo/recycle-pin-hookup PR after
this one.
- Test plan: dual-lane integration tests + recycle-pin unit test.
Existing legacy tests unchanged.
- Rollback: default flip is one-line; legacy removal is a separate
later PR.
4 open questions for architect (wire collision option, 2.5 split,
default flip timing, legacy removal timing).
Out of scope: §3.2 #3 interleave, retry budget (parallel PR),
liveShipTargetLSNSentinel removal (waits for legacy removal).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* transport: dual-lane wiring (BlockExecutor + StartRebuild branch)
First wiring step per docs/recovery-wiring-plan.md §1-§3. Adds the
parallel-flag plumbing for routing StartRebuild through the
core/recovery package's PrimaryBridge while leaving the legacy
single-lane path completely untouched on the default constructor.
Architect ACK on §11 Resolution 1 (separate ports, Option A) drives
the design: dual-lane uses a separate listen address from the
legacy port; this commit only does the primary-side dial; replica's
listen loop is illustrated in dual_lane_test.go and will be hoisted
into cmd/blockvolume in a follow-up.
What lands:
core/transport/executor.go
+ DualLaneConfig struct (Bridge / DialAddr / ReplicaID).
+ dualLane *DualLaneConfig field on BlockExecutor.
+ NewBlockExecutorWithDualLane(primaryStore, replicaAddr,
dualLaneAddr, coord, replicaID) constructor.
+ Bridge captures executor's onStart/onClose via closures so
SetOnSession*Callback continues to work post-construction.
core/transport/rebuild_sender.go
+ StartRebuild branches on e.dualLane != nil.
+ startRebuildDualLane: dial dual-lane port, call
bridge.StartRebuildSession, immediately FinishLiveWrites
(legacy semantic — no live writes during rebuild). Logs the
same "executor: rebuild start" marker QA helpers scrape, with
"(dual-lane)" suffix for trace clarity.
core/transport/dual_lane_test.go
+ runDualLaneListener test helper (illustrates what cmd will do
in production: net.Listen + accept loop spawning
recovery.ReplicaBridge.Serve per conn).
+ TestDualLane_BlockExecutor_StartRebuild — full path:
OnSessionStart fires, OnSessionClose fires with achievedLSN ==
primaryH, replica's substrate matches primary byte-for-byte,
coordinator returns to PhaseIdle.
+ TestDualLane_LegacyConstructorIsNotDualLane — guard that
the existing NewBlockExecutor stays legacy (dualLane == nil).
Validation: 2 new tests pass; all existing core/transport tests
unchanged; full repo `go test ./...` green.
OUT OF SCOPE for this PR (per wiring plan §10):
- cmd/blockvolume flag wiring (next commit).
- WAL recycle path consuming MinPinAcrossActiveSessions
(architect priority 2.5 — separate g7-redo/recycle-pin-hookup
PR per §11 Resolution 2).
- Removing core/transport/replica.go::liveShipTargetLSNSentinel
lane shim (waits for legacy removal milestone).
- §3.2 #3 single-queue real-time interleave (architect priority #2).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* wiring: cmd flag + replication factory + listener (dual-lane reachable from binary)
Second wiring step per docs/recovery-wiring-plan.md. After this commit,
the daemon binary actually exposes the dual-lane recovery path: a flag
selects mode, the replication volume injects the right BlockExecutor
factory per peer, and a separate listener binds at port+1 for inbound
recover-session conns.
cmd/blockvolume/main.go
+ --recovery-mode=legacy|dual-lane flag (default legacy).
+ Validation: rejects unknown values at parse time.
+ In dual-lane mode, after constructing replVolume:
- new per-volume recovery.PeerShipCoordinator,
- SetDualLaneExecutorFactory wires per-peer
NewBlockExecutorWithDualLane closures,
- separate listener at deriveDualLaneAddr(data-addr) running
recovery.ReplicaBridge.AcceptDualLaneLoop in its own goroutine,
- graceful close via deferred cancel + ln.Close at daemon shutdown.
+ deriveDualLaneAddr helper: host:port → host:port+1 (deployment
convention, wiring plan §4 Option A).
cmd/blockvolume/dual_lane_addr_test.go
+ Pins the port+1 convention: IPv4, IPv6, port=0 boundary,
overflow at 65535, malformed inputs.
core/replication/volume.go
+ dualLaneExecutorFactory type (factory takes replicaID alongside
addr — the legacy 2-arg signature does not).
+ newDualExec field, nil-default = use legacy newExec.
+ UpdateReplicaSet branches on which factory is set per peer.
+ SetDualLaneExecutorFactory exported setter for cmd to inject the
per-volume coordinator-capturing closure. MUST be called before
UpdateReplicaSet (existing peers do not retroactively re-construct).
core/recovery/integration_stub.go
+ Hoist AcceptDualLaneLoop helper from the test file to a public
method on ReplicaBridge. Production cmd uses this directly;
test wrapper now just calls it.
core/transport/dual_lane_test.go
+ Refactor runDualLaneListener to use the new public helper instead
of an inline accept loop. Lifecycle simplified (ctx cancel + ln
close → loop returns).
Validation: cmd/blockvolume tests + full repo go test ./... PASS.
Default --recovery-mode=legacy keeps existing G5-* / G6 behavior
identical.
Out of scope (still): WAL recycle path consuming MinPin (g7-redo/
recycle-pin-hookup, separate PR per architect §11 Resolution 2),
removing legacy lane shim, §3.2 #3 interleave.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* component: dual-lane engine-driven happy path (wiring step 3)
Closes the wiring milestone per docs/recovery-wiring-plan.md §7 +
architect "P0 = component layer dual-lane full chain" (2026-04-29).
Full chain pinned: master fact → adapter.OnAssignment → engine
ingest Identity → emits ProbeReplica → executor.Probe → adapter
ingests RecoveryFacts → engine.decide() picks rebuild (R<S) →
emits StartRebuild → adapter dispatches to dual-lane-mode
BlockExecutor → recovery.PrimaryBridge.StartRebuildSession →
sender goroutine over the replica's separate dual-lane port →
recovery.Receiver applies base lane + barrier → SessionClosedCompleted
flows back through executor.OnSessionClose → adapter →
engine.Trace records the event.
Cluster builder additions:
+ WithDualLaneRecovery() — composable with WithEngineDrivenRecovery.
+ Coord() — exposes the per-volume PeerShipCoordinator for assertion.
+ DualLaneReplicaAddr(i) — diagnostic.
+ ReplicaNode.DualLaneAddr — populated when dual-lane mode set.
+ Start() branches: per-replica dual-lane listener bound on
127.0.0.1:0 alongside the legacy listener; per-volume coord
instantiated before executors so each NewBlockExecutorWithDualLane
captures the same instance.
Substrate: MemoryWAL (new factory in cluster.go) — NOT BlockStore
or walstore. Architect-bound rationale for using memorywal rather
than walstore here:
- V2-faithful per-LSN replay (RecoveryModeWALReplay, write-time
LSN through ScanLBAs) — matches the dual-lane recovery contract
the test asserts.
- In-memory; no /tmp churn between tests; no flusher/checkpoint
timing surprises in scenario assertions.
- Already part of the contract test table (BlockStore / WALStore /
MemoryWAL all pass the same 12 tests), so substrate parity is
covered separately.
Tests pinned (both PASS, runs in ~30ms each on memorywal):
TestDualLane_EngineDrivenRebuild_HappyPath:
- Engine emits StartRebuild after probe-result ingest.
- Trace records SessionClosedCompleted within 5s deadline.
- coord.Phase("r-0") == PhaseIdle post-session.
- Replica's substrate matches primary byte-for-byte across the
rebuilt range (12 LBAs).
TestDualLane_CoordReleasesPinFloorAfterSession:
- Pin floor released; MinPinAcrossActiveSessions reports
anyActive=false post-session.
- PinFloor("r-0") == 0 after coord.EndSession.
- INV-SESSION-TEARDOWN-IS-EXPLICIT.
Out of scope (still):
- Hardware integration (separate phase).
- WAL recycle path consuming MinPin (g7-redo/recycle-pin-hookup,
architect §11 Resolution 2).
- §3.2 #3 single-queue real-time interleave (architect priority #2).
- Multi-replica fanout under dual-lane (single replica here for
focus).
Full repo `go test ./...` PASS.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per architect ruling 2026-04-27 (Option B: absorb fix in G5-5C as
Batch #7), this batch fixes the host wiring gap revealed by
hardware run 3:
ROOT CAUSE: cmd/blockvolume constructs ONE *VolumeReplicaAdapter
for the host's own slot (Identity.ReplicaID = primary's-own-slot).
G5-5C ProductionProbeFn forwarded peer probe results into that
adapter. Engine apply.go:117-128 checkReplicaID correctly drops
events targeted at peer (replicaID != Identity.ReplicaID) as
wrong_replica. Result: probe success on wire, but no StartCatchUp
ever dispatched.
FIX: per-peer adapter, each tracking its peer's identity, each
wired to dispatch engine commands to that peer's transport executor.
NEW FILES:
- core/host/volume/peer_command_executor.go (~140 LOC)
PeerCommandExecutor adapts peer's transport.BlockExecutor to
satisfy adapter.CommandExecutor. Most methods delegate verbatim
(Probe, StartCatchUp, StartRebuild, StartRecoverySession,
InvalidateSession, Fence). Two value-adds:
1. SetOnSessionStart/Close intercept inner callbacks to drive
peer.SetState (Degraded → CatchingUp on start; CatchingUp →
Healthy on Success). Without this, peer state stays Degraded
after successful catch-up and probe loop keeps polling.
2. PublishHealthy/Degraded translate engine verdicts to
peer.SetState/peer.Invalidate. Inner executor's
Publish* are log-only; runtime peer state machine is what
gates Ship + ProbeIfDegraded.
- core/host/volume/peer_adapter_registry.go (~140 LOC)
PeerAdapterRegistry maps ReplicaID → *VolumeReplicaAdapter.
OnPeerAdded constructs PeerCommandExecutor + adapter, primes
with AssignmentObserved for the peer's identity. OnPeerRemoved
drops the adapter. AdapterFor lookups for the router probeFn.
Self-replicaID guard refuses host-own-slot registration.
Idempotent double-add. Lineage-bump produces fresh adapter.
Close drops everything.
UPDATED FILES:
- core/replication/volume.go: ConfigurePeerLifecycleHook (onAdded,
onRemoved). Hook fired from UpdateReplicaSet add/remove/lineage-
bump teardown paths under v.mu. Configure-once contract; replays
current peer set on configure (so registry catches up to peers
added before hook).
- core/host/volume/probe_loop_wiring.go: AdapterRouter signature
type added. ProductionProbeFn now takes router instead of single
adapter; routes per-peer; nil-router and missing-peer paths
fail-closed.
- cmd/blockvolume/main.go: construct PeerAdapterRegistry; wire
ConfigurePeerLifecycleHook; pass registry.AdapterFor to
ProductionProbeFn. Failure paths cleaned up the same way as
prior wire steps.
- core/host/volume/boundary_guard_test.go: PCDD-STUFFING-001 fence
now allows TWO sites for adapter.AssignmentInfo composite
literals: decodeAssignmentFact (master decode boundary) AND
OnPeerAdded (per-peer engine identity priming, G5-5C Batch #7).
Other sites still fail.
- core/replication/component/g5_5c_restart_catchup_test.go:
configureProbeLoopOnCluster now uses AdapterRouter signature
(closure over c.primary.adapters[0]).
NEW TESTS (15 total, all PASS):
- peer_adapter_registry_test.go (7): RegisterAndPrimes,
DropsAdapter, SelfReplicaIDRefused, DoubleAddIdempotent,
LineageBumpTeardown, CloseDropsAll, NilSafe.
- peer_command_executor_test.go (5): PublishHealthy → SetState,
PublishDegraded → Invalidate, SessionStart → CatchingUp,
SessionClose → Healthy, DelegatesProbe.
- probe_loop_wiring_test.go (3 updated + 2 new):
NilRouter_ReturnsErrAndDoesNotPanic,
RouterReturnsNil_ReturnsErr,
RouterPicksByReplicaID (new — pins per-peer routing contract).
Test results: full ./... regression PASS at 17:58. No behavioral
regression on G5-4 / earlier T4 paths. Component test #6
(restart-catch-up convergence) still PASSES via new router signature.
NEW INV (replaces previously-deferred G5-5D INV):
- INV-G5-5C-PER-PEER-ADAPTER-PER-PEER-ENGINE — production binary
constructs *VolumeReplicaAdapter per (volume × admitted peer).
Engine.checkReplicaID correctness preserved.
Next: m01 hardware re-run #4. Expected GREEN within 30s deadline.
Architect Batch #6 review 2026-04-27 ratified scope: end-to-end
wiring + convergence test, mirror G5-5 hardware step #4 without
iSCSI/iptables harness. 5 implementation constraints all addressed:
#1 determinism: bounded retries, 30 ms loop interval, 20 ms
cooldown base, 200 ms cap, hard 8 s deadline on convergence
wait. CI flake guard via 1.5 s no-convergence window in negative
control test.
#2 kill semantic: ReplicaListener.Stop() blocks on wg.Wait waiting
for active handler conns to drain, but on localhost the primary
side never closes the live-ship conn so handlers block forever
on ReadMsg. Added ReplicaListener.StopHard() that closes active
conns BEFORE waiting; KillReplicaListener routes through it. The
pre-existing Stop() semantics are preserved for the regular
teardown path. Same-port rebind via NewReplicaListener retry
loop with 2 s deadline (TIME_WAIT tolerance).
#3 probe path same as cmd/blockvolume: configureProbeLoopOnCluster
uses volume.ProductionProbeFn (NOT a stub) → ConfigureProbeLoop
→ StartProbeLoop. The exact closure main installs in production.
#4 assertion layer: byte-equal convergence only — no engine R/S/H
peeks. Architect ruling: "至少一条: ReplicaDegraded → probe →
catch-up dispatched → frontier/byte-equal".
#5 no rebuild branch verification: test asserts convergence only,
not which engine command was emitted. In this scenario the
smartwal store's post-rebind boundaries land R<S so engine
picks Rebuild; that's incidental, not a property the test pins.
Files:
- core/transport/replica.go: +StopHard method, +conns map for
active-conn tracking; pre-existing Stop semantics unchanged.
- core/replication/component/cluster.go: KillReplicaListener now
calls StopHard.
- core/replication/component/g5_5c_restart_catchup_test.go (new):
- TestG5_5C_RestartCatchUp_Convergence: positive end-to-end test.
- TestG5_5C_RestartCatchUp_NoConvergence_WithoutProbeLoop:
negative control — same scenario without ConfigureProbeLoop
must NOT converge in 1.5 s window. Without this control, the
positive test could pass via some other accidental
reconvergence pathway; this pin proves the probe loop is
load-bearing.
Helpers (test-local):
- rebindReplicaListener: same-port restart with 2 s rebind retry.
- configureProbeLoopOnCluster: production wiring on cluster harness.
- drivePeerAdmit: AssignmentInfo + initial ProbeResult to reach
Healthy.
- writeOneBlock: write through StorageBackend so WriteObserver
fires (not direct store write).
Three-counter SessionID onboarding note (architect Batch #5 follow-up):
core/replication/peer.go now documents in code why three counters
exist (peerSessionID for live-ship; adapter probe counter for
engine-emitted ProbeReplica; probeSessionID for G5-5C runtime-
driven probes) and why none cross paths.
Test results:
- TestG5_5C_RestartCatchUp_Convergence: PASS (0.05 s)
- TestG5_5C_RestartCatchUp_NoConvergence_WithoutProbeLoop: PASS (1.54 s)
- Full ./... regression: PASS (every package, no behavioral
regression on G5-4 / earlier T4 paths).
Next: m01 hardware run of iterate-m01-replicated-write.sh
verify_restart_catchup expecting #1/#2/#3 regression GREEN + #4
GREEN within deadline. After hardware GREEN, sw drafts §close.
HARD GATE #3 surfaced 2 real bugs in engine-driven recovery flow that
synthetic OnSessionClose injection didn't expose. Both fixed here.
Bug #1 — catch-up exhaustion missed escalation when Decision was
re-classified mid-flight:
Symptom: stray auto-probe arriving between catch-up retries
re-classified Recovery.Decision (R<S → Rebuild). Exhaustion-branch
checked stale Decision and fell through to terminal-degraded
instead of round-47 escalation.
Fix: key on st.Session.Kind == SessionCatchUp (truth = what
session actually failed), not on mutable Recovery.Decision.
Bug #2 — WALRecycled set Decision=Rebuild but never emitted
StartRebuild; subsequent probe could downgrade:
Symptom: WALRecycled escalation only emitted PublishDegraded; no
rebuild command. A subsequent probe with R>=S could re-classify
back to CatchUp before any rebuild fired.
Fix: new RecoveryTruth.RebuildPinned sticky bool. Set by both
WALRecycled escalation AND catch-up exhaustion. decide() honors
it as override — forces Decision=Rebuild + emits StartRebuild
regardless of R/S/H. Cleared by successful rebuild
SessionCompleted (or identity reset).
WALRecycled also now emits StartRebuild immediately (in addition
to PublishDegraded for diagnostic surface).
Bug #3 (architect-required rule) — already correct:
Rebuild's MaxRetries=0 routes the first rebuild failure to the
existing terminal-degraded branch. No code change needed.
New invariants pinned:
INV-REPL-REBUILD-DECISION-STICKY — once escalated to rebuild
(WALRecycled or exhaustion), probe re-classification cannot
downgrade to CatchUp before rebuild completes.
INV-REPL-REBUILD-EMITTED-ON-WAL-RECYCLED — WALRecycled escalation
emits StartRebuild immediately, not just PublishDegraded.
Full L2 tests (HARD GATE #3) — all PASS through real
engine→adapter→executor wiring (NOT synthetic injection):
- TestT4d4_FullL2_CatchupRetryExhausted_EscalatesToRebuild
- TestT4d4_FullL2_WALRecycled_EscalatesImmediate
- TestT4d4_FullL2_LastSentMonotonic_AcrossRetries (QA #8 full form)
Files:
- core/engine/state.go — RebuildPinned field with invariant doc
- core/engine/apply.go — sticky-rebuild gate in decide();
WALRecycled emits StartRebuild + pins; exhaustion uses
Session.Kind + pins; rebuild SessionCompleted clears pin
- core/engine/recovery_test.go — fixtures set Session.Kind:
SessionCatchUp (was relying on old Decision-based check)
- core/replication/component/t4d4_full_l2_matrix_test.go — NEW,
3 HARD GATE #3 tests via engine-driven flow with substrate
fault injection wraps
Verified: full V3 suite green; m01 -race ×20 stress on the 3 HARD
GATE tests, no flakes.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per T4d mini-plan v0.5 §2.4 (architect round-47 expanded scope).
Closes 3 of 4 HARD CLOSE GATE items (#1#2#4); #3 full L2 matrix
+ QA #8 LastSentMonotonic full form deferred to part C with
substrate fault injection.
ROUND-47 ENGINE CHANGE — catchup-exhaustion escalates to rebuild:
- core/engine/apply.go applySessionFailed: catch-up budget exhaustion
now DIRECTLY emits StartRebuild (Decision flips to Rebuild,
StartRebuild command emitted with current Recovery.H as TargetLSN).
Pre-round-47: cleared Decision + emitted PublishDegraded; rebuild
only fired if a fresh probe arrived. Round-47: rebuild path becomes
engine-driven end-to-end without probe dependency.
- Rebuild has MaxRetries=0 per DefaultRuntimePolicyFor; rebuild
failure terminates (Decision cleared, PublishDegraded emitted).
Pinned by INV-REPL-CATCHUP-EXHAUSTION-ESCALATES-TO-REBUILD +
INV-REPL-REBUILD-FAILURE-TERMINAL.
- Existing TestSessionFailed_NonRecycled_RetriesUntilBudget updated
for round-47 escalation (asserts StartRebuild emit on attempt #4
+ Decision=Rebuild + DecisionReason="catchup_budget_exhausted").
WITHENGINEDRIVENRECOVERY() REAL — round-47 HARD GATE #1 + #2:
- core/replication/component/cluster.go: WithEngineDrivenRecovery()
now installs ONE VolumeReplicaAdapter per replica at Start.
Adapters are wired to executors via the constructor's
executor-callback registration (existing adapter ctor behavior).
- New PrimaryNode.adapters field + Cluster.Adapter(idx) accessor.
- New Cluster.DriveAssignment / Cluster.DriveProbeResult helpers
for test scenarios driving engine state through real adapter.
- Stub warning text + log message removed; engine-driven recovery
is now the real path when opted in.
G5-DECISION-001 SERIALIZABILITY — round-47 obligation:
- core/engine/g5_decision_001_serializability_test.go pins that
engine.ReplicaState (+ all nested truth structs) round-trips
through encoding/json cleanly. T4d-4 obligation: keep struct
serializable so G5 can choose Path A (persist recovery state
across primary restart) without structural rewrite.
- 2 tests: full-state round-trip + zero-value round-trip
- T4d-4 does NOT implement persistence — just maintains the
serializability property.
NEW TESTS (9):
core/engine/recovery_test.go (2 new + 1 updated):
- TestT4d4_CatchupExhaustionEscalatesToRebuild (round-47 #4 pin)
- TestT4d4_RebuildExhaustionIsTerminal (rebuild MaxRetries=0
termination)
- (existing) TestSessionFailed_NonRecycled_RetriesUntilBudget
updated for round-47 escalation semantic
core/engine/g5_decision_001_serializability_test.go (2):
- TestG5Decision001_ReplicaState_RoundTripJSON
- TestG5Decision001_ReplicaState_ZeroValueStable
core/replication/component/t4d4_engine_driven_test.go (5):
- TestT4d4_WithEngineDrivenRecovery_IsReal (HARD GATE #1)
- TestT4d4_AdapterWithoutWithEngineDrivenRecovery_IsNil (fence)
- TestT4d4_DriveAssignment_EngineEmitsProbeReplica
- TestT4d4_RoundTrip_AssignmentToProbeToCatchUp_EngineDriven
- TestT4d4_CatchupBudgetExhausted_EngineEmitsRebuild
Existing test updated for round-47:
- core/adapter/adapter_test.go
TestPreparedNeverStarted_FailsClosedOnImmediateStartError:
set rebuildErr matching catchUpErr; assert chain ends at
Degraded after retry+escalate+rebuild-terminal (was: assert
PhaseFailed after first attempt — round-47 makes that
intermediate not terminal).
NOT in part B (deferred to part C):
- HARD GATE #3: Full L2 matrix incl QA #8 LastSentMonotonic full form
— needs substrate fault injection wrapping engine-driven flow
- Windows TempDir cleanup race + sessionID coordination + test rename
Forward-carry status:
- Round-47 engine change preserves all prior round-43/44/46
invariants (lane purity, stale-skip, no per-LBA regression)
- T4d-1 typed-kind contract: forward-carries
- T4d-2 lane-pure apply gate: forward-carries
- T4d-3 R+1 threading: forward-carries
- T4d-4 part A (RecoveryMode + Stop lifecycle): forward-carries
- 22 packages green; 0 failures
Refs: T4d mini-plan v0.5 §2.4 (architect-ratified expanded scope);
round-47 architect ruling (catchup-exhaustion escalates to rebuild +
G5-DECISION-001); G-1 sign 80036404c (G-1 v0.2).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per T4d mini-plan v0.4 §2.4 expanded scope. Part A of three: smaller
substrate cleanups + lifecycle hardening land first; Path B fold
(ReplicationVolume↔adapter wiring + WithEngineDrivenRecovery real)
follows as part B; Windows cleanup + L2 matrix as part C.
T4c §I row 6 closure (RecoveryMode interface method):
- core/storage/logical_storage.go — add RecoveryMode() to
LogicalStorage interface (returns substrate's tier-1 sub-mode
per memo §5.1 / §13.0a)
- core/storage/store.go BlockStore.RecoveryMode() →
RecoveryModeStateConvergence (in-memory; ScanLBAs synthesizes)
- core/storage/walstore.go WALStore.RecoveryMode() →
RecoveryModeWALReplay (V2-faithful per-LSN)
- core/storage/smartwal/store.go Store.RecoveryMode() →
RecoveryModeStateConvergence (per-LBA dedup)
- core/transport/catchup_sender.go — replace duck-typed
CheckpointLSN probe with e.primaryStore.RecoveryMode() interface
call. Forwards cleanly through component framework wraps via
embedded LogicalStorage.
- core/replication/component/faults.go godoc — replace stale
"MASKED by wrap" limitation note with T4d-4 closure note;
AssertSawRecoveryMode now works correctly under wraps
T4d-4 lifecycle (BUG-005 non-repeat):
- core/replication/volume.go — Stop() canonical entry point added
(delegates to existing Close); semantic clarity over Close().
Both methods are equivalent in T4d-4; Stop() is the named entry
for "stop volume lifecycle activity" while Close() retained for
backward compatibility. Future expansions (drain pending I/O,
stop background goroutines) land in Stop().
- INV-REPL-LIFECYCLE-HANDLE-BORROWED-001 pinned by
TestReplicationVolume_Stop_DoesNotCloseBorrowedStore: store is
STILL usable after volume.Stop (substrate handle is borrowed,
never closed by us — BUG-005 discipline)
- TestReplicationVolume_Stop_Idempotent: second + later Stop calls
are no-ops returning nil
- TestReplicationVolume_Stop_TearsDownPeers: empty-set lifecycle pin
Tests added (5 new):
- TestReplicationVolume_Stop_Idempotent
- TestReplicationVolume_Stop_DoesNotCloseBorrowedStore
- TestReplicationVolume_Stop_TearsDownPeers
- TestStorageRecoveryMode_BlockStore_StateConvergence
- TestStorageRecoveryMode_Walstore_WALReplay
- TestStorageRecoveryMode_LogicalStorageInterface_HasMethod
(compile-time fence pinning RecoveryMode is on the interface,
not just on substrate impls)
NOT in part A (deferred to part B / C):
- ReplicationVolume↔adapter wiring (Path B fold, part B)
- WithEngineDrivenRecovery real binding (Path B fold, part B)
- Full L2 integration matrix (part C)
- Windows TempDir cleanup race (part C)
- Test rename per kickoff §5 (part C)
- sessionID coordination (T4c §I row 5; part C — minor)
22 packages green; 0 failures. Forward-carries: T4c-2 + T4d-1 +
T4d-2 + T4d-3 invariants all green; new RecoveryMode plumbing
preserves T4c-2 INV-REPL-RECOVERY-MODE-OBSERVABLE.
Refs: T4d mini-plan v0.4 §2.4 (architect-ratified expanded scope);
T4c §I row 6 (substrate RecoveryMode method); kickoff §2.1 (BUG-005
non-repeat lifecycle); G-1 sign 80036404c (G-1 v0.2 + planning
artifacts).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Architect round-46 rejected my lane-discriminator implementation:
the gate inspecting `lineage.TargetLSN > 1` to dispatch lane was a
"payload-derived signal" — wrong placement. The fix: gate is
LANE-PURE; CALLER decides lane from connection/session handler
context.
GATE API REWORKED:
- Removed: Apply(lineage, ...) + isRecoveryLane(lineage) helper
- Added: ApplyRecovery(lineage, lba, data, lsn) — explicit recovery
lane (stale → skip data + advance recoveryCovered)
- Added: ApplyLive(lineage, lba, data, lsn) — explicit live lane
(stale → return error fail-loud; never advance recoveryCovered)
- Gate methods do NOT inspect lineage.TargetLSN for lane decisions
TRANSPORT INTERFACE REWORKED:
- transport.ApplyHook becomes 2-method interface (ApplyRecovery +
ApplyLive)
- replica.go MsgShipEntry handler dispatches CALLER-SIDE based on
TargetLSN==liveShipTargetLSNSentinel; this is a TRANSITIONAL SHIM
with explicit TODO marking it as caller-side-only — the
architectural fence (gate is lane-pure) is the durable property
- TODO references future fix: true handler-context lane via
per-connection lane tag, separate live/recovery handler routes,
or distinct listener ports (T4e or post-G5 refactor)
- liveShipTargetLSNSentinel const lives in transport (NOT importing
replication for the value; same wire-stable constant)
REGRESSION TESTS (architect round-46 HARD GATE):
- TestApplyGate_RecoveryWithTargetLSN1_RoutesToRecoveryLane —
recovery lineage with TargetLSN=1 (the OLD live-ship sentinel
value): pre-rework this routed to live and fail-loud'd a stale
recovery entry; post-rework gate honors caller's ApplyRecovery
choice → stale skips silently + recovery coverage advances
- TestApplyGate_LiveWithTargetLSN100_RoutesToLiveLane — mirror:
live lineage with TargetLSN=100 (would have been recovery
pre-rework): post-rework gate honors caller's ApplyLive choice →
stale fail-louds + recovery coverage NOT advanced
TESTS REPLACED / RENAMED:
- TestApplyGate_LaneDiscriminator_RecoveryWhenTargetLSNAboveLive
REMOVED (the gate no longer has a lane discriminator helper)
- TestComponent_LaneDerivedFromTargetLSN renamed →
TestComponent_LanePurity_CallerControlsDispatch — repurposed:
uses identical lineage payload across two test paths, only the
caller's choice of method differs; gate honors choice; pins
INV-REPL-LANE-DERIVED-FROM-HANDLER-CONTEXT (round-46 strengthened
meaning: handler context, NOT payload-derived signals)
REMAINING TESTS UPDATED:
- All gate.Apply(...) call sites in apply_gate_test.go +
apply_gate_scenarios_test.go updated to use ApplyRecovery /
ApplyLive based on the test's intended lane (recoveryLineage →
ApplyRecovery; liveLineage → ApplyLive)
Forward-carry status:
- T4d-1 typed-kind contract unaffected (gate orthogonal to failure
classification)
- All round-43/44 invariants still pinned by the 16 tests; lane-
routing now via explicit method instead of payload sniffing
- 22 packages green; 0 failures
- T4d-3 G-1 sign HARD GATE now satisfied per round-46 QA call
T4d-3 unblocked. T4d-4 unblocked + parallel-eligible.
Refs: round-46 architect ruling (rework lane discriminator);
mini-plan v0.3 §2.2 (apply gate); kickoff §9.3 #2 (Q2 — lane
implicit from handler context).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pre-T4d-1 hotfix per architect-ratified kickoff sequencing
(round-44 governance call): substrate-level guard lands ahead of
the larger T4d-2 replica recovery apply gate work. Closes a
production storage-contract violation independent of the larger
T4d batch.
Bug (round-41 architect-identified, round-43 demo-confirmed):
core/storage/store.go:264 set s.walHead = lsn unconditionally.
Older-LSN ApplyEntry regressed walHead, violating
LogicalStorage contract §3 rule 3 ("stable frontier never goes
backward").
Empirically demonstrated live at round-43:
ApplyEntry(LSN=10) → walHead=10
ApplyEntry(LSN=5) → walHead=5 ← REGRESSION
Fix:
if lsn > s.walHead {
s.walHead = lsn
}
Same monotonic-update pattern as walstore.ApplyEntry:544 and
smartwal.ApplyEntry:358 already use. Brings BlockStore in line.
Architectural placement (round-43 sign):
Replica recovery apply gate (T4d-2 primary fix) is the primary
correctness boundary; this guard is defense-in-depth for paths
that may bypass the gate (live duplicate, retry, future
cross-substrate scenarios). Inline godoc comment names the
T4d-2 gate as the primary boundary so the role is clear.
Test (un-skipped from round-41/43 adversarial set):
TestComponent_BlockStore_ApplyEntry_OldLSN_DoesNotRegressWalHead
(renamed from TestComponent_Adversarial_BlockStoreApplyEntry
RegressesWalHead — the bug name no longer applies).
Pre-fix: t.Skip + T4d TODO. Post-fix: passes; pins the
monotonic guard against regression.
Zero semantic change to any code that worked before. T4d-1 / T4d-2
will not conflict with this hotfix — different files, different
layers.
go test ./... -count=1 → 22 packages green (regression test
passes; no other test affected).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
QA round-42 refined the round-41 invariant
INV-REPL-RECOVERY-STALE-ENTRY-SKIP-PER-LBA with two scoping rules
that must be honored at T4d implementation:
(1) INV-REPL-RECOVERY-STALE-SKIP-DATA-ONLY-NOT-ACCOUNTING:
Stale skip applies to DATA WRITE only. Per-session accounting
(bitmap, completion mask, scan coverage) MUST update as though
the entry was processed. Otherwise:
- Recovery session's completion logic thinks LBA wasn't reached
- Bitmap signals "recovery hasn't covered this slot" to live lane
- Barrier achievedLSN judgment is wrong
Skip means: don't write data. Still mark "I saw this LBA."
(2) INV-REPL-LIVE-LANE-NEVER-SKIPS-LSN:
Per-LBA-LSN skip rule applies to RECOVERY lane ONLY. Live ship
lane MUST NOT skip on stale LSN — live writes are authoritative
on (lineage, session) grounds and that gating is sufficient.
An "old LSN" on live is a duplicate/replay; per-LBA-LSN
comparison is recovery-lane-only.
Files updated:
- stale_entry_adversarial_test.go: TestComponent_StaleEntrySkip_
RuleStatement extended with both refinements + 2 new T4d
adversarial test requirements (recovery-stale-skip-still-marks-
bitmap; live-lane-old-LSN-applies-normally)
- memory feedback_recovery_stale_entry_skip.md: refinements +
expanded T4d blocker list
T4d blocker list now (round-42 revision):
1. Per-LBA applied LSN tracking at replica apply layer
2. Recovery apply skips entries whose LSN <= per-LBA applied LSN
3. Skip data write but UPDATE per-session accounting (refinement #1)
4. Apply skip rule on recovery lane only; live keeps current
lineage-gated apply (refinement #2)
5. BlockStore.ApplyEntry: gate walHead update on lsn > walHead
6. 5 adversarial tests un-skipped + extended (architect set + QA
refinement set)
22 packages green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>