Commit Graph
24 Commits
Author SHA1 Message Date
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