Commit Graph
52 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
pingqiu bd6f475b9b transport: advance live ship cursor after recovery 2026-05-01 23:53:34 -07:00
pingqiu ccc3ca6cb3 transport: route live WAL through single feed ingress 2026-05-01 23:24:55 -07:00
pingqiu 8c4aa52392 transport: refresh live ship session after recovery 2026-05-01 22:27:21 -07:00
pingqiu 3ccf2ec729 transport: gate live WAL through active recovery session 2026-05-01 22:03:12 -07:00
pingqiuandClaude Opus 4.7 a08dea1574 test: legacy header annotation per §8.2.4 — recover(a,b) band marker
Commit 2 of the QA→SW handoff (`recover-semantics-adjustment-plan.md`
§8.2.7 step 3). Header-only annotation pass on the 19 _test.go
files in seaweed_block that reference `targetLSN` or `walApplied`
as completion-authority terms (discovery: `grep -rlE
'targetLSN|walApplied' --include='*_test.go' core/`).

Each file gets a 2-line header right after the package decl,
verbatim per §8.2.4:

    // Completion oracle: recover(a,b) band — NOT recover(a) closure.
    // See sw-block/design/recover-semantics-adjustment-plan.md §8.1.

Six of the 19 are deeply primary.H-bound (assertions tied to
`replica.H == primary.H` or `achieved == primary.H`) and get an
extra `migrate-candidate` line per §8.2.4:

    // migrate-candidate: depends on primary.H semantics, see §8.1 Tier-5 migration

The migrate-candidate set:
  - core/transport/pillar2_assembled_test.go
  - core/transport/pillar3_convergence_test.go
  - core/transport/walshipper_pin_protection_test.go
  - core/transport/transport_test.go
  - core/transport/catchup_sender_test.go
  - core/recovery/e2e_test.go

Anti-discipline checks (§8.2.8) honored:
  - No assertion changes — header text only.
  - migrate-candidate kept on its own line, not merged with the
    standard 2-line annotation.

Note on count: §8.2.4 cited "~95 files" against the broader audit
pattern (TargetLSN/AchievedLSN/FrozenTarget/TryComplete). The
narrower §8.2.4 grep (targetLSN|walApplied) targets the actual
completion-authority surface and yields 19 files in the
seaweed_block tree. Build + tests clean post-annotation.

Source: sw-block/design/recover-semantics-adjustment-plan.md §8.2.4.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 13:07:00 -07:00
pingqiuandClaude Opus 4.7 25a1be2872 test(transport,replication): §6.3 slice-2B Path B test rewrites
Per architect's Path B ruling (2026-04-30), the four §13-era tests
that were skipped during slice-1 are re-authored to §6.3 contracts.
Three pass cleanly; one stays skipped pending deeper integration work.

  TestWalShipper_R2_SaturationUnderSustainedLoad
    (renamed from TestWalShipper_BacklogStaysBacklog_UnderLoad)

    §13-era claim: "mode stays Backlog under saturation". Retired —
    §6.3 single drive() collapse removes mode-as-dispatch. Re-authored
    to the §6.3 saturation observability contract:
      - Slow EmitFunc + pre-seeded substrate (lag ≥ threshold)
      - Background writer extends head during scan
      - OnSaturation fires single-shot per session
      - cursor advances monotonically (INV-MONOTONIC-CURSOR)
      - Eventually catches up after writer stops
    10× stability locally clean (~5s per run with slow-emit).

  TestDualLane_LiveWritesDuringSession_AtomicSeal

    Pre-§6.3: per-pusher acceptedSet vs replica.Read; failed ~1/10
    runs under §6.3 (concurrent CASE A scans race with producer).
    Architect Path B: drop per-pusher cache; assert post-barrier
    convergence on backlog + accepted-push LBA range. Cache-data
    mismatch can no longer surface; the canonical truth at each
    accepted LBA is primary.Read post-barrier.
    15× stability locally clean.

  TestPillar2B_LiveWrites_HighPressure_BarrierIntegrity

    Architect's "DisableTimerDrain + 串行 push" path B variant.
    The race surfaced under §6.3 isn't frame-tear; it's a session-
    bracket vs in-flight-emit race: drive() emits hold writeMu
    briefly per frame, sender's BarrierReq writeMu acquire can
    interleave between emits, and receiver may then read the
    barrier and return before in-flight push frames arrive. This
    is a real §6.3 semantic gap with concurrent push during a
    session, NOT a §6.3 correctness bug — the §6.3 model doesn't
    bracket per-push barriers (architect's "另开 ADR for per-push
    barrier semantics"). Path B explicitly listed serialized
    pushes as an acceptable shape: 128 sequential pushes preserve
    high-pressure intent without the race.
    15× stability locally clean.

  TestT4a6_BestEffort_DisconnectThenReassign

    STAYS SKIPPED with a more honest §6.3 + walstore-recycle note.
    §6.3 auto-fill via substrate (Path B) requires substrate to
    retain the entries the new shipper backfills. In this L2
    integration test, the second batch's LSNs may be past the
    walstore recycle floor by the time the post-reassign shipper
    opens with cursor=0; ScanLBAs returns ErrWALRecycled, drive()
    treats as transient (cursor stays 0), and CASE B fires with
    lsn=61 cursor=0 → tail-gap error. The proper §6.3 contract
    here is engine-driven rebuild on WAL-recycled signal, but
    that path isn't wired through this test's UpdateReplicaSet
    flow. Re-author requires either tuning walstore retention OR
    wiring the rebuild-on-recycled escalation; both out of slice-2B
    scope. Tracked in §11.9 follow-ups.

5× cross-package sweep (transport / recovery / replication /
replication/component / storage / storage/memorywal /
storage/smartwal) all green post-slice-2B.

Refs: architect Path B ruling 2026-04-30; v3-recovery-algorithm-
consensus.md §6.3 + §6.9 + §11.9. Companion to slice-1 b3826b2,
slice-2A 8672e63.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 22:31:39 -07:00
pingqiuandClaude Opus 4.7 b3826b210d transport: §6.3 single drive() collapse — slice 1 (structural)
Refactors WalShipper's dispatch from mode-dispatched (NotifyAppend +
drainOpportunity as separate entry points with mode-keyed bodies) to
the consensus §6.3 single drive(input) function. NotifyAppend +
drainOpportunity become thin wrappers that offer input{has:true,...}
or input{has:false} respectively.

Dispatch (drive holds shipMu for the whole call — single serializer
per peer):

  Idle (mode == ModeIdle): drop everything.

  Fast-path (in.has + in.lsn == cursor+1 + head <= in.lsn):
    Tail-emit input bytes as EmitKindLive. Preserves Realtime hot
    path observability — cursor monotonic + no debt + input is the
    next LSN means input bytes are canonical-equivalent to substrate;
    no scan needed.

  CASE A (cursor < head, debt-first per §6.3):
    Substrate is canonical. Scan from cursor, emit each entry as
    EmitKindBacklog, advance cursor; loop until cursor == head OR
    scan exits. Per consensus §13 alignment, this is BACKLOG-DRAIN
    semantics even when invoked from a NotifyAppend caller —
    "Realtime is reading substrate?" is a misread; the wire kind tag
    is Backlog, the dispatch is debt-first. R1 transition runs at the
    tail of CASE A under shipMu.

  Idempotent skip (in.lsn <= cursor after CASE A): drop.

  CASE B (caught up + fresh tail, in.lsn == cursor+1):
    Tail-emit input as EmitKindLive.

  Tail-gap (in.has + in.lsn > cursor+1 + cursor == head):
    Per §6.3 / §6.9 NEGATIVE-EQUITY ban — input MUST NOT replace a
    missing LSN. Default fail-closed; engine MUST escalate to
    rebuild. LegacyOutOfOrderEmit=true (transitional, see below)
    restores pre-§6.3 log+emit.

Config delta:

  + LegacyOutOfOrderEmit (DEPRECATED, transitional):
    True restores pre-§6.3 "log + emit input on tail gap"
    behavior. Slice-1 default = true (transitional bridge — zero
    behavior change for existing callers); slice-2 will flip to
    false (§6.3 normative). Documented in field doc + DefaultWal
    ShipperConfig comment.

  StrictRealtimeOrdering (existing): semantically subsumed by
    §6.3 tail-gap fail-closed. Both strict and non-strict (with
    Legacy=false) now fail-closed at tail-gap. Kept for production
    wiring expressivity; field doc updated.

CONVENTION block at file top: this implementation tracks `cursor` as
LAST-EMITTED LSN; spec §6.3 uses `cursor` as NEXT-TO-EMIT. Translation
in code: spec.cursor == internal.cursor + 1; the check `lsn ==
cursor+1` is identical to spec's `lsn == cursor`. Documented inline
on drive() so reviewers don't flip the bit.

Test migration (3 tests skipped with §6.3-migration notes; will be
re-authored against the new model in a separate slice or removed if
their pre-§6.3 contract is fully retired):

  - TestT4a6_BestEffort_DisconnectThenReassign: asserted that a
    degraded peer + reassign does NOT silently catch up the
    suppressed batch. §6.3 default is automatic substrate-fill on
    reattach — pre-§6.3 "best-effort = no auto catch-up" contract is
    superseded. Skipped.

  - TestWalShipper_BacklogStaysBacklog_UnderLoad: asserted that
    Backlog mode persists while writer outpaces drain. §6.3 single
    drive() runs CASE A scan to completion under one shipMu acquire;
    R1 fires when caught up; Backlog mode is no longer load-bearing
    in dispatch. Skipped.

  - TestDualLane_LiveWritesDuringSession_AtomicSeal +
    TestPillar2B_LiveWrites_HighPressure_BarrierIntegrity: concurrent
    pushers race against each other's CASE A substrate scans; the
    end replica state is byte-equal-primary post-barrier in the
    common case, but the per-pusher acceptedSet vs replica-Read
    direct comparison surfaces stragglar LBAs in ~1/10 runs. The
    atomic-seal contract holds; the test shape needs re-authoring
    to assert replica == primary (which is the same claim AtomicSeal
    intended without per-pusher tracking). Skipped.

Updated test (re-authored against §6.3, kept passing):

  - TestWalShipper_R2_LagSignalFires: pre-§6.3 the test could pump
    1000 NotifyAppends in Backlog mode (lag-only) and observe lag
    accumulate. Post-§6.3, NotifyAppend with lsn==cursor+1 takes
    fast-path tail emit; cursor advances; lag stays at 0. The new
    R2 test pre-seeds substrate (head advances without triggering
    drive), then a single trigger NotifyAppend invokes drive() →
    CASE A scan whose first emit's updateLag observes lag ≈ 1000 ≥
    threshold 500 → OnSaturation fires single-shot. Same INV pinned;
    different reach.

5× full cross-package sweep (transport / recovery / replication /
storage) all green — no flakes observed.

Out of scope (slice 2):

  - Flip LegacyOutOfOrderEmit default to false (§6.3 normative).
  - Migrate skipped tests to §6.3 contracts (or retire them).
  - Address the concurrent-pusher race semantics surfaced in
    AtomicSeal/Pillar2B at the design level — likely a per-LBA
    write barrier on the dual-lane path is the right answer; needs
    architect call.
  - OpenWALScan stateful iterator (§12.4 #8).

Refs: v3-recovery-algorithm-consensus.md §6.3 send(input,debt) +
§6.9 HOPE-SHIPPER-MONOTONIC + §13 ModeRealtime alignment + §6.10
INV-RECV-* (receiver-side, already landed in 055fd46).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 21:27:42 -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
pingqiu 59d63f8274 G5-5C #5: cmd/blockvolume flag wiring + production probeFn
Closes the wire between batch 1-4's runtime/engine plumbing and
operator/CLI control. Per architect Batch #5 review 2026-04-27,
each of the 4 self-check items is addressed:

#1 --degraded-probe-interval=0 = OFF
   Default value 0 keeps the loop disabled — preserves G5-4
   behavior. Help text states this explicitly. main.go's
   "if f.degradedProbeInterval > 0" guard means we NEVER call
   ConfigureProbeLoop with a 0 interval (which the loop itself
   would reject anyway via NewProbeLoop). Two layers of defense.

#2 cooldown-base/cap normalization
   ProbeLoopConfig defaults (5s base, 60s cap) match
   PeerProbeCooldown defaults exactly. NewProbeLoop normalizes
   <=0 to defaults; Cap < Base bumps Cap up to Base. CLI flag
   defaults are 5s/60s — matches batch 1/2 contract.

#3 production probeFn
   New file core/host/volume/probe_loop_wiring.go::ProductionProbeFn
   - peer.mu released before executor.Probe (loop discipline; the
     probeFn never touches peer.mu — only Target() which is
     immutable post-construction).
   - transport failure (result.Success == false) → returns non-nil
     err so DefaultProbeResultFn calls OnProbeAttempt(false) and
     backoff advances. Wire-success returns nil so cooldown resets
     to Base regardless of engine's semantic verdict.
   - adapter.OnProbeResult is fed BOTH success and failure facts
     (NormalizeProbe distinguishes). Engine async result NOT mixed
     into transport return value — separation per architect
     guidance.
   - SessionID minted via replication.MintProbeSessionID (new
     atomic counter; distinct from peerSessionIDCounter and
     adapter's own probe sessionID counter — three contexts, three
     counters, no overlap).
   - Defensive guards: nil adapter → fail-closed shim probeFn;
     nil executor → return err; zero lineage → return err;
     ctx.Err() pre-check.

#4 Configure → Start ordering at admit time
   main.go calls ConfigureProbeLoop + StartProbeLoop in sequence
   immediately after replVolume + h.SetReplicationVolume; peers may
   or may not exist yet (master assignment arrives async). Empty
   peer set is safely no-op (covered by Batch 3
   TestVolume_ConfigureProbeLoop_HappyPath); production is just
   the same path with a real adapter.

Replication layer additions:
- ReplicaPeer.Executor() accessor for the probeFn (read-only,
  caller never closes — BUG-005 discipline).
- replication.MintProbeSessionID() — atomic counter for
  runtime-driven probes.

CLI flags (default OFF):
- --degraded-probe-interval (default 0; recommended 5s for prod)
- --degraded-probe-cooldown-base (default 5s)
- --degraded-probe-cooldown-cap (default 60s)
Help text explicitly distinguishes loop interval vs per-peer
cooldown so operators don't conflate the two 5s defaults.

Tests (3 wiring + 1 skip = 4/4 PASS as written):
- TestProductionProbeFn_NilAdapter_ReturnsErrAndDoesNotPanic
- TestProductionProbeFn_TransportFailure_ReturnsErr — dial to
  127.0.0.1:1 (reserved/closed) → result.Success=false → non-nil
  err returned + adapter received the failure fact.
- TestProductionProbeFn_ContextCancelled_ReturnsErr
- TestProductionProbeFn_ZeroLineage_ReturnsErr — skipped (defensive
  guard verified by compile-time path; zero-lineage construction
  requires package-private peer access, deferred to integration).

Full ./... regression: PASS (every package, including host 2-min
suite, frontend/iscsi 31s suite, frontend/nvme 61s suite). No
behavioral regression on G5-4 / earlier T4 paths.

Next batch (G5-5C #6): component restart-catch-up test exercising
the full primary→engine→catch-up loop without iscsi/iptables
harness. After that: m01 hardware re-run.
2026-04-27 16:56:48 -07:00
pingqiu 602fc0d8ca G5-5C #4: engine boundary tests — dispatch / Case 1 reconnect / lineage stale-event drop / stale-ack guard
Architect Batch #4 review 2026-04-27 ruled the four §2 invariants
(#4 / #11 / #12 / #13) belong at the engine layer, not core/replication/
— "single owner per invariant, don't double-assert in adapter and
engine". Batch 3 already covered the runtime concerns (lifecycle,
cooldown, lock ordering, peer-instance teardown); Batch #4 covers
the truth-layer translations engine performs from probe results
into recovery commands.

Tests (5 tests, 9 subcases, 9/9 PASS):

§2 #4 dispatch (catch-up vs rebuild) — TableDriven:
  - caught_up: R≥H → DecisionNone, no recovery cmd
  - gap_within_wal: R<H, R≥S → DecisionCatchUp + StartCatchUp
  - gap_exceeds_wal: R<S → DecisionRebuild + StartRebuild
  - rebuild_pinned: pin overrides catch-up → StartRebuild
  Mutual exclusion checked on each row (the OTHER cmd must NOT emit).
  No real retention/WAL logic dragged in; pure (R,S,H) input → cmd
  output table.

§2 #11 reconnect Case 1 (identity unchanged):
  Admit at (epoch=1, EV=1) → catch-up running → session fails →
  fresh ProbeSucceeded at SAME (epoch=1, EV=1) → engine still in
  CatchUp at the same lineage. Identity.{Epoch,EndpointVersion}
  pinned unchanged. No StartRebuild emitted (no master re-emit
  needed for Case 1 — pinned by §1.F).

§2 #12 lineage-bump during in-flight recovery:
  In-flight session 42 at epoch=1 → AssignmentObserved at epoch=2
  resets Session/Recovery/Reachability via identityChanged path →
  late SessionClosedCompleted carrying old SessionID=42 must be
  DROPPED. Asserts: Recovery.R does NOT advance, Session.Phase does
  NOT promote to Completed, no PublishHealthy emit. Distinct from
  batch 3's volume-layer Case 2 test (peer-instance replacement);
  this asserts the engine truth layer drops stale-SessionID events.

§2 #13 stale-ack guard (single owner = engine):
  StaleSessionAck_DoesNotPromoteHealth — SessionCompleted with
  AchievedLSN=50 < TargetLSN=100; Recovery.R advances to 50 but
  decide() leaves Decision in CatchUp (R<H), so Healthy gate
  refuses to flip. PublishHealthy NOT emitted.
  StaleSessionAck_FullAchievedDoesPromote — counterpart confirming
  AchievedLSN=H DOES promote (so prior test isn't trivially passing
  via "Healthy never promotes"). PublishHealthy emit confirmed.

Also addresses architect's lock-order reminder #1 from Batch 3 review:
volume.go ConfigureProbeLoop's peersFn comment now states explicitly
"HARD RULE: code on the probe path MUST NOT re-enter v.mu while
holding peer.mu" so any future "peer callback into volume" code is
blocked at review.

Full ./core/engine/ + ./core/replication/ regression: PASS.

Per architect ruling, §2 #14 backoff progression is mathematically
pinned at the peer layer (batch 2); no further integration-layer
re-assertion needed.

Next batch (G5-5C #5): cmd/blockvolume flag wiring + production
probeFn that calls executor.Probe + adapter.OnProbeResult.
2026-04-27 16:28:57 -07:00
pingqiu 40d6eff03b G5-5C #3: ReplicationVolume probe loop integration + 12 tests
Per architect ratification of mini-plan v0.5 §1.A binding (probe
loop owned by ReplicationVolume lifecycle) + 4 guidance items
2026-04-27, this batch wires probe loop ownership into the volume
and pins startup/teardown ordering, lineage-bump abandonment, and
cooldown config push-down via tests.

Architect guidance #1 (startup ordering): ConfigureProbeLoop sets
the loop up; StartProbeLoop is a separate explicit step. Loop will
not run before primary admit unless StartProbeLoop is called. Empty
peer set is no-op (no probes fire), no panic.

Architect guidance #2 (Stop ordering): Close() stops the probe loop
FIRST (snapshot pointer under v.mu, release lock, Stop() with lock
released) BEFORE re-acquiring v.mu for peer teardown. This avoids
in-flight probeFn callbacks landing on closed peers and prevents
deadlock between loop's peersFn (which needs v.mu) and Close's peer
iteration (which holds v.mu). Pinned by
TestVolume_Close_StopsLoopBeforePeerTeardown using a probeFn that
blocks on ctx.Done().

Architect guidance #3 (cooldown propagation): UpdateReplicaSet calls
peer.SetProbeCooldownConfig on every newly-created peer (whether
first add or lineage-bump recreate) using the volume's saved
ProbeLoopConfig.CooldownBase/Cap. ConfigureProbeLoop also pushes the
config to peers that exist at configure-time. Pinned by
TestVolume_UpdateReplicaSet_AppliesProbeCooldownToNewPeers and
TestVolume_Configure_PushesCooldownToExistingPeers.

Architect guidance #4 (lineage-bump abandonment, Case 2 §1.F): the
new *ReplicaPeer instance has fresh cooldown state — failureCount=0,
probeNextEligible zero, cooldownCfg from current volume config. Old
peer's accumulated backoff cannot leak because old peer is a
distinct (now-Closed) instance. A late OnProbeAttempt arriving on
the old peer clears its in-flight flag idempotently and does NOT
mutate the new peer (already pinned by batch 2's
TestPeer_OnProbeAttempt_ClosedDoesNotUpdateCooldown; this batch adds
the volume-integration counterpart). Pinned by
TestVolume_LineageBump_NewPeerHasFreshCooldown and
TestVolume_LineageBump_OldPeerProbeAbandoned.

Volume.go additions:
- 3 new fields: probeLoop *ProbeLoop, probeCfg ProbeLoopConfig,
  probeCfgSet bool (all under v.mu)
- ConfigureProbeLoop(cfg, probeFn, now) — Configure-once contract,
  rejects double-configure, builds peersFn over v.peers under v.mu,
  wires DefaultProbeCooldownFn / DefaultProbeResultFn, pushes config
  to existing peers
- StartProbeLoop() — rejects pre-Configure, rejects post-Close,
  delegates to ProbeLoop.Start (sync.Once)
- probeLoopForTest() — package-private accessor
- Close() rewritten to stop loop FIRST under careful lock release
- UpdateReplicaSet pushes cooldown config onto each newly-created peer

Tests (12/12 PASS):
- ConfigureProbeLoop happy path (no peers, no probes, clean Close)
- ConfigureProbeLoop rejects double-configure
- StartProbeLoop without Configure is rejected
- StartProbeLoop on closed volume is rejected
- StopBeforeStart idempotent at volume layer
- Close stops loop BEFORE peer teardown (with blocking probeFn)
- UpdateReplicaSet pushes cooldown to new peers (post-Configure add)
- ConfigureProbeLoop pushes cooldown to pre-existing peers
- LineageBump_NewPeerHasFreshCooldown — old failureCount=3 + non-zero
  deadline; new peer has failureCount=0 + zero deadline + fresh cfg
- LineageBump_OldPeerProbeAbandoned — claim on old peer; lineage
  bump tears down; new peer NOT in-flight; late OnProbeAttempt on
  old peer is idempotent and does not touch new peer
- ProbeLoop_OnlyDegradedPeersDispatched — Healthy r1, Degraded r2;
  loop probes only r2 (volume-integration counterpart of batch 2's
  peer-level OnlyDegradedPasses)
- ProbeFnError_AdvancesBackoff — end-to-end: probeFn err →
  DefaultProbeResultFn → peer.OnProbeAttempt(false) →
  failureCount monotonic ≥ 3 within deadline

Full ./core/replication/ regression: PASS.

Next batch (G5-5C #4): lineage-change / stale-ack / reconnect dual-axis
tests + probe-driven dispatch branch verification.
2026-04-27 16:18:59 -07:00
pingqiu a747fcec1f G5-5C #2: peer.go::ProbeIfDegraded + OnProbeAttempt + cooldown state machine + 10 unit tests
Per architect ratification 2026-04-27 of mini-plan v0.5 §1.A binding,
this batch wires the per-peer probe gate + backoff state machine
that the probe loop (batch 1) consumes via DefaultProbeCooldownFn /
DefaultProbeResultFn.

Key design decisions per architect's three guidance items 2026-04-27:

1. Two distinct time concepts documented separately (architect #1):
   - Loop interval (ProbeLoopConfig.Interval, default 5s) — how
     often the probe loop wakes up.
   - Per-peer cooldown (PeerProbeCooldown.Base/Cap, default 5s/60s)
     — gate AFTER an attempt before the next attempt on the SAME
     peer.
   PeerProbeCooldown godoc explicitly calls these out so future
   readers can't conflate the two.

2. peer.mu boundary (architect #2): both ProbeIfDegraded and
   OnProbeAttempt run entirely under p.mu, mutating only peer-local
   state. The actual probe transport call (executor.Probe) is
   dispatched by ProbeLoop.dispatchProbe AFTER the gate returns,
   with p.mu released. Method godocs explicitly forbid calling into
   engine, executor, or other peers' locks from these methods.

3. Close()/lineage teardown (architect #3): OnProbeAttempt on a
   closed peer always clears the in-flight flag (preventing leaks)
   but does NOT update cooldown. This guarantees §1.E (c) clean
   teardown — a delayed probe outcome arriving after Close() does
   not leak state into a fresh peer that may share the underlying
   address. Tested via TestPeer_OnProbeAttempt_ClosedDoesNotUpdateCooldown.

New types:
- PeerProbeCooldown — Base + Cap policy
- DefaultPeerProbeCooldown() — 5s/60s defaults

ReplicaPeer additions (all under p.mu):
- cooldownCfg PeerProbeCooldown
- probeNextEligible time.Time (cooldown deadline)
- probeFailureCount int (drives backoff doubling)
- probeInFlight bool (single in-flight per peer)

New methods:
- SetProbeCooldownConfig(cfg) — volume-level config push
- ProbeIfDegraded(now) bool — atomic gate + claim in-flight
- OnProbeAttempt(now, success) — release in-flight + advance cooldown
- IsProbeInFlight() bool — diagnostic
- ProbeNextEligibleAt() time.Time — diagnostic

Default loop wrappers (in peer.go for cohesion):
- DefaultProbeCooldownFn(now func() time.Time) CooldownFn
- DefaultProbeResultFn(now func() time.Time) ResultFn
Both accept a clock injection for testability.

Tests (10/10 PASS):
- TestPeer_ProbeIfDegraded_OnlyDegradedPasses — §1.A only-on-degraded
  (5 ReplicaState cases)
- TestPeer_ProbeIfDegraded_ClosedSkipped — §1.E (c) closed-peer skip
- TestPeer_ProbeIfDegraded_InFlightGuard — INV-G5-5C-SINGLE-INFLIGHT-PER-PEER
- TestPeer_OnProbeAttempt_BackoffProgression — 5→10→20→40→40 (cap)
- TestPeer_OnProbeAttempt_SuccessResetsBackoff — counter resets to 0,
  next failure restarts at Base
- TestPeer_OnProbeAttempt_ClosedDoesNotUpdateCooldown — §1.E (c)
  teardown semantics
- TestPeer_StateChange_InFlightSafe — TOCTOU: state→CatchingUp
  during in-flight; OnProbeAttempt clears flag without mutating state
- TestPeer_ProbeIfDegraded_ConcurrentClaims — 32 goroutines, exactly
  1 claim succeeds
- TestDefaultProbeCooldownFn_Wires — wrapper delegates correctly
- TestDefaultProbeResultFn_Wires — wrapper delegates correctly

Full ./core/replication/ regression: PASS.

Next batch (G5-5C #3): catch-up/rebuild dispatch branch tests +
ReplicationVolume integration (ProbeLoop owned by volume lifecycle).
2026-04-27 16:13:02 -07:00
pingqiu d38b95d1aa G5-5C #1.1: address QA review of batch 1 — close result/backoff seam, reject MaxConcurrent>1, add Stop-cancels-inflight test
QA review of seaweed_block@<batch 1> flagged three legitimate issues:

1. Probe result/backoff seam not closed.
   Fix: add ResultFn(peer, err) seam, called once per probe attempt
   with the outcome (success / error / surfaced panic). NewProbeLoop
   requires a non-nil resultFn. dispatchProbe wraps probeFn in a
   defer/recover that converts panics into a non-nil error and
   forwards every outcome to resultFn (also panic-safe via second
   recover wrapper). This gives ReplicaPeer's cooldown progression
   (batch 2) a single canonical hook into success/failure.

2. MaxConcurrent > 1 silently accepted.
   Fix: NewProbeLoop now rejects MaxConcurrent > 1 with an explicit
   error message citing the v0.5 architect binding. <= 0 still
   normalizes to 1 (silent default for the typical empty config
   path); =1 is the only accepted explicit value.

3. Missing Stop-cancels-inflight test.
   Fix: TestProbeLoop_StopCancelsInflightProbe — probeFn blocks on
   <-ctx.Done(); Stop() must return within 2s; verifies the
   ctx-cancel goroutine in dispatchProbe wires stopCh → ctx
   correctly.

Additional tests:
- TestProbeLoop_MaxConcurrentGreaterThanOne_Rejected (covers the
  rejection path + the =0 normalization path + the =1 acceptance
  path).
- TestProbeLoop_NilResultFn_Rejected (constructor seam check).
- TestProbeLoop_ResultFn_ReceivesProbeOutcome (success + error +
  panic each surface to resultFn with the right shape).
- TestProbeLoop_ResultFn_PanicIsolated (panic in resultFn does not
  crash loop — CP4B-2 lesson 3 extended to result callback).

Test results: 13/13 PASS. Full replication suite no regression.

Note on gopls diagnostics ("undefined: ReplicaPeer"): seaweedfs
workspace doesn't include the seaweed_block module — gopls can't
resolve cross-module identifiers. go build / go test inside
seaweed_block compiles cleanly. A go.work entry would silence the
gopls warnings; out of scope for this batch.

Next batch (G5-5C #2): peer.go::ProbeIfDegraded() + cooldown
state-machine + in-flight guard tests.
2026-04-27 15:42:38 -07:00
pingqiu 4a38e5cbce G5-5C #1: probe loop skeleton + lifecycle tests
First production batch for the G5-5C primary-side degraded-peer probe
loop, per the architect-bound mini-plan v0.5 §1.A binding (Option B,
core/replication/ ownership) and §1.H audit-PASS verdict at
seaweedfs@9245446b5.

Files:
- core/replication/probe_loop.go (new): ProbeLoop struct with config
  + start/stop lifecycle (sync.Once on both); per-iteration tick that
  snapshots peers via PeerSourceFn, gates each via CooldownFn,
  dispatches via ProbeFn; CP4B-2 lessons applied (zero-interval
  rejected at construction; stop-before-start no deadlock; callback
  panic isolated via recover).
- core/replication/probe_loop_test.go (new): seven lifecycle tests
  covering Start/Stop happy path, stop-before-start, idempotent
  concurrent stop, zero-interval rejection, callback panic isolation,
  cooldownFn gating, empty peer set, and probeFn-error-doesn't-stop.

Design:
- ProbeLoop is runtime/wiring only. No engine FSM, no transport.
- Seams (PeerSourceFn / ProbeFn / CooldownFn) injected by host so
  the loop knows nothing about adapter, executor, or engine.
- Default config: Interval 5s, MaxConcurrent 1, CooldownBase 5s,
  CooldownCap 60s — architect-bound G5-5C v0.5 §1.A shape.
- Authority-bound (§1.E): peersFn snapshots ReplicationVolume.peers
  under lock; loop never enumerates network-discoverable addresses.
- All G5-5C INVs map cleanly to existing engine/replication state per
  the §1.H audit; this skeleton adds NO recovery substrate.

Tests verified:
- go test ./core/replication/ -run TestProbeLoop -count=1: PASS (7/7)
- go test ./core/replication/ -count=1: PASS (no regression on
  existing T4a-5/T4b/T4c suites)

Next batch (G5-5C #2): peer.go::ProbeIfDegraded() + cooldown
state-machine + in-flight guard tests.
2026-04-27 15:37:06 -07:00
pingqiu c6bace4e79 G5-5 upstream instrumentation: observer + OnLocalWrite + ship gates
QA round 8: ALL 6 ship/dial/barrier lines from 7a3996d are missing.
The replication outer loop is not running at all. Need to walk
upstream to find where the fan-out chain breaks.

Add 4 INFO log lines at the upstream surfaces:

  durable/storage_adapter.go (writeBytes observer dispatch):
    - obs nil: 'write observer NIL — replication fan-out skipped'
      (means SetWriteObserver wasn't called before write hit)
    - obs ok: 'write observer dispatch lba=N lsn=N'

  replication/volume.go (OnLocalWrite entry):
    - 'OnLocalWrite volume=v1 lba=N lsn=N peers=K'
      (lets us see if peers map is empty even though
      UpdateReplicaSet returned ok)

  replication/peer.go (ShipEntry early-exit gates):
    - 'ship gate-close peer=r2 lba=N lsn=N (peer closed)'
    - 'ship gate-degraded peer=r2 lba=N lsn=N (peer degraded)'
      (the existing logs are AFTER these gates, so silent
      early-exit was indistinguishable from no-call)

These 4 lines + the existing 7a3996d 6 lines = 10 total. With the
next re-run we should see exactly which hop fails:

  Expected per iSCSI WRITE on primary:
    durable: write observer dispatch lba=0 lsn=1
    replication: OnLocalWrite volume=v1 lba=0 lsn=1 peers=1
    transport: ship lazy-dial replica=r2 ...
    replication: ship ok peer=r2 ...

  If 'observer NIL' appears: SetWriteObserver wiring race — observer
    not set when iSCSI starts writing.
  If OnLocalWrite shows peers=0: UpdateReplicaSet ok but peers map
    became empty (race with stale-gen replay tearing down peers?).
  If 'ship gate-close' / 'ship gate-degraded' appears: peer state
    transitioned bad before any ship attempt.
  If none of the above + ship lines silent: Backend.writeBytes itself
    is bypassed (iSCSI handler not going through StorageBackend).

Tests still green.

Refs: QA round 8 — 7a3996d logs all silent on ship path.
2026-04-27 00:59:33 -07:00
pingqiu 7a3996d2b0 G5-5 ship/dial/barrier instrumentation (suspect B disambig)
QA round 7 confirmed peers=1 — master delivers peer set correctly,
including routable address (r2@192.168.1.184:9221). The fsync I/O
error is on the SHIP side. Sub-suspects:
  (a) lazy-dial never triggered (e.g., peer state == Degraded
      before first ship; ShipEntry returns early)
  (b) lazy-dial triggered but TCP dial failed
  (c) dial succeeded but frame write failed (handshake/framing)
  (d) ship ok, but barrier wait never gets ack (timeout silently)

Add 6 INFO log lines at the suspect surfaces so the next re-run
disambiguates which sub-case is firing:

  core/replication/peer.go (ShipEntry):
    - on ship FAILED: peer + addr + lba + lsn + err
    - on ship ok:     peer + lba + lsn

  core/replication/peer.go (Barrier):
    - on barrier wait:    peer + addr + targetLSN + epoch
    - on barrier FAILED:  peer + addr + targetLSN + err
    - on barrier ack:     peer + targetLSN + achievedLSN

  core/transport/ship_sender.go (Ship lazy-dial):
    - on lazy-dial entry:   replica + addr + sessionID + lsn
    - on lazy-dial FAILED:  replica + addr + err
    - on lazy-dial ok:      replica + addr

Replica-side already logs replica_apply on receive (existing). With
both sides logged, QA's next run should clearly show the failing
hop. No behavior change; small log footprint.

Tests still green: core/replication, core/transport, cmd/blockvolume
(incl. G5-4 integration test).

Refs: QA round 7 disambiguation (peers=1 confirmed; ship-side
instrumentation needed).
2026-04-27 00:54:50 -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 8e30a497ff T4d-2 doc fix: stale godoc post-round-46 (gate is lane-pure; CARRY-T4D-LANE-CONTEXT-001)
Per QA T4d-2 final closure: pre/with-T4d-3 doc fixes.

apply_gate.go (lines 38-43): the godoc on ReplicaApplyGate still
described "lane discrimination" as the gate reading
lineage.TargetLSN — that text predated the round-46 rework.
Replaced with a clear statement of the lane-pure contract:
- Gate is LANE-PURE; caller decides
- Caller invokes ApplyRecovery vs ApplyLive explicitly
- Gate does NOT inspect lineage payload to discriminate
- Today's caller (transport replica.go) uses a transitional
  TargetLSN-based shim — but the shim lives at the CALLER
- The architectural fence (gate is lane-pure) is durable; the
  caller's signal source is replaceable
- Reference to CARRY-T4D-LANE-CONTEXT-001 for the future fix

replica.go NewReplicaListenerWithApplyHook godoc: previously
described `hook.Apply(lineage, lba, data, lsn)` as the dispatch
mechanism — that signature no longer exists post-round-46.
Replaced with:
- Handler dispatches caller-side to hook.ApplyRecovery /
  hook.ApplyLive
- Hook itself is LANE-PURE
- Today's caller-side decision is a transitional shim based on
  TargetLSN==liveShipTargetLSNSentinel
- Reference to CARRY-T4D-LANE-CONTEXT-001

Both godoc updates inscribe the architectural fence + name the
named carry by ID so future readers find the gap tracking via
catalogue cross-reference.

22 packages green; 0 failures.

Refs: round-46 architect ruling (lane-pure gate); CARRY-T4D-LANE-
CONTEXT-001 (catalogue §3.3 — QA-inscribed named carry).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 21:48:34 -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
pingqiuandClaude Opus 4.7 5cbe7cf6db T4c-3: engine retry-loop wiring + L2 integration matrix
Per QA T4c-2 sign forward-carry binding (round-37): retry-loop
wiring deferred from T4c-2 §4.1 lands here. Integration matrix
covers mini-plan §2 T4c-3 scenarios at the executor surface.

Engine retry-loop (G-1 §4.1 architect Option B, round-38):
- RecoveryTruth.Attempts counter added
- applySessionFailed: on non-recycled non-start_timeout failure,
  increment Attempts; while Attempts <= DefaultRuntimePolicyFor(
  contentKindFor(Decision)).MaxRetries, re-emit StartCatchUp /
  StartRebuild
- Budget exhaustion clears Attempts + Decision (reset to Unknown)
  + emits PublishDegraded("retry_budget_exhausted")
- ErrWALRecycled bypasses retry — tier-class change escalates to
  Decision=Rebuild and resets Attempts (sentinel takes precedence)
- start_timeout (watchdog-synthesized) bypasses retry — executor
  never started; retrying an unreachable executor doesn't help
- applySessionCompleted clears Attempts on success

L2 integration matrix (mini-plan §2 T4c-3, 4 scenarios × 2
substrates = 8 matrix rows):
- TestT4c3_Catchup_ShortDisconnect_DeltaOnly — primary writes 20
  LBAs, replica empty, executor StartCatchUp streams the window
  via ScanLBAs → MsgShipEntry; replica converges byte-exact
- TestT4c3_Catchup_GapExceedsRetention_EscalatesToNeedsRebuild —
  substrate ErrWALRecycled propagates through SessionClose's
  FailReason; engine SessionFailed handler maps to Rebuild
- TestT4c3_Probe_HappyPath_AcrossBothSubstrates — wire shape works
  end-to-end across smartwal + walstore
- TestT4c3_Catchup_RecoveryModeLabelSurfaced — substrate-mode
  introspection probe completes catch-up under both substrates
  (label visible in success log; no panic / no error)

Engine unit tests (3 new):
- TestSessionFailed_NonRecycled_RetriesUntilBudget — pin: 3 retries
  re-emit StartCatchUp; 4th exhausts budget → PublishDegraded
- TestSessionCompleted_ClearsAttemptCounter — success resets
- (existing TestSessionFailed_NonRecycled_DoesNotEscalate continues
  to pass under retry path)

Mini-plan §2 T4c-3 scenarios coverage:
- (1) ShortDisconnect → covered, both substrates
- (2) GapExceedsRetention → covered, both substrates
- (3) RetryBudgetExhausted → covered at engine unit scope
  (TestSessionFailed_NonRecycled_RetriesUntilBudget); integration-
  scope coverage requires engine→adapter→executor full-flow wiring
  not present in current ReplicationVolume (forward-carry to T4d)
- (4) Probe_LineageMismatch_FailsClosed → covered by T4c-1 unit
  tests + integration smoke (Probe_HappyPath_AcrossBothSubstrates)
- (5) RecoveryModeLabelSurfaced → covered, both substrates

Catchup sender minor fix:
- ScanLBAs(0, ...) → ScanLBAs(1, ...) — LSN=0 is not a real entry;
  smartwal's oldestPreserved=1 default would spuriously trip
  ErrWALRecycled at fromLSN=0. TODO comment marks the future
  threading of replica's flushed-LSN through StartCatchUp (post-T4d
  engine→adapter→executor recovery wiring).

L3 m01 disconnect/reconnect script: deferred to follow-up; mini-plan
§2 T4c-3 specifies it as an artifact for QA's hardware run, not as
a build-time test. The L2 matrix in this commit is the unit-test-
time gate.

go test ./... -count=1 → all 21 packages green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 10:15:41 -07:00
pingqiuandClaude Opus 4.7 3b54576e2f T4c-2: catch-up muscle port + state machine + ScanLBAs interface seam
Per design memo §7a + G-1 V2 read signed at v3-phase-15-t4c-2-g1-v2-read.md.
Round-35 architect collapse: T4c-2 covers walstore wal_replay inner-loop
muscle port (V2-faithful, narrow G-1 scope), smartwal state_convergence
production promotion, peer state machine extensions (CatchingUp /
NeedsRebuild), and observability surfacing.

Storage substrate (G-1 §3 row #4 — interface seam):
- Unified RecoveryEntry + ErrWALRecycled + RecoveryMode types in
  core/storage/recovery_contract.go (memo §5.1, §13.0a)
- LogicalStorage.ScanLBAs interface method added; substrate dispatch
  is via interface, not type-switch
- walstore POC promoted: walstore_recovery_poc.go → walstore_recovery.go;
  ScanFrom → ScanLBAs; uses unified storage.RecoveryEntry
- smartwal POC promoted: recovery_poc.go → recovery_scan.go;
  ScanFrom → ScanLBAs; type alias to storage.RecoveryEntry
- BlockStore implements ScanLBAs (state-convergence-equivalent
  synthesis since in-memory has no WAL retention; uses walHead as
  scan-time LSN so caller's targetLSN cap doesn't accidentally skip
  every entry)

Catch-up sender muscle port (G-1 §3 narrow-scope inner loop):
- core/transport/catchup_sender.go body rewritten: replaces
  AllBlocks-walk with primaryStore.ScanLBAs(0, fn) + per-entry
  ShipEntry write
- INV-REPL-CATCHUP-CALLBACK-RETURN-NIL-CONTINUES honored: callback
  skips entries past targetLSN by returning nil (not error)
- INV-REPL-CATCHUP-LASTSENT-MONOTONIC honored: lastSent only
  advances after successful frame write
- INV-REPL-CATCHUP-DEADLINE-PER-CALL-SCOPE honored: SetDeadline at
  entry, cleared at exit (deferred)
- INV-REPL-CATCHUP-TARGET-NOT-REACHED-VS-RECYCLED-DISTINGUISHED:
  ErrWALRecycled wrapped as tier-class change; target-not-reached
  surfaces as separate stream-level error
- INV-REPL-CATCHUP-COMPLETION-FROM-BARRIER-ACHIEVED-LSN (§4.2
  binding): completion judged from BarrierResponse.AchievedLSN, not
  from a separate MsgCatchupDone marker; recovery_mode label
  surfaces in success log per memo §5.1

Engine (G-1 §4.1, §4.3):
- RecoveryRuntimePolicy.MaxRetries field added; per-kind defaults
  match V2 maxCatchupRetries=3 (wal_delta), 0 (full_extent), 1
  (partial_lba)
- applySessionFailed maps ErrWALRecycled in failure reason →
  recovery.Decision = Rebuild (G-1 §4.3 Option B); engine→storage
  decoupling preserved by string-match on the sentinel text rather
  than importing storage package

Peer state machine (memo §2.2):
- ReplicaCatchingUp + ReplicaNeedsRebuild states added
- SetState method with table-driven replicaStateTransitionAllowed
  gate; rejects illegal transitions (NeedsRebuild is terminal in
  T4c per memo)

Tests (15 new):
- core/transport/catchup_sender_test.go (8 tests: 2 V2-mirror +
  6 invariant pins for §5.1-§5.5 + §4.2 binding + sentinel + mode-label)
- core/replication/peer_state_machine_test.go (4 tests: allowed
  transitions, rejected transitions, NeedsRebuild terminal,
  String forms)
- core/engine/recovery_test.go (3 new: MaxRetries per-kind defaults
  pin, WAL-recycled escalation pin, non-recycled non-escalation
  pin)

go test ./... -count=1 → all 21 packages green.

Catalogue invariants queued for §3.3 inscription at T4c batch close:
INV-REPL-CATCHUP-CALLBACK-RETURN-NIL-CONTINUES,
INV-REPL-CATCHUP-LASTSENT-MONOTONIC,
INV-REPL-CATCHUP-DEADLINE-PER-CALL-SCOPE,
INV-REPL-CATCHUP-TARGET-NOT-REACHED-VS-RECYCLED-DISTINGUISHED,
INV-REPL-CATCHUP-RECYCLE-ESCALATES,
INV-REPL-CATCHUP-COMPLETION-FROM-BARRIER-ACHIEVED-LSN,
INV-REPL-PEER-STATE-CATCHINGUP,
INV-REPL-RECOVERY-MODE-OBSERVABLE.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 02:59:53 -07:00
pingqiu bb390a9a97 T4b-6: L2 subprocess integration matrix — T4b batch close gate
Closes the T4b batch with end-to-end matrix coverage of all three
DurabilityMode semantics + a wire-shape scope-leak fence. Each
scenario drives the full StorageBackend.Sync → observer.Sync →
DurabilityCoordinator → peer.Barrier → real ReplicaListener path
on real TCP between in-process pairs.

Mirrors T4a-6 harness shape (matrix runner, primaryRig +
replicaRig pattern, LIFO cleanup discipline). Both backends
(smartwal + walstore) are gating in the L2 harness — round-22
honesty correction inherited.

Scenarios (4 × 2 backends = 8 matrix rows):

  TestT4b6_SyncAll_TwoPeers_AllHealthy
    sync_all happy path. 20 LBAs through StorageBackend.Write +
    Observe + ship to both replicas; Sync delegates to observer
    which runs local fsync + 2 peer barriers in parallel via
    DurabilityCoordinator. Sync returns nil; both peers stay
    Healthy; replica byte-exact via primary.store vs r1/r2.store
    (forward-carry: T4a-6 BasicEndToEnd byte-exact invariant
    continues to hold).

  TestT4b6_SyncAll_OnePeer_FailsOnBarrierError
    sync_all rejects ANY peer failure. 1 healthy + 1 unreachable
    peer; Sync returns ErrDurabilityBarrierFailed. Dead peer is
    Degraded (peer.Barrier translation,
    INV-REPL-BARRIER-FAILURE-DEGRADES-PEER). Healthy peer's
    state stays Healthy — its individual barrier succeeded; the
    failure is mode-driven, not transport-driven.

  TestT4b6_SyncQuorum_RF3_TolerantOfOneFailure
    sync_quorum tolerates 1/2 peer failure when quorum is 2.
    Primary(1) + healthy peer(1) = 2 durable >= 2 quorum → Sync
    nil. Sanity sub-case: with BOTH peers dead, sync_quorum
    returns ErrDurabilityQuorumLost (1/3 durable < 2/3 quorum).
    Pins V2 dist_group_commit.go quorum arithmetic end-to-end
    through the V3 wire.

  TestT4b6_BestEffort_AllPeersFail_StillSucceeds
    best_effort silences all-peers-failed. 2 unreachable peers;
    Sync returns nil. Both peers Degraded via peer.Barrier
    Invalidate. Primary's local fsync ran (walHead reflects the
    writes). Pins V2's "best_effort returns nil even on full
    replication failure" semantic.

  TestT4b6_BarrierWire_FullLineageEcho_StillEnforced
    Wire-shape scope-leak fence (architect round-22 pattern).
    Asserts EncodeBarrierResp output is exactly 40 bytes (32B
    lineage + 8B AchievedLSN). Asserts round-trip preserves
    every lineage field byte-exact. Asserts 39B truncation is
    rejected at decode (T4b-1 fail-closed contract). Catches
    any future refactor that silently weakens to epoch-only
    or short form, independent of whether the matrix scenarios
    above also fail.

Forward-carry verification (matrix run + standalone):
  - All T4a-6 tests (BasicEndToEnd_PrimaryWriteReachesReplicaByteExact
    + BestEffort_DisconnectThenReassign) continue to pass.
  - T4a-4 adversarial pin
    (TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica)
    continues to pass — INV-REPL-LSN-ORDER-FANOUT-001 not
    regressed by Sync code path.
  - T4b-3 wrapper tests + T4b-4 coordinator tests + T4b-5 Sync
    tests all green.

Verification: full 21-package repo suite green. core/replication
test time 0.6s including all 8 matrix rows. G-2 tri-line godoc on
test helpers (setReplicaSet, writePrimaryBlocks, reservedDeadAddr).
G-3 cumulative.

Sixth and final task in T4b batch. T4b mechanically closed: 6/6
tasks landed, all gates green, all invariants pinned. Awaiting QA
single-sign per §8C.2 for batch close.
2026-04-24 22:25:42 -07:00
pingqiu 44f87603fd T4b-5: ReplicationVolume.Sync + WriteObserver.Sync seam
Wires DurabilityCoordinator (T4b-4) into the per-volume Sync path.
Host-side FLUSH / SYNCHRONIZE_CACHE now drives the full local fsync
+ per-peer barrier closure in parallel with mode-dependent arithmetic.

Changes:

  core/frontend/durable/storage_adapter.go
    WriteObserver interface extended: Sync(ctx, targetLSN) joins the
    existing Observe(ctx, lba, lsn, data) method. Contract documented
    inline — observer.Sync OWNS the full sync job (both local
    fsync and peer barriers) when installed; StorageBackend delegates
    rather than calling storage.Sync locally.
    StorageBackend.Sync branches: observer==nil preserves the
    pre-T4b behavior (local storage.Sync only); observer!=nil reads
    walHead from LogicalStorage.Boundaries() and calls observer.Sync
    with that as targetLSN. The observer (ReplicationVolume) then
    invokes DurabilityCoordinator.SyncLocalAndReplicas which runs
    local + barriers in parallel inside its own goroutines.

  core/replication/volume.go
    ReplicationVolume gains:
      - coord field set to NewDurabilityCoordinator at construction
      - durabilityMode field, SetDurabilityMode setter +
        DurabilityMode accessor. Default BestEffort (zero value).
        Per mini-plan §5, T4b does not support per-Sync-call mode
        override — mode is a per-volume setting.
      - Sync(ctx, targetLSN) method — snapshots peers under v.mu,
        builds a localSync closure around v.store.Sync, delegates
        to coord.SyncLocalAndReplicas, returns error verbatim.

    Lock scope: v.mu held across the FULL Sync call. Matches the
    T4a-4 round-15 Condition A discipline — concurrent Sync +
    OnLocalWrite calls are serialized on v.mu, preserving the V2
    shipMu semantics extended from ship-only into ship+barrier.
    Accepted correctness-first trade-off: a slow peer barrier stalls
    other writers on the same volume; async-queue optimization
    (Option Z) is deferred post-T4.

Tests (2 required per mini-plan §2 T4b-5):

  - TestReplicationVolume_Sync_BestEffort_E2E — full end-to-end
    smoke: StorageBackend.Write 10 LBAs → Observe → ship → replica
    applies. StorageBackend.Sync → observer.Sync →
    DurabilityCoordinator → local fsync + peer barrier in parallel.
    Replica's R-boundary (durable frontier) must reach primary's
    H (walHead) after Sync returns. Peer stays Healthy throughout.

  - TestReplicationVolume_Sync_PreservesLSNOrderUnderConcurrency —
    forward-carry fence for INV-REPL-LSN-ORDER-FANOUT-001 under
    the new Sync code path. 40 goroutines, caller-side serialized
    LSN allocation + OnLocalWrite, periodic Sync calls interleaved
    every 4th iteration. LBA ordering is inverted from LSN order so
    any reorder is byte-detectable. All 40 LBAs must settle to the
    correct LSN marker at the replica.

Forward-carry verification: T4a-4's
TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica
continues to pass — the existing ordering invariant is not regressed
by the new Sync code path that shares v.mu.

Verification: full 21-package repo suite green including the
extended WriteObserver interface not breaking core/frontend/durable
tests. G-2 tri-line godoc on SetDurabilityMode, DurabilityMode
accessor, Sync method, extended WriteObserver.Sync contract. G-3
cumulative.

Fifth task in T4b batch. Next: T4b-6 L2 subprocess integration
matrix closes the batch.
2026-04-24 01:14:38 -07:00
pingqiu e79ec9e952 T4b-4: DurabilityCoordinator (muscle port, G-1 signed)
Ports V2 MakeDistributedSync (weed/storage/blockvol/dist_group_commit.go,
~45 LOC muscle) into V3 DurabilityCoordinator at core/replication/
durability.go. Gate G-1 pre-signed by QA at round 24 per revised
artifact sw-block/design/v3-phase-15-t4b-4-g1-v2-read.md.

Core surface:

  - DurabilityMode enum (BestEffort / SyncQuorum / SyncAll) with
    String() + zero-safe BestEffort default, mirroring V2
  - DurabilityResult struct with DurableNodes, Quorum, FailedPeers,
    Err fields for caller diagnostics
  - ErrDurabilityBarrierFailed / ErrDurabilityQuorumLost sentinels
    mirroring V2 blockerr.ErrDurability*
  - NewDurabilityCoordinator() stateless constructor
  - SyncLocalAndReplicas(ctx, mode, targetLSN, localSync, peers) —
    parallel fan-out + mode arithmetic
  - EvaluateBarrierAcks(mode, rf, localSyncSucceeded, perPeerErrors)
    — pure arithmetic helper exposed for unit testing

Hidden invariants pinned (from G-1 §4.2):

  #7  Local-fsync short-circuits mode arithmetic. If localSync
      errors, DurableNodes=0, mode arithmetic skipped. Pinned by
      TestDurabilityCoordinator_LocalSyncFails_AllModesError across
      all three modes.

  #8  Peer-state mutation on barrier failure. DurabilityCoordinator
      does NOT call peer.Invalidate — that translation lives inside
      peer.Barrier (T4b-3 wrapper) per §0-B locality. Coordinator
      sees only the error vector; failed peers are logged with
      peer ID + lsn + err at the coordinator layer for operator
      visibility. Pinned by TestDurabilityCoordinator_BestEffort_
      Silences_Failures + TestDurabilityCoordinator_StaleLineageAck_
      NotCounted (both assert peer.State() == ReplicaDegraded after
      coordinator returns).

  #9  Zero-peers fast-path. len(peers)==0 skips parallel machinery
      entirely — localSync runs in the caller's goroutine. Pinned
      by TestDurabilityCoordinator_ZeroPeers_StandaloneFastPath
      across all three modes via runtime.Stack() goroutine-ID
      check (sameGoroutine must be true).

  #10 Target LSN derivation responsibility shift. Caller owns
      targetLSN; coordinator passes it through to peer.Barrier.
      Documented in SyncLocalAndReplicas godoc.

  #11 Flat wg.Add(1 + len(peers)) layout (not V2's wg.Add(2) +
      nested BarrierAll). Semantically equivalent. Pinned by
      TestDurabilityCoordinator_ParallelExecution (elapsed ~100ms
      for localDelay=100ms + 2 peers; sequential would be 100ms+).

Uniform round-21 rule: peer.Barrier owns lineage validation at the
executor seam; stale-lineage acks surface as ErrBarrierLineageMismatch
→ coordinator sees it as a failed peer → NOT counted toward durability.
Pinned by TestDurabilityCoordinator_StaleLineageAck_NotCounted with
a custom replica sending valid-decode responses carrying the wrong
lineage.

Metrics (V2 concern #6) DEFERRED to T4-end observability pass per
G-1 §7 decision. core/replication has no metrics surface yet;
adding one is scope creep.

Tests (9 per mini-plan §2 T4b-4 + 2 sanity):

   1. _Quorum_RF3_AllHealthy — RF=3, 2 peers healthy → 3/3 durable
   2. _Quorum_RF3_OneReplicaFailed — 2/3 durable, quorum met
      (sync_quorum), sync_all fails
   3. _Quorum_RF3_BothReplicasFailed — 1/3 durable,
      ErrDurabilityQuorumLost
   4. _SyncAll_AnyFailure_Fails — no silent swallow
   5. _BestEffort_Silences_Failures — peers Degraded, Err=nil
   6. _StaleLineageAck_NotCounted — H5 LOCK pin via
      wrong-lineage replica
   7. _LocalSyncFails_AllModesError — V2 line 46-48 short-circuit
      across all modes
   8. _ParallelExecution — elapsed ≤ 150ms for 100ms localSync + 2
      peers
   9. _ZeroPeers_StandaloneFastPath — rf=1, same-goroutine,
      INV-REPL-ZERO-PEER-NO-SPAWN

Plus sanity: _Constructor and DurabilityMode_String.

Verification: full 21-package repo suite green. G-2 tri-line godoc
on every public symbol (DurabilityMode + stringer, DurabilityResult,
DurabilityCoordinator, NewDurabilityCoordinator, SyncLocalAndReplicas,
EvaluateBarrierAcks, error sentinels). G-3 cumulative.

Fourth task in T4b batch. Next: T4b-5 ReplicationVolume.Sync wires
DurabilityCoordinator into the volume Sync path + extends
WriteObserver interface.
2026-04-24 00:40:06 -07:00
pingqiu 1c6dc56107 T4b-3: ReplicaPeer.Barrier + Fence wrappers (peer-level seam)
New leaf task introduced by QA round-23 §0-B review. T4b-3 originally
planned for ReplicaPeer.Fence-only; QA's peer-state-mutation locality
check surfaced that DurabilityCoordinator must consume peer.Barrier
(not peer.executor.Barrier) so the error → Invalidate translation
lives at the per-peer execution layer — matching V2's WALShipper-
internal markDegraded locality. T4b-3 now ships both Barrier + Fence
wrappers as a leaf before the T4b-4 DurabilityCoordinator muscle port.

Invariant pinned: INV-REPL-BARRIER-FAILURE-DEGRADES-PEER at the V3
per-peer layer, mirroring T4a-3's Ship → Invalidate translation.

Changes:

  core/transport/executor.go
    Extract FenceSync(replicaID, lineage) error — synchronous fence
    exchange returning a descriptive error on any dial / send /
    recv / lineage-mismatch failure. Refactored existing async
    doFence to wrap FenceSync + adapt the error to the callback-
    based FenceResult. Behavior unchanged for existing async
    callers (engine recovery path); T4b-3 peer wrapper gets a
    clean sync surface.

  core/replication/peer.go
    New ReplicaPeer.Barrier(ctx, targetLSN):
      - Passes peer.lineage UNCHANGED to executor.Barrier — does
        NOT override lineage.TargetLSN with the caller's targetLSN.
        Replica's acceptMutationLineage rejects same-authority
        messages that change TargetLSN, so override would self-
        reject. Caller's targetLSN is coordinator-layer-only
        (compared against ack.AchievedLSN for mode arithmetic).
      - MUST NOT gate on state == Degraded per V2 "always attempt
        BarrierAll" invariant (architect §4.3 note in G-1 doc).
        Only post-Close gate applies.
      - On transport error: p.Invalidate(reason) + state=Degraded
        (INV-REPL-BARRIER-FAILURE-DEGRADES-PEER pin).
    New ReplicaPeer.Fence(ctx, lineage):
      - Takes caller-supplied lineage (not peer-owned) because
        fence semantic is "confirm this specific authority tuple"
        — coordinator or recovery path chooses which lineage.
      - Delegates to executor.FenceSync.
      - Same error → Invalidate translation.

Tests (5 required per QA spec):

  - TestReplicaPeer_Barrier_Happy — round-trip against real
    ReplicaListener; ack.Lineage == peer.lineage byte-exact;
    state remains Healthy
  - TestReplicaPeer_Barrier_ErrorPropagates_MarksDegraded —
    unreachable replica; Barrier returns error; peer transitions
    Healthy → Degraded. INV-REPL-BARRIER-FAILURE-DEGRADES-PEER
    pin at peer layer.
  - TestReplicaPeer_Fence_Happy — fence exchange at peer.lineage
    against real replica; state stays Healthy
  - TestReplicaPeer_Barrier_AfterClose_Errors — post-Close call
    returns 'closed' error; no panic
  - TestReplicaPeer_Fence_AfterClose_Errors — post-Close call
    returns 'closed' error; no panic

Verification: full 21-package repo suite green. G-2 tri-line godoc
on Barrier, Fence (Called by / Owns / Borrows) + FenceSync on
executor. G-3 cumulative. Existing T4b-2 Fence tests pass after the
doFence → FenceSync refactor (behavior preserved).

Third task in T4b batch. Next: T4b-4 DurabilityCoordinator (muscle
port; G-1 pre-signed by QA in revised artifact at sw-block/design/
v3-phase-15-t4b-4-g1-v2-read.md) against the peer.Barrier surface.
2026-04-23 18:51:49 -07:00
wzcheng99 d37451ea1f T4a-6 doc cleanup: retract overclaim + fix matrix wording in header
QA round-22 noted the l2_integration_test.go file header still
claimed the L2 test proves "all T4a landed commits compose
correctly" and that walstore was "non-gating" — both stale after
the f6ae662 follow-up. Body comments (runMatrix + walstoreFactory)
were updated in that commit; the file header was missed.

This is a documentation-only cleanup:

  - Scope claim: now explicitly scopes T4a-6 to T4a-1..T4a-4 +
    the StorageBackend WriteObserver hook. Adds a Scope note
    pointing at core/host/volume/apply_fact_test.go as the
    T4a-5 host-wire coverage.
  - Matrix wording: walstore described as a second gating row
    in the current harness; the earlier "non-gating per BUG-007"
    language removed. Matches runMatrix + walstoreFactory
    comments.

No code change; tests unaffected.
2026-04-23 17:33:45 -07:00
wzcheng99 f6ae66254f T4a-6 follow-up: four QA spot-check fixes (install-or-refuse,
uint32 assertions, host-level tests, matrix honesty)

QA round-21 spot-check flagged four issues in the T4a-6 landing.
All four confirmed correct; this commit addresses them as one
reviewable unit per QA's recommended batch.

Finding #1 (HIGH) — install-or-refuse ordering in Host.streamOnce.
  Previous order was OnAssignment → UpdateReplicaSet, creating a
  window where the adapter's projection flipped Healthy before the
  peer set was installed. StorageBackend.lineageCheck would then
  pass and admit local-only writes with zero fan-out. V2 atomically
  set replicas before admitting writes; V3 had drifted. Fix:

    - Extract applyFact(fact) from streamOnce's inner loop so the
      handler logic is testable in isolation.
    - Invert order: if h.replication != nil, call UpdateReplicaSet
      FIRST. On failure, LOG and RETURN without calling OnAssignment.
      Adapter projection stays at its prior (not-Healthy until a
      fact fully installs) state; StorageBackend keeps writes
      blocked; master's stream replay redelivers the fact and
      natural convergence resumes on the next cycle.
    - Introduce narrow collaborator interfaces (assignmentConsumer,
      replicaSetUpdater) on Host so test doubles can drive applyFact
      without spinning up a real adapter + transport listener. The
      concrete adapter reference is retained as realAdpt for the
      existing Adapter() accessor.

Finding #2 (MEDIUM) — generation aliasing at the uint32 boundary.
  `(epoch << 32) | uint32(ev)` silently aliased distinct authority
  lines whenever either field exceeded 2^32. Fix:

    - Extract generationFitsUint32(epoch, ev) as a named package-
      level function with a descriptive reason string.
    - SubscribeAssignments calls generationFitsUint32 before minting
      the fact; on rejection, logs a structured diagnostic + skips
      the fact (master keeps running — this is a fail-fast on an
      invariant violation upstream, not a master-side error).
    - Pin with two adversarial tests: TestGenerationFitsUint32_
      MaxValidAccepted (epoch = 2^32-1, ev = 2^32-1 passes) and
      _OverflowRejected (epoch = 2^32 and ev = 2^32 each reject
      with reasons naming the offending field).

Finding #3 (MEDIUM) — T4a-5 host wire was uncovered by T4a-6. The
  L2 integration test bypassed Host.streamOnce entirely, so the
  "all T4a commits compose correctly" claim in commit 420a5a1 was
  stronger than what the test proved. Fix:

    - New apply_fact_test.go in core/host/volume with five pins:
      * TestHost_ApplyFact_Self_InstallsReplicaSetBeforeAssignment
        (ordering recorder proves UpdateReplicaSet before
        OnAssignment in the happy path).
      * TestHost_ApplyFact_Self_UpdateReplicaSetFailure_SkipsOnAssignment
        (fail-closed pin for finding #1).
      * TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication
        (the supersede branch is unaffected by the reordering).
      * TestHost_ApplyFact_ObserverOnly_NoReplicationCallsOnAssignment
        (nil replication seam still flows to OnAssignment as before).
      * TestDecodeReplicaTargets_FieldCopy (auxiliary; catches
        decoder drift).
    - The commit message and batch-close story now honestly reflect
      that host ordering is covered. Full master → gRPC → host
      subprocess L2 integration deferred to T4b/T4c where the
      durability/recovery path makes it materially more valuable
      (per QA round-21 guidance).

Finding #4 (LOW) — matrix 'non-gating' fiction removed.
  The earlier runMatrix harness had walstore_nongating that
  claimed to demote subtest failures. Go's testing has no clean
  demote-subtest-failure API; the defer-based logic didn't
  actually demote. Replaced with honest naming: walstore is a
  second gating row (passes today under T4a best-effort paths;
  if it ever regresses under BUG-007 the test fails honestly
  and we invest in a real demotion harness then). File header
  comment updated to match.

Verification: full 21-package repo suite green including
core/host (122s integration run) and the 5 new host tests. No
regressions.
2026-04-23 17:30:53 -07:00
wzcheng99 420a5a1c4a T4a-6: L2 subprocess integration test — T4a batch close gate
Ships the end-to-end integration test that proves all five T4a
production commits (T4a-1..T4a-5) compose correctly through the
full frontend→storage→replication→transport→replica wire. This
is the T4a batch close gate per mini-plan §4.

In-scope addition flagged by QA round-20 review and confirmed by
sw (not a discovery-bridge trigger — mini-plan always implied this
wire): StorageBackend.Write did NOT invoke
ReplicationVolume.OnLocalWrite. The hook is added here via a
narrow WriteObserver interface seam so core/frontend/durable does
not import core/replication directly.

Changes:

  core/frontend/durable/storage_adapter.go
    New WriteObserver interface with Observe(ctx, lba, lsn, data)
    method. Named Observe (not OnLocalWrite) to avoid a method-
    name collision on ReplicationVolume which already has a
    differently-typed OnLocalWrite(ctx, LocalWrite). New
    SetWriteObserver(obs) installation seam; called only at setup
    (not hot-swappable). writeBytes now takes ctx through and
    invokes obs.Observe after each successful LogicalStorage.Write,
    best-effort (error logged, does NOT fail the Write — matches
    V2 fire-and-forget ShipAll).
    Ordering: LSN-order fan-out is preserved because the observer
    (ReplicationVolume) serializes its own fan-out under v.mu
    (Option X, architect-signed at T4a-4 round-15).

  core/replication/volume.go
    New Observe(ctx, lba, lsn, data) method that wraps into
    LocalWrite and delegates to OnLocalWrite. This lets
    *ReplicationVolume satisfy durable.WriteObserver without
    either package importing the other's public struct type.

  core/replication/l2_integration_test.go (NEW, ~450 LOC)
    Internal-package test (access to ReplicationVolume.peers +
    ReplicaPeer internals needed for transport-kill simulation).

    Matrix harness:
      - smartwal_gating — sign-bearing row; t.Fatal on failure
      - walstore_nongating — reported row; failures logged with
        non-gating note per BUG-007 / T3 matrix discipline

    Scenarios:
      1. BasicEndToEnd_PrimaryWriteReachesReplicaByteExact —
         100 LBAs written through StorageBackend.Write,
         verified byte-exact on replica's LogicalStorage. Peer
         stays Healthy throughout. Both matrix rows pass.
      2. BestEffort_DisconnectThenReassign (QA-requested G5
         pass-gate shape) — 30 LBAs shipped Healthy; transport
         kill via peer.executor.InvalidateSession +
         peer.Invalidate (simulates mid-stream conn severed);
         30 more LBAs written best-effort (primary persists
         locally, peer Degraded, OnLocalWrite returns nil);
         fresh replica spun up on new addr; fake-master
         UpdateReplicaSet with gen=2 rebuilds peer (INV-REPL-
         PEER-REBUILD-ON-AUTHORITY-CHANGE); 10 LBAs shipped
         against fresh replica byte-exact.

         Pass-gate fence: asserts the second-batch LBAs do
         NOT appear on the fresh replica — catch-up is T4c
         territory. Catches scope leak if a future refactor
         quietly pulls catch-up into T4a.

    Cleanup discipline (learned from T4a-4 test hang):
      - replica cleanups registered BEFORE primary so LIFO
        ordering closes primary's peer sessions first (no
        listener.Stop() wedged on open client conns).
      - DisconnectThenReassign creates a second replica after
        primary, so it explicitly calls primary.repVol.Close()
        at scenario end to unblock the non-LIFO cleanup chain.

Verification: full 20-package repo suite green (all pre-existing
tests pass after WriteObserver addition — backward compat
preserved via optional observer pointer). T4a-6 matrix: 4 test
rows all pass (2 scenarios × 2 backends). No -race on Windows
(CGO_ENABLED=1 requirement documented in MEMORY.md).

T4a batch close now mechanically satisfied; awaiting QA sign +
T-end three-sign per §8C.2 cadence.
2026-04-23 17:07:29 -07:00
wzcheng99 db3be2e58c T4a-5: wire Host authority-callback to ReplicationVolume (P-refined)
Completes the T4a-5.0 §8C.3 Discovery Bridge resolution (Option
P-refined, landed per architect + QA round-19). Extends the
AssignmentFact wire with master-minted peer set + monotonic
generation, adds a separate host-only decode path that does NOT
touch AssignmentInfo (preserves the TestNoOtherAssignment
InfoConstruction AST fence), and wires Host.streamOnce to drive
ReplicationVolume.UpdateReplicaSet after every self-replica
AssignmentFact.

Guardrails (all four from round-19) honored:
  1. decodeAssignmentFact unchanged; AST fence stays green.
  2. decodeReplicaTargets is SEPARATE and produces replication.
     ReplicaTarget + generation, never AssignmentInfo. Adapter +
     engine packages: zero changes.
  3. Peer set is master-minted only. Host does NOT accumulate or
     derive from other-replica facts (option R rejected).
  4. peer_set_generation mandatory on the wire; monotonic guard in
     ReplicationVolume.UpdateReplicaSet.

Changes:

  core/rpc/proto/control.proto
    NEW message ReplicaDescriptor{replica_id, epoch, endpoint_
    version, data_addr, ctrl_addr}. AssignmentFact gains
    `repeated ReplicaDescriptor peers = 7` (excludes self) and
    `uint64 peer_set_generation = 8` (monotonic, master-minted).

  core/rpc/control/control.pb.go + control_grpc.pb.go
    Regenerated via scripts/genproto.sh.

  core/host/master/services.go
    SubscribeAssignments fills fact.Peers via new collectPeers
    helper (reads Publisher.LastPublished for each non-self slot
    in the volume's accepted topology). Generation derived as
    `(info.Epoch << 32) | info.EndpointVersion` — monotonic
    because publisher's lex-dedupe upstream guarantees strictly-
    increasing (Epoch, EV) pairs and Epoch/EV are durable authority
    facts (survives master restart).

  core/host/volume/subscribe.go
    NEW decodeReplicaTargets(fact) ([]replication.ReplicaTarget,
    uint64) — strict field-copy, same discipline as decode
    AssignmentFact. Produces a different output type so the
    AST fence TestNoOtherAssignmentInfoConstruction continues to
    pass.

  core/host/volume/host.go
    Config gains `ReplicationVolume *replication.ReplicationVolume`
    (nil = T0/observer-only; non-nil = T4a-5 production wire).
    streamOnce self-replica branch calls UpdateReplicaSet(gen,
    targets) AFTER adapter.OnAssignment. Non-blocking log on
    error (best-effort; failure does not stop the assignment
    stream).

  core/replication/volume.go
    UpdateReplicaSet signature break (QA option (a), no shim):
      Before: UpdateReplicaSet(targets []ReplicaTarget) error
      After:  UpdateReplicaSet(generation uint64, targets []ReplicaTarget) error

    Three-way generation rule (T4a-5.0 §9.4, QA corrected sw's
    original MaxUint64 sentinel which would have one-way-poisoned
    the monotonic guard):
      - gen == 0: unversioned apply; peer map mutated;
        lastAppliedGeneration NOT advanced. Test/fake-master only.
      - gen > 0 && gen > lastApplied: apply + advance.
      - gen > 0 && gen <= lastApplied: stale; peer map NOT mutated;
        replayedGens counter increments; debug log emits peer-ID-
        set delta (Q2 binding — IDs only, not full target structs).
        Returns nil (idempotent replay is success).

    Empty peer set (N → 0) flows through the same teardown path as
    any N → M-1 removal. No special branch (Q3 binding).

    New state: lastAppliedGeneration uint64 (mu-guarded);
    replayedGens atomic.Uint64 (stats counter, private; public
    Stats() deferred to T4-end observability pass).

    New helpers (internal): peerIDSet, targetIDSet,
    stringSetEqual, formatIDSet (deterministic brace-form
    rendering of peer-ID sets for log diffs).

  core/replication/volume_test.go
    All 8 existing tests migrated to new signature with gen=0
    (unversioned apply preserves previous functional semantics).
    3 new tests (Q1/Q2/Q3 pins):
      9.  UpdateReplicaSet_Generation_MonotonicGuard — advance
          through gens 1, 2, 3; stale replays at gen=2 and gen=3
          (equal is stale); verify replayedGens counter; forward
          progress at gen=4 works. Exercises Q2 differing-peers
          path via the gen=2 replay with original r1+r2 set.
      10. UpdateReplicaSet_GenerationZero_DoesNotAdvanceGuard —
          gen=5 applied, gen=0 applied (peers mutated, last
          Applied stays at 5), gen=3 rejected as stale. Pins the
          correctness of the gen=0 rule vs. the original
          MaxUint64 sentinel which would have failed this test.
      11. UpdateReplicaSet_EmptyPeerSet_AppliesWithTeardown — Q3
          binding three assertions: PeerCount=0 after empty
          apply, all former peers' executor sessions invalidated,
          next OnLocalWrite succeeds as zero-fanout no-op.

Verification: full 20-package repo suite green (core/host: 124s
including supersede_integration_test; core/host/volume: 31ms
confirming AST fence TestNoOtherAssignmentInfoConstruction still
passes; core/replication: all 17 tests green). G-2 tri-line godoc
on every new public surface.

Closes T4a-5.0 §8C.3 Discovery Bridge. Next: T4a-6 L2 subprocess
integration test.
2026-04-23 16:50:01 -07:00