Hardware-validated diagnosis of the scenario #5/#6 "engine retry/escalate
gap" QA flagged: the bridge's onStart/onClose lambdas in
NewBlockExecutorWithDualLane built SessionStartResult /
SessionCloseResult WITHOUT the ReplicaID field. The engine's
checkReplicaID dropped both events as `wrong_replica` ("event for ,
engine owns r2"), so Session.Phase stuck at Starting forever,
hasActiveSession returned true permanently, and every subsequent
post-completion StartRebuild dispatch was silently suppressed.
This explained QA's pattern: probe r2 success R=0 S=1 H>>0 → engine
correctly classifies as Decision=rebuild (verified by adapter trace
{decision rebuild (R < S)}) but emits zero commands because of the
phase-stuck guard. The peer's runtime state diverged from the engine's
session truth: peer.SetState(Healthy) fires on the executor callback
side (which never checks ReplicaID) but engine.Apply rejects.
Scenario #2 "succeeded" only because peer.SetState(Healthy) is enough
for the harness's wait_until_peer_healthy check; the engine's session
state was already broken at that point. Scenarios #5/#6 needed a
second rebuild and that's where the bug surfaced.
Hardware result post-fix:
G7 #2: dispatch=3s, complete=3s, total=6s — GREEN.
G7 #5: rebuild dispatches in 2s (was: never dispatched). New failure
is at byte-equal verify (498 mismatches over 5500 LBAs) — the
concurrent-writes-during-rebuild seam (T4 wire-fromLSN vs
shipper-anchor split) flagged in v3-rebuild-from-lsn-pin-
clarification §4. Out of scope of this fix.
Adapter diagnostic logs (`g7-debug:`) added in core/adapter/adapter.go
that pinpointed the bug — left in for QA verification of next run.
Will gate them or remove in a follow-up commit once stable.
Anchor: hardware trace g7-20260502T012553Z primary-fail.log line
"trace=[{event SessionStarted} {wrong_replica event for , engine
owns r2}]" — the empty ReplicaID being dropped.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Hardware-validated fix for the silent rebuild stall on 40da4c8. Three
coordinated changes that close the gap between unit-test-green and
hardware-completing dual-lane rebuild:
1. **`startRebuildDualLane` — sentinel translation**
Caller passed `fromLSN=0` to the bridge, taken literally by
`WalShipper.StartSession(0)`. On a primary that's been running,
the WAL retention floor is at `checkpointLSN` (entries through
the checkpoint are durable in the extent and the WAL ring has
recycled past 0); `ScanLBAs(0)` immediately returns
`ErrWALRecycled`, the wal goroutine errors, sender exits before
barrier emission, hardware silently stalls.
Fix: pass `sessionFromLSN = targetLSN` (the snapshot pin). Base
lane covers the snapshot through the checkpoint, WAL drain has
nothing to ship at the pin (cursor==head), live writes during
the session flow via NotifyAppend on the steady-state path.
2. **`WalShipper.DrainBacklog` — cursor-caught-up shortcut**
At the dual-lane bootstrap with `cursor == fromLSN == targetLSN
== primary head`, the loop entered ScanLBAs and hit the recycle
gate. Add an early shortcut: if `cursor >= head` at iter start,
skip ScanLBAs and try the R1 transition directly.
3. **`RebuildSession.SeedWalApplied` + receiver wiring**
For a base-only rebuild (WAL drain ships nothing), `walApplied`
stayed at 0; `TryComplete`'s `walApplied >= targetLSN` conjunct
could never hold. Seed it with `fromLSN` at SessionStart so the
predicate satisfies after `MarkBaseComplete` + `WitnessBarrier`.
4. **`executor.go` dual-lane onClose — completion marker**
QA harness `wait_until_rebuild_complete` greps for
`executor: rebuild complete, sent N blocks (targetLSN=N)` —
emitted only by the legacy `doRebuild` path. Mirror it on the
dual-lane bridge's onClose callback so the harness recognizes
completion identically across modes.
Hardware result (G7 #2 — empty replica join, 1000 LBAs):
rebuild dispatched in 1s, completed in 1s after dispatch
(total 2s), 1000 LBAs byte-equal verified post-rebuild.
Markers fired: `barrier prepare ... WalLegOk=true` +
`barrier handshake ... match=true` + peer state
`catching_up → healthy`.
Known seam (out of scope, T4-during-live-writes):
When live writes arrive during the session, the receiver's T4
monotonic checker expects `lsn == appliedWalLSN+1` where
`appliedWalLSN` is seeded to `fromLSN`. Live writes get LSNs
starting at `fromLSN`, breaking T4. Resolving this requires
splitting the wire-fromLSN (T4 expectation) from the
shipper-anchor (DrainBacklog cursor) — separate work. The
hardware harness's scenario #5 (concurrent writes during
rebuild) hits an unrelated probe-loop dispatch issue first
and never gets to exercise this seam.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Replaces the recover(a,b) sole completion gate (`walApplied >=
TargetLSN`) at both Tier-1 sites with the §IV.2.1 realizable conjunct
synthesized from existing observables (ProbeBarrierEligibility witness
+ baseDone + barrier round-trip). Per recover-semantics-adjustment-plan
§1, "session semantically complete" claim moves from replica-side
verdict to coordinator-owned authority on the primary.
Tier-1 sites updated:
RebuildSession.TryComplete (replica, layer-1):
baseDone ∧ walApplied >= targetLSN ∧ barrierWitnessed
PeerShipCoordinator.CanEmitSessionComplete (primary, system close):
phase != Idle ∧ baseDone ∧ achieved >= targetLSN
∧ (walLegOkWitnessed → walLegOkAtBarrier)
Mechanics:
- Receiver latches RebuildSession.WitnessBarrier() on frameBarrierReq
arrival, BEFORE TryComplete. BarrierReq arrival = primary attests
PrimaryWalLegOk under shipMu (§IV.2.1 disjunction).
- Sender records PrimaryWalLegOk witness via
Coordinator.RecordBarrierWalLegOk(walLegOk) immediately after the
ProbeBarrierEligibility snapshot, BEFORE writing frameBarrierReq.
- Bridging-sink path (no probe) leaves walLegOkWitnessed=false; the
conjunct collapses to legacy (back-compat preserved while §IV.2.1
probe wiring is dual-lane-only). Test coverage in
TestRecoverA_BridgingSinkPath_LegacyCollapse pins this.
A-class conformance stubs unskipped (recover_a_conformance_test.go):
A1 TestRecoverA_DebtZeroPath_BarrierEligible SKIP→GREEN
A2 TestRecoverA_LiveTailPath_BarrierEligible… SKIP→GREEN
A3 TestRecoverA_Disjunction_EitherPathSuffices SKIP→GREEN
A4 TestRecoverA_NeitherPath_NotEligible SKIP→GREEN
+ TestRecoverA_BridgingSinkPath_LegacyCollapse GREEN (new)
A4 binding: walLegOk=false witness → CanEmit refuses → sender returns
FailureContract on close. Wire-level emission gating (§IV.2.2 stronger
"MUST NOT be emitted") is the B-class barrierEmitFreeze wave — out of
scope. A-class pins the binding at the close gate.
C-class still SKIP (CheckpointCutSeq on wire, achieved-as-cut-witness).
Y kept as comparator pre-C-class (`achieved >= targetLSN` retained;
"Y as enumerator only" defers to C-class wave).
Whole-tree go test ./... -count=1 green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds Receiver.appliedWalLSN/recvFromLSN tracking and checkMonotonic /
enforceWalWireMonotonic per §IV.0 T4 (recover-semantics-adjustment-plan
§7 v3.28 substrate-mode carve-out).
Behavior:
- SessionStart seeds recvFromLSN=appliedWalLSN=FromLSN.
- Each frameWALEntry runs enforceWalWireMonotonic before ApplyWALEntry.
- RecoveryModeWALReplay: requires lsn == appliedWalLSN+1; gap returns
FailureContract; exact-duplicate / backward returns FailureProtocol.
- StateConvergence (smartwal ScanLBAs): skipped — frontier LSN may
legitimately repeat across many RecoveryEntry payloads.
Tests:
- TestReceiver_checkMonotonic_T4: forward / duplicate / gap / backward.
- TestReceiver_checkMonotonic_boundaryDup: lsn==FromLSN before any
apply is a Protocol failure (not a no-op).
Authored by architect; submitted on user request.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
First behavioral wave of the recover(a) migration now that Gate G0 is
closed. OBSERVABILITY ONLY — no completion-predicate replacement,
no semantic change to BarrierReq emission gating. The recover(a,b)
band path stays GREEN as today; this commit adds the §IV.2.1
PrimaryWalLegOk observation tuple and Option B cutID counter so QA's
hardware oracle (§8.2.6) can wire round-trip grep in parallel with
A/B/C-class implementation.
Anti-discipline checks (§8.2.8) honored:
- All 5 marker fields per the §8.2.6 schema (no simplification).
- Conformance stubs in core/recovery/recover_a_conformance_test.go
remain SKIPPED — predicate replacement is the A-class wave.
Substrate changes:
WalShipper (core/transport/wal_shipper.go):
+ firstLiveEmitted atomic.Bool — set on first EmitKindLive emit
(fast-path or post-CASE-A residual); reset on StartSession.
Implements PrimaryLiveTail's per-session monotonic property.
+ ProbeBarrierEligibility() — single-shot snapshot under shipMu
returning (debtZero, liveTail, walLegOk, cursor, head). The
§IV.2(2) guard is simplified at this layer to "ever emitted
Live" — component-layer exercises the real guard.
RecoverySink (core/transport/recovery_sink_adapter.go):
+ ProbeBarrierEligibility delegate — duck-types the
barrierEligibilityProbe interface in core/recovery so the
dual-lane production path can populate marker logs.
PeerShipCoordinator (core/recovery/peer_ship_coordinator.go):
+ barrierAttempt counter on peerShipState — increments per
NextBarrierCut call within a session; resets to 0 at
StartSession (per architect Option B in plan §8.2.6).
+ NextBarrierCut(replicaID) (cutID, error) — first call per
session yields 1; pre-§IV.2.4 wire change this is a
coordinator-local sequence; post-C-class it becomes the
wire CheckpointCutSeq with no log-prefix change.
Sender.Run (core/recovery/sender.go):
+ barrierEligibilityProbe interface (optional, sink-side).
+ Two log lines per BarrierReq round-trip (5 fields each per
§8.2.6 schema):
replication: barrier prepare replica=<id> sessionID=<n>
cut=CCS:<cutID> PrimaryDebtZero=<bool> LiveTail=<bool>
WalLegOk=<bool> cursor=<n> head=<n>
replication: barrier handshake cut=CCS:<cutID>
achieved=<n> match=<bool>
Pre-C-class `match=true` unconditionally — the same cutID
flows from prepare to handshake by construction. Post-C-class
becomes the real wire-vs-engine compare.
+ Markers fire only on the dual-lane production path (sink
implements barrierEligibilityProbe); bridging-sink path
doesn't emit them — pre-§IV.2.1 markers are dual-lane-only
per the §8.2.6 hardware oracle scope.
Tests:
core/transport/probe_barrier_eligibility_test.go (new):
- FreshShipper_DebtZero — at construction, cursor==head==0,
walLegOk via debtZero.
- LiveEmitFlipsLiveTail — fast-path Live emit sets liveTail
monotonically.
- StartSessionResetsLiveTail — per-session monotonic reset
contract.
core/recovery/peer_ship_coordinator_test.go:
+ TestCoordinator_NextBarrierCut_MonotonicPerSession —
first-call-yields-1, monotonic increment, per-session reset
on StartSession-after-EndSession.
What this commit does NOT do (waiting for A-class wave):
- Replace `walApplied >= TargetLSN` predicate in TryComplete.
- Replace `achievedLSN >= targetLSN` in CanEmitSessionComplete.
- Replace Sender.Run's success-path FailureContract on
`achieved < target`.
- Add CheckpointCutSeq to BarrierReq/Resp wire payload.
- Un-skip conformance stubs.
Each of those is its own slice that turns ≥1 conformance stub
SKIP→GREEN as it lands.
Refs: recover-semantics-adjustment-plan.md §8.2 / §8.2.6
(Option B cutID); v3-recovery-algorithm-consensus.md §IV.2.1
(PrimaryDebtZero / LiveTail / WalLegOk); §I P8 (recover(a) vs
recover(a,b)). Companion to the QA→SW handoff commits 599f60e /
a08dea1 / faafa46.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Commit 3 of the QA→SW handoff (`recover-semantics-adjustment-plan.md`
§8.2.7 step 4). Adds 8 SKIPPED red-test anchors covering the three
G0-合同-unblockable categories from §8.2.5; D/E/F deferred until
G0-身份 + G0-wire close per the same section.
File: core/recovery/recover_a_conformance_test.go
Categories landed:
A. PrimaryWalLegOk disjunction (§IV.2.1) — 4 stubs:
- DebtZeroPath_BarrierEligible
- LiveTailPath_BarrierEligibleAfterEverEmittedLive
- Disjunction_EitherPathSuffices
- NeitherPath_NotEligible
B. Lock discipline at BarrierReq emission (§IV.2.2 barrierEmitFreeze)
— 2 stubs:
- BarrierReqUnderShipMu_NoInterleaveWithDriveEmits
(codifies the slice-2B Pillar2B race fix)
- BarrierImminentFlag_FreezesDriveEmits
(Option 3 from architect's lock-discipline trade-off)
C. AchievedLSN as cut-witness, not target-crossing (§IV.2.4)
— 2 stubs:
- AchievedLSN_PerCutWitness
- SuccessWith_AchievedLSN_BelowTarget
(codifies FS-4 reverse from §8.2.3 — Y as enumerator only)
Anti-discipline checks (§8.2.8) honored:
- Every t.Skip carries a reason citing §IV.2.1 / §IV.2.2 / §IV.2.4
+ the unblocking G0 sub-gate; no bare t.Skip.
- No production type imports (stubs only declare Skip; real test
bodies land alongside impl).
- D/E/F categories explicitly NOT included per §8.2.5.
Verified: go test runs the stubs as SKIP entries; commit 1's oracle
table tests still GREEN. The skip messages double as a TODO list
visible to anyone running `go test -v` against core/recovery.
Source: sw-block/design/recover-semantics-adjustment-plan.md §8.2.5.
Companion to commit 1 (`599f60e` dual-oracle table) and commit 2
(`a08dea1` legacy header annotation).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Commit 2 of the QA→SW handoff (`recover-semantics-adjustment-plan.md`
§8.2.7 step 3). Header-only annotation pass on the 19 _test.go
files in seaweed_block that reference `targetLSN` or `walApplied`
as completion-authority terms (discovery: `grep -rlE
'targetLSN|walApplied' --include='*_test.go' core/`).
Each file gets a 2-line header right after the package decl,
verbatim per §8.2.4:
// Completion oracle: recover(a,b) band — NOT recover(a) closure.
// See sw-block/design/recover-semantics-adjustment-plan.md §8.1.
Six of the 19 are deeply primary.H-bound (assertions tied to
`replica.H == primary.H` or `achieved == primary.H`) and get an
extra `migrate-candidate` line per §8.2.4:
// migrate-candidate: depends on primary.H semantics, see §8.1 Tier-5 migration
The migrate-candidate set:
- core/transport/pillar2_assembled_test.go
- core/transport/pillar3_convergence_test.go
- core/transport/walshipper_pin_protection_test.go
- core/transport/transport_test.go
- core/transport/catchup_sender_test.go
- core/recovery/e2e_test.go
Anti-discipline checks (§8.2.8) honored:
- No assertion changes — header text only.
- migrate-candidate kept on its own line, not merged with the
standard 2-line annotation.
Note on count: §8.2.4 cited "~95 files" against the broader audit
pattern (TargetLSN/AchievedLSN/FrozenTarget/TryComplete). The
narrower §8.2.4 grep (targetLSN|walApplied) targets the actual
completion-authority surface and yields 19 files in the
seaweed_block tree. Build + tests clean post-annotation.
Source: sw-block/design/recover-semantics-adjustment-plan.md §8.2.4.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Commit 1 of the QA→SW handoff catalog (`recover-semantics-adjustment-
plan.md` §8.2.7 step 2). Pure-function spec-semantics test, no
production type imports — `RecoverState` + `BarrierWitness` are
test-local data shapes per §8.2.1 (anti-discipline check #3:
oracle test must NOT couple to core/* production types).
What this commit adds:
BandOracle (legacy recover(a,b)):
walApplied ≥ TargetLSN ∧ baseDone
RecoverAOracle (§IV.2.1):
baseDone ∧ PrimaryWalLegOk ∧ BarrierWitness with CutMatch
where PrimaryWalLegOk = (cursor==head) ∨ LiveClassEmitted
8-case counterexample table per §8.2.3:
- 4 sanity rows (both oracles agree)
- 4 CORE rows showing the dual-oracle independence:
FS-1, FS-2, FS-3: Band-true while RecoverA-false
(debt remaining, no barrier, cut mismatch)
FS-4 (reverse): Band-false while RecoverA-true
(Y as enumerator only — walApplied<Y
but LiveTail+barrier hold)
TestRecoverA_DualOracle_MutualIndependence:
Explicit pin that neither oracle implies the other. This is the
minimal expression of the dual-oracle motivation (plan §8.1):
keeping both green-by-each-side without forcing either's
completion authority on the other.
Test status: GREEN — table-driven, no production deps, no I/O.
Becomes the green-1 anchor of the §8.1 four-tier red-green ladder
that sw + QA will extend (commit 3 stubs are A/B/C skipped pending
G0 sub-gates).
Source: sw-block/design/recover-semantics-adjustment-plan.md §8.2
(QA-canonical handoff). The 8-case state vectors + oracle function
bodies are copied verbatim from §8.2.1 / §8.2.2 / §8.2.3 — sw-side
adjustments are gofmt + file-header convention only.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per architect's Path B ruling (2026-04-30), the four §13-era tests
that were skipped during slice-1 are re-authored to §6.3 contracts.
Three pass cleanly; one stays skipped pending deeper integration work.
TestWalShipper_R2_SaturationUnderSustainedLoad
(renamed from TestWalShipper_BacklogStaysBacklog_UnderLoad)
§13-era claim: "mode stays Backlog under saturation". Retired —
§6.3 single drive() collapse removes mode-as-dispatch. Re-authored
to the §6.3 saturation observability contract:
- Slow EmitFunc + pre-seeded substrate (lag ≥ threshold)
- Background writer extends head during scan
- OnSaturation fires single-shot per session
- cursor advances monotonically (INV-MONOTONIC-CURSOR)
- Eventually catches up after writer stops
10× stability locally clean (~5s per run with slow-emit).
TestDualLane_LiveWritesDuringSession_AtomicSeal
Pre-§6.3: per-pusher acceptedSet vs replica.Read; failed ~1/10
runs under §6.3 (concurrent CASE A scans race with producer).
Architect Path B: drop per-pusher cache; assert post-barrier
convergence on backlog + accepted-push LBA range. Cache-data
mismatch can no longer surface; the canonical truth at each
accepted LBA is primary.Read post-barrier.
15× stability locally clean.
TestPillar2B_LiveWrites_HighPressure_BarrierIntegrity
Architect's "DisableTimerDrain + 串行 push" path B variant.
The race surfaced under §6.3 isn't frame-tear; it's a session-
bracket vs in-flight-emit race: drive() emits hold writeMu
briefly per frame, sender's BarrierReq writeMu acquire can
interleave between emits, and receiver may then read the
barrier and return before in-flight push frames arrive. This
is a real §6.3 semantic gap with concurrent push during a
session, NOT a §6.3 correctness bug — the §6.3 model doesn't
bracket per-push barriers (architect's "另开 ADR for per-push
barrier semantics"). Path B explicitly listed serialized
pushes as an acceptable shape: 128 sequential pushes preserve
high-pressure intent without the race.
15× stability locally clean.
TestT4a6_BestEffort_DisconnectThenReassign
STAYS SKIPPED with a more honest §6.3 + walstore-recycle note.
§6.3 auto-fill via substrate (Path B) requires substrate to
retain the entries the new shipper backfills. In this L2
integration test, the second batch's LSNs may be past the
walstore recycle floor by the time the post-reassign shipper
opens with cursor=0; ScanLBAs returns ErrWALRecycled, drive()
treats as transient (cursor stays 0), and CASE B fires with
lsn=61 cursor=0 → tail-gap error. The proper §6.3 contract
here is engine-driven rebuild on WAL-recycled signal, but
that path isn't wired through this test's UpdateReplicaSet
flow. Re-author requires either tuning walstore retention OR
wiring the rebuild-on-recycled escalation; both out of slice-2B
scope. Tracked in §11.9 follow-ups.
5× cross-package sweep (transport / recovery / replication /
replication/component / storage / storage/memorywal /
storage/smartwal) all green post-slice-2B.
Refs: architect Path B ruling 2026-04-30; v3-recovery-algorithm-
consensus.md §6.3 + §6.9 + §11.9. Companion to slice-1 b3826b2,
slice-2A 8672e63.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Architect ruling 2026-04-30: §6.3 normative tail-gap fail-closed
becomes the default. LegacyOutOfOrderEmit defaults to false in
DefaultWalShipperConfig; new code MUST NOT rely on log+drop-gap
behavior. The shipper does NOT silently emit input bytes for a
missing-LSN case; engine MUST escalate to rebuild.
Test migration to §6.3 fail-closed default (sequential cursor+1
LSNs, production-mirror pattern):
- dual_lane_p2d_profile_test: P2d wire-format dispatch tests
used arbitrary lsn=50/200 for distinctness. Changed to lsn=1
(cursor+1 fast-path); wire-format claims (SWRP preamble vs
frameWALEntry, kind tag) unchanged.
- recovery_sink_adapter_test: post-EndSession context-restore
tests used arbitrary lsn=100/9999. Changed to use
shipper.Cursor()+1 dynamic so fast-path fires; rule-2 context-
restore claim is independent of LSN value.
- walshipper_resident_test (3 phase tests): cross-session
NotifyAppends with lsn={1,2,3} mismatched cursor (StartSession
rewinds cursor to fromLSN=0). Changed to dynamic shipper.Cursor()
+1 per phase.
- ship_sender_test (StaleEpoch_SilentDrop): fresh-epoch sanity
Ship with lsn=2 → cursor=0 mismatch under §6.3. Changed to
lsn=1.
- wal_shipper_executor_test (AdvancesCursor): ships at lsn={10,
20, 15} testing cursor-advances claim. Re-authored to lsn={1, 2,
1 idempotent} — production-mirror dense sequence.
- wal_shipper_executor_test (RegistryStableConcurrent): pre-§6.3
used 8×25 concurrent Ships with random LSNs (header itself
flagged "concurrent Ship is NOT production"). Re-authored per
architect Path B ruling: sequential Ship from one goroutine
(with lossless cursor==maxLSN assertion as the §6.3 contract
permits) + concurrent WalShipperFor lookups (the registry-
stability claim). Concurrency stress preserved on the part that
survives §6.3.
5× consecutive cross-package sweep (transport / recovery /
replication / replication/component / storage / storage/memorywal /
storage/smartwal) all green. No flakes.
Production audit (cmd/blockvolume + cluster.go): both use
NewWalShipper → DefaultWalShipperConfig, now Legacy=false. Production
flow inserts NotifyAppend(lsn==cursor+1) per primary's WAL append
chain — fast-path fires, no tail-gap reachable. If a tail gap ever
surfaces under load (network drop / shipper bug), the engine sees
the error and escalates to rebuild — the explicit §6.3 contract.
Refs: architect ruling 2026-04-30 (Path B + Legacy=false default);
v3-recovery-algorithm-consensus.md §6.3 + §6.9 NEGATIVE-EQUITY.
Companion to slice-1 b3826b2.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Refactors WalShipper's dispatch from mode-dispatched (NotifyAppend +
drainOpportunity as separate entry points with mode-keyed bodies) to
the consensus §6.3 single drive(input) function. NotifyAppend +
drainOpportunity become thin wrappers that offer input{has:true,...}
or input{has:false} respectively.
Dispatch (drive holds shipMu for the whole call — single serializer
per peer):
Idle (mode == ModeIdle): drop everything.
Fast-path (in.has + in.lsn == cursor+1 + head <= in.lsn):
Tail-emit input bytes as EmitKindLive. Preserves Realtime hot
path observability — cursor monotonic + no debt + input is the
next LSN means input bytes are canonical-equivalent to substrate;
no scan needed.
CASE A (cursor < head, debt-first per §6.3):
Substrate is canonical. Scan from cursor, emit each entry as
EmitKindBacklog, advance cursor; loop until cursor == head OR
scan exits. Per consensus §13 alignment, this is BACKLOG-DRAIN
semantics even when invoked from a NotifyAppend caller —
"Realtime is reading substrate?" is a misread; the wire kind tag
is Backlog, the dispatch is debt-first. R1 transition runs at the
tail of CASE A under shipMu.
Idempotent skip (in.lsn <= cursor after CASE A): drop.
CASE B (caught up + fresh tail, in.lsn == cursor+1):
Tail-emit input as EmitKindLive.
Tail-gap (in.has + in.lsn > cursor+1 + cursor == head):
Per §6.3 / §6.9 NEGATIVE-EQUITY ban — input MUST NOT replace a
missing LSN. Default fail-closed; engine MUST escalate to
rebuild. LegacyOutOfOrderEmit=true (transitional, see below)
restores pre-§6.3 log+emit.
Config delta:
+ LegacyOutOfOrderEmit (DEPRECATED, transitional):
True restores pre-§6.3 "log + emit input on tail gap"
behavior. Slice-1 default = true (transitional bridge — zero
behavior change for existing callers); slice-2 will flip to
false (§6.3 normative). Documented in field doc + DefaultWal
ShipperConfig comment.
StrictRealtimeOrdering (existing): semantically subsumed by
§6.3 tail-gap fail-closed. Both strict and non-strict (with
Legacy=false) now fail-closed at tail-gap. Kept for production
wiring expressivity; field doc updated.
CONVENTION block at file top: this implementation tracks `cursor` as
LAST-EMITTED LSN; spec §6.3 uses `cursor` as NEXT-TO-EMIT. Translation
in code: spec.cursor == internal.cursor + 1; the check `lsn ==
cursor+1` is identical to spec's `lsn == cursor`. Documented inline
on drive() so reviewers don't flip the bit.
Test migration (3 tests skipped with §6.3-migration notes; will be
re-authored against the new model in a separate slice or removed if
their pre-§6.3 contract is fully retired):
- TestT4a6_BestEffort_DisconnectThenReassign: asserted that a
degraded peer + reassign does NOT silently catch up the
suppressed batch. §6.3 default is automatic substrate-fill on
reattach — pre-§6.3 "best-effort = no auto catch-up" contract is
superseded. Skipped.
- TestWalShipper_BacklogStaysBacklog_UnderLoad: asserted that
Backlog mode persists while writer outpaces drain. §6.3 single
drive() runs CASE A scan to completion under one shipMu acquire;
R1 fires when caught up; Backlog mode is no longer load-bearing
in dispatch. Skipped.
- TestDualLane_LiveWritesDuringSession_AtomicSeal +
TestPillar2B_LiveWrites_HighPressure_BarrierIntegrity: concurrent
pushers race against each other's CASE A substrate scans; the
end replica state is byte-equal-primary post-barrier in the
common case, but the per-pusher acceptedSet vs replica-Read
direct comparison surfaces stragglar LBAs in ~1/10 runs. The
atomic-seal contract holds; the test shape needs re-authoring
to assert replica == primary (which is the same claim AtomicSeal
intended without per-pusher tracking). Skipped.
Updated test (re-authored against §6.3, kept passing):
- TestWalShipper_R2_LagSignalFires: pre-§6.3 the test could pump
1000 NotifyAppends in Backlog mode (lag-only) and observe lag
accumulate. Post-§6.3, NotifyAppend with lsn==cursor+1 takes
fast-path tail emit; cursor advances; lag stays at 0. The new
R2 test pre-seeds substrate (head advances without triggering
drive), then a single trigger NotifyAppend invokes drive() →
CASE A scan whose first emit's updateLag observes lag ≈ 1000 ≥
threshold 500 → OnSaturation fires single-shot. Same INV pinned;
different reach.
5× full cross-package sweep (transport / recovery / replication /
storage) all green — no flakes observed.
Out of scope (slice 2):
- Flip LegacyOutOfOrderEmit default to false (§6.3 normative).
- Migrate skipped tests to §6.3 contracts (or retire them).
- Address the concurrent-pusher race semantics surfaced in
AtomicSeal/Pillar2B at the design level — likely a per-LBA
write barrier on the dual-lane path is the right answer; needs
architect call.
- OpenWALScan stateful iterator (§12.4 #8).
Refs: v3-recovery-algorithm-consensus.md §6.3 send(input,debt) +
§6.9 HOPE-SHIPPER-MONOTONIC + §13 ModeRealtime alignment + §6.10
INV-RECV-* (receiver-side, already landed in 055fd46).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
smartwal isn't in core/storage/contract_test.go's implementation
matrix (intentional — the experimental subpackage stays
self-contained per its own test header), so the §6.10 BASE bypass
contract was unverified at the smartwal-named level after
055fd46. This test mirrors TestContract_WriteExtentDirect against
the smartwal substrate directly.
Asserts:
- WriteExtentDirect succeeds, Read returns bytes (smartwal reads
always pull from extent — the ring is not consulted)
- Frontier (H, nextLSN) NOT advanced (BASE has no LSN; ring NOT
touched)
- Subsequent ApplyEntry shadows correctly via writeAt's normal
extent overwrite + ring append
- Substrate-level: WriteExtentDirect after ApplyEntry IS allowed
to overwrite — pins that bitmap arbitration is the receiver's
job, not the substrate's. Prevents a future "let's silently
dedupe at substrate" change from quietly subverting §6.10.
Refs: v3-recovery-algorithm-consensus.md §6.10 (INV-RECV-BITMAP-CORE);
mini-plan §11.8 receipt for 055fd46; closes the smartwal coverage
gap noted in the SW status report.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
§6.10 BASE bypass (commit 055fd46) made base lane fast enough that
the original Pillar 2 C wire-abort test became race-prone:
sometimes the entire session — base + WAL + barrier round-trip —
completed before the test's "close every accepted conn" code path
fired, leading to Success=true when the test expected Success=false.
Reproduced as ~3/20 fail rate after the §6.10 change.
Switch the failure mechanism from "close conn mid-session" (timing-
dependent) to faulty-read substrate (deterministic): the same
faultyReadStorePillar2 used by Pillar 2 A. Read fails after 4
successful base-block reads → streamBase returns Substrate failure →
bridge onClose → OnSessionClose with Success=false. No wire timing
involved.
The semantic claim of the test is unchanged: prove that a session
which fails on the failure path triggers rule-2 emit-context restore.
Pre-session SnapshotEmitContext returns (nil, zero, SteadyMsgShip)
on a fresh replica; post-session snapshot must equal pre-session.
That assertion is preserved.
What's no longer in scope here:
- Mid-session network drop / replica crash specifically — this
test no longer claims to exercise that path. Future "real
network drop" coverage would need a controllable wire-fault
listener (test-infra follow-up); slice-1 deferred wire-tap
helper covers the same cost-of-test-infra slice.
Stability: 20 consecutive runs of TestPillar2C alone, 5 consecutive
full-transport-suite runs, all green post-fix.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Implements consensus §6.10 (INV-RECV-BITMAP-CORE / INV-RECV-WAL-NAIVE):
BASE lane writes go directly to extent, bypassing the LSN-tracked WAL
apply path entirely. The receiver's per-session bitmap is the sole
arbiter of BASE-vs-WAL conflict at this LBA; substrate stale-skip is
irrelevant for BASE because BASE never enters the WAL.
Substrate contract delta (LogicalStorage):
+ WriteExtentDirect(lba uint32, data []byte) error
Writes one block's bytes to the substrate's extent. No LSN. No
frontier (R/S/H) advancement. Substrate stale-skip / WAL apply
machinery NOT invoked. Receiver pairs with AdvanceFrontier in
MarkBaseComplete to keep post-rebuild frontier reporting honest.
Implementations:
- BlockStore — write to in-memory blocks map; nextLSN/walHead
untouched.
- memorywal — append a record with LSN=0 sentinel; no
retention/nextLSN advance. Receiver bitmap
discipline keeps semantics correct (BASE only
reaches substrate when WAL hasn't touched LBA).
- WALStore — wraps existing private writeExtent; pwrites to
extent file, no WAL append, no dirty-map entry.
- smartwal.Store — pwrites directly to extent at lba's offset; ring
NOT touched, no LSN/frontier advance.
RebuildSession changes:
- ApplyBaseBlock now calls store.WriteExtentDirect(lba, data) instead
of store.ApplyEntry(lba, data, targetLSN). The targetLSN-as-base-LSN
POC compromise (which silently rode substrate stale-skip) is gone.
- MarkBaseComplete now calls store.AdvanceFrontier(targetLSN) — the
explicit frontier-advance that ApplyEntry's side effect previously
provided implicitly. Pre-§6.10, BASE applies bumped walHead per
LBA; now we make the bump explicit at base-done.
Contract test (TestContract_WriteExtentDirect): pins
- WriteExtentDirect succeeds and Read returns the bytes
- Frontier (H) and nextLSN MUST NOT advance (BASE has no LSN)
- Subsequent ApplyEntry at LSN > 0 shadows the BASE bytes
runs against BlockStore-mem / WALStore / MemoryWAL.
Refs: v3-recovery-algorithm-consensus.md §6.10 (INV-RECV-BITMAP-CORE,
INV-RECV-WAL-NAIVE); §6.3 cursor-monotonic sender invariant; mini-plan
§12 design-candidate doc-track.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>