Commit Graph
49 Commits
Author SHA1 Message Date
pingqiuandClaude Opus 5.5 314b79bff1 volume: a probe dispatch acts only for the peer it was admitted for
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>
2026-11-25 10:33:10 -08:00
pingqiuandClaude Opus 5.5 88a03a40bb component: the apply-failure recovery test follows deferred priming
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>
2026-11-25 10:33:10 -08:00
pingqiuandClaude Opus 5.5 58b3c02386 replication: learn new peers' stores outside the volume lock; convergence test
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>
2026-11-25 06:53:38 -08:00
pingqiuandClaude Opus 5.5 5bf6e17ab1 replication, master, volume: count a peer only with the master-recorded store
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>
2026-11-25 06:43:45 -08:00
pingqiuandClaude Opus 5.5 5d315bcf5d replication: tests for the write-ACK count of an unacknowledged store
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>
2026-11-25 06:18:03 -08:00
pingqiu 731f278542 storage: fail rebuild snapshots on read faults and preserve RMW fencing 2026-11-19 16:03:15 -08:00
pingqiu 80ba50dfd2 test(replication): pin WAL across both two-replica catch-up sessions 2026-11-18 07:22:56 -08:00
pingqiu 731b1118eb test(replication): retain WAL for both RF2 catch-up sessions across checkpoint 2026-11-18 04:23:00 -08:00
pingqiu a81bca4926 feat(storage): activate mapped v3 through the production storage callers 2026-11-18 03:49:47 -08:00
pingqiu ddcc379470 test: assert durable global Sync frontier and retain replay fixture WAL 2026-11-16 15:50:40 -08:00
pingqiuandClaude Opus 5.5 48db2739ec ci: add a test workflow (build, vet, go test -short) and harden dead-port tests
- .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>
2026-11-16 11:47:44 -08:00
pingqiuandClaude Opus 5.5 78f56c31d8 test: release the stale-BASE hold with a defer, before executor shutdown
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>
2026-11-15 16:07:23 -08:00
pingqiuandClaude Opus 5.5 02fb0914b4 test: Pillar3 SameLBAArbitration holds a stale BASE frame instead of a pre-barrier hook
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>
2026-11-15 15:57:37 -08:00
pingqiuandClaude Opus 5.5 16f22e903a test: make Pillar3 SameLBAArbitration deterministic with a pre-barrier hold
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>
2026-11-15 15:48:26 -08:00
pingqiuandClaude Opus 5.5 26fd85069d component: accept every push outcome the production caller treats as non-failure
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>
2026-11-15 10:42:43 -08:00
pingqiuandClaude Opus 5.5 57f0359f8a component: the push-live-during-rebuild test accepts a session that already sealed or closed
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>
2026-11-15 10:38:27 -08:00
Ping QiuandClaude Opus 5.5 cd1555b705 transport: close the replica connection when ApplyEntry fails (#93)
* 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>
2026-11-15 02:10:50 -08:00
pingqiu 45b21313b4 replication: close executor lifecycle before store teardown 2026-07-30 03:33:05 -07:00
pingqiu 080b80e25f test: synchronize restart catch-up admission probe 2026-07-30 01:59:37 -07:00
pingqiuandClaude Opus 4.7 6a5d54678c docs(core): drop internal phase/gate prefixes from production comments
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>
2026-05-03 16:05:49 -07:00
pingqiu f476817e34 G9C: pin replica ready after post-close ack in dual-lane component path 2026-05-02 19:56:23 -07:00
pingqiu 13f168f592 test(g9a): prove best-effort still recovers lagging peer 2026-05-02 18:38:18 -07:00
pingqiu b3f4bbcd80 test(g8): pin failover authority fence and data continuity prelude 2026-05-02 14:53:15 -07:00
pingqiu 0a08b9238c adapter: expose flow control diagnostics 2026-05-02 12:31:22 -07:00
pingqiu 75f748b079 component: observe flow control from storage boundaries 2026-05-02 12:28:28 -07:00
pingqiu a1618330cc transport: route replica lane by connection context 2026-05-02 00:49:45 -07:00
pingqiu 0648f3b3ab test(replication): wait live-ready before component bridge pushes 2026-05-02 00:04:29 -07:00
pingqiuandClaude Opus 4.7 c0c84036be test(component): pillar 3 slice-2 — same-LBA arbitration on engine-driven path
Mirrors slice-1 (transport-stack only, cf232f2 + 39d57f2) onto the
full engine-driven path: component.Cluster + DriveAssignment +
DriveProbeResult dispatches StartRebuild via the engine command
flow, BlockExecutor + PrimaryBridge + RecoverySink + Sender +
WalShipper execute it, SessionStartResult / SessionCloseResult flow
back through the adapter as Trace events.

Single subtest in core/replication/component/dual_lane_engine_test.go:

  TestPillar3Slice2_EngineDriven_SameLBAArbitration
    - Seed 12 LBAs via PrimaryWriteN (pattern A).
    - DriveAssignment + DriveProbeResult → engine emits StartRebuild.
    - Live-overwrite LBA {3, 5, 7} via PrimaryWrite + bridge.PushLive
      Write (pattern B, LSN > seedN, RouteSessionLane verified).
    - Wait for StartRebuild + SessionClosedCompleted in adapter Trace.
    - Assert replica == primary on every seeded LBA, with the
      discriminating direction on overwritten LBAs (must hold B).

What slice-2 newly proves over slice-1:
  - Full adapter→engine→executor→bridge dispatch is exercised
    (slice-1 calls executor.StartRebuild directly; slice-2 lets
    the engine's command/event loop drive it).
  - SessionStartResult / SessionCloseResult callbacks close the
    command-event loop back to the engine — observable via
    SessionClosedCompleted in adapter.Trace.

Out of scope (slice-2):
  - RF > 1.
  - §IV T2 closure (architect-open).
  - Wire-level frame tap.
  - Long-duration soak.

10× stability check locally; cross-package sweep (transport /
recovery / replication) all green.

Refs: v3-recovery-wal-shipper-mini-plan.md §11.7 pillar 3.
Companion to 11392ba / eb4071e / cc457c0 / ceac3bf / cf232f2 /
39d57f2.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 11:53:33 -07:00
pingqiuandClaude Opus 4.7 eb4071ed05 fix(test): align component cluster harness to replica-%d (Phase 0 prerequisite)
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>
2026-04-30 10:57:09 -07:00
pingqiu 843188bd6d review-fix: T4a Realtime sequence guard + drainOpportunity TOCTOU
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).
2026-04-30 09:31:26 -07:00
pingqiuandClaude Opus 4.7 ad7bc74d3a P2d: WalShipper-routed dual-lane rebuild + per-connection wire format
Architect ratification (2026-04-30 §10): dual-lane port emits recovery
frameWALEntry; legacy port keeps MsgShipEntry. Single resident
WalShipper per (volume, replicaID); per-connection format selected by
emit profile on walShipperEntry, switched by recovery session brackets.

Changes:

  recovery: export WriteWALEntryFrame(w, kind, lba, lsn, data) — public
    helper for transport-side EmitFunc to write the dual-lane WAL frame
    format. Wraps internal writeFrame + encodeWALEntry.

  transport.WalShipper: EmitFunc signature gains EmitKind parameter.
    NotifyAppend Realtime path passes EmitKindLive; DrainBacklog scan
    passes EmitKindBacklog. Allows EmitFunc to choose WALKindBacklog
    vs WALKindSessionLive on the dual-lane wire.

  transport.BlockExecutor:
    + EmitProfile { SteadyMsgShip, DualLaneWALFrame }
    + walShipperEntry.emitProfile field (atomic with conn + lineage)
    + EmitFunc dispatches on profile + kind:
        SteadyMsgShip + any kind → MsgShipEntry (SWRP envelope +
          EncodeShipEntry)
        DualLaneWALFrame + Live → frameWALEntry(WALKindSessionLive)
        DualLaneWALFrame + Backlog → frameWALEntry(WALKindBacklog)
    + EmitFunc treats nil conn as silent drop (matches Idle-mode
      semantics; avoids racing against session-bracket installation
      when callers inject live writes via PushLiveWrite during the
      WalShipperFor → sink.StartSession window)
    - updateWalShipperEmitContext takes profile param
    - SnapshotEmitContext returns profile too
    - Ship() passes EmitProfileSteadyMsgShip to preserve legacy wire

  transport.RecoverySink:
    + NewRecoverySinkWithProfiles for explicit profile control
    + sessionProfile / steadyProfile fields
    + StartSession installs session profile (default: DualLaneWALFrame)
    + EndSession seals the sink (sealed=true under sealMu) FIRST, then
      restores steady context. Matches senderBacklogSink.flushAndSeal
      contract — post-EndSession NotifyAppend returns ErrSinkSealed
      (clean "session is closing" signal during the window between
      session-end and bridge-map-removal).

  transport.startRebuildDualLane (production hot path):
    - Snapshots steady (conn, lineage, profile) before constructing sink
    - Builds RecoverySink with session profile=DualLaneWALFrame
    - Calls bridge.StartRebuildSessionWithSink (replaces
      StartRebuildSession with bridging sink)
    Result: WalShipper handles both backlog drain (DrainBacklog) and
    live writes (NotifyAppend) during the session, on the dual-lane
    port, in recovery wire format. EndSession restores steady context
    (legacy port + MsgShipEntry).

Tests:
  + TestP2d_EmitDispatch_SteadyMsgShipProfile — wire bytes start with
    SWRP magic + msgType=MsgShipEntry.
  + TestP2d_EmitDispatch_DualLaneWALFrameProfile_LiveKind — wire
    bytes are recovery frame format with WALKindSessionLive tag.
  + TestP2d_EmitDispatch_DualLaneWALFrameProfile_BacklogKind —
    DrainBacklog scan emits with WALKindBacklog tag.
  + TestRecoverySink_NotifyAppendAfterEndSession_Sealed — post-
    EndSession NotifyAppend returns ErrSinkSealed.

Existing E2E coverage (now routed through WalShipper):
  - TestDualLane_BlockExecutor_StartRebuild — byte-equal post-rebuild
    (profile dispatch correct → receiver decodes → bytes land).
  - TestDualLane_LiveWritesDuringSession_AtomicSeal — 40 concurrent
    pushes, all byte-equal on replica.
  - TestDualLane_EngineDrivenRebuild_HappyPath +
    TestDualLane_EngineDrivenRebuild_WithPushLiveDuringSession
    (component-level engine→adapter→executor→bridge full chain).

Cluster gains BlockExecutor(replicaIdx) accessor for component tests
that exercise dual-lane bridge surfaces.

go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS, no regressions.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 01:13:48 -07:00
Ping Qiu 5b64dfd3c5 recovery: WAL recycle gate consumes MinPin (priority 2.5) (#14)
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.
2026-04-29 16:23:37 -07:00
Ping QiuandClaude Opus 4.7 d8b30f5956 G7-redo wiring: cmd flag + replication factory + transport + component fixture (dual-lane reachable from binary) (#13)
* 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>
2026-04-29 16:23:07 -07:00
pingqiu ca04592639 G5-5C #7: per-peer adapter wiring (production fix for hardware-revealed gap)
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.
2026-04-27 18:09:00 -07:00
pingqiu 8d813f6ca1 G5-5C #6: end-to-end restart-catch-up component test + StopHard listener
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.
2026-04-27 17:25:22 -07:00
pingqiuandClaude Opus 4.7 2d86f3ba5b G5-1 QA scenarios: 2 distinct-from-sw component tests + 1 known-gap skip
Per architect round-49 G5 v0.3 ratification: G5-1 cleared to start
immediately (no architect dependency; component framework binds T4d-4
part B WithEngineDrivenRecovery directly).

Background: T4d catalogue had 9 scenarios; sw absorbed most into batch
test files (apply_gate_scenarios_test.go, t4d3_scenarios_test.go,
t4d4_engine_driven_test.go, t4d4_full_l2_matrix_test.go,
stale_entry_adversarial_test.go, frontier_regression_test.go). Real
QA distinct-value scenarios remaining:

PASSING:
  - TestG5_QA_LifecycleStop_DuringActiveCatchUp_NoHandleLeak (matrix)
    Adversarial timing: sever mid-catch-up; verify substrate handle
    survives + remains functional. Pins INV-REPL-LIFECYCLE-HANDLE-
    BORROWED-001 (BUG-005 non-repeat) under timing pressure.
    Not covered by sw's batch tests.
  - TestG5_QA_RF2_BothReplicasReachByteEqual (matrix)
    G5 multi-replica fan-out scope: 2 replicas catch up independently
    and both converge byte-exact with primary. Sw covers single-
    replica; this verifies multi-replica independence.

SKIPPED (known framework gap):
  - TestG5_QA_LaneDiscipline_LiveAndRecoveryConcurrent_MultiReplica
    Live-ship + concurrent CatchUp share sessionID=1; receiver rejects
    second session as "stale ship session=1". Same gap as T4c §I
    cross-orchestration carry + CARRY-T4D-LANE-CONTEXT-001 territory.
    When framework gains per-call session minting, scenario unblocks.
    Gate API itself pinned by sw's TestComponent_LanePurity_
    CallerControlsDispatch — durable fence; composition test waits.

Framework workarounds (per T4d catalogue §7 missing primitives):
  - WithBlockGeometry(256, 4096) for scenarios touching LBA > 64
  - replicasFirstNLBAsEqual local helper instead of
    AssertNoPerLBARegression
  - Single catch-up per replica per test (avoids sessionID=1 collision)

22 packages green; full component package smoke passes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 15:58:43 -07:00
pingqiuandClaude Opus 4.7 4d73c3978e T4d-4 part C: full L2 matrix + 2 engine bug fixes (HARD GATE #3)
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>
2026-04-25 23:36:47 -07:00
pingqiuandClaude Opus 4.7 028ea64fc6 T4d-4 part B: engine-driven recovery wiring + rebuild-on-exhaustion + G5-DECISION-001 serializability
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>
2026-04-25 23:05:00 -07:00
pingqiuandClaude Opus 4.7 e8aec8b954 T4d-4 part A: RecoveryMode interface method + Stop lifecycle (BUG-005 non-repeat) + framework wrap fix
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>
2026-04-25 22:40:04 -07:00
pingqiuandClaude Opus 4.7 3351a66ff2 T4d-3: R+1 threading + import-discipline fence (G-1 v0.2 PORT items 1-5; CARRY-T4D-LANE-CONTEXT-001 Option B)
Per T4d mini-plan v0.3 §2.3 + G-1 v0.2 (architect+QA-signed
2026-04-25). Refs G-1 sign: pending hash (G-1 doc lives in
seaweedfs sw-block/design/v3-phase-15-t4d-3-g1-v2-read.md v0.2);
QA approval round-46 cleared T4d-3 start.

PORT items landed (G-1 v0.2 §3, items 1-5):

Item 1 — start boundary: engine.StartCatchUp gains FromLSN field;
engine emits Recovery.R + 1 (decide path + retry-loop re-emit).
Pinned by INV-REPL-CATCHUP-FROMLSN-IS-REPLICA-FLUSHED-PLUS-1 +
INV-REPL-CATCHUP-FROMLSN-FROM-ENGINE-STATE-NOT-PROBE.

Item 2 — per-call deadline: preserved unchanged (T4c-2 INV-REPL-
CATCHUP-DEADLINE-PER-CALL-SCOPE forward-carries).

Item 3 — last-sent monotonic + completion: preserved unchanged
(T4c-2 invariants forward-carry; barrier ack remains completion
truth).

Item 4 — retry budget: engine retry-loop reuses ORIGINAL Recovery.R
+ 1 on re-emit per G-1 §6.2 architect Option A (no inter-attempt
re-probe; apply gate handles over-ship). Pinned by
TestT4d3_CatchUp_RetryReusesOriginalRPlus1.

Item 5 — retention-miss escalation: T4d-1 typed-kind contract
already in place; engine branches on FailureKind. Forward-carry.

V3-NATIVE items (no V2 source per G-1 v0.2 §4):
- Engine-owned retry loop (Q1) — already in place at T4c-3
- Unified recovery command model — T4c-pre-B
- Lane-aware apply gate integration — T4d-2
- BarrierResponse.AchievedLSN as completion truth — T4c-2
- Package-boundary discipline — pinned by new
  TestT4d3_Catchup_TransportNeverImportsSubstrateInternals
  (parses transport .go files via go/parser; fails if any
  substrate-internal package import surfaces)

Signature ripple (10 files):
- engine.StartCatchUp{FromLSN uint64} added (no removals)
- adapter.CommandExecutor.StartCatchUp interface +1 param
- transport.BlockExecutor.StartCatchUp + doCatchUp +1 param
- 4 test executor stubs (mockExecutor, closureExecutor,
  policyClosureExecutor, restartExecutor) + production
  HealthyPathExecutor + noopExecutor + ops nopExecutor
- transport.recovery_session.go bridge passes fromLSN=1 (legacy
  StartRecoverySession path; forward-carry to T4e for explicit
  fromLSN field on StartRecovery)
- adapter.adapter_test.go bridge passes fromLSN=1
- 5 transport test call sites + 3 component integration test sites
- component framework CatchUpReplica helper passes fromLSN=1
  (transitional shim; tests needing explicit R+1 use direct
  executor invocation per G-1 §7)

NEW TESTS (G-1 §7 test parity matrix):
- core/engine/t4d3_rplus1_test.go (3 tests):
  - TestT4d3_CatchUp_Engine_RPlus1_FromOwnState_NotProbeDirectly
    (pins INV-REPL-CATCHUP-FROMLSN-FROM-ENGINE-STATE-NOT-PROBE)
  - TestT4d3_CatchUp_RetryReusesOriginalRPlus1 (G-1 §6.2 Option A)
  - TestT4d3_StartCatchUpStruct_HasFromLSNField (compile fence)
- core/transport/t4d3_rplus1_test.go (3 tests):
  - TestT4d3_CatchUp_ScansFromReplicaR_NotGenesis (substrate
    receives caller-supplied fromLSN; sender does NOT add +1)
  - TestT4d3_CatchUp_StartCatchUpSignature_FromLSNRequired
  - TestT4d3_CatchUp_NonEmptyReplica_BlockStoreOverShipsExpected
    (round-46 ADDITION 2 substrate-bound naming — opposing-
    assertion regression fence per §9 caveat)
- core/transport/import_discipline_test.go (1 test):
  - TestT4d3_Catchup_TransportNeverImportsSubstrateInternals
    (Q3 INV-REPL-TRANSPORT-STORAGE-CONTRACT-ONLY; parses transport
    sources, fails on substrate-internal imports)
- core/replication/component/t4d3_scenarios_test.go (4 tests):
  - TestT4d3_CatchUp_NonEmptyReplica_ShortGap_BandwidthBounded_
    Walstore (substrate-bound bandwidth observation)
  - TestT4d3_CatchUp_NonEmptyReplica_ShortGap_BandwidthBounded_
    Smartwal (mirror)
  - TestT4d3_RetryAfterReplicaAdvanced_OverScansHandledByApplyGate
    (round-46 ADDITION 1 — pins §6.2 Option A safety claim:
    over-scan + apply gate per-LBA stale-skip; assertions cover
    byte-exact convergence + no per-LBA regression + coverage
    union completeness)
  - TestT4d3_RecoveryTargetLSN1_KnownGap (CARRY-T4D-LANE-CONTEXT-
    001 Option B close — SKIPPED with explicit forward-binding
    for the T4e or beyond fix; gate API itself is already
    lane-pure, only caller's signal source needs upgrading)

CARRY-T4D-LANE-CONTEXT-001 close (round-46 architect HARD CLOSE
CONDITION): Option B chosen (NOT Option A) because true handler/
session-context lane signal is a much larger refactor (separate
listener ports OR per-connection lane tag via session-registration
handshake OR new MessageType — all wire/transport-architectural
changes). Architect listed Option B as acceptable. The skip-marked
test documents the H=1 known gap; godoc cites
CARRY-T4D-LANE-CONTEXT-001 explicitly for catalogue cross-reference.

NOT in T4d-3 scope (deferred):
- Engine-driven recovery wiring through ReplicationVolume↔adapter
  (G-1 §4 Item A integration scope) — engine retry-loop is
  unit-tested; full ReplicationVolume↔adapter binding is a
  follow-up task. Rationale: this commit is large enough; landing
  the R+1 threading + import discipline as one piece + adding
  end-to-end engine-driven recovery wiring as another keeps
  reviewability tractable. T4d-4 owns the lifecycle integration;
  the engine-driven-recovery wiring fits naturally there OR as a
  T4d-3-followup.

Forward-carry status:
- T4d-1 typed-kind contract: forward-carries unchanged
- T4d-2 lane-pure apply gate: forward-carries; round-46 lane
  discipline still honored (gate doesn't sniff lineage)
- All round-43/44 stale-skip invariants: forward-carry green
- T4c-2 6 catch-up invariants: forward-carry under R+1 threading
  (verified via T4c muscle tests still passing)
- 22 packages green; 0 failures

Tests added: 11 (per G-1 §7 matrix).

Refs: T4d mini-plan v0.3 §2.3 (architect-ratified); G-1 v0.2
QA-signed (CARRY-T4D-LANE-CONTEXT-001 close condition Option B);
round-46 architect ruling (lane-pure gate); kickoff §9 (Q1/Q2/Q3).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 22:10:44 -07:00
pingqiuandClaude Opus 4.7 c0cccb0947 T4d-2 follow-up: lane-pure gate API (round-46 architect rework)
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>
2026-04-25 21:32:27 -07:00
pingqiuandClaude Opus 4.7 1a6c508226 T4d-2: replica recovery apply gate (lane-aware, 2-map split, Option C hybrid)
Per T4d mini-plan v0.3 §2.2 (architect-ratified). Round-43 lock +
round-44 refinement: lane-aware per-LBA stale-skip with coverage-
advance on skip; live-lane stale fail-loud; 2-map split. The
correctness boundary for "no per-LBA data regression."

NEW core/replication/apply_gate.go:
- ReplicaApplyGate component + per-session state (applyGateSession
  with appliedLSN + liveTouched + recoveryCovered maps)
- Apply(lineage, lba, data, lsn) routes by lane (Q2: lane derived
  from lineage.TargetLSN signal — > liveShipTargetLSN = recovery;
  == liveShipTargetLSN = live; no wire byte added)
- applyRecovery: if lsn <= appliedLSN[lba] → skip data + advance
  recoveryCovered (round-44 #1); else apply + update both maps
- applyLive: if lsn <= appliedLSN[lba] → return error (round-44 #2
  INV-REPL-LIVE-LANE-STALE-FAILS-LOUD); else apply + update
  appliedLSN + liveTouched ONLY (NOT recoveryCovered)
- initSessionLocked: queries store.AppliedLSNs() at session init
  (Option C hybrid per kickoff §2.5 #1); falls back to empty map
  on ErrAppliedLSNsNotTracked (BlockStore) with INFO log
- SessionState / SessionRecoveryCoverage / SessionAppliedLSN —
  read-only inspection helpers for tests + ops

Pinned invariants (T4d mini-plan §4 #6):
- INV-REPL-NO-PER-LBA-DATA-REGRESSION (goal-level)
- INV-REPL-RECOVERY-STALE-ENTRY-SKIP-PER-LBA (mechanism)
- INV-REPL-RECOVERY-COVERAGE-ADVANCES-ON-SKIP (round-44)
- INV-REPL-LIVE-LANE-STALE-FAILS-LOUD (round-44)
- INV-REPL-RECOVERY-COVERAGE-RESTART-SAFE (Option C makes pinnable)
- INV-REPL-LANE-DERIVED-FROM-HANDLER-CONTEXT (Q2)

Transport wiring (core/transport/replica.go):
- New transport.ApplyHook interface (Apply method); duck-typed adapter
  so replication.ReplicaApplyGate satisfies it without an import
  cycle (replication already imports transport)
- New NewReplicaListenerWithApplyHook constructor; existing
  NewReplicaListener delegates with hook=nil (preserves T4a/T4b/T4c
  behavior — direct apply when no gate installed)
- MsgShipEntry handler: if hook installed, delegate; live-lane
  fail-loud error → log + drop conn (round-44 #2)

Component framework wiring (core/replication/component/cluster.go):
- WithApplyGate() builder option installs the gate on every replica's
  listener
- ReplicaNode gains ApplyGate field
- Cluster.ApplyGate(idx) accessor for tests asserting per-session
  gate state

Tests (16 new):
- core/replication/apply_gate_test.go (13 unit tests on the gate):
  lane discriminator (5 cases), recovery stale-skip data + coverage
  advance, fresh apply advances both, live stale fail-loud,
  live stale doesn't advance recoveryCovered, lane independence
  across distinct sessions, Option C BlockStore fallback,
  Option C substrate-seed honored, restart-mid-recovery (BlockStore
  documented limitation), restart-safe via substrate seed (full
  Option C path), substrate apply error propagates, CloseSession
  releases state
- core/replication/component/apply_gate_scenarios_test.go (4
  integration scenarios): RecoveryStaleSkip_CoverageStillAdvances
  (round-44 #1), LiveLaneStaleEntry_FailsLoud (round-44 #2),
  LaneDerivedFromTargetLSN (Q2), OptionCHybrid_WalstoreSeed
  (substrate-seed integration)
- core/replication/component/stale_entry_adversarial_test.go:
  TestComponent_Adversarial_StaleEntryDoesNotRegress UN-SKIPPED
  (round-46) — now uses cluster.WithApplyGate(); pin
  INV-REPL-RECOVERY-STALE-ENTRY-SKIP-PER-LBA at integration scope

Forward-carry status (preserved):
- All T4a/T4b/T4c invariants forward-carry green
- T4d-1 typed-kind contract unaffected (gate orthogonal to failure
  classification)
- T4c apply path unchanged when WithApplyGate not requested

NOT in T4d-2 scope (deferred per mini-plan §1.2):
- Engine-driven full-flow integration (T4d-3 wires
  ReplicationVolume↔adapter; T4d-2's WithEngineDrivenRecovery hook
  remains stub)
- Substrate-side stale-skip in walstore/smartwal ApplyEntry (T4d-1
  caveat: where practical; gate is the authoritative correctness
  boundary)

22 packages green; 16 new tests; 1 previously-skipped test now
PASSING.

Refs: T4d mini-plan v0.3 §2.2 (architect-ratified 2026-04-25);
kickoff §9 Q1/Q2/Q3; round-43/44 architect text; round-46 QA
approval clearing T4d-2 start.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 19:57:44 -07:00
pingqiuandClaude Opus 4.7 dea8481bb6 BlockStore: gate walHead update on lsn > walHead (round-43 substrate hardening, defense-in-depth)
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>
2026-04-25 15:52:39 -07:00
pingqiuandClaude Opus 4.7 360e540c76 component: round-43 architect sign — fix shape inscribed (recovery apply gate)
Architect round-43 signed the T4d fix shape:

  T4d stale-entry safety belongs at the REPLICA RECOVERY APPLY
  GATE (a NEW component, lane-aware), with substrate fixes as
  defense-in-depth. The invariant is about NO PER-LBA DATA
  REGRESSION, not just frontier monotonicity.

The gate is lane-aware:

  live lane:
    use existing lineage/session/live-order rules
    do not use recovery stale-skip; do not update recovery coverage

  recovery lane:
    always update recovery accounting / coverage
    if entry.LSN <= perLBAAppliedLSN[LBA]:
        skip data write
    else:
        ApplyEntry(...)
        update perLBAAppliedLSN[LBA] = entry.LSN

perLBAAppliedLSN source: from storage if exposed cleanly; else
session-local map seeded from recovery/live applies. Pre-existing
state correctness eventually requires substrate to expose per-LBA
applied LSN metadata.

T4d task list (round-43 final):

  1. PRIMARY FIX — replica recovery apply gate (new component)
     - Lane-aware (live vs recovery)
     - Per-LBA applied LSN tracking
     - Recovery: skip data write on stale; always update accounting
     - Live: passes through unchanged
  2. DEFENSE-IN-DEPTH — substrate hardening:
     - BlockStore.ApplyEntry: gate walHead = lsn on lsn > walHead
     - walstore + smartwal: substrate-level stale-protection or
       per-LBA applied LSN exposure
  3. 5 adversarial tests un-skipped + extended (architect set +
     QA refinement set, unchanged from round-42)

Files updated:
- stale_entry_adversarial_test.go: TestComponent_StaleEntrySkip_
  RuleStatement extended with round-43 gate shape (verbatim) +
  task list
- memory feedback_recovery_stale_entry_skip.md: round-43 fix
  shape + perLBAAppliedLSN source caveat + substrate triage table
- design memo v3-phase-15-t4c-architect-review-changelist.md §3:
  round-43 sign inscribed; substrate triage table replaces older
  per-substrate-action table

22 packages green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 15:31:17 -07:00
pingqiuandClaude Opus 4.7 357f286eae component: round-42 QA refinements — data-only skip + recovery-lane scope
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>
2026-04-25 15:12:32 -07:00
pingqiuandClaude Opus 4.7 d2d765a7f3 component: round-41 stale-entry invariant — frontier partial-pin + adversarial skip-tests
Architect round-41 corrected my earlier "frontier monotonicity is
sufficient" answer. Two real concerns surfaced + inscribed:

(1) Frontier-monotonicity tests are PARTIAL PINS only.
They cover benign full-replay shape (over-scan completes through
to the restoring entry). They do NOT prove safety under
INTERRUPTED replay where a stale entry overwrites newer state and
the conn dies before the restoring entry arrives. File header on
frontier_regression_test.go now says so explicitly.

(2) BlockStore.ApplyEntry sets walHead = lsn UNCONDITIONALLY.
Older-LSN apply regresses walHead, violating logical_storage.go §3
rule 3 ("stable frontier never goes backward"). My earlier "BlockStore
is idempotent" claim was wrong.

Architect rule (revised T4d blocker): pinLSN < replicaLSN is
LEGAL and EXPECTED (probe-time R can advance during recovery via
live lane / barrier / prior partial catch-up). Don't fight it;
make recovery apply stale-safe per LBA.

Required invariant — INV-REPL-RECOVERY-STALE-ENTRY-SKIP-PER-LBA:
  A replica MUST NOT apply a recovery-stream entry if that LBA is
  already known to contain data from an equal or higher LSN.

Substrate behavior verified at round-41:
- walstore: per-LSN scan emits BOTH old + new → vulnerable to
  interrupted-replay corruption (T4d must add per-LBA stale skip)
- smartwal: state-convergence emits scan-time LSN with current
  data → stale-safe by construction (current data only)
- BlockStore: walHead regresses on older-LSN apply → contract
  violation; T4d must gate walHead update on lsn > walHead

Files added:

stale_entry_adversarial_test.go (3 tests):
- TestComponent_Adversarial_StaleEntryDoesNotRegress (skipped
  with T4d TODO; expected to FAIL on walstore today; T4d
  un-skips when per-LBA stale skip lands)
- TestComponent_Adversarial_BlockStoreApplyEntryRegressesWalHead
  (skipped; pins the BlockStore bug for T4d fix)
- TestComponent_StaleEntrySkip_RuleStatement (always passes;
  godoc-style searchable inscription of the architect rule)

frontier_regression_test.go header updated:
- File-level "PARTIAL PIN" notice naming the limitation
- TestComponent_CatchupFromBelowReplicaLSN_NoFrontierRegression
  godoc clarifies "FULL successful replay" scope

Memory updated:
- feedback_recovery_stale_entry_skip.md captures the architect
  rule + required invariant + T4d blocker shape

T4d blocker list (round-41 revision):
1. Per-LBA applied LSN tracking at replica apply layer
2. Recovery apply skips entries whose LSN <= per-LBA applied LSN
3. BlockStore.ApplyEntry: gate walHead update on lsn > walHead
4. 3 adversarial tests un-skipped + extended:
   - same LBA old/new + sever before new → no regression
   - repeated recovery window → byte state stable
   - live races recovery old → live wins

go test ./... -count=1 → 22 packages green (adversarial tests
skipped with explicit T4d TODOs).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 15:08:50 -07:00
pingqiuandClaude Opus 4.7 1be3c134ba T4c QA Stage-1: 3 round-40 scenarios using gap-closure primitives
Round 40 follows up commit 370a0e8 (sw closed 3 of 4 framework gaps).
Adds 3 component-scope scenarios on top of the round-39 trio, bringing
T4c QA Stage-1 coverage to 6 scenarios / 11 matrix rows, all green.

New (round 40):
  BarrierAchievedLSN_PartialProgress_DistinctFromCompletion
    pins INV-REPL-CATCHUP-COMPLETION-FROM-BARRIER-ACHIEVED-LSN: a
    catch-up that ships some-but-not-all entries MUST surface as
    Success=false, distinct from a clean close at the same LSN, and
    MUST NOT be conflated with ErrWALRecycled (engine retry/rebuild
    branching depends on the sentinel distinction).

  DeadlinePerCallScope_NoSpilling
    pins INV-REPL-CATCHUP-DEADLINE-PER-CALL-SCOPE via two back-to-back
    live-ship batches on the same wire. Reframed from the original
    live-ship -> catch-up -> live-ship design after authoring revealed
    a session-ID conflict (live-ship and explicit CatchUpReplica claim
    sessionID=1 independently). Cross-orchestration form is forward-
    carried to T4d alongside WithEngineDrivenRecovery.

  LastSentMonotonic_WithinCall
    pins INV-REPL-CATCHUP-LASTSENT-MONOTONIC at the within-call layer
    using NewObservedScanWrap. Cross-call form (LastSentMonotonic_
    AcrossRetries) requires WithEngineDrivenRecovery (T4d-stubbed)
    so the engine drives multi-call retry with advancing fromLSN;
    today CatchUpReplica restarts at fromLSN=1 every call.

Authoring observation: original DeadlinePerCallScope design hit a
sessionID=1 collision between live-ship and explicit CatchUpReplica.
Surfaced as forward-carry; the in-wire deadline-scope pin survives
the reframing intact.

Cumulative: 6 T4c QA scenarios / 11 matrix rows / all green.
Stage-2 m01 carry-over: LastSentMonotonic_AcrossRetries (engine-loop
form) waits on WithEngineDrivenRecovery wiring at T4d.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 11:09:46 -07:00
pingqiuandClaude Opus 4.7 370a0e8de9 component framework: close 3 of 4 QA-flagged gaps; stub 4th for T4d
QA round-39 Stage 1 flagged 4 framework gaps blocking deferred
scenarios. This commit closes 3 of 4 with primitives + demos;
4th (engine-driven recovery) is API-stubbed pending T4d wiring.

Closed gaps:

(1) WithPrimaryStorageWrap(fn) builder option
- Cluster.WithPrimaryStorageWrap installs a substrate transform
  before BlockExecutors bind; wraps may override any LogicalStorage
  method. Three pre-built wraps in faults.go:
  - NewRecycledScanWrap()             — always returns ErrWALRecycled
  - NewSeverDuringScanWrap(N, err)    — emits N entries then severs
  - NewObservedScanWrap(*atomic.Int32) — counts emit observations
- Demos: TestComponent_RecycledScanWrap_EscalatesToRebuild,
  TestComponent_SeverDuringScan_PartialProgress,
  TestComponent_ObservedScanWrap_CountsEmits

(2) Live-ship primitive driving ReplicationVolume.OnLocalWrite
- Cluster.WithLiveShip() builder option spins up StorageBackend +
  ReplicationVolume; configured replicas auto-registered as peers
- PrimaryWriteViaBackend(lba, data) writes through the production
  data-plane entry → WriteObserver hook → fan-out to replicas
- PrimaryWriteViaBackendN(n) batch helper
- Demo: TestComponent_LiveShip_PrimaryWriteViaBackend_FansOut

(4) Mid-stream drop helper SeverDuringScan
- Implemented as NewSeverDuringScanWrap above; counts entries via
  atomic.Int32 inside the substrate wrap and returns the configured
  sever error after N successful emits
- Robust to substrates with fewer than N entries (no-op rather than
  fail-closed, so scenarios are emit-count-tolerant)

API-stubbed for T4d:

(3) WithEngineDrivenRecovery() — option records intent, emits a
one-shot t.Logf warning at Start, runs as direct-executor mode.
Forward-carry: when T4d wires ReplicationVolume↔adapter, this
option swaps the adapter-aware constructor in. Demo:
TestComponent_EngineDrivenRecovery_StubWarning pins the API
shape so scenarios authored today won't need to change when
behavior lands.

Known limitation documented in faults.go: substrate-extension
methods (e.g. walstore.CheckpointLSN) are MASKED by the wrap
because Go embedding only exposes interface methods. The catch-up
sender's recovery_mode label probe duck-types CheckpointLSN; under
a wrap, it always sees state_convergence regardless of underlying
substrate. Forward-carry: refactor mode-label detection behind a
substrate-reported RecoveryMode() method that wraps can forward.

5 new demos = 9 matrix rows (smartwal+walstore where applicable).
go test ./... -count=1 → 22 packages green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 11:01:43 -07:00
pingqiuandClaude Opus 4.7 6a3b84cd29 component test framework: cluster harness + 7 demo scenarios
QA-requested (round-39): build a component test framework so QA can
author T4c-follow-up + T4d scenarios in ~20-30 lines without
re-deriving cluster setup boilerplate.

Lands `core/replication/component/` package with:

- Cluster builder: NewCluster(t, factory).WithReplicas(n).Start()
  → fully wired primary + N replicas over real localhost TCP using
  production code paths (BlockStore + ReplicaListener + BlockExecutor)
- RunMatrix(t, scenario): runs the scenario across smartwal + walstore;
  both substrates gate per round-22 sign-bearing discipline
- RunSubstrate(t, name, factory, scenario): single-substrate runner
  for substrate-specific pins
- Write/sync primitives: PrimaryWrite, PrimaryWriteN, PrimarySync,
  ReplicaApply (for setting up pre-existing replica state)
- Recovery primitives: CatchUpReplica, ProbeReplica
- Fault injection: KillReplicaListener, SeverConnection
- Convergence assertions: WaitForConverge, AssertReplicaConverged
- Mode-label assertions: AssertSawRecoveryMode with ExpectAnyMode /
  ExpectWALReplay / ExpectStateConvergence constants
- Log capture: tees log.Default writer into per-test buffer so mode-
  label assertions don't need stderr parsing
- Mode-constant init-time pin: panics if ExpectWALReplay /
  ExpectStateConvergence drift from storage.RecoveryMode* values

7 demo scenarios in cluster_test.go double as smoke for the framework
+ copy-paste templates for QA:

- TestComponent_HappyCatchUp — simplest scenario shape
- TestComponent_GapExceedsRetention_Recycled — substrate fault wrap
  pattern (recycledScanStub demonstrates ScanLBAs override for
  ErrWALRecycled injection)
- TestComponent_ProbeHappy — probe wire smoke across substrates
- TestComponent_TwoReplicas_BothConverge — multi-replica fan-out
- TestComponent_PartialReplicaThenCatchUp — ReplicaApply for
  pre-existing partial state setup
- TestComponent_RecoveryModeLabel_Walstore — per-substrate label pin
  (wal_replay)
- TestComponent_RecoveryModeLabel_Smartwal — per-substrate label pin
  (state_convergence)
- TestComponent_ModeConstantsStable — drift fence

Authoring guide: sw-block/design/v3-phase-15-component-test-guide.md
documents the API + common patterns + extension discipline. Aim:
~20-30 lines per new scenario.

Forward-carry items (sw will add when needed):
- WithPrimaryStorageWrap(wrap) option — substrate fault injection at
  the executor layer (today the wrap pattern only works at the
  storage layer; substrate-level executor-test integration needs
  the option)
- WithEngineDrivenRecovery() option — when T4d lands the
  ReplicationVolume↔adapter wiring, the framework gains the engine-
  driven recovery flow as an opt-in mode

go test ./... -count=1 → all 22 packages green (component is the
new package).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 10:35:27 -07:00