Commit Graph
174 Commits
Author SHA1 Message Date
pingqiuandClaude Opus 4.7 aa05cff2df test(transport): pillar 2 C — deterministic faulty-store failure (was wire-abort race)
§6.10 BASE bypass (commit 055fd46) made base lane fast enough that
the original Pillar 2 C wire-abort test became race-prone:
sometimes the entire session — base + WAL + barrier round-trip —
completed before the test's "close every accepted conn" code path
fired, leading to Success=true when the test expected Success=false.
Reproduced as ~3/20 fail rate after the §6.10 change.

Switch the failure mechanism from "close conn mid-session" (timing-
dependent) to faulty-read substrate (deterministic): the same
faultyReadStorePillar2 used by Pillar 2 A. Read fails after 4
successful base-block reads → streamBase returns Substrate failure →
bridge onClose → OnSessionClose with Success=false. No wire timing
involved.

The semantic claim of the test is unchanged: prove that a session
which fails on the failure path triggers rule-2 emit-context restore.
Pre-session SnapshotEmitContext returns (nil, zero, SteadyMsgShip)
on a fresh replica; post-session snapshot must equal pre-session.
That assertion is preserved.

What's no longer in scope here:
  - Mid-session network drop / replica crash specifically — this
    test no longer claims to exercise that path. Future "real
    network drop" coverage would need a controllable wire-fault
    listener (test-infra follow-up); slice-1 deferred wire-tap
    helper covers the same cost-of-test-infra slice.

Stability: 20 consecutive runs of TestPillar2C alone, 5 consecutive
full-transport-suite runs, all green post-fix.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 13:47:02 -07:00
pingqiuandClaude Opus 4.7 055fd468a0 storage+recovery: §6.10 BASE bypass — WriteExtentDirect + RebuildSession switch
Implements consensus §6.10 (INV-RECV-BITMAP-CORE / INV-RECV-WAL-NAIVE):
BASE lane writes go directly to extent, bypassing the LSN-tracked WAL
apply path entirely. The receiver's per-session bitmap is the sole
arbiter of BASE-vs-WAL conflict at this LBA; substrate stale-skip is
irrelevant for BASE because BASE never enters the WAL.

Substrate contract delta (LogicalStorage):

  + WriteExtentDirect(lba uint32, data []byte) error

  Writes one block's bytes to the substrate's extent. No LSN. No
  frontier (R/S/H) advancement. Substrate stale-skip / WAL apply
  machinery NOT invoked. Receiver pairs with AdvanceFrontier in
  MarkBaseComplete to keep post-rebuild frontier reporting honest.

Implementations:

  - BlockStore       — write to in-memory blocks map; nextLSN/walHead
                       untouched.
  - memorywal        — append a record with LSN=0 sentinel; no
                       retention/nextLSN advance. Receiver bitmap
                       discipline keeps semantics correct (BASE only
                       reaches substrate when WAL hasn't touched LBA).
  - WALStore         — wraps existing private writeExtent; pwrites to
                       extent file, no WAL append, no dirty-map entry.
  - smartwal.Store   — pwrites directly to extent at lba's offset; ring
                       NOT touched, no LSN/frontier advance.

RebuildSession changes:

  - ApplyBaseBlock now calls store.WriteExtentDirect(lba, data) instead
    of store.ApplyEntry(lba, data, targetLSN). The targetLSN-as-base-LSN
    POC compromise (which silently rode substrate stale-skip) is gone.
  - MarkBaseComplete now calls store.AdvanceFrontier(targetLSN) — the
    explicit frontier-advance that ApplyEntry's side effect previously
    provided implicitly. Pre-§6.10, BASE applies bumped walHead per
    LBA; now we make the bump explicit at base-done.

Contract test (TestContract_WriteExtentDirect): pins
  - WriteExtentDirect succeeds and Read returns the bytes
  - Frontier (H) and nextLSN MUST NOT advance (BASE has no LSN)
  - Subsequent ApplyEntry at LSN > 0 shadows the BASE bytes
runs against BlockStore-mem / WALStore / MemoryWAL.

Refs: v3-recovery-algorithm-consensus.md §6.10 (INV-RECV-BITMAP-CORE,
INV-RECV-WAL-NAIVE); §6.3 cursor-monotonic sender invariant; mini-plan
§12 design-candidate doc-track.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 13:46:45 -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 39d57f215a test(transport): pillar 3 slice-1 polish per architect review
Non-blocking improvements landed before slice-2:

  1. AchievedLSN assertion. Was log-only; now asserts
     res.AchievedLSN == post-session primary.H, which is
     frozenTarget + len(overwrites) by construction. Tighter than
     "achieved >= target" — catches a SessionLive frame that
     silently didn't apply (achieved would lag) or barrier ack
     drifting past the actually-shipped tail.

  2. Convergence assertion now compares replica.Read(lba) against
     primary.Read(lba) directly (replica == primary), not just
     against the cached bRefs payload. Defence-in-depth: if a
     future receiver bug diverges from primary in a way that
     "happens to" still match the cache, the primary-direct
     comparison catches it. bRefs check retained as test-internal
     sanity that the live-write payload itself wasn't dropped.

  3. Comment fix: "5× locally" → "10 consecutive runs" to match
     what the stability check actually did.

  4. Companion-SHA list in the file header now lists cf232f2
     (this slice itself) alongside Phase 0 / C3 / Pillar 2
     commits — easier blame.

10× consecutive runs deterministic post-polish; cross-package
sweep (transport / recovery / replication) all green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 11:50:40 -07:00
pingqiuandClaude Opus 4.7 cf232f2866 test(transport): pillar 3 slice-1 — same-LBA arbitration on transport stack
Mini-plan §11.7 pillar 3 (receiver-side convergence): when the same
LBA is touched by both the backlog (WAL ≤ targetLSN) AND a live
write during the session (WAL > targetLSN flushed at seal), the
replica's final state matches the higher-LSN write. AtomicSeal and
Pillar 2 B both use disjoint LBA ranges (push window > base window),
so neither asserts the arbitration claim.

Single subtest in core/transport/pillar3_convergence_test.go:

  TestPillar3Slice1_ReceiverConvergence_LiveOverwritesBacklog_SameLBAs
    - Seed primary with 12 LBAs (LBA 0..11, pattern A_i). Sync,
      primaryH=12.
    - StartRebuild with frozenTarget=12.
    - After OnSessionStart: live-overwrite LBA {3, 5, 7} with pattern
      B_i (LSN 13/14/15 > frozenTarget → SessionLive path).
    - After barrier: untouched LBAs (0,1,2,4,6,8,9,10,11) → seed A;
      overwritten LBAs (3,5,7) → live B.

The discriminating assertion is on the overwritten LBAs: a receiver
without proper wire-ordering or apply-order arbitration could leave
those LBAs at A. Convergence to B for all three captures the
INV-PILLAR3-SAMELBA-CONVERGENCE invariant. Verified deterministic
across 10 consecutive runs.

In-scope (slice-1):
  - Transport stack only (NewBlockExecutorWithDualLane + real
    RecoverySink + runDualLaneListener + real receiver).
  - Single arbitration assertion across multi-LBA seed + overwrites.

Out of scope (deferred):
  - Full engine/cluster path (component.Cluster.DriveAssignment +
    DriveProbeResult) — slice-2 territory.
  - §IV T2 (architect-open at consensus §IV) — this slice asserts
    barrier semantics under a frozen target only.
  - RF > 1, long-duration soak.
  - Wire-level frame tap with explicit LSN-monotonicity proof —
    convergence here is asserted via post-barrier replica reads;
    frame integrity remains transitive (any torn frame → receiver
    decode fail → session.Success = false).

Refs: v3-recovery-wal-shipper-mini-plan.md §11.7 pillar 3 (receiver
convergence). Companion to 11392ba / eb4071e / cc457c0 / ceac3bf.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 11:45:10 -07:00
pingqiuandClaude Opus 4.7 ceac3bfc84 test(transport): pillar 2 — fault-injection on the assembled stack (A+B+C)
Mini-plan §11.7 pillar 2: same fault dimensions as C3 fault-injection,
but on the manager-assembled stack (BlockExecutor + PrimaryBridge +
real RecoverySink + recovery.Sender + resident WalShipper +
PeerShipCoordinator under unified replicaID). C3 used a spy
WalShipperSink and net.Pipe; this slice exercises the same robustness
through TCP + real receiver.

Three sibling tests in core/transport/pillar2_assembled_test.go:

  A — TestPillar2A_BaseError_AssembledStack_FailReason
      faultyReadStorePillar2 wraps the primary; Read fails after 4
      successful base-block reads. Asserts: OnSessionClose Success=false
      with FailReason wrapping the synthetic error; coord.Phase back to
      Idle (EndSession defer ran); replica.R < primary.H (recovered
      frontier never reached the target — barrier never fired).

  B — TestPillar2B_LiveWrites_HighPressure_BarrierIntegrity
      Sibling to TestDualLane_LiveWritesDuringSession_AtomicSeal with
      different focus: larger backlog (300 entries) + more pushers
      (16 × 8 = 128 attempts) for genuine writeMu contention; stricter
      convergence (replica.H == primary.H exactly post-barrier — not
      asserted by AtomicSeal). Frame integrity is asserted transitively
      through Success=true: any torn frame would fail receiver decode.
      Documents wire-tap as a future test-infra follow-up.

  C — TestPillar2C_WireAbortMidSession_AssembledStack_RestoresEmitContext
      Production-equivalent abort: peer drops connection mid-session
      (network failure / replica crash) — startRebuildDualLane uses
      context.Background, so wire close is the closest analog to C3's
      ctx-cancel test. Snapshots the resident WalShipper's pre-session
      emit context, aborts mid-session, asserts post-session snapshot
      equals pre (rule-2 restore). Plus: OnSessionClose with FailReason,
      coord.Phase=Idle.

What's intentionally out of scope:
  - Wire-level frame tap with explicit decode + LSN-monotonicity
    (current tests prove integrity transitively).
  - Pillar 3 (receiver convergence with live writes during session,
    bitmap/barrier interaction, T2 hardware soak).
  - streamBase ctx-awareness (C3 #2B variant — separate follow-up).

Refs: v3-recovery-wal-shipper-mini-plan.md §11.7 pillar 2; architect
sign-off "A+B+C 一个 commit"; Phase 0 unified replicaID (11392ba).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 11:34:04 -07:00
pingqiuandClaude Opus 4.7 cc457c06c4 test(recovery): C3 fault-injection — BASE/WAL goroutine pair termination
Three table-shaped subtests covering the failure paths of Sender.Run's
BASE ∥ WAL goroutine pair (§6.8 #6 / P6 / G3). Companion to the
existing TestC3_BaseWalParallel_FramesInterleave (happy path /
overlap claim).

  #1  BASE error → WAL exits via groupCtx.Done
      Faulty store fails primaryStore.Read after N reads; streamBase
      returns a Substrate failure; groupCancel from BASE goroutine
      unblocks DrainBacklog parked on ctx; spy sink confirms
      drainCtxErrSeen != nil; lifecycle counters StartSession=1,
      EndSession=1; Run returns within 2s.

  #3  Outer ctx cancel → both lanes wind down
      Caller cancels parent ctx mid-session after WAL goroutine has
      entered DrainBacklog. Run returns within 2s; coord.EndSession
      defer fires (Phase back to Idle); sink.EndSession defer fires
      exactly once; DrainBacklog observed ctx cancellation.

  #2A WAL error → Run terminates (variant A — narrow)
      Spy sink returns synthetic error from DrainBacklog. BASE
      goroutine runs to completion (small store; streamBase is not
      ctx-aware). Run returns the WAL failure with PhaseBacklog;
      errors.Is unwraps to the synthetic; lifecycle counters correct.

      NOT asserted: prompt BASE stop on WAL failure. streamBase has
      no ctx-check today; variant B (future follow-up) would pair a
      periodic groupCtx.Err() check inside streamBase's loop with a
      strict prompt-stop assertion. Test header documents this.

Spy WalShipperSink: structural-typing match (no exported types added);
records StartSession / DrainBacklog / EndSession call counts; per-test
drainBehavior selects immediate / block-until-ctx / synthetic-error.

Refs: v3-recovery-wal-shipper-mini-plan.md §11.7 pillar 2 (dual-line
execution); architect-recommended scope #1 + #3 + #2A.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 11:15:45 -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
pingqiuandClaude Opus 4.7 11392baf41 fix(transport): unify replicaID in startRebuildDualLane (Phase 0 Fix #1)
INV-RID-UNIFIED-PER-SESSION: the engine arg replicaID is the single
source of truth for keying coord / WalShipper / sink / bridge for a
recovery session. Pre-fix, startRebuildDualLane built the RecoverySink
with the engine arg but called bridge.StartRebuildSessionWithSink with
the construction-time dl.ReplicaID. If the two diverged, the post-emit
hook keyed coord.RecordShipped under arg while the bridge keyed
coord.PinFloor under dl.ReplicaID — the keys never reconciled, no
error fired, watchdog timed out long after.

Fix:
  (a) Fail-closed assert at session entry: non-empty dl.ReplicaID must
      equal recovery.ReplicaID(arg). Empty stays permissive (legacy /
      test omission; arg flows through unchanged).
  (b) Thread argRID through to bridge.StartRebuildSessionWithSink so
      coord and sink key uniformly under arg from this point on.

Tests (core/transport/replicaid_unified_test.go):
  - TestPhase0Fix1_DriftRejected_FailsClosedAtEntry: non-empty drift
    returns error before any wire activity; coord.Phase Idle under
    both IDs; OnSessionStart/Close never fire.
  - TestPhase0Fix1_HappyPath_ArgEqualsConstructionID: aligned IDs,
    full rebuild, frontier converges, coord returns to Idle.
  - TestPhase0Fix1_EmptyConstructionRID_ArgFlowsThrough: empty
    construction RID bypasses guard; arg keys both bridge and sink;
    coord lifecycle observed under arg, never under empty key.

Refs: v3-recovery-execution-institution.md "Entity layering &
assembly contract" Phase 0; v3-recovery-wal-shipper-mini-plan §11.6.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 10:56:57 -07:00
pingqiu 4f6d5c22e4 docs: drainOpportunity comment matches §13 dual-mode contract
Architect code-review caught comment/code mismatch: docstring above
drainOpportunity still said "Realtime mode: if cursor < head, scan
to fill the gap" — but the implementation correctly returns early
when mode != ModeBacklog (matches consensus §13 E-WALSHIPPER-DUAL-
MODE / mini-plan §11.2a / T4a no-replay carve-out).

Risk this doc-debt prevented: future contributor reads the stale
comment, "fixes" the function to scan in Realtime, re-introduces
the silent-divergence bug C2 closed (Realtime substrate scan would
replay dead-window writes when peer comes back online).

Comment now states the dual-mode contract explicitly with a
DO-NOT-ADD-A-REALTIME-BRANCH warning citing §13 / T4a / CHK-
WALSHIPPER-TIMER-DRAIN's ModeBacklog scope.

No code logic change.

go test all four packages — PASS.
2026-04-30 09:47:15 -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
pingqiu 14a0d32d40 docs: §6.8 review-derived invariants — DisableTimerDrain + lock order
Architect review of C1+C2+C3 (offline against §6.8 / §IV / §V) flagged
two doc gaps that should be inline in the code, not just PR descriptions:

1. DisableTimerDrain (wal_shipper.go WalShipperConfig):
   - PRODUCTION MUST leave false. §6.8 #4 is MUST: "primary-idle
     starvation forbidden". Setting true in production violates
     architect contract.
   - Test-only invariant: shipper MUST NOT linger in cursor < head
     without alternative drain source. Today's only users are R2
     saturation tests (scope-bounded).

2. Lock hierarchy (executor.go walShipperEntry.writeMu):
   - shipMu → writeMu (always; reversal risks deadlock).
   - WalShipper holds shipMu; calls EmitFunc under it; EmitFunc
     acquires writeMu.
   - recovery.Sender.writeFrame acquires only writeMu (does not
     hold shipMu). Order is consistent: shipMu outermost when both
     in play.

No code logic change; documentation tightening so future readers
can verify §6.8 mechanical SINGLE-SERIALIZER without re-deriving
from grep.

go test all four packages — PASS.
2026-04-30 08:56:49 -07:00
pingqiu dd370a5367 C3: BASE ∥ WAL parallel in Sender.Run (§6.8 #6 / P6 / G3)
Architect §6.8 #6 BASE ∥ WAL WALL-CLOCK OVERLAP: extent/base bulk
SHOULD overlap WAL drain where product permits (reduces wall-clock
pin exposure). Pre-C3 Sender.Run ran streamBase fully before
sink.DrainBacklog — strictly serial.

Sender.Run now spawns two goroutines:
  Base goroutine:  streamBase → frameBaseDone → coord.MarkBaseDone
  WAL goroutine:   sink.StartSession → sink.DrainBacklog

Both share writeMu via C1 (sink's WriteMu() duck-typing). Frame
integrity preserved by mutex-bounded interleaving on the wire —
two writers never interleave bytes within a single frame. Wall-
clock benefit comes from CPU/IO overlap (substrate scans, encoding,
small base-block writes).

Coordination:
  - groupCtx with cancel; first failing goroutine cancels to
    unblock the other (in particular DrainBacklog observes ctx).
  - Both error channels collected; first non-nil error returned.
  - Barrier writes after both goroutines complete (errgroup-Wait
    pattern via two channels).

Note on physical reality: shared writeMu means base waits on slow
WAL writes (and vice versa). This is correct serialization. Hard
SLO on base under bursty WAL would need a separate credit channel
(out of scope §6.8 #6 strict reading; see consensus §6.8 note).

Test:
  + TestC3_BaseWalParallel_FramesInterleave — receiver-side capture
    parses sender's wire stream into a frame sequence; asserts at
    least one frameWALEntry appears BEFORE the last frameBaseBlock
    in that sequence (interleaved progress, not strictly base-
    then-WAL). Verified: firstWAL index << lastBase index.

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

C1+C2+C3 close §6.8 nine MUSTs:
  ✓ #1 SINGLE-SERIALIZER (C1: shared writeMu)
  ✓ #2 ONE TAPE (single shipMu + cursor; substrate is canonical)
  ✓ #3 PRIORITY (C2: drain in cursor order during Backlog)
  ✓ #4 TIMER (C2: self-driving Backlog drain)
  ✓ #5 FRAMING ≠ SECOND TAPE (P2d: profile selects encoder, not tape)
  ✓ #6 BASE ∥ WAL (C3: errgroup goroutines)
  ✓ #7 R1 (existing: assertCaughtUpAndEnableTailShipLocked)
  ✓ #8 R2 (existing: OnSaturation single-shot per session)
  ✓ #9 send(·,·) consistency (C2: NotifyAppend + drain dispatch)
2026-04-30 03:11:54 -07:00
pingqiu 78169075c2 C2: WalShipper self-driving Backlog drain + DisableTimerDrain config
§6.8 #4 / consensus v3.8 §V CHK-WALSHIPPER-TIMER-DRAIN: Backlog mode
must self-drive via periodic timer (or shipper-internal loop) so
backlog cannot depend solely on new appends — primary-idle
starvation forbidden.

Scope (architect framing):
  - §6.8 #4 TIMER drain applies to BACKLOG mode (recovery session
    backlog phase). Realtime mode is driven by NotifyAppend (T4a
    best-effort steady ship).
  - Realtime NotifyAppend keeps direct-emit semantics (cursor advances
    1:1 with caller's lsn). The strict "cursor < head → drain" path
    in Realtime broke T4a's no-replay invariant (dead-window writes
    surfaced on a fresh peer post-rebuild — that's T4c territory).

WalShipper additions:
  + EmitKind enum + EmitFunc signature gain `kind` param (delivered
    in C1's predecessor commit; carried here for completeness).
  + nudgeCh / stopCh / timerDone goroutine plumbing.
  + timerLoop runs for shipper's lifetime; stops via Stop() (also
    called from Stop chan close).
  + drainOpportunity: scans substrate from cursor, emits in scan
    order, advances cursor; post-scan R1 transition opportunity
    (Backlog → Realtime when caught up).
  + nudgeDrainLocked for sub-IdleSleep wake (collapses multiple
    nudges into one wake).

WalShipperConfig:
  + DisableTimerDrain (default false) — suppresses the goroutine
    for tests that need manual DrainBacklog control (R2 saturation
    tests drive lag without auto-drain interfering).

NotifyAppend behavior:
  - Backlog mode: lag-only (no emit). Drain is the emit path.
  - Realtime mode: direct emit using caller's data.
  - Idle mode: silent no-op.

Substrate ScanLBAs semantics:
  - fromLSN passed as cursor directly. memorywal exclusive lower;
    smartwal inclusive lower; callback's `e.LSN <= s.cursor` filter
    aligns both. ErrWALRecycled treated as transient (engine layer
    re-anchors session).

Tests:
  + TestC2_TimerDrainsIdle (CHK-WALSHIPPER-TIMER-DRAIN) — substrate
    seeded; StartSession(0); timer alone catches up cursor + R1
    transitions Backlog → Realtime. NO NotifyAppend or DrainBacklog
    calls.
  + TestC2_PriorityOldFirst — drain emits LSN-ascending (oldest
    first); all kind=EmitKindBacklog (Backlog scan).
  + TestC2_NoGapDenseLSNEdge — substrate seeded + drained; then a
    Realtime NotifyAppend for one new entry direct-emits (the dense
    single-LSN case the user flagged).
  + TestC2_TimerNudge_FromNotifyAppend — skipped placeholder for
    future Backlog-mode nudge from external trigger.

Existing tests:
  - TestWalShipper_R2_LagSignalFires / NoSpuriousSignal — added
    DisableTimerDrain: true so test drives lag manually (auto-drain
    would catch up and saturation never fires).

go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS.
2026-04-30 03:09:42 -07:00
pingqiu c314b608df C1: shared writeMu + post-emit RecordShipped hook (§6.8 #1)
Architect review of ad7bc74 against §6.8 / consensus v3.8 nine
MUSTs: two correctness fixes — concurrency safety (writer race) +
accounting (missing RecordShipped on WalShipper-routed path).

§6.8 #1 SINGLE-SERIALIZER (mechanical):
  walShipperEntry adds writeMu sync.Mutex.
  EmitFunc holds it during conn.Write.
  recovery.WalShipperSink gains optional duck-typed sub-interface
    `interface{ WriteMu() *sync.Mutex }`. transport.RecoverySink
    implements it via e.WalShipperWriteMu(replicaID).
  recovery.Sender.NewSenderWithSink: duck-types the sink; if WriteMu()
    present, sender.sharedWriter = sink.WriteMu(). writeFrame uses
    sharedWriter when set, falling back to its own writerMu otherwise.

  Result: in dual-lane sessions, Sender.writeFrame (SessionStart /
  BaseBlock / BaseDone / BarrierReq) AND EmitFunc (frameWALEntry)
  serialize on the same per-replica entry mutex. No more interleaved
  header/payload from two concurrent writers on the same conn.

  Steady (Ship) path uses entry's own writeMu uncontended (only Ship
  writes the legacy port).

Accounting (post-emit RecordShipped):
  walShipperEntry adds postEmit func(lsn uint64). EmitFunc fires
  outside writeMu after a successful conn.Write.
  WalShipperSink gains optional sub-interface
    `interface{ SetPostEmitHook(func(lsn uint64)) }`.
  RecoverySink implements via e.SetWalShipperPostEmitHook.
  recovery.Sender.Run: at session start (after defers), checks if
    sink supports SetPostEmitHook; if so, installs
    func(lsn) { coord.RecordShipped(replicaID, lsn) } and clears
    via defer at session end.

  Result: each successful WalShipper-routed emit (Backlog scan or
  Live NotifyAppend) advances coord.shipCursor in lockstep with
  emit. Pre-C1 the dual-lane path silently left shipCursor at
  fromLSN; future code that depends on the cursor (BacklogDrained,
  TryAdvanceToSteadyLive, observability) was latent-broken.

Tests:
  + TestC1_WriteMu_SharedAcrossSenderAndWalShipper — sink.WriteMu()
    and executor.WalShipperWriteMu return same mutex address.
  + TestC1_WriteMu_NoInterleave — concurrent NotifyAppend emits
    parse cleanly as a sequence of well-formed recovery frames
    (no header/payload interleave detected).
  + TestC1_PostEmitHook_AdvancesShipCursor — full dual-lane rebuild
    completes cleanly; replica frontier reaches primaryH; coord
    returns to Idle. Exercises the post-emit hook on every shipped
    LSN without panic / hook misuse.

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

Companion: sw-block design mini-plan §11.2 / §11.3 (commit 058305225
on seaweedfs/feature/sw-block).
2026-04-30 02:38:30 -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
pingqiuandClaude Opus 4.7 a96373dda9 transport: pin protection + ack-feedback advance + release tests
Pins the user-stated architectural invariant:

  Steady: WalShipper handles NotifyAppend (recv) + emit (peer).
  Recovery session: pin floor PROTECTED at fromLSN so substrate WAL
    retention can't recycle entries the session still needs.
  Pin advances via FEEDBACK: replica BaseBatchAck → recovery.Sender
    readerLoop → coord.SetPinFloor → pin advances; substrate may
    now recycle below the new floor.
  Session end: pin released.

Tests:

  + TestPin_ProtectedDuringSession_AdvancesViaFeedback_ReleasedOnEnd —
    full single-replica lifecycle:
      1. coord.StartSession → pin = fromLSN
      2. RecoverySink.StartSession → WalShipper Backlog;
         pin still = fromLSN (shipper mode change must NOT move pin)
      3. coord.SetPinFloor(replica, ackLSN, S) — simulates
         readerLoop's BaseBatchAck translation; pin advances
      4. Out-of-order lower-LSN ack: pin must NOT regress
      5. RecoverySink.EndSession → shipper Realtime;
         pin survives (sink.EndSession is shipper-side, doesn't
         release coord pin)
      6. coord.EndSession → pin released to 0

  + TestPin_MultiSession_MinPinAcrossActiveSessions — cluster-wide
    invariant: WAL retention gated by min pin across all active
    sessions. Slow replica's pin floors the whole cluster; fast
    replicas advancing past it don't unlock recycling. After all
    sessions end, anyActive=false and no floor is enforced.

Together these confirm the user's architecture: WalShipper-side
mode transitions and coord-side pin lifecycle are orthogonal —
sink.EndSession ≠ session-pin-release; only coord.EndSession
releases. Production callers (recovery.Sender.Run defer) call BOTH
on every exit path, which is what the existing wiring already does.

go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (no regressions; 2 new tests).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 00:49:04 -07:00
pingqiuandClaude Opus 4.7 822d8414f1 transport: WalShipper-as-resident integration tests
Pins the algorithmic invariant the user named in §10 framing:

  WalShipper 常驻; recovery 时是 Backlog; 追平后仍在同一实例上变成
  Realtime, 再接 steady 的 NotifyAppend.

One resident WalShipper per (volume, replicaID); steady ship and
recovery sessions share the SAME instance; mode transitions are
internal to the shipper; the recovery session is just a bracket
(StartSession / EndSession) around it.

Tests:

  + TestWalShipper_Resident_SameInstanceAcrossSessions —
    INV-SINGLE: WalShipperFor returns the same instance during
    and after multiple consecutive RecoverySink-bracketed sessions
    on the same replica.

  + TestWalShipper_Resident_ModeTransitionsAcrossSessions —
    pins the cycle: Realtime → (StartSession) → Backlog →
    (DrainBacklog R1) → Realtime → (EndSession) → Realtime,
    repeatable across consecutive sessions.

  + TestWalShipper_Resident_SteadyShipBetweenSessions — full
    timeline: steady NotifyAppend → recovery session 1 → steady
    NotifyAppend → recovery session 2 → steady NotifyAppend.
    Recording EmitFunc captures all emits; verifies the three
    steady-phase emits use steady lineage (rule 2 holds across
    multiple bracket cycles).

  + TestWalShipper_Resident_NotifyAppendDuringSession_BacklogMode —
    while a session holds the shipper in Backlog mode, concurrent
    steady NotifyAppend calls are lag-only (no emit). After
    EndSession, post-session NotifyAppend emits normally under
    restored steady context. Pins the mode-decision boundary.

go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (no regressions; 4 new tests).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 00:43:06 -07:00
pingqiuandClaude Opus 4.7 946dee3031 transport: dual-lane E2E failure-path coverage
Three failure-mode tests pinning clean teardown across the full
StartRebuild → bridge → Sender → wire stack:

  + TestDualLane_ReplicaListenerStopped_BeforeRebuild — listener
    closed before dial; StartRebuild surfaces the dial error
    synchronously; coordinator never advances past Idle (session
    never registered).

  + TestDualLane_ReplicaListenerStopped_MidSession — listener
    accepts and immediately closes the conn (no Receiver behind it);
    Sender's first writeFrame fails with Wire failure; OnSessionClose
    fires Success=false; coordinator returns to Idle via Sender.Run's
    deferred coord.EndSession; PrimaryBridge's senders entry torn
    down (subsequent PushLiveWrite returns "no active session").

  + TestDualLane_SubsequentRebuild_AfterFailure_Succeeds — regression:
    after a failed rebuild teardown, a fresh rebuild on the same
    replica with a healthy listener succeeds end-to-end. Verifies
    registry / coordinator state is genuinely cleaned, not just
    dead-but-still-occupying-slots.

This pins the deferred-EndSession contract at the integration level:
no matter how Sender.Run exits (success, wire error, ctx cancel),
both sink.EndSession and coord.EndSession fire — observable as
PrimaryBridge sender-map cleanup + coordinator Idle.

go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (no regressions; 3 new tests).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 00:39:08 -07:00
pingqiuandClaude Opus 4.7 e2cde75d43 transport: dual-lane E2E with concurrent live writes during session
Closes the test gap the recovery package's e2e_test.go disclaimed at
the dual-lane (cross-process-shape) level: live writes pushed via
PrimaryBridge.PushLiveWrite during an active dual-lane rebuild
session, exercising senderBacklogSink.flushAndSeal's atomic-seal
boundary on the real TCP wire.

Tests:

  + TestDualLane_LiveWritesDuringSession_AtomicSeal — full chain:
      StartRebuild → engine→adapter→executor (dual-lane) → bridge →
      Sender.Run → streamBacklog (100 backlog LBAs) + flushAndSeal +
      barrier; concurrently 8 workers × 5 = 40 pushers via
      bridge.PushLiveWrite. Asserts the atomic-seal contract:
      every push that returned nil MUST be byte-equal on replica.
      Verified: 40/40 pushes accepted, all on replica.

  + TestDualLane_LiveWritesDuringSession_AchievedLSN — sanity
      lower bound: achievedLSN >= frozenTarget after backlog drain.

  + TestDualLane_PushLiveWrite_NoSession_Errors — bridge guard:
      PushLiveWrite without an active session returns an explicit
      "no active session for replica" error.

Substrate: memorywal on primary so live writes get LSN > frozenTarget
and streamBacklog filters them for flushAndSeal to ship as
WALKindSessionLive (BlockStore's walHead-synthesized LSN would have
collapsed all backlog entries past targetLSN under concurrent
primary.Write). Replica stays BlockStore.

This is G7 §2 #4 (concurrent writes during rebuild) in scope as the
architect ratified — the dual-lane bridging path now has end-to-end
coverage of that scenario, independent of P2d.

go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (no regressions; 3 new tests).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 00:37:23 -07:00
pingqiuandClaude Opus 4.7 de2dceaf32 recovery+transport: pre-decision integration helpers (P2d-parallel)
Two parallel-safe wiring helpers that don't lock in the dual-lane
wire-body format (P2d still architect-gated) but unblock the
production wiring sequence so the format swap, when it lands, is
mechanical.

transport.BlockExecutor.SnapshotEmitContext(replicaID):
  - Accessor that returns the per-replica WalShipper's current
    (emitConn, emitLineage) under emitCtxMu — same lock discipline
    as production EmitFunc.
  - Honest signal when no entry exists: returns (nil, zero) so
    callers can pass through to NewRecoverySink as the steady-
    restore values without a special case.
  - Canonical caller pattern (P2d-post): snapshot BEFORE
    constructing RecoverySink → pass to NewRecoverySink as the
    steady context → EndSession's rule-2 restore lands the right
    values.

recovery.PrimaryBridge.StartRebuildSessionWithSink(...):
  - New entry point that accepts an external WalShipperSink (e.g.,
    transport.RecoverySink wrapping the per-replica WalShipper).
  - Existing StartRebuildSession unchanged — continues to use the
    bridging senderBacklogSink path (legacy compatible).
  - Internal startRebuildSessionLocked is shared between the two
    public methods; switches between NewSenderWithBacklogRelay and
    NewSenderWithSink based on whether sink is nil.
  - Fail-closed: nil sink → explicit error (callers that want the
    bridging path call StartRebuildSession explicitly).

Tests:
  + TestSnapshotEmitContext_NoEntry_ReturnsZero
  + TestSnapshotEmitContext_AfterUpdate_ReturnsCurrent
  + TestSnapshotEmitContext_ThenRecoverySink_RestoresCaptured —
    end-to-end of the canonical wiring pattern: snapshot → build
    sink with snapshotted steady → run session → assert restored
    context matches snapshot.
  + TestPrimaryBridge_StartRebuildSessionWithSink_NilRejected
  + TestPrimaryBridge_StartRebuildSessionWithSink_InvokesSinkLifecycle —
    sink receives StartSession + DrainBacklog + EndSession in order
    when invoked through the bridge's public surface.
  + TestPrimaryBridge_StartRebuildSession_StillUsesBridgingSink —
    regression: legacy entry point still installs senderBacklogSink.

go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (incl. existing test suite, no regressions).

Production enable still requires P2d (wire body format / applier
owner / replay source). These helpers are "ready but not switched
on" — calling StartRebuildSessionWithSink today would produce a
wire-format mismatch on the dual-lane port (executor's EmitFunc
encodes MsgShipEntry; recovery.Receiver decodes frameWALEntry).
The §10 decision request on seaweedfs/feature/sw-block resolves
that.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 00:17:42 -07:00
pingqiuandClaude Opus 4.7 bb36a601b8 transport: RecoverySink — review-feedback doc tightening
Three doc-only follow-ups from architect code review of 845c810
(non-blocking; no logic changes):

  1. NewRecoverySink — explicit caller obligations:
     - Defer EndSession at the StartSession call site so a
       StartSession error path still restores steady context
       (recovery.Sender.Run already does this; production callers
       using NewRecoverySink directly must too).
     - nil sessionConn = programmer error (Realtime emits would have
       nowhere to go). nil steadyConn = honest only when no steady
       ship was in flight; next steady emit fails closed at EmitFunc.

  2. installRecordingShipper (test helper) — TEST-ONLY /
     single-goroutine note. The entry.shipper assignment bypasses
     walShipperMu deliberately; production paths take that mutex.
     Don't lift the pattern into production or concurrent tests
     without re-introducing the lock.

Test suite unchanged; go test ./core/transport/ -run TestRecoverySink
still PASS (6/6).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 00:03:03 -07:00
pingqiuandClaude Opus 4.7 845c81071d transport: RecoverySink adapter scaffolding + rules-1+2 tests
Pre-decision parallel work for P2d (per architect ratification): the
transport-side adapter that satisfies recovery.WalShipperSink by
duck typing, plus integration tests that pin architect P1 review
rules 1+2. No wire-format branching — the adapter inherits whatever
EmitFunc executor.WalShipperFor wired in. P2d resolves MsgShipEntry
vs frameWALEntry; this adapter survives that decision either
unchanged (if "unify on MsgShipEntry") or via swap of the underlying
shipper construction (if "use frameWALEntry on dual-lane port" or
envelope tag).

RecoverySink:
  - NewRecoverySink(executor, replicaID, sessionConn/Lineage,
    steadyConn/Lineage)
  - StartSession: updateWalShipperEmitContext(session) BEFORE
    WalShipper.StartSession (rule 1)
  - DrainBacklog / NotifyAppend: thin delegate
  - EndSession: WalShipper.EndSession FIRST, then
    updateWalShipperEmitContext(steady) (rule 2)

Tests (lifecycle ordering only — no wire decode):
  + TestRecoverySink_StartSession_InstallsSessionContext —
    direct post-condition, white-box check on entry.emitConn /
    emitLineage after StartSession returns.
  + TestRecoverySink_DrainBacklogEmits_UseSessionContext —
    rule 1 indirect: install recording EmitFunc; assert every
    backlog drain emit captures session context. Stale context
    would surface immediately on the first drain emit.
  + TestRecoverySink_EndSession_RestoresSteadyContext —
    rule 2 direct: post-EndSession entry context == steady.
  + TestRecoverySink_NotifyAppendAfterEndSession_UsesSteadyContext —
    rule 2 indirect: post-EndSession Realtime emit captures
    steady context at emit time.
  + TestRecoverySink_FullLifecycle — combined ordering across
    StartSession → DrainBacklog → EndSession → post-session
    NotifyAppend; each phase's emits use the expected context.
  + TestRecoverySink_SatisfiesWalShipperSink — compile-time
    duck-type check via locally re-declared interface (no
    recovery import to keep cycle-free option open).

Recording EmitFunc strategy: replace per-replica WalShipperEntry's
shipper with a fresh one whose EmitFunc reads emitConn/emitLineage
under emitCtxMu (same lock discipline as production) and records
into a slice. This captures the at-emit-time context — the only
honest evidence of rule-1 / rule-2 ordering without coupling to
wire format.

go test ./core/transport/ ./core/recovery/ ./core/replication/{,component} —
all PASS (incl. existing test suite, no regressions).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 23:57:52 -07:00
pingqiuandClaude Opus 4.7 8f51ec6f29 recovery: P2c-B-2 — delete Close/closeCh/liveQueue/drainAndSeal
Buffer state moves into senderBacklogSink (sinkMu / queue / sealed
fields, flushAndSeal method); Sender no longer owns any live-write
scaffolding. Sender.Run flow becomes:

  StartSession → BaseLane → BaseDone → sink.StartSession →
  sink.DrainBacklog → barrier → return

DrainBacklog (in the bridging sink) does scan + flushAndSeal +
seal atomically — sender.Run barriers as soon as it returns.
There is no engine "go barrier" signal anymore; the previous
sender.Close / closeCh / FinishLiveWrites pattern is gone.

Atomic-seal contract migrates from sender.drainAndSeal (queueMu)
to senderBacklogSink.flushAndSeal (sinkMu): NotifyAppend that lands
before the seal lock is captured + shipped; pushes after see
"sink sealed" error. EndSession is the defer-safety net (idempotent
seal so post-Run NotifyAppend still gets explicit error).

Deleted from Sender:
  - Close(), closeCh, closeOnce
  - queueMu, liveQueue, sealed, walItem
  - drainAndSeal, bufferLiveWriteLocked
  - PhaseAwaitClose

Deleted from PrimaryBridge:
  - FinishLiveWrites (engine→sender "go barrier" signal no longer
    needed — barrier auto-fires after DrainBacklog)

Updated:
  - transport/rebuild_sender.go: drop FinishLiveWrites call
  - sender.Run defer: just sink.EndSession + coord.EndSession
  - failure.go: remove PhaseAwaitClose

Tests rewritten per architect rule 3 (delete scaffolding once e2e
cases that inject mid-session writes pass barrier convergence
through the new path):

  e2e_test.go:
    - 5 sender.Close() calls removed
    - TestE2E_RebuildWithLiveWritesDuringSession: push live writes
      BEFORE sender.Run starts — sink buffers under sinkMu until
      flushAndSeal ships them
    - TestE2E_KindCountsPinsBacklogVsLive: substrate switched to
      memorywal (preserves write-time LSN) so push-before-Run
      preserves LSN > frozenTarget filter discipline; BlockStore's
      walHead-synthesized LSN would have shifted under push-before
    - TestE2E_PushLiveWriteAtomicSeal: race window is now between
      pushers and sink's flushAndSeal seal point; contract holds

  integration_stub_test.go:
    - TestIntegrationStub_LifecycleCallbacks: drop FinishLiveWrites
    - TestIntegrationStub_CtxCancelUnblocksSender: skipped — no
      idle wait window to cancel into post-B-2
    - TestIntegrationStub_FailureTypedOnCancellation: skipped —
      same reason

  sender_walshipper_sink_test.go:
    - TestSenderBacklogSink_NotifyAppend_BuffersForFlushAndSeal:
      white-box accessor now reads sink's queue (was sender's)
    - var _ WalShipperSink = &senderBacklogSink{} (pointer receiver)
    - TestSender_WithSink_DelegationOrder: drop sender.Close;
      Run barriers autonomously after DrainBacklog returns

Verified: all recovery (incl. 5 e2e) + transport + replication +
replication/component tests PASS. Net deletion: -175 lines.

Note: dual-lane frameWALEntry vs MsgShipEntry alignment remains
P2d. The bridging senderBacklogSink stays as the in-package sink
until then; once a real transport.WalShipper sink replaces it,
the buffer + flushAndSeal scaffolding here goes too.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 23:27:44 -07:00
pingqiuandClaude Opus 4.7 bf84ed4ab1 recovery: P2c-B-1 — single live path via sink.NotifyAppend (TDD)
Add NotifyAppend(lba, lsn, data) error to WalShipperSink interface.
Sender.PushLiveWrite now routes through s.sink.NotifyAppend instead
of touching liveQueue directly — the sink owns buffering / ordering
discipline.

Bridging path (senderBacklogSink) implements NotifyAppend by
buffering into the sender's liveQueue under queueMu — production
discipline (architect rule 2). streamBacklog is one-shot ScanLBAs;
direct wire emit during the scan would interleave LSNs and break
the receiver's monotonic-LSN check, so the buffer + ordered
drainAndSeal flush stays as the safety net until P2d aligns the
dual-lane wire format.

When P2d swaps in a real transport.WalShipper sink, NotifyAppend
will route to WalShipper.NotifyAppend (Backlog mode lag-tracking;
Realtime direct ship under shipMu) — at that point the queueMu /
liveQueue / drainAndSeal scaffolding can be deleted (slice B-2).

Tests:
  + TestSender_PushLiveWrite_RoutesViaSinkNotifyAppend — RED→GREEN,
    pins the routing contract (incl. error propagation from sink).
  + TestSenderBacklogSink_NotifyAppend_BuffersForDrainAndSeal — pins
    the bridging-path buffer discipline.

  recordingSink in tests gains NotifyAppend + snapshotNotifyAppend.

Verified:
  - go test ./core/recovery/ — all PASS, including 5 e2e tests
    (PushLiveWriteAtomicSeal exercises mid-session writes and
    barrier convergence end-to-end).
  - go test ./core/transport/ ./core/replication/{,component} — all PASS.

Note: dual-lane frameWALEntry vs MsgShipEntry alignment remains P2d;
backlog relay continues as the bridging sink until then.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 23:00:30 -07:00
pingqiuandClaude Opus 4.7 616583fc38 recovery: P2c-A — sink mandatory; remove legacy Run() else branch
Slice A (mechanical, dead-code removal):
  - NewSenderWithSink panics on nil sink (was: silent promote to legacy)
  - NewSender → private newSender (only used by sink-installing
    constructors as builder)
  - Run() drops the `if s.sink != nil { ... } else { legacy }` split;
    sink path is unconditional. INV-NO-DOUBLE-LIVE at recovery layer
    is now a structural guarantee (one emit path, not a runtime check)
  - TryAdvanceToSteadyLive call site removed (kickoff Q3 collapsed
    Phase enum to {Idle, Active}; barrier-ack is the completion
    signal)

Kept for slice B per architect framing:
  - Close, drainAndSeal, liveQueue, sealed, closeCh, queueMu, walItem
  - PushLiveWrite (still feeds session-lane tails until live writes
    route through WalShipper.NotifyAppend)
  - streamBacklog (called by senderBacklogSink.DrainBacklog)

Tests:
  + TestNewSenderWithSink_NilSinkPanics — locks sink-mandatory contract
  - TestSender_NoSink_FallsBackToLegacyBehavior — replaced by panic test

go test ./core/recovery/ ./core/transport/ — all PASS.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 22:41:40 -07:00
pingqiu ee60eb0ced recovery: P2b — backlog relay sink + e2e migration
Sender's WAL pump now flows through a sink in P2b too — but via a
backlog-relay adapter that keeps the same frameWALEntry wire
behavior as legacy streamBacklog. This keeps the receiver path
(decoder + RebuildSession.ApplyWALEntry on dual-lane port) untouched.
Real rewind / transport.WalShipper integration is P2d (which also
wires the dual-lane / receiver decoding alignment).

Why a relay-not-real-WalShipper for P2b:
  Recovery's receiver consumes frameWALEntry on the dual-lane port.
  transport.WalShipper writes MsgShipEntry on the executor's legacy
  port. Plugging transport.WalShipper directly into recovery.Sender
  in P2b would mean wire-format mismatch + receiver dispatch break.
  The intentional shim is `senderBacklogSink` (DrainBacklog →
  streamBacklog) — sink-shape API, same wire bytes.

Changes:

  sender.go:
    + senderBacklogSink — adapts streamBacklog() to WalShipperSink:
        StartSession / EndSession are no-ops (real rewind stays in
        transport.WalShipper for P2d); DrainBacklog calls the existing
        streamBacklog() in-place.
    + NewSenderWithBacklogRelay(primary, coord, conn, replicaID) —
        constructs sender with senderBacklogSink{s: s}. Used by all
        existing e2e + integration callers in P2b.
    Sink-mode Run() flow: after sink.DrainBacklog returns nil, the
        legacy `<-closeCh` wait + drainAndSeal still run so
        PushLiveWrite session-lane entries (the existing test
        scenario that injects post-target writes) keep converging.
        P2c can move session-live into NotifyAppend once transport
        WalShipper is wired.
    NewSenderWithSink doc updated to reflect the closeCh + drainAndSeal
        retention until P2c.

  e2e_test.go:
    All NewSender(...) → NewSenderWithBacklogRelay(...). No assertion
    changes; same e2e shape, sink-mode path now exercised end-to-end.

  integration_stub.go:
    PrimaryBridge uses NewSenderWithBacklogRelay so the
    bridge-shaped lifecycle (StartRebuildSession + PushLiveWrite +
    FinishLiveWrites) still works through the sink branch.

  sender_walshipper_sink_test.go:
    + TestSender_WithSink_DelegationOrder: spawns a goroutine that
      `sender.Close()` after `<-sink.drainCalledCh` so sink-mode
      Run unblocks past the closeCh wait and reaches sink.EndSession +
      barrier path (otherwise drainCalledCh never fires).
    + TestNewSenderWithBacklogRelay_installsRelaySink: smoke test
      that the new constructor installs senderBacklogSink and the
      type satisfies WalShipperSink (compile-time check).
    Lint fix: remove sync/atomic copy from earlier scaffolding.
    Header comments clarified for P2 stage progression.

Test sweep:
  go test ./core/recovery/... → all PASS (legacy path + sink path
    both exercised; e2e tests now run via the relay sink).
  go test ./core/transport/... → all PASS (no transport changes
    in P2b).
  go test ./core/replication/... ./core/replication/component/...
    → all PASS.

Roadmap note (architect-aware):
  P2c — make sink required; delete legacy NewSender pump (streamBacklog
        + closeCh + drainAndSeal + PushLiveWrite + liveQueue + sealed
        + queueMu + walItem + Close). Sink-mode Run is already the
        future shape; legacy path is deletable when no caller relies
        on Close + drainAndSeal.
  P2d — wire transport.WalShipper into recovery.Sender by aligning
        wire format (dual-lane vs legacy port) at receiver decoding.
        Then NewSenderWithBacklogRelay can be retired in favor of
        NewSenderWithSink(real walShipperAdapter). Transport-layer
        integration tests for architect rules 1+2 (updateContext
        before StartSession; restore after EndSession) land here.
2026-04-29 22:29:47 -07:00
pingqiu 04b0bb2fc4 recovery: P2a — WalShipperSink interface + Sender delegate (TDD)
Per v3-recovery-wal-shipper-mini-plan.md §3 P2 — "Drain API wired
from recovery.Sender; delete/disable recovery/sender duplicate
pump". P2a is the smallest green-on-merge step: introduce the
sink, make Sender accept it as OPTIONAL, branch Run() based on
presence. P2b/c migrate existing tests + delete legacy pump.

Architect 2026-04-29 P1 review ratification: "Proceed with P2 TDD
as you outlined, and keep these two integration rules explicit
in tests:
  1. updateWalShipperEmitContext(replicaID, sessionConn,
     sessionLineage) before StartSession.
  2. After EndSession, restore whatever lineage conn Ship will
     use, or the next steady emit will use stale recovery
     lineage on the wire."

Rules 1 + 2 are caller obligations and live in transport (P2d).
P2a establishes the SINK interface contract that those rules
plug into.

WalShipperSink interface (core/recovery/sender.go):
  type WalShipperSink interface {
      StartSession(fromLSN uint64) error
      DrainBacklog(ctx context.Context) error
      EndSession()
  }

  Lives in core/recovery to avoid import cycle (transport
  imports recovery for ReplicaID etc.). transport.WalShipper
  satisfies it via duck typing.

  Boundary docstring spells out architect rules 1+2 as caller
  obligations; Sender does not enforce them.

Sender constructor:
  NewSender(...)              — legacy path (sink == nil; Run uses
                                streamBacklog/closeCh/drainAndSeal).
                                P2c removes this path.
  NewSenderWithSink(..., sink) — sink-mode path (Run delegates).
                                Defensive: nil sink promotes to
                                NewSender so behavior is predictable.

Run() branching:
  if s.sink != nil:
      defer s.sink.EndSession()  // always-cleanup defer FIRST so
                                 // it fires on every exit path
                                 // (success, StartSession err,
                                 // DrainBacklog err, barrier err).
      s.sink.StartSession(fromLSN)
      s.sink.DrainBacklog(ctx)
      // skip TryAdvanceToSteadyLive (kickoff Q3 collapse:
      // {Idle, Active}; barrier-ack is the only completion signal)
  else:
      // LEGACY: streamBacklog → closeCh wait → drainAndSeal →
      // TryAdvanceToSteadyLive (P2c removes)

  Failure mapping for sink errors:
    sink.StartSession err → FailureContract @ PhaseBacklog
    sink.DrainBacklog err (ctx) → FailureCancelled @ PhaseBacklog
    sink.DrainBacklog err (other) → FailureSubstrate @ PhaseBacklog

Test (TDD, sender_walshipper_sink_test.go):
  TestSender_WithSink_DelegationOrder
    - recordingSink mock captures call order
    - Run sender (with deliberately non-converging setup so test
      doesn't depend on barrier success)
    - Assert: sink.callOrder = [StartSession, DrainBacklog, EndSession]
    - Assert: startCalls/drainCalls/endCalls all 1 (always-cleanup)
    - Assert: fromLSN argument forwarded to sink.StartSession

  Other sink-test scaffolds (NoSink_FallsBackToLegacy,
  WithSink_DelegatesStartSession, WithSink_EndSessionAlwaysCalled,
  WithSink_StartSessionFailureAborts, WithSink_NoStreamBacklog
  Reachable) marked t.Skip — they will be filled in as P2b/c
  delete the legacy path and provide the e2e harness for sink-
  driven WAL pump.

Test infrastructure:
  recordingSink — mock with mutex-guarded call log; also has
                  shipDuringDrain hook + drainBlocksUntil channel
                  for P2b's e2e tests where the sink does pump
                  WAL via the test wire.

Test deadlock fix (caught during impl):
  receiver returning error didn't close replicaConn → sender's
  readerLoop blocks forever reading. Fixed by closing replicaConn
  immediately after receiver.Run returns in the test goroutine.
  Documented in test comments.

Test sweep:
  go test ./core/recovery/ -run "TestSender_WithSink_DelegationOrder"
  → PASS (0.00s).
  go test ./core/recovery/ ./core/transport/ -count=1
  → all PASS (no regression on legacy path, including existing
    e2e tests that still use NewSender / sender.Close /
    PushLiveWrite — those keep working in P2a).

Next:
  P2b — migrate existing e2e tests (TestE2E_RebuildHappyPath etc.)
        to NewSenderWithSink + a real walShipper / passthrough
        sink. Required before P2c.
  P2c — make sink required; delete streamBacklog, drainAndSeal,
        PushLiveWrite, liveQueue, sealed, closeCh, queueMu,
        walItem, Close.
  P2d — transport-layer integration tests for architect rules
        1 (updateContext before StartSession) and 2 (restore
        after EndSession). Wire BlockExecutor.startRebuildDualLane
        to call updateWalShipperEmitContext + walShipper.StartSession.
2026-04-29 22:22:20 -07:00
pingqiu f905ef40fa transport: P1 architect review fixes — encoding seam + test scope
Architect P1 review (2026-04-29 of commit 0d3e379) found 4 items.
This commit fixes #1, #2, #3 + adds #4 doc note. All required before
P2's recovery.Sender wiring trusts the same EmitFunc for backlog
emit.

#1 (P2 SHOWSTOPPER): encoding seam moved INTO EmitFunc.

  Before: Ship() pre-encoded payload via EncodeShipEntry, passed
  encoded bytes as `data` to NotifyAppend. EmitFunc just did
  `WriteMsg(conn, MsgShipEntry, data)`.

  Hidden bug for P2: when DrainBacklog calls `s.emit(e.LBA, e.LSN,
  e.Data)` with e.Data = raw substrate bytes from ScanLBAs, NOT
  pre-encoded ShipEntry, EmitFunc would WriteMsg garbage. Replica's
  MsgShipEntry handler would fail decode. Architect: "wiring
  recovery to this same EmitFunc without encoding in or before emit
  will ship garbage on rebuild/catch-up".

  After: EmitFunc owns EncodeShipEntry. WalShipper hands raw
  `(lba, lsn, data)` tuples; EmitFunc encodes per-call using
  walShipperEntry.emitLineage. Both steady (Ship) and backlog
  (P2 DrainBacklog) feed the SAME EmitFunc shape — one encoding
  seam, one wire frame type.

  Implementation:
    - walShipperEntry adds emitLineage RecoveryLineage field.
    - WalShipperFor's EmitFunc reads lineage from entry under
      emitCtxMu, calls EncodeShipEntry inside.
    - updateWalShipperConn renamed to updateWalShipperEmitContext;
      now sets BOTH conn AND lineage atomically.
    - Ship() passes RAW data (block bytes), NOT pre-encoded payload.

  Future P2: recovery.Sender's session-installer calls
  updateWalShipperEmitContext with session lineage before
  walShipper.StartSession. After session ends, restores steady
  lineage. SAME EmitFunc handles both flows.

#2: TestBlockExecutor_StableUnderConcurrent_Ship test scope
    clarified.

  Architect: "cursor == maxLSN does not prove no lost emits — if
  goroutines finish out of LSN order, Realtime's idempotent-skip
  drops lowers while cursor still ends at maxLSN".

  Renamed: TestBlockExecutor_WalShipperRegistry_StableUnderConcurrent_Ship
  Test now explicitly pins:
    - INV-SINGLE registry stability under concurrent Ship load.
    - cursor advanced from 0 (some Ship landed).
    - cursor ≤ maxLSN (sanity bound).
  And explicitly does NOT pin:
    - "all 200 LSNs reach the wire" — that's lossless-emit
      semantics, requires production-mirror serialized Ship pattern
      (held under volume.mu in production via OnLocalWrite).
      Belongs to P2 e2e where serialized Ship matches production.

  Comment block at top of test calls out architect P1 review #2
  as the rationale.

#3: ordering invariant for updateWalShipperEmitContext documented.

  Architect: "every code path that can emit must refresh conn
  context the same way Ship does (or centralize 'resolve conn
  then notify')".

  Added explicit invariant doc on updateWalShipperEmitContext:
  "every code path that ends in an emit (steady Ship, future
  recovery-session backlog DrainBacklog, future Activate) MUST
  refresh this context BEFORE the call that may emit. Otherwise
  EmitFunc emits with stale lineage / nil conn".

#4: registry lifecycle TODO documented.

  Architect: "walShippers is never torn down when a peer goes
  away with new session/conn semantics. Probably fine for MVP;
  watch replica churn / InvalidateSession".

  Added doc note: walShippers entries are never torn down today;
  P3+ may add Forget(replicaID) hook for replica churn / lineage
  invalidation / executor reuse. Out of scope for MVP since
  current call sites construct one BlockExecutor per
  (volume, replica) lifecycle.

Test sweep:
  go test ./core/transport/ -count=1 → all PASS (including the
    renamed test with weaker but honest assertions).
  Wider sweep (transport + recovery + storage + replication +
    replication/component): all PASS.

Net effect: P2 (recovery.Sender thin) can now plug DrainBacklog
into the SAME walShipper that Ship() uses, with EmitFunc handling
encoding for both. The "5th time wrong pump" risk is materially
lower.
2026-04-29 22:11:07 -07:00
pingqiu 0d3e3795d2 transport: P1 — BlockExecutor WalShipper registry + Ship delegate
Per v3-recovery-wal-shipper-mini-plan.md §3 P1, with TDD discipline
(tests first, impl drives by failing tests):

Tests written first (wal_shipper_executor_test.go, RED phase):
  TestBlockExecutor_WalShipperRegistry_GetOrCreate
    spec §3 INV-SINGLE — WalShipperFor idempotent get-or-create;
    different replicaIDs get distinct instances; concurrent calls
    for same replicaID linearize through walShipperMu.

  TestBlockExecutor_Ship_AdvancesWalShipperCursor
    Ship() delegates to per-replica WalShipper. Observable via
    cursor advancing per Ship call. Idempotent Ship with lsn ≤
    cursor (NotifyAppend's idempotent-skip path) does NOT regress
    cursor.

  TestBlockExecutor_WalShipperFor_StableUnderConcurrent_Ship
    Strong INV-SINGLE under load — 8 writer goroutines × 25 Ships
    each (200 distinct LSNs) all funnel through the same shipper
    instance; cursor reaches max LSN.

3a coverage (architect 2026-04-29 ratification): "仅 Ship 只走
WalShipper (mock transport)". Mock here is net.Pipe with
io.Copy(io.Discard, replicaConn) — Ship's wire writes succeed,
test asserts on cursor advancement (the delegation observable).

3b deferred per architect to nightly: "Sender + Ship integration
冒烟" (cross-component INV-NO-DOUBLE-LIVE). Will be added when
P2 wires recovery.Sender to call walShipper.StartSession /
DrainBacklog (replacing its own streamUntilHead).

Implementation (driven by failing tests):

  core/transport/executor.go:
    + walShipperMu sync.Mutex
    + walShippers map[string]*walShipperEntry
    + walShipperEntry struct { shipper *WalShipper; emit conn ctx }
    + WalShipperFor(replicaID) *WalShipper — get-or-create; on
      create, the EmitFunc closes over entry.emitConn (mu-guarded
      pointer that Ship updates per-call)
    + updateWalShipperConn(replicaID, conn) — Ship's per-call
      hook to set the conn the EmitFunc will use

  core/transport/ship_sender.go:
    Modified Ship():
      - Lineage validation + epoch fence + lazy dial: UNCHANGED.
      - After conn resolved + payload encoded: delegate to
        WalShipperFor + updateWalShipperConn + NotifyAppend.
      - The walShipper's EmitFunc does the WriteMsg under shipMu
        (INV-NO-DOUBLE-LIVE at the wire path).
    No behavior change for callers: Ship's signature, return
    semantics (silent-drop on stale epoch, error on dial/write
    failure, nil on success) all preserved.

Architectural notes:

  - WalShipper.Activate(0) at first WalShipperFor — Realtime mode
    immediate. First Ship's lsn > 0 emits cleanly.
  - emitConn is mutable per-Ship: caller's session conn may change
    over time (lazy dial, session re-attach). EmitFunc reads under
    entry.emitCtxMu so mutations are visible.
  - Idempotent NotifyAppend (lsn <= cursor) returns nil silently;
    Ship caller can't distinguish from successful emit. Acceptable
    for fire-and-forget contract.

Test sweep (TDD GREEN):
  go test ./core/transport/ -run "TestBlockExecutor_(WalShipper|Ship_)"
  → 3 PASS, 0 FAIL.

  Wider sweep:
  go test ./core/transport/ ./core/recovery/ ./core/storage/...
          ./core/replication/component/ ./core/replication/
  → all PASS — no regression in existing executor / recovery /
    storage / replication tests.

LOC delta:
  + executor.go    ~70 LOC (registry struct + WalShipperFor +
                            updateWalShipperConn)
  ~ ship_sender.go ~10 LOC change (delegate via NotifyAppend)
  + wal_shipper_executor_test.go ~250 LOC (3 tests)

Next: P2 — recovery.Sender drops streamUntilHead/PushLiveWrite/
drainAndSeal; calls walShipper.StartSession + DrainBacklog
instead. TDD again, write tests first against the new
"recovery.Sender does NOT own WAL pump" contract.
2026-04-29 22:02:11 -07:00
pingqiu c3d8907725 transport: WalShipper P0 cleanup per architect signoff
Architect 2026-04-29 P0 review: signed off, two doc-vs-impl mismatches
to fix + one dead-code cleanup. All comment / dead-field changes; zero
behavior change.

(1) EmitFunc docstring (line ~46-48):
    Was: "Returning an error transitions WalShipper to Backlog (or
          stays Backlog if already there) and aborts the current emit"
    Reality: NotifyAppend in Realtime returns the error AS-IS;
            mode does not flip; cursor is NOT advanced for the failed
            emit. Degraded decision belongs to executor/engine.
    Fix: docstring now accurately describes propagate-and-don't-flip
         semantic. Prevents next reader from "fixing" wal_shipper.go
         to flip to Backlog on emit error (which would be wrong per
         spec — degraded is upstream's call).

(2) sessionActive struct field comment (line ~154-155):
    Was: "EndSession returns to Idle"
    Reality: EndSession sets sessionActive=false + mode=Realtime
            (NOT Idle). Mode goes to Idle ONLY at NewWalShipper ctor;
            no API path returns to Idle from non-Idle once Activate
            or StartSession has run.
    Fix: docstring describes actual transition; flags Idle as
         ctor-only state.

(3) stopBacklog field — dead code:
    Was: chan struct{} created in StartSession, closed in
         EndSession, but no goroutine ever reads from it.
         DrainBacklog uses ctx for cancellation; stopBacklog is
         unreferenced.
    Fix: deleted the field + StartSession's make + EndSession's
         close. Architect option was "comment as P2-reserved OR
         delete"; deleted to match architect's "dead code is worse
         than missing code" principle. If P2 (or any future
         backlog-goroutine refactor) needs it, it'll be added then.

R2 test concurrency note (architect 2026-04-29):
    `OnSaturation` callback uses `t.Errorf` from non-test goroutine.
    P0 stress (count=20, multiple 1-second runs) is clean; future
    hardening could use channel + main-goroutine assert. NOT
    required for P0 merge per architect; logging here so reviewer
    knows it's a known soft spot.

Test sweep:
    go test ./core/transport/ -run "TestWalShipper_" -count=1 → all
    PASS (10 PASS + 1 SKIP for RegistrySingleton P1 placeholder).

Memories saved (cross-conversation rules from this round):
    feedback_lsn_from_allocator_not_boundaries.md — never derive
        "LSN of this Write" from Boundaries(); use Write's return.
    feedback_tdd_when_spec_locked.md — when spec is normative, write
        conformance tests FIRST against spec § references; impl-first
        is the pattern that caused 3 recovery-component rewrites.

Next: P1 — BlockExecutor registry + Ship delegate. TDD again.
2026-04-29 21:50:41 -07:00
pingqiu cb4a137ce6 transport: WalShipper Q1+Q3 fixes from architect review (P0 green)
Per architect 2026-04-29 review of g7-redo/wal-shipper-impl:

Q1a (INV-SUBSET fromLSN+1 anchoring):
  TestWalShipper_DeliveredEqualsCursor — replaced "expected LSN 1..head"
  with explicit `fromLSN+1, ..., head` derivation. fromLSN=0 still in
  this case (so first emit IS LSN 1) but assertion is now general:
  future variants with fromLSN > 0 work without rewriting test logic.

Q1b (CursorMonotonic seed/fromLSN alignment):
  Earlier seed (LSN 1..5) + fromLSN=10 had `head < fromLSN` — an edge
  that exposes R1 bugs but doesn't pin INV-MONOTONIC-CURSOR cleanly.
  Changed seed to LSN 1..15 so head=15 ≥ fromLSN=10, giving DrainBacklog
  a real range (10, 15] to ship. Assertions strengthened: post-drain
  cursor==head, idempotent NotifyAppend with lsn<cursor doesn't regress.

Q1c (BacklogStaysBacklog_UnderLoad err loosening):
  Spec §5.3 normative content is "R1 must not fake-Realtime under
  saturation"; whether DrainBacklog returns nil or non-nil at ctx
  deadline is impl choice. Removed strict `drainErr != nil` Fatal,
  removed errors.Is check; primary contracts (mode != Realtime AND
  cursor < head) stay as Errorf. drainErr now logged as observation.

Q3 (R1_DoubleCheckRejectsRace fixedHeadSource):
  Replaced HeadSourceFromStorage + sleep-until-cursor≥8 heuristic
  with explicit fixedHeadSource control. Substrate Write happens
  BEFORE head bump (atomicity: any scan after the bump sees LSN 11
  in substrate). NotifyAppend after bump covers race-lost-the-window
  branch (R1 already flipped → realtime emit).

Q4 (R2 single-shot per session — already correct):
  Test asserts `fired ≤ 1` per session. Architect ratified per-session
  single-shot; cross-session re-fire works because StartSession
  resets saturationFired flag. Spec §6 line for "default per-session
  at most once; cross-session can re-fire" is architect's edit
  (separate from this commit).

TEST BUG FOUND DURING `go test` (architect-prompted "fix-then-code"):

  6 sites used `lsn, _, _ := primary.Boundaries()` which captures R
  (syncedLSN, FIRST return value), not H. memorywal.Boundaries returns
  `(R, S, H)`; only Sync() advances R, so concurrent NotifyAppend after
  Write got stale lsn=preSyncedLSN, hit the idempotent-skip path
  (`lsn <= cursor`), and live writes during session vanished.

  Fixed by using primary.Write's RETURNED lsn directly:
    - Old:  _, _ = primary.Write(lba, data)
            lsn, _, _ := primary.Boundaries()
    - New:  lsn, _ := primary.Write(lba, data)

  6 fix sites: R1_NoGapAtTransition (line 396), NoDoubleLive (566),
  R2_LagSignalFires (627), R2_NoSpuriousSignal (669),
  BacklogToRealtime_Happy (717), BacklogStaysBacklog_UnderLoad (786).

  Two tests went from RED → GREEN purely via this test bugfix:
    - TestWalShipper_R1_NoGapAtTransition: was cursor=102 want 200;
      now cursor=200 == finalHead, all 200 LSN in emit log.
    - TestWalShipper_BacklogToRealtime_Happy: was emit count=10 want
      11; now 11 emits (10 backlog + 1 realtime LSN 11).

  Other tests passed coincidentally because their assertions don't
  depend on the lsn parameter to NotifyAppend being correct (e.g.,
  R2 tests count fired hooks, not exact LSN sequences).

  IMPLEMENTATION (wal_shipper.go) is unchanged — no behavior bug
  surfaced. Tests had the bug; spec-driven discipline still worked
  (failing tests forced inspection that found the test bug, not a
  silent green-on-bad-impl).

Test results:
  go test ./core/transport/ -run "TestWalShipper_" -count=1 → all
    PASS (10 PASS + 1 SKIP for RegistrySingleton P1 placeholder)
  go test ... -run "R1_NoGap|R1_DoubleCheck|NoDoubleLive" -count=20
    → no flake under stress (architect Q3 alternate gate; -race not
    enabled per Windows+CGO note in memory)
  Wider sweep core/transport/ + core/recovery/ + core/storage/... +
    core/replication/component/ all green.

Next: P1 (BlockExecutor.Ship delegate to walShipper) — TDD again,
write tests against INV-NO-DOUBLE-LIVE + INV-SINGLE (registry)
first.
2026-04-29 21:44:29 -07:00
pingqiu 3234476a3a transport: WalShipper draft for architect review (TDD checkpoint)
Spec-driven test-first work per architect 2026-04-29 ratification:
"先写完让 architect 看看然后写 code". This commit lands ONLY:

  - core/transport/wal_shipper.go      — initial implementation hypothesis
  - core/transport/wal_shipper_test.go — 10 spec-§9 tests

The tests are NOT run; wal_shipper.go is NOT validated against them.
This is the spec→code BRIDGE: architect reviews tests against
v3-recovery-wal-shipper-spec.md §3 (INV) + §5 (R1) + §6 (R2) + §9
(min test names); after ratification, implementation gets fixed
under test pressure (NOT the other way around).

Test catalog (matching spec §9 exactly):

  TestWalShipper_RegistrySingleton           — INV-SINGLE
                                                t.Skip — registry lives
                                                in BlockExecutor (P1
                                                mini-plan)
  TestWalShipper_CursorMonotonic             — INV-MONOTONIC-CURSOR
                                                (cursor never regresses
                                                outside session entry)
  TestWalShipper_RewindOnceAtSessionEntry    — INV-MONOTONIC-CURSOR
                                                (one legal rewind path
                                                via StartSession)
  TestWalShipper_DeliveredEqualsCursor       — INV-SUBSET (emitted set
                                                = (fromLSN, cursor]
                                                exactly, contiguous)
  TestWalShipper_R1_NoGapAtTransition        — INV-NO-GAP-R1 (concurrent
                                                writer while drain →
                                                R1 transitions; every
                                                LSN ∈ [1, finalHead]
                                                in emit log exactly
                                                once)
  TestWalShipper_R1_DoubleCheckRejectsRace   — spec §5.1 (head moved
                                                during check window;
                                                R1 stays Backlog,
                                                next scan picks up
                                                missed LSN)
  TestWalShipper_NoDoubleLive                — INV-NO-DOUBLE-LIVE
                                                (recordingEmit tracks
                                                in-flight emits across
                                                4 concurrent writers
                                                + drain; maxInFlight ≤ 1)
  TestWalShipper_R2_LagSignalFires           — spec §6.2 (Backlog mode
                                                with lag > threshold
                                                fires OnSaturation
                                                exactly once per
                                                session)
  TestWalShipper_R2_NoSpuriousSignal         — spec §6.3 (load-safe
                                                scenario, OnSaturation
                                                never fires)
  TestWalShipper_BacklogToRealtime_Happy     — spec §4 default priority
                                                end-to-end happy path
                                                (no race)
  TestWalShipper_BacklogStaysBacklog_UnderLoad — spec §5.3 explicit
                                                non-guarantee (writer
                                                outpaces drain → mode
                                                stays Backlog, not
                                                fake-Realtime)

Implementation hypothesis (wal_shipper.go) covers spec §2 state +
§4 default priority + §5 R1 (assertCaughtUpAndEnableTailShipLocked
double-check inside shipMu) + §6 R2 (lag tracking + OnSaturation
hook). Hypothesis is what tests will VALIDATE OR INVALIDATE — not
authoritative.

Architect review prompt:

  Q1: Are the 10 tests' assertions a faithful read of spec §3
      invariants + §5 R1 + §6 R2? If a test allows behavior the
      spec forbids (or rejects behavior the spec permits), flag.
  Q2: Is the t.Skip on RegistrySingleton acceptable for this PR
      scope (registry lands in P1 per mini-plan §3)?
  Q3: TestWalShipper_R1_DoubleCheckRejectsRace uses heuristic timing
      (sleep until cursor ≥ 8 then inject write) — do you want a
      more deterministic harness (e.g., fixedHeadSource that lets
      test inject head changes synchronously)? Acceptable as-is for
      P0; if not, mini-plan §4 row needs sharpening.
  Q4: TestWalShipper_R2_LagSignalFires asserts exact "fired == 1"
      single-shot per session. Spec §6.2 says "exactly once when
      synthetic load drives lag past threshold". If saturation
      conditions briefly clear and re-fire later (same session),
      should the hook re-fire? Spec implicit single-shot; please
      confirm or sharpen.

After architect ratification: run tests against wal_shipper.go;
fix implementation where tests fail; iterate. Tests are
authoritative; impl bends to them.

Branch: g7-redo/wal-shipper-impl off phase-15. Does NOT touch
g7-redo/unified-wal-impl (archived per mini-plan §0). Does NOT
touch BlockExecutor / recovery.Sender / coord — those are P1+P2
in mini-plan §3.
2026-04-29 21:33:46 -07:00
Ping Qiu 24f2b40dd1 docs: relocate V3 recovery design docs to seaweedfs/sw-block/design/ (#17)
Per repository policy: dev/design docs live in
seaweedfs/sw-block/design/, not in seaweed_block/docs/. Companion
to the seaweedfs commit at 04b9d1ea5 which adds the same content
under v3-recovery-* prefix.

Removed (paths now in seaweedfs/sw-block/design/):

  docs/recovery-pin-floor-wire.md
    → v3-recovery-pin-floor-wire.md
  docs/recovery-wiring-plan.md
    → v3-recovery-wiring-plan.md
  docs/recovery-execution-institution.md
    → v3-recovery-execution-institution.md
  docs/recovery-inv-test-map.md
    → v3-recovery-inv-test-map.md

Three more design docs that were in flight on g7-redo branches
(unified-wal-kickoff, unified-wal-mini-plan,
hardware-canonical-paper) were never on phase-15 and are also
now in seaweedfs/sw-block/design/. Their seaweed_block branches
are deleted as part of the same relocation cleanup.

Code paths and commit messages still reference the old doc paths
in git history — that's normal; new code references the
v3-recovery-* paths in seaweedfs.

No code changes in this commit; pure relocation.
2026-04-29 17:16:30 -07:00
Ping Qiu 1c453375cf recovery: PinUnderRetention bypasses retry budget (priority #3 [retry] Option A) (#15)
Architect-ratified Option A 2026-04-29: bug-fix shape for the
boundary mapping gap that let `recovery.FailurePinUnderRetention`
fall through to `engine.RecoveryFailureTransport` (retryable). Engine
re-emitted Start* on the same lineage, the same ack triggered the
same pin violation, and the lineage spun until the retry budget
exhausted — masking the "fresh probe + new lineage" signal the
typed envelope was meant to surface.

Pinned by INV-PIN-COMPATIBLE-WITH-RETENTION at the engine retry
gate. Option B kickoff (per-failure-kind budget + lossless recovery
↔ engine mapping + retry observability) tracked separately; Option
B prerequisites #3 [retry] backoff/wall-clock cap.

Engine kind (`core/engine/events.go`):
  + RecoveryFailurePinUnderRetention — typed enum value + String case.
    Documented non-retryable, distinct from WALRecycled (which auto-
    escalates to Rebuild). PinUnderRetention is mid-session contract
    violation; new lineage decision belongs to next probe.

Engine retry path (`core/engine/apply.go::applySessionFailed`):
  + Early-return branch mirroring StartTimeout pattern: trace +
    PublishDegraded; Attempts unchanged; Decision NOT auto-flipped
    (counter-WALRecycled — engine doesn't pre-decide rebuild vs
    catch-up at fresh fromLSN).

Boundary mapping (`core/transport/recovery_session.go::classifyRecoveryFailure`):
  + New `*recovery.Failure` errors.As branch. Option A scope:
    PinUnderRetention only. Other recovery kinds (Wire, Protocol,
    Substrate, Contract, Cancelled, SingleFlight, Unknown) deferred
    to Option B kickoff — fall-through fence test asserts they keep
    landing on Transport until B lands explicit cases.

Tests (5 new):
  Engine retry-bypass (3 in `recovery_pin_retention_test.go`):
    + TestT4d_PinUnderRetention_BypassesRetryBudget — headline:
      no Start* re-emit; Attempts unchanged; PublishDegraded emitted;
      Decision NOT auto-escalated.
    + TestT4d_PinUnderRetention_AtBudgetEdge_DoesNotEscalate —
      negative pin: even at wal_delta MaxRetries=3 edge, pin
      violation MUST NOT trigger round-47 catch-up-exhaustion-→-
      rebuild path (proves the bypass branch doesn't bump the
      counter).
    + TestRecoveryFailureKind_PinUnderRetention_String — diagnostic
      surface pin (logs / traces grep on this string).
  Boundary mapping (2 in `classifier_pin_under_retention_test.go`):
    + TestClassifier_RecoveryPinUnderRetention_MapsToEngineKind —
      headline mapping; counter-pin asserts NOT Transport fallback.
    + TestClassifier_RecoveryFailure_OtherKinds_StillFallThrough —
      Option B fence: enumerates every deferred recovery kind,
      asserts they fall through to Transport. Forces Option B to
      consciously update both the production switch and this test.

Verified: `go test ./core/engine/ ./core/transport/ ./core/recovery/
./core/storage/... ./core/replication/component/ -count=1` — all
green.

inv-test-map.md row INV-PIN-COMPATIBLE-WITH-RETENTION extended:
coord layer + engine retry-bypass + boundary mapping; status flips
to "pinned (coord + engine retry-bypass + boundary mapping)".

Branch hygiene: stacked off `g7-redo/recycle-pin-hookup` for context
linkage, but architect-tagged "可与 wiring 并行" — separate concurrent
PR. Depends on neither wiring nor recycle-pin-hookup at code level.
2026-04-29 16:23:57 -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
Ping QiuandClaude Opus 4.7 e1403b548e G7-redo: BaseBatchAck wire + pin_floor advancement (was #12; rebased onto phase-15 post-#11) (#16)
* recovery: BaseBatchAck wire + pin_floor advancement (#3)

Implements docs/recovery-pin-floor-wire.md per architect ACK on
2026-04-29. Closes the two forward-direction Layer-2 INVs:

  INV-PIN-ADVANCES-ONLY-ON-REPLICA-ACK
  INV-PIN-COMPATIBLE-WITH-RETENTION

What lands:

Wire (core/recovery/wire.go):
- frameBaseBatchAck = 0x07 (receiver → primary direction).
- Payload: [8 SessionID][8 AcknowledgedLSN][4 BaseLBAUpper] = 20 bytes.
- Independent frame (architect §11 Resolution 3) — not piggyback.

Failure taxonomy (core/recovery/failure.go):
- New FailureKind FailurePinUnderRetention. Distinct from
  WALRecycled (cold-start scan failure) — this is mid-session
  contract violation, retryable=false (architect §11 Resolution 1).
- New phases PhaseRecvAckWrite, PhasePinUpdate.

Coordinator (core/recovery/peer_ship_coordinator.go):
- SetPinFloor(id, floor, primarySBoundary) (architect §11 Resolution 2:
  explicit parameter, not callback). Caller computes inputs;
  coordinator stays substrate-free.
- Check ordering: monotonic guard FIRST, retention check second.
  Avoids spurious PinUnderRetention on early-session acks where
  receiver's walApplied is still 0 while primary's S has advanced.

Receiver (core/recovery/receiver.go):
- Cadence config: K blocks (default 256) ∨ T elapsed (default 100ms),
  via NewReceiver / NewReceiverWithCadence.
- Mandatory ack on MarkBaseComplete (BaseDone path).
- Cadence-driven ack during base lane streaming.
- AcknowledgedLSN = session.Status().WALApplied; BaseLBAUpper
  tracks highest base LBA installed.

Sender (core/recovery/sender.go):
- New goroutine readerLoop demuxes inbound frames (BaseBatchAck
  during base lane, BarrierResp at session end).
- barrierRespCh (buffered=1) delivers result to main Run goroutine
  at barrier-wait point.
- BaseBatchAck handler: validates SessionID, fetches primary's S
  via Boundaries(), calls coord.SetPinFloor with the typed Failure
  flowing back through barrierRespCh on retention violation.

Tests:
- 2 new SetPinFloor unit tests (RejectsBelowRetention +
  ZeroBoundaryDisablesCheck).
- 1 new e2e test (TestE2E_PinFloorAdvancesIncrementally) using
  K=8 cadence over 50-LBA backlog to drive multiple acks.
- Existing test signatures updated for the new SetPinFloor arity.
- 36/36 PASS in core/recovery; whole repo green.

Cross-references updated:
- core/recovery/doc.go: pin INV section now points at design doc §3-§5.
- docs/recovery-inv-test-map.md: forward rows for the two INVs
  upgraded from "_Pending #3_" to "design landed; impl pending #3"
  in the prior commit; this commit will also need a follow-up
  to flip them to "pinned" once architect / QA validates the
  test cites — left for the merge-back PR.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: inv-test-map — flip pin INVs to pinned + add PinUnderRetention row

Both forward-direction Layer-2 INVs now have concrete test cites:
- INV-PIN-ADVANCES-ONLY-ON-REPLICA-ACK → TestE2E_PinFloorAdvancesIncrementally
- INV-PIN-COMPATIBLE-WITH-RETENTION → TestCoordinator_SetPinFloor_RejectsBelowRetention
                                       + TestCoordinator_SetPinFloor_ZeroBoundaryDisablesCheck

Layer-3 retryable matrix bumped from 8 kinds to 9 with the new
FailurePinUnderRetention row.

Test sweep summary: 86 results (was 83 in POC, +3 from this branch).

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:22:19 -07:00
Ping QiuandClaude Opus 4.7 107ef82c43 G7-redo POC: dual-lane recovery package + memorywal substrate + pin-floor wire design (#11)
* G7-redo POC: dual-lane recovery package — mechanism + e2e

Self-contained package at core/recovery/ implementing the dual-lane
rebuild/recover algorithm per v3-recovery-live-line-backlog-spec.md.
Independent of core/transport (no integration yet — that lands as a
separate PR per architect ruling: "parallel + flag, don't replace
existing path until one happy path runs green alongside").

Layer 1 (receiver-side mechanism):
- bitmap.go: RebuildBitmap, per-LBA WAL-wins-base flag.
  INV-DUAL-LANE-WAL-WINS-BASE; no internal lock (V2-faithful).
- rebuild_session.go: RebuildSession with ApplyBaseBlock /
  ApplyWALEntry(kind, ...) / MarkBaseComplete / TryComplete.
  TryComplete = baseDone ∧ walApplied ≥ targetLSN
  (INV-SESSION-COMPLETE-ON-CONJUNCTION-LAYER1).

Layer 2 (primary-side orchestration):
- peer_ship_coordinator.go: PeerShipCoordinator with phase enum
  (Idle / DrainingHistorical / SteadyLiveAllowed), pin_floor
  management, and RouteLocalWrite. Per architect ruling on
  CHK-NO-FAKE-LIVE-DURING-BACKLOG: while session is non-Idle,
  RouteLocalWrite returns SessionLane regardless of phase.
  SteadyLiveAllowed is publication-permission, not a routing gate.

Wire (core/recovery/wire.go):
- 6 frame types (SessionStart, BaseBlock, BaseDone, WALEntry,
  BarrierReq, BarrierResp).
- WALEntry carries a Kind byte (Backlog / SessionLive) for
  observability; explicitly NOT a convergence proof.

Sender / Receiver (core/recovery/sender.go, receiver.go):
- Sender takes context.Context; defer always sets sealed=true and
  calls coord.EndSession (closes architect-flagged "receiver fails
  early; does sender still seal" question).
- Sender flow: SessionStart → base lane → BaseDone → backlog scan
  → wait Close() | ctx.Done() → drainAndSeal → TryAdvance →
  barrier.
- POC: SEQUENTIAL phases — backlog completes before live writes
  drain. Spec §3.2 #3 (single ordered queue with LSN-real-time
  interleave) is the next milestone, NOT satisfied by this POC.
  Documented in doc.go.

Tests (e2e_test.go + per-file unit tests):
- Happy path, live writes during session, atomic seal under push
  vs Close race, kind-count pinning across backlog/live split.
- 21/21 PASS. Race tests need Linux for -race; Windows host
  cannot enable race detector under cross-compile.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* G7-redo POC: Layer 3 failure taxonomy + integration stub

Wraps every error path in sender / receiver / bridge with a typed
*Failure carrying {Kind, Phase, Underlying}. Engine integration code
(later) inspects via errors.As / AsFailure to drive retry budget.

failure.go:
- FailureKind enum (8 values): Wire, Substrate, Contract are
  retryable; Protocol, Cancelled, SingleFlight, WALRecycled,
  Unknown are not. Matrix pinned by failure_test.go.
- Phase enum (13 values) tags where in the session lifecycle the
  failure surfaced. Diagnostic only — not part of the retry
  decision.
- AsFailure(err) helper for callers; nil-safe Error()/Retryable().

integration_stub.go:
- PrimaryBridge / ReplicaBridge demonstrate the CommandExecutor-
  shaped surface (StartRebuildSession / PushLiveWrite /
  FinishLiveWrites / OnSessionStart / OnSessionClose) WITHOUT
  touching core/transport. Architect priority #1: "出一条薄链路
  早一点发现 lifecycle/回调不匹配".
- StartRebuildSession synchronously calls coord.StartSession
  before spawning the goroutine, so callers reading
  coord.RouteLocalWrite immediately after it returns
  deterministically observe a non-Idle phase.

Tests:
- TestFailure_RetryableMatrix pins all 8 kinds.
- TestIntegrationStub_FailureTypedOnReceiverDown — peer closes
  conn before any frame → typed Failure(Wire, SendStart|BaseLane),
  Retryable=true.
- TestIntegrationStub_FailureTypedOnCancellation — ctx cancel
  during AwaitClose → Failure(Cancelled, AwaitClose),
  Retryable=false.
- 33/33 PASS total across the package.

Out of scope (next milestones):
- BaseBatchAck → pin_floor incremental advancement (architect #3).
- Single-queue LSN real-time interleave (architect #2 / spec §3.2 #3).
- Integration with core/transport (parallel-flag PR).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* core/storage/memorywal: V2-faithful in-memory WAL substrate

memorywal.Store is the third LogicalStorage implementation alongside
BlockStore (current-state map) and WALStore (on-disk WAL+extent).
Like BlockStore it has zero on-disk dependency, but unlike BlockStore
it uses an append-only record log so per-LSN replay semantics are
preserved:

  - Each Write captures its contemporaneous LSN; the record is
    never rewritten in place.
  - ScanLBAs(fromLSN, fn) emits each record's REAL write-time LSN
    (RecoveryModeWALReplay, V2-faithful).
  - 3 writes to the same LBA produce 3 ScanLBAs entries, NOT 1
    deduped entry — matches walstore, not BlockStore.
  - AdvanceWALTail(newTail) trims records and sets an explicit
    `recycleFloor`; subsequent ScanLBAs(fromLSN < recycleFloor)
    returns storage.RecoveryFailure(Kind=WALRecycled), and
    errors.Is(err, ErrWALRecycled) holds via Unwrap.
  - AppliedLSNs returns a real per-LBA highest-LSN map (BlockStore
    returns ErrAppliedLSNsNotTracked).

The recycleFloor / retainStart split avoids a spurious-recycled
trap: ApplyEntry installing a record at a high LSN (e.g. lsn=100)
without prior writes does NOT make ScanLBAs(0) think recovery is
impossible — recycledFloor is bumped only by AdvanceWALTail.

Conformance: added to the existing core/storage contract test
table. All 12 TestContract_* tests now run against three impls:
BlockStore-mem / WALStore / MemoryWAL — same assertions, all green.

Refactor required: contract_test.go moved from package `storage`
to package `storage_test` (external) so it can import memorywal
without a cycle. The shared `makeBlock` helper used by other
internal _test files (flusher_test, walstore_test) moved to a
new `testhelpers_test.go` package `storage` to keep them building.

Production placement note: this lives next to BlockStore + WALStore
in the existing substrate tree (no `core/storage/` reshuffling).
Use it from any test/component that needs WAL-replay semantics
without on-disk overhead — recovery package POC + future
component-level rebuild scenarios.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: recovery INV ↔ test mapping (G7-redo POC)

Per architect closure on g7-redo/dual-lane-recovery-poc: maps every
declared INV (Layer 1 mechanism / Layer 2 orchestration / Layer 3
taxonomy / substrate contract conformance) to its pinning test
function + file:line at branch HEAD.

Sections:
- Layer 1 — receiver-side mechanism (3 INVs, all pinned).
- Layer 2 — primary-side orchestration (9 INVs; 7 pinned, 2 forward
  pending #3 BaseBatchAck → pin_floor).
- Spec CHK-* — phase / barrier / no-fake-live (3 checks, all pinned).
- Substrate contract — 12 LogicalStorage contract tests run across
  BlockStore / WALStore / MemoryWAL (3 impls) + 5 MemoryWAL-specific
  semantics not satisfiable by BlockStore.
- Layer 3 failure taxonomy — 6 INVs, all pinned (matrix + nil-safety
  + extraction + wire/cancel surface + always-seal-on-error).
- Forward-direction — 6 INVs declared but deliberately untested with
  target milestones (pin/recycle wiring, sparse base, overlap-history
  bitmap-as-claim, single-queue interleave, ship-phase observability).

Test sweep summary: 83 test results across the package; race-detector
status flagged for Linux CI.

Includes how-to-keep-current procedure for follow-up PRs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: pin_floor / BaseBatchAck wire design (#3 architect priority)

Single source of truth for the next milestone — receiver→primary
ack cadence, SetPinFloor semantics, retention inequality, and the
proposed FailurePinUnderRetention kind. Design only; implementation
lands on a follow-up branch.

Closes the two forward-direction INVs in the inv-test-map's
Layer-2 section once impl lands:
  - INV-PIN-ADVANCES-ONLY-ON-REPLICA-ACK
  - INV-PIN-COMPATIBLE-WITH-RETENTION

Cross-references added:
  - core/recovery/doc.go: pin INV section now points at the design
    doc sections (§3 cadence, §4 semantics, §5 retention inequality).
  - docs/recovery-inv-test-map.md: forward rows updated from
    "_Pending #3_" to "design landed; impl pending #3" with
    explicit pointer to the design doc.

Open questions for architect (in §11 of the design doc):
  1. New FailurePinUnderRetention kind vs reuse FailureWALRecycled
     with a Phase discriminator. Recommend new kind.
  2. SetPinFloor signature: parameter for primary's S boundary vs
     coordinator-held callback. Recommend parameter.
  3. Wire compat at production wiring time: keep new frame or fold
     into MsgShipEntry with a flag. Recommend keeping new frame.

Out of scope (explicit, §10):
  - §3.2 #3 single-queue real-time interleave (architect priority #2).
  - Wiring into core/transport.
  - WAL recycle path consuming MinPinAcrossActiveSessions.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: pin-floor wire design — architect ACK on §11 (2026-04-29)

All three open questions resolved per architect ratification:
1. FailurePinUnderRetention = new FailureKind (not reused).
2. SetPinFloor takes explicit parameter (not callback).
3. Independent frame 0x07 (not piggyback).

Implementation gates the next branch g7-redo/pin-floor.

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:19:50 -07:00
pingqiu ca21ed83d3 G6 #2-5: --wal-retention-lsns flag + walstore retention gate + tests
Per G6 §1.A α binding (architect 2026-04-29) + §1.H audit
PROCEED-with-minor-patch verdict at seaweed_block@5b09768.

§1.A α implementation (operator-tunable WAL retention window):

- core/storage/walstore.go (+27 LOC): new field
  recoveryRetentionLSNs uint64 + SetRecoveryRetentionLSNs/
  RecoveryRetentionLSNs accessors. Zero (default) preserves
  pre-G6 strict checkpoint-driven recycle.

- core/storage/walstore_recovery.go (+15 LOC, 8 LOC reshape):
  recovery scan gate relaxed from
    if fromLSN <= checkpointLSN
  to
    floor = checkpointLSN - retentionLSNs (saturating to 0)
    if fromLSN <= floor
  Boundary semantic preserved: == floor is rejected, > floor
  accepted. Diagnostic detail string extended with retentionLSNs
  + floor for forensics.

- core/frontend/durable/provider.go (+22 LOC): new ProviderConfig
  field WALRetentionLSNs; plumbed into both openExisting (line 346)
  and createFresh (line 374) walstore paths via
  ws.SetRecoveryRetentionLSNs. ImplSmartWAL ignores the flag
  (ring capacity bounds retention; documented in godoc).

- cmd/blockvolume/main.go (+12 LOC, 1 reshape):
  --wal-retention-lsns flag (uint64, default 0). Help text
  documents substrate-specific semantics (walstore honors;
  smartwal sizes via --durable-blocks). Plumbed into
  durable.ProviderConfig.WALRetentionLSNs.

§2 #3 engine table-driven dispatch test:

- core/engine/g6_walrecycle_dispatch_test.go (NEW, ~190 LOC):
  TestG6_SessionFailed_DispatchByFailureKind_TableDriven (3
  subcases): WALRecycled → Decision=Rebuild + RebuildPinned=true
  + StartRebuild emit; Transport / SubstrateIO → no rebuild pin,
  retry catch-up.
  TestG6_RebuildPinned_StaysSticky_AcrossProbe: post-WAL-recycled
  pin survives a fresh probe that would classify as catch-up;
  Decision stays Rebuild; no StartCatchUp emit.
  TestG6_WALRecycled_PublishDegradedSurfaceFires: PublishDegraded
  AND StartRebuild emit on the same Apply (operator-visible
  signal alongside recovery dispatch).

§2 substrate retention-gate tests:

- core/storage/walstore_retention_test.go (NEW, ~150 LOC):
  4 tests covering Default/Zero=strict-recycle (pre-G6 baseline),
  NonZero=widens window with floor=checkpoint-retention,
  LargerThanCheckpoint=clamps to 0 (saturating subtraction),
  TypedFailureKind=*RecoveryFailure envelope preserved (load-
  bearing for transport's classifyRecoveryFailure path).

Test results:
- core/storage/ TestWALStore_RecoveryRetention_*: 4/4 PASS
- core/engine/ TestG6_*: 3 tests + 3 subcases = 6/6 PASS
- Full ./... regression: in progress (will report after).

Pinned by:
- INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE (§2 #2 + #4 hardware
  retention-OK case)
- INV-G6-CATCHUP-CONVERGES-WITHIN-RETENTION (§2 #4 hardware)
- INV-G6-WALRECYCLE-DISPATCHES-REBUILD (§2 #3 engine + #5 hardware)
- INV-G6-ENGINE-NO-REBUILD-PINNED-ON-OTHER-FAILURES (§2 #3 negative
  control: Transport / SubstrateIO do NOT pin rebuild)

Halt-condition NOT triggered. Full audit plumbing was already in
place (T4d-1 typed envelopes + T4d-1 transport mapping + apply.go
WALRecycled branch); G6 #2-#5 add only the operator knob, the
substrate gate relaxation, and the test pins.

Next: QA harness extension (wait_until_rebuild_dispatched)
unblocked by commit #1's rebuild-START log marker; D-scenario
extended for §2 #4 + #5 single-run per §2 #6.
2026-04-28 02:02:44 -07:00
pingqiu d7c6f8aca3 G6 #1: rebuild-START log marker for QA observability
Per G6 §1.H audit work envelope item #1 + §2 #5 acceptance:
StartRebuild fires the wire-level rebuild path asynchronously
(goroutine launched at line 31 in rebuild_sender.go); pre-G6 the
only log marker was 'executor: rebuild complete, sent N blocks'
which fires AFTER completion. QA's G5-5C scenario D 5s scrape
window saw nothing because rebuild execution exceeded the window
— there was no START marker to wait on.

Add a deterministic START marker BEFORE the goroutine spawns:

  executor: rebuild start replica=<id> sessionID=<n> epoch=<n>
    EV=<n> targetLSN=<n>

Fixed string shape so QA's wait_until_rebuild_dispatched helper
can grep deterministically. Includes lineage tuple for forensics
(matches existing engine StartRebuild command shape; future
multi-session debugging can correlate START → COMPLETE on
sessionID).

Pinned by: INV-G6-WALRECYCLE-DISPATCHES-REBUILD (load-bearing
hardware pin §2 #5).

Test results: full ./core/transport/ + ./core/engine/ regression
GREEN. No behavioral change — pure observability addition.
2026-04-28 01:56:19 -07:00
pingqiu 5b097689ad G6 §1.H code-start audit: PROCEED-with-minor-patch verdict
Per G6 mini-plan v0.1 §2 #1, sw publishes audit findings as a
commit note before any production code change.

AUDIT METHOD: greped seaweed_block/core/{storage,transport,engine}
+ cmd/blockvolume for the WALRecycled chain; cited apply.go +
recovery_session.go + walstore_recovery.go line numbers as evidence.

PER-INV FINDINGS:

[1] Substrate-layer WALRecycled production
    Location: core/storage/walstore_recovery.go:72-73 +
    core/storage/smartwal/recovery_scan.go:96-97
    Both walstore + smartwal return
    storage.NewWALRecycledFailure(ErrWALRecycled, detail) — TYPED
    *RecoveryFailure envelope (NOT bare sentinel). Status: ✅ wired.

[2] Transport-layer mapping (storage error → engine kind)
    Location: core/transport/recovery_session.go:35-48
    classifyRecoveryFailure uses errors.As(err, &rf) to extract
    StorageRecoveryFailureWALRecycled → engine.RecoveryFailureWALRecycled.
    Called from core/transport/executor.go:520 at finishSession.
    Status: ✅ wired.

[3] Engine-layer dispatch (RecoveryFailureWALRecycled → StartRebuild)
    Location: core/engine/apply.go:applySessionFailed lines 519-547
    On e.FailureKind == RecoveryFailureWALRecycled:
      - Decision = DecisionRebuild
      - RebuildPinned = true
      - Attempts = 0
      - Emit PublishDegraded (diagnostic surface)
      - Emit StartRebuild IMMEDIATELY (provided !hasActiveSession,
        which holds at this point because Phase just set to
        PhaseFailed)
    Cited INV: INV-REPL-REBUILD-EMITTED-ON-WAL-RECYCLED.
    Status: ✅ wired.

[4] Runtime per-peer dispatch (engine command → wire)
    Location: G5-5C Batch #7 PeerCommandExecutor +
    PeerAdapterRegistry (core/host/volume/peer_*).
    PeerCommandExecutor.StartRebuild → transport.BlockExecutor.
    StartRebuild → wire-level rebuild_sender.
    Status: ✅ wired (verified by G5-5C component test
    g5_5c_restart_catchup_test.go which exercised the rebuild
    branch on smartwal store).

[5] --wal-retention-* flag
    Location: cmd/blockvolume/main.go (parseFlags)
    Status: ❌ NOT PRESENT. Must be added for §1.A α binding.
    Plumbing: flag → durable provider construction → walstore /
    smartwal recovery_scan. Estimate: ~40 LOC across 3 files.

[6] Current retention mechanism
    walstore.go is append-only (no physical wraparound; no
    Truncate calls beyond initial file resize). The 'recycle' is
    purely the checkpointLSN-based logical gate at recovery scan
    time. To implement α: relax walstore_recovery.go:67 from
    'fromLSN <= checkpointLSN' to 'fromLSN <= checkpointLSN -
    retentionLSNs'. Mirror in smartwal/recovery_scan.go.

QA D OBSERVATION INTERPRETATION:
The 'no rebuild dispatch in 5s window' observation is most likely
(a) — existing-and-correct chain — combined with (i) rebuild
execution time on the wire exceeds 5s for the scenario, AND
(ii) no explicit 'rebuild starting' log line exists today; only
'executor: rebuild complete, sent N blocks' fires AFTER completion.
This is a TEST DESIGN issue (window too short + no start marker),
not a missing dispatch. G6 hardware step #5 fixes both via:
- wait_until_rebuild_dispatched helper polling for new marker
- new log marker at rebuild session START in rebuild_sender.go

OVERALL VERDICT: PROCEED-with-minor-patch.

§1.H halt-condition: NOT triggered. The engine FSM + transport
mapping + substrate envelope + runtime per-peer dispatch are all
already wired and tested individually. The gap is at the
operability boundary, not the recovery substrate.

WORK ENVELOPE (per §1.A α + §1.H findings):
1. Add --wal-retention-lsns flag in cmd/blockvolume/main.go
   (~10 LOC). Default value TBD — recommend 10000 LSNs.
2. Plumb retention into walstore.New + smartwal.openInitialized
   constructors (~15 LOC).
3. Relax recovery scan gate to honor retention (~10 LOC each
   in walstore_recovery.go + smartwal/recovery_scan.go).
4. Add explicit rebuild-START log marker in
   transport/rebuild_sender.go (~5 LOC) so QA's
   wait_until_rebuild_dispatched helper has a deterministic
   marker (NOT just rebuild-complete which fires post-run).
5. Add engine-layer table-driven test pinning
   RecoveryFailureWALRecycled → Decision=Rebuild +
   RebuildPinned=true + StartRebuild emit; negative case for
   Transport / SubstrateIO failure kinds (~80 LOC test).
6. Add walstore + smartwal substrate test for retention gate
   (fromLSN within retention → scan succeeds; fromLSN past
   retention → ErrWALRecycled) (~40 LOC test).
7. New INV inscribed: INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE
   (per §1.A α) + INV-G6-WALRECYCLE-DISPATCHES-REBUILD +
   INV-G6-CATCHUP-CONVERGES-WITHIN-RETENTION +
   INV-G6-ENGINE-NO-REBUILD-PINNED-ON-OTHER-FAILURES.

TOTAL ESTIMATE: ~160 LOC production + ~120 LOC tests.

NEXT STEPS:
- sw: code per work envelope above. First commit: rebuild-START
  log marker (unblocks QA harness work). Then: --wal-retention-lsns
  flag + plumbing. Then: tests.
- QA: now unblocked to write wait_until_rebuild_dispatched helper
  + extend D-scenario script for §2 #4 + #5 in single run per #6.

This audit fulfills §2 #1 (audit-published-as-commit-note before
production code change).
2026-04-28 01:44:00 -07:00
pingqiu 7ea0e16577 gitignore: exclude G5-5* iteration build artifacts
Cross-compile workflow for m01 hardware iteration leaves behind:
- _g5_bin/ (staged binaries before scp to m01)
- blockmaster / blockmaster.exe + blockvolume / blockvolume.exe
  (Windows-side go build outputs)

None of these belong in version control. Ignoring at the repo root
(anchored, not recursive) so they don't pollute git status during
hardware iteration cycles.
2026-04-28 00:56:01 -07:00
pingqiu 0b29dcd505 G5-5C addendum: P0 product fix — frontend volume capacity from durable config
QA expanded scenario testing surfaced a real production bug: iSCSI
target advertises 1 MiB capacity (DefaultVolumeBlocks=2048 ×
DefaultBlockSize=512) regardless of --durable-blocks /
--durable-blocksize, breaking any workload above LBA 256.

Architect ruling 2026-04-28: option (a) — inline patch as G5-5C
addendum, re-verify before §close ledger update. Per architect:
"否则 §close 是签 off 在一套对大卷必挂的二进制上,会削弱 credibility".

Root cause: cmd/blockvolume/main.go constructed iscsi.TargetConfig
+ nvme.TargetConfig WITHOUT setting Handler.{BlockSize, VolumeSize}.
Frontend HandlerConfig zero-values fell back to package defaults
(2048 × 512 = 1 MiB).

Fix:
- New helper computeFrontendVolumeSize(blocks, blockSize) (uint64,
  error) with overflow guard. Rejects zero, rejects multiplications
  that overflow uint64.
- main.go branches on f.durableRoot:
  * --durable-root SET: plumb (BlockSize, VolumeSize) from
    --durable-blocks × --durable-blocksize into both iscsi and nvme
    HandlerConfig.
  * --durable-root UNSET (memback path): leave HandlerConfig zero-
    valued; frontend keeps historical 1 MiB / 512 B contract that
    existing T2 tests expect (regression-safe).

NEW INV: INV-G5-FRONTEND-CAPACITY-FROM-DURABLE-CONFIG
"iSCSI/NVMe externally-visible volume capacity and block size MUST
derive from --durable-blocks × --durable-blocksize when --durable-
root is set, not silently fall back to frontend defaults."
Inscribed in v3-invariant-ledger.md.

NEW TESTS (cmd/blockvolume/frontend_capacity_test.go, 6/6 PASS):
- TestComputeFrontendVolumeSize_ProductOfBlocksAndBlockSize: 5
  cases including 256 MiB (the case that exposed the bug).
- TestComputeFrontendVolumeSize_RejectsZero
- TestComputeFrontendVolumeSize_OverflowGuard
- TestIscsiHandlerCapacity_FromDurableConfig: round-trip via
  iscsi.NewSCSIHandler asserting VolumeSize/BlockSize.
- TestNvmeHandlerCapacity_FromDurableConfig: same on nvme.NewIOHandler.
- TestFrontendDefaults_StillReturn1MiB: negative-control documenting
  the legacy default fallback (the bug shape) — pins behavior so
  future readers can grep for the bug pattern by INV ID.

Regression: full ./... PASS. Memback path tests (frontend/nvme
TestT2Process_NVMe_AttachWriteRead and friends) unchanged because
HandlerConfig stays zero-valued for that path.

Why §close evidence runs missed it: every G5-5/G5-5C scenario wrote
≤ 3 LBAs (LBA[0] / LBA[1] / LBA[2]); volume capacity assertion was
never exercised. Test-design gap, not honesty gap. QA expansion
catalog adds scale-sequential ≥1000 LBAs.

QA action: rebuild bins from this commit; re-run scale-sequential
on m01 (1000 LBAs × 4 KiB = 4 MiB sequential + verify); confirm
canonical 6-step suite still GREEN at 1 MiB memback default.
Architect final §close single-sign on tree containing this fix.
2026-04-27 23:19:06 -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 1868918b96 G5-5C: harden replica kill in verify_restart_catchup (TERM+KILL+port-release wait)
First m01 hardware run (b77rzzhc2) failed at #4 verify_restart_catchup
because the replica restart hit 'bind: address already in use' on
status port 9291 — TERM alone left the prior process holding the
port at restart time. Probe loop on primary correctly tried 5x and
got connection-refused, replica process never came up.

This is a script orchestration issue, NOT a G5-5C software issue.
Primary log (artifacts-20260427T <run2>) shows the probe loop
fired on schedule with the right cooldown progression — there was
just nothing to probe.

Fix: kill replica with TERM (1s) → KILL fallback → poll ss for
port 9291 release (up to 10s) before returning. Replica restart
then has a clean port to bind to.

Run this fix on m01 and re-verify #4 GREEN before §close.
2026-04-27 17:35:39 -07:00
pingqiu 8b83d49b54 G5-5C: enable --degraded-probe-interval=5s on primary in iterate script
Per mini-plan v0.5 §1.A architect binding: production primary runs
probe loop at 5s interval. The script's primary launch now passes
--degraded-probe-interval=5s so verify_restart_catchup can converge
within the 30s deadline (5s loop + ~10s catch-up + safety).

Replica side stays unchanged (probe loop is primary-only).
2026-04-27 17:30:32 -07:00
pingqiu 130e95e226 G5-5C #6.1: doc-fix Stop vs StopHard production/test guidance per Batch 6 review
Architect Batch 6 review 2026-04-27 follow-up: clarify in code that
Stop is the production shutdown path; StopHard is for test
fault-injection / emergency stop only. Prevents future misuse where
operators reach for StopHard as a default shutdown route, masking
graceful-drain bugs.

No code change. No test change.
2026-04-27 17:29:48 -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