Commit Graph
139 Commits
Author SHA1 Message Date
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
pingqiu 602fc0d8ca G5-5C #4: engine boundary tests — dispatch / Case 1 reconnect / lineage stale-event drop / stale-ack guard
Architect Batch #4 review 2026-04-27 ruled the four §2 invariants
(#4 / #11 / #12 / #13) belong at the engine layer, not core/replication/
— "single owner per invariant, don't double-assert in adapter and
engine". Batch 3 already covered the runtime concerns (lifecycle,
cooldown, lock ordering, peer-instance teardown); Batch #4 covers
the truth-layer translations engine performs from probe results
into recovery commands.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Full ./core/replication/ regression: PASS.

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

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

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

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

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

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

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

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

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

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

Full ./core/replication/ regression: PASS.

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

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

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

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

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

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

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

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

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

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

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

Next batch (G5-5C #2): peer.go::ProbeIfDegraded() + cooldown
state-machine + in-flight guard tests.
2026-04-27 15:37:06 -07:00
pingqiu 6729babae5 G5-5 round 14: pre-flight stale-iptables cleanup in start_cluster
Investigation found root cause of round-13 silent failures:
M02 had a leftover INPUT DROP rule from an earlier run's
verify_network_catchup that used the OLD pattern
(`iptables -I INPUT` on M02). When that earlier run aborted via
set -e before reaching its cleanup `iptables -D`, the rule
persisted across runs. Round 13's rewrite changed to OUTPUT-on-m01
but didn't clean up the legacy INPUT-on-M02 leftover. The stale
rule blocked m01→M02:9221 ship/barrier traffic for ALL subsequent
runs; primary's peer entered degraded state on first ship attempt;
all rounds after the original poisoning incident saw the symptom
"replica daemon dies silently" because the SCRIPT's pkill found
nothing (replica had been killed by the script's own pkill but
no ship traffic ever flowed during the run).

Diagnosis sequence:
  1. ssh m01→M02:9221 TCP test: timeout (FAIL=124)
  2. m01 iptables: empty (rules out m01-side block)
  3. M02 iptables INPUT: `DROP tcp dpt:9221` (~50 dropped pkts)
  4. `iptables -D INPUT -p tcp --dport 9221 -j DROP` on M02
  5. Re-test: ssh→TCP echo OK
  6. Re-run: chain flows through to all 3 verify steps

Fix: start_cluster() now drops both possible patterns pre-flight:
  - sudo iptables -D OUTPUT -d  -p tcp --dport  -j DROP   (round-13 pattern)
  - sudo iptables -D INPUT -p tcp --dport  -j DROP                 (round-12 leftover)
Both with || true so missing rules don't fail set -e.

Round-14 result on m01:
  ✓ verify_cluster_ready
  ✓ verify_byte_equal       (LBA[0]=0xab)
  ✓ verify_network_catchup  (LBA[1]=0xcd byte-equal in 8s after iptables disconnect+heal)
  ✗ verify_restart_catchup  (LBA[2]=0xef MISMATCH — real recovery-path finding)

The verify_restart_catchup failure is exactly the case architect
ruling 2 named: 'run #4 naively first; if it doesn't converge,
that is a real recovery-path finding to surface, not a test flaw.'

Primary's log evidence:
  After replica killed → ship attempt → barrier timeout → peer
  invalidated (degraded). Primary writes LBA[2]=0xef while replica
  down → 'ship gate-degraded peer=r2 lba=2 lsn=3 (peer degraded)'
  — ship is gated out before any TCP attempt. Replica restarts;
  no mechanism triggers primary to re-establish the peer
  connection or re-ship the missed entries.

Architecturally the engine-driven catch-up path needs a trigger
(probe success, assignment re-emit, etc.) to bring a degraded
peer back online + replay missed LSNs. G5-5 surfaces that this
trigger isn't wired into the binary's runtime — surface for
architect / QA decision: (a) defer #4 to a follow-up batch with
a dedicated peer-recovery fix; (b) implement now within G5-5
scope.

Refs: round 14 m01 self-iteration; investigation traced 4
indirection layers to find the leftover iptables rule.
2026-04-27 02:15:22 -07:00
pingqiu b3f90387e3 G5-5 round 13: rewrite #3/#4 to byte-equal pattern + helpers
Per architect ratification round 13 + QA planning input:
  - Add wait_until_byte_equal(lba, pattern, deadline_s) helper —
    cycles kill→m01verify→restart per poll until match or timeout.
    Caller-side honest about OpenReadOnly's no-concurrent-writer
    assumption.
  - Add iscsi_write_pattern(lba, count, pattern) helper using
    python3 binary write (byte-exact pattern; tr does not grok
    \xHH escapes per round-12 finding).
  - Rewrite verify_network_catchup with iptables OUTPUT drop on
    m01 toward M02_IP:M02_REPLICA_DATA_PORT. trap RETURN ensures
    iptables -D runs on any exit path. Pass condition is direct
    byte-equal at LBA[1]=0xcd, not engine-state H/R polling.
  - Rewrite verify_restart_catchup with replica killall+restart
    pattern. Run NAIVELY first per architect ruling — if catch-up
    doesn't converge with BestEffort durability, that is a real
    recovery-path finding to surface, not a test flaw.
  - Diagnostic snapshots from /status/recovery kept as supporting
    evidence only, not pass/fail oracle.

KNOWN ISSUE — round 13 self-test on m01: even verify_byte_equal
(which worked on round 12 part C) now fails before reaching
m01verify. Replica daemon on M02 dies silently after recording
supersede; subsequent SSH_M02 pkill matches nothing → set -e
exit. Replica's primary log ends at 'recording supersede, not
applying to adapter'; no exit/panic/SIGSEGV trace in journalctl
or dmesg. Needs further investigation:
  - Is replica daemon exiting cleanly via some path I'm not aware of?
  - Is there an unbuffered panic going to /dev/null because of
    setsid+nohup+</dev/null?
  - Was round-12-part-C's success actually flaky?

Pausing self-iteration here. Round 13 rewrite is complete in
script; #2 byte-equal already proven on hardware in round 12
part C (committed at 82e9018). #3/#4 need additional debug
either (a) on the daemon's lifecycle, or (b) on the script's
sequencing of the replica daemon during multi-step scenarios.

Refs: architect ruling round 13; QA planning input.
2026-04-27 02:01:03 -07:00
pingqiu 82e9018bae G5-5 round 12 part C: fix dd 0xab fill (tr lacks \xHH escape support)
QA round 12 self-test on m01: m01verify reported MISMATCH on
LBA 0 — but inspecting the bytes via xxd showed the primary's
on-disk file matched the replica's, both 0x78 (ASCII 'x') × 4096.
Replication chain is correct; the script wrote the wrong bytes.

Root cause: the script used 'tr "\0" "\xab"' which DOES
NOT produce 0xab. tr's escape grammar recognizes only octal
(\NNN) and a small set of letter escapes (\n, \t, ...);
\xHH is not understood — tr substitutes with the literal first
char of the replacement string, which is '\' parsed loosely
giving 'x' (0x78). Verified empirically on m01:

  $ dd if=/dev/zero bs=4096 count=1 2>/dev/null | tr "\0" "\xab" | xxd | head -1
  00000000: 7878 7878 7878 7878 7878 7878 7878 7878  xxxxxxxxxxxxxxxx

Fix: use python3 binary write — guaranteed byte-exact 0xab fill:
  python3 -c "...sys.stdout.buffer.write(b'\xab' * 4096)..."

Round 12 part C result on m01:
  ✓ verify_cluster_ready
  ✓ verify_byte_equal — m01verify reports 'OK 1 LBA(s) byte-equal'

This is the FIRST end-to-end PASS of acceptance criterion #2 on
real hardware. The replication chain (lineage latch + ship +
barrier + apply) is verified working. verify_network_catchup
still hits H-advance false-positive (engine state semantic is
probe-driven, not local-write-driven; same as fix in #2 but
applied per-step); will address next.

Refs: round 12 m01 self-test full progression
(rounds 1-11 surfaced 14 distinct bugs each isolated and fixed).
2026-04-27 01:43:07 -07:00
pingqiu 8d6c4a807b G5-5 round 12 part B: fix walstore filename v1.walstore → v1.bin
m01verify in verify_byte_equal expected v1.walstore but
durable provider's volumePath uses VolumeID+".bin" (provider.go:133).
Same fix in verify_network_catchup and verify_restart_catchup
helpers if they reference the file path.
2026-04-27 01:39:03 -07:00
pingqiu 2c1ee6e3e5 G5-5 round 12: drop H-advance preflight in verify_byte_equal
Engine's Recovery.H is updated by probe events
(RecoveryFactsObserved), not by local writes. At adoption time
engine sets H = walHead = nextLSN (already 1 for empty walstore);
local write at LSN=1 advances nextLSN to 2 internally, but
Recovery.H stays at 1 until a probe re-reads boundaries. Using
H-advance as a 'silent write failure' preflight produces a false
positive — H stays at 1, check fails, but the actual write +
ship + barrier all completed (per primary log evidence).

Round 11+12 m01 evidence shows the full chain flows:
  durable: dp.Open latching identity volume=v1 replica=r1 epoch=1 ev=1
  durable: StorageBackend.SetIdentity latched ...
  iscsi: SCSI WRITE handler lba=0 transferLen=8 dataOut=4096
  durable: StorageBackend.Write entry offset=0 len=4096
  durable: write observer dispatch lba=0 lsn=1
  replication: OnLocalWrite volume=v1 lba=0 lsn=1 peers=1
  transport: ship lazy-dial replica=r2 ok
  replication: ship ok peer=r2 lba=0 lsn=1
  iscsi: SCSI WRITE backend.Write ok lba=0
  iscsi: SCSI SYNCHRONIZE_CACHE handler entry
  replication: barrier wait peer=r2 targetLSN=1 epoch=1
  replication: barrier ack peer=r2 targetLSN=1 achievedLSN=1
  iscsi: SCSI SYNCHRONIZE_CACHE backend.Sync ok

Replication is working end-to-end on m01+M02 hardware.

Fix: replace H-advance check with informational log; let
m01verify byte-equal compare be the actual proof. Same change
unchanged for verify_network_catchup and verify_restart_catchup
(they still use H comparisons but for different semantics —
catch-up convergence, where H is the engine-level boundary and
the comparison is against replica's R, which the engine DOES
update on session completion).

Refs: round 12 self-test on m01 cross-node — chain flows
end-to-end; H-advance was the only false-positive blocking
m01verify from running.
2026-04-27 01:34:46 -07:00
pingqiu 2e8c3a0469 G5-5 fix v2: latch on Epoch=0, not all-fields-zero (round-11 bug)
QA round 11 reported the 41045e5 fix didn't take effect — same
ErrStalePrimary as round 10. Reason: my latch condition required
ALL FOUR Identity fields zero, but at EnsureStorage construction
time, AdapterProjectionView.Projection() returns:
  VolumeID  = cfg.VolumeID  ("v1" — non-empty, from CLI)
  ReplicaID = cfg.ReplicaID ("r1" — non-empty, from CLI)
  Epoch     = engine state Epoch (0 — no AssignmentObserved yet)
  EV        = engine state EndpointVersion (0 — same)

So the captured b.id = {v1, r1, 0, 0} — partially-zero, not
all-zero. SetIdentity's strict zero-check refused to update.
Subsequent lineageCheck saw proj.Epoch=1 vs b.id.Epoch=0 → still
ErrStalePrimary.

Fix: latch keys on Epoch (the meaningful "no authority line yet"
indicator). VolumeID/ReplicaID match is asserted as paranoia but
unchanged. Drift past a non-zero Epoch is still rejected (failover
safety net preserved via lineageCheck).

Plus 2 diagnostic INFO logs (per QA round-11 ask):
  durable: dp.Open latching identity from projection volume=N
    replica=N epoch=N ev=N (post-waitHealthy)
  durable: StorageBackend.SetIdentity latched volume=N replica=N
    epoch=N ev=N

Test renamed: LatchFromZero → LatchFromZeroEpoch. Now constructs
backend with the realistic pre-assignment shape ({v1, r1, 0, 0})
and verifies (a) latch transitions from Epoch=0, (b) drift past
non-zero Epoch is rejected, (c) Identity returns the latched
value.

Tests still green: durable, blockvolume (G5-4 integration), master,
authority, replication, replication/component.

Refs: QA round 11 — fix didn't take effect; my zero-check was
wrong about the pre-assignment Identity shape.
2026-04-27 01:26:00 -07:00
pingqiu 41045e542f G5-5 fix: latch StorageBackend.Identity post-Healthy via dp.Open
QA round 10 disambiguated: the iSCSI write reached
StorageBackend.Write but gate-rejected with 'frontend: stale
primary lineage'. Root cause: G5-5 introduced EnsureStorage which
constructs the StorageBackend BEFORE the assignment fact lands.

Original V3 design: dp.Open blocks on waitHealthy; the backend
is constructed AFTER projection.Healthy=true; wrap() captures
proj.Epoch/EV at that moment as the immutable Identity.

G5-5 changed: replicas need open storage even when projection
won't reach Healthy (their authority is the bound primary).
EnsureStorage opens storage role-agnostically. But it ALSO
constructs the backend at construction time — and at that
moment view.Projection() returns zero values (no assignment
landed yet). The captured Identity is zero. Once the assignment
lands and projection flips Healthy with Epoch=1/EV=1, every
subsequent gate compares proj{Epoch:1, EV:1, ...} against
b.id{Epoch:0, ...} and returns ErrStalePrimary.

V2 reference confirms: V2's iscsi.BlockDevice → vol.WriteLBA path
uses the engine's CURRENT epoch (not a captured one), so V2
doesn't have this issue. V3's snapshot model is sound; what's
missing is a re-stamp on first promotion to Healthy.

Fix: add SetIdentity(id) to StorageBackend with latch-from-zero
semantic.
  - Latch-from-zero: zero-id backend transitions to the supplied
    identity. One-shot — subsequent calls with a different id
    are REJECTED (returns false). Preserves the failover safety
    net (lineage drift past the latched value still fails closed
    via lineageCheck → ErrStalePrimary).
  - dp.Open's success path (after waitHealthy) now calls
    h.backend.SetIdentity() with the current projection's lineage.
    Idempotent for already-latched same-value backends.

Test: TestG5_5_SetIdentity_LatchFromZero — covers (a) zero →
first identity (allowed), (b) same identity again (no-op), (c)
drift attempt (rejected, identity unchanged so lineageCheck
fail-closed still works). Runs against both walstore + smartwal.

Tests still green: durable (0.6s), blockvolume (16.5s, G5-4
integration test still PASS), master, authority.

Refs: QA round 10 — gate-rejected disambiguation; V2 reference
read confirms architectural diff (V2 vol.WriteLBA uses live
epoch; V3 captures snapshot).
2026-04-27 01:18:15 -07:00
pingqiu 4ec7bd0c2e G5-5 instrumentation: SCSI handler + StorageBackend.Write entry
QA round 9 confirmed: even durable: write observer line is missing.
The iSCSI WRITE never reaches StorageBackend.writeBytes. Need to
walk further upstream — either the iSCSI handler isn't getting the
SCSI WRITE command, or it's getting it but using the wrong backend.

Add 6 instrumentation lines across two layers:

  core/frontend/iscsi/scsi.go (doWrite):
    - SCSI WRITE handler entry (fires on every WRITE_10/16 arrival)
    - SCSI WRITE rejected (LBA out of range)
    - SCSI WRITE rejected (short dataOut)
    - SCSI WRITE backend.Write FAILED
    - SCSI WRITE backend.Write ok

  core/frontend/iscsi/scsi.go (handleSCSI SYNC_CACHE branch):
    - SCSI SYNCHRONIZE_CACHE handler entry
    - SCSI SYNCHRONIZE_CACHE backend.Sync FAILED
    - SCSI SYNCHRONIZE_CACHE backend.Sync ok

  core/frontend/durable/storage_adapter.go (Write):
    - StorageBackend.Write entry (every Write call)
    - StorageBackend.Write gate-rejected (gate() returned err)

Disambiguation matrix for QA's next run:

  No 'iscsi: SCSI WRITE handler' line:
    → iSCSI session/login layer rejects command before SCSI handler.
       Check if Normal session established correctly; check whether
       initiator's volume sees the right size via READ_CAPACITY.

  iscsi: SCSI WRITE handler line present, but no
  durable: StorageBackend.Write entry:
    → SCSI handler reaches a DIFFERENT backend instance (not the
       observer-wired StorageBackend). Wiring fix in main.go required.

  iscsi: SCSI WRITE handler + durable: StorageBackend.Write entry,
  but no observer dispatch:
    → backend gate() rejected (closed/non-operational/lineage drift).
       gate-rejected line fires.

  All instrumentation fires through to ship/barrier:
    → Replication is working.

Tests still green: iscsi (30.9s), durable (0.5s), blockvolume (16.7s).

Refs: QA round 9 — observer line missing from upstream
instrumentation; need iSCSI-side disambiguation.
2026-04-27 01:06:57 -07:00
pingqiu c6bace4e79 G5-5 upstream instrumentation: observer + OnLocalWrite + ship gates
QA round 8: ALL 6 ship/dial/barrier lines from 7a3996d are missing.
The replication outer loop is not running at all. Need to walk
upstream to find where the fan-out chain breaks.

Add 4 INFO log lines at the upstream surfaces:

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

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

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

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

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

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

Tests still green.

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

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

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

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

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

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

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

Refs: QA round 7 disambiguation (peers=1 confirmed; ship-side
instrumentation needed).
2026-04-27 00:54:50 -07:00
pingqiu 5187083fc6 G5-5 logging: INFO line on UpdateReplicaSet success + adopted-as-primary
QA round 6 finding: primary log silent on replication; can't
disambiguate 'peers=0 delivered' (timing gap) from 'peers=N delivered
but ship failed' (TCP/network). Pre-existing log discipline only
emits on the FAILURE branches:
  - line 488: recording supersede (when fact.ReplicaID != self)
  - line 502: UpdateReplicaSet failed

Add INFO logs on the success path so operators / hardware-test
harness can see what's actually being installed without -v / debug
flags:

  blockvolume: volume v1 replication UpdateReplicaSet ok (gen=N,
    peers=K): [r2@192.168.1.184:9221 ...]
  blockvolume: volume v1 adopted as PRIMARY at r1@1 (EV=1)

Small log footprint (one line per fact emission, fact emissions
are rare). Production-acceptable verbosity. No behavior change.

Tests: cmd/blockvolume integration test still PASS (16.4s);
core/host/volume green.

Refs: QA round 6 — primary-fail.log silence.
2026-04-27 00:39:42 -07:00
pingqiu 2347ccb72d G5-5A round 54 follow-ups: freshness gate + lineage rule + comment
Architect review round 54 findings (3 items, all addressed):

HIGH 1 — SlotFact ignores freshness:
  ObservationStore explicitly says expired observations stay
  visible but are 'semantically ineligible for supported snapshot
  synthesis'. SlotFact was scanning the full observation map
  without checking ExpiresAt. For peer-set construction this is
  wrong: a stale heartbeat addr is unsafe to dial.
  Fix: SlotFact now skips observations where now > obs.ExpiresAt.
  New test TestObservationStore_SlotFact_ExpiredObservation_FailsClosed
  verifies the boundary (ok=true within FreshnessWindow,
  ok=false past expiry).

HIGH 2 — path 1 mis-stamps live-ship lineage:
  resolvePeers path 1 was using the peer's OWN LastPublished
  Epoch/EV. If LastPublished(v1, r2) returns r2's retained
  historical authority line (e.g., r2 was previously bound at
  Epoch=N before reassignment to r1 at Epoch=N+1), primary r1
  would stamp live-ship frames under r2's old N — breaks the
  apply gate at the replica which expects current authority.
  Fix: BOTH paths now stamp peer.Epoch/EV with subscriber's
  lineage. Authority/observation supplies addresses only;
  subscriber stamps lineage. Updated TestResolvePeers_BothBound
  to pin this (peer's old 4/1 must NOT win over subscriber's
  5/2). path-1-preferred test still passes — it's about which
  ADDR wins, not lineage.

LOW 3 — stale comment:
  collectPeers godoc still claimed observation-derived peers
  'carry Epoch=0 + EndpointVersion=0 to mark observation-derived'.
  Out of date since round-54 inheritance fix. Rewrote comment
  block to reflect current rule: both paths stamp subscriber's
  lineage; authority/observation supplies addresses only.

All G5-5A tests still pass (10/10); cmd/blockvolume G5-4
integration test PASS; full V3 suite green.

Refs: architect round 54 review of 61f5ff6.
2026-04-27 00:30:45 -07:00
pingqiu 61f5ff62a8 G5-5A: master peer-set from observed supporting replicas
Architect ratification round 54 (2026-04-27): collectPeers may
synthesize peer descriptors for topology slot members observed by
heartbeat even when they don't have a bound authority publication.

Root cause from QA round 54: V3 controller only mints
AssignmentInfo for the BOUND replica (Publisher.apply path).
Supporting replicas have no published authority line, so
master.collectPeers' pub.LastPublished returns false for them,
peers list is empty, primary's ReplicationVolume has no peers,
fan-out/Sync barrier has no acks → iSCSI fsync I/O error.

Architect Option A (chosen): collectPeers falls back to
ObservationStore for slot members without published lines.
Topology membership is the allow-list (option R / arbitrary
observed nodes still rejected). Authority state stays clean —
Option B (mint presence records into pub.state) was rejected.

Implementation:

  core/authority/observation_store.go:
    + SlotFact(volumeID, replicaID) — returns latest-observation
      SlotFact across all servers; fail-closed on empty DataAddr.

  core/host/master/services.go:
    collectPeers signature changes from (volumeID, selfReplicaID
    string) to (volumeID string, selfInfo adapter.AssignmentInfo)
    so observation-derived peers can inherit subscriber's Epoch/EV.

    Body extracted to pure helper resolvePeers() for testability.

    Peer construction policy:
      Path 1: pub.LastPublished hits → use authority Epoch/EV/addrs
      Path 2: SlotFact hits → use heartbeat addrs + INHERIT
              SUBSCRIBER'S Epoch/EV (live ships carry primary's
              lineage; replica validates against it)
      Else:   skip fail-closed

    Inheriting subscriber's Epoch/EV is required because
    ReplicaPeer constructor (replication/peer.go:130) rejects
    zero values — the lineage stamps every outgoing live-ship
    frame, and primary's authority is what the supporting replica
    validates against.

Tests:
  core/authority/observation_store_slotfact_test.go: 5 tests
    (round trip, empty store, fail-closed empty addr,
    latest-wins across servers, vol/replica mismatch)
  core/host/master/services_g5_5a_test.go: 5 tests
    (headline r1-bound + r2-observed-only, both bound,
    neither bound nor observed, nil obs store, path-1 wins
    over path-2)

All 10 G5-5A tests pass; full V3 suite green (23/23 packages
incl. cmd/blockvolume G5-4 integration test still green).

No engine/adapter behavior change — touches master/observation
peer-set construction only.

Refs: QA round 54 finding (cross-host fsync I/O error);
architect Option A ratification 2026-04-27.
2026-04-27 00:18:51 -07:00
pingqiu 715ed15abf G5-5 script: bind+advertise routable IP, not 0.0.0.0 (cross-host fix)
QA round 54: cluster came up, iSCSI session established, but
fsync (SYNCHRONIZE CACHE) returned I/O error. Root cause: replica
bound --data-addr 0.0.0.0:9221 AND advertised that string to master
heartbeat. Master minted AssignmentFact.peers[*].DataAddr=0.0.0.0:9221.
Primary's BlockExecutor tried to dial 0.0.0.0:9221 — unroutable
destination — connection failed. Replication fan-out + Sync barriers
silently failed (best-effort log line; the fsync gets I/O error).

The daemon advertises the literal --data-addr string verbatim:
  cmd/blockvolume/main.go:230 → cfg.DataAddr = f.dataAddr
  → host heartbeats DataAddr to master
  → master.collectPeers copies it into AssignmentFact.peers
  → primary dials peers[*].DataAddr

So for cross-host the bind addr MUST be a routable IP, not 0.0.0.0.
On Linux, binding to a specific local-interface IP works fine and
ensures the literal advertised string is routable.

Fix: extract M01_IP / M02_IP from M01_HOST / M02_HOST and use as
both bind and advertise:
  Tier 2: M01_PRIMARY_BIND_IP=${M01_IP}, M02_REPLICA_BIND_IP=${M02_IP}
  Tier 1: M01_PRIMARY_BIND_IP=127.0.0.1, M02_REPLICA_BIND_IP=127.0.0.1

start_primary / start_replica now use the IP variables for both
--ctrl-addr and --data-addr. Master's --listen stays 0.0.0.0 (it's
the destination of heartbeats, not advertised).

This is a script-side fix only; daemon code unchanged. Refs QA
round 54.
2026-04-26 23:56:14 -07:00
pingqiu e83827a102 G5-5 script: drop -n from launch ssh (conflicts with bash -s stdin)
QA round 53 isolation: SSH_OPTS included -n which redirects ssh
stdin from /dev/null. With bash -s, remote bash reads script from
stdin — stdin is EOF (because -n) so bash exits immediately, daemon
never starts, master.log stays empty.

QA evidence: dbg.sh on m01 reproduced heredoc form WITHOUT -n;
bash -s correctly read heredoc, blockmaster launched, port 9180
bound, proof.txt confirmed heredoc execution.

Fix per architect option (A): split SSH options into two sets:
  SSH_OPTS_BASE   — shared: -T (no PTY) + BatchMode=yes
  SSH_OPTS        — base + -n; for ssh host CMD patterns
  SSH_OPTS_LAUNCH — base only (no -n); for ssh host bash -s

launch_m01 / launch_m02 use SSH_OPTS_LAUNCH. PTY-hang protection
comes from -T alone, present in both sets.

Verified: launch_m01 heredoc body executes; variable expansion
works; remote-shell PID resolves correctly.
2026-04-26 23:45:01 -07:00
pingqiu 20d04965d9 G5-5 script: bash -s heredoc launch (option A) — fix line-collapse hang
QA round 53 finding (Tier 2 m01 → M02): start_replica's SSH session
hung even on Linux (m01 native ssh, no Windows-Git-Bash quirks).
Root cause is a `\<newline>` line-collapse hazard in the
double-quoted SSH command argument:

  $SSH_LAUNCH_M02 "
  setsid nohup /tmp/g5-blockvolume \
      --master ... \
      ...
      > .../replica.log 2>&1 </dev/null &
  disown \$! 2>/dev/null || true
  sleep 1
  exit 0"

The local shell processes `\<newline>` as line continuation INSIDE
the double-quoted string. The `\` at end of every option line
collapses lines, which can in some bash interactions produce a
joined argv where `&` runs into `disown` directly with no
separator. Remote bash then parses the joined statement
incorrectly, never executes `disown $!` / `sleep 1` / `exit 0`,
remains attached to the bg daemon, and SSH hangs.

The `\<newline>` substitution happens in the LOCAL shell (the one
running iterate.sh), so it's not Windows-Git-Bash-specific —
reproduces on m01 (Linux) too.

Fix per architect option (A) round 53: pipe the command body to
remote bash via `bash -s` heredoc instead of double-quoted ssh
argument.

  launch_m01 <<EOF
  setsid nohup CMD ARG1 ARG2 ... > LOG 2>&1 </dev/null &
  disown \$! 2>/dev/null || true
  sleep 1
  exit 0
  EOF

With heredoc + `bash -s`:
  - body is piped to remote bash's stdin verbatim
  - newlines are preserved literally regardless of any local
    shell processing
  - statement boundaries are unambiguous
  - daemon command on a single line (no `\<newline>` continuations)
    eliminates the entire ambiguity class

Implementation:
  - new launch_m01() / launch_m02() functions handle Tier 1
    (LOCAL_MODE=1, run via local `bash -s`) and Tier 2 (run via
    `ssh ... bash -s`) with shared timeout-prefix logic
  - start_master / start_primary / start_replica use the new
    helpers + heredoc body
  - removed SSH_LAUNCH_M01 / SSH_LAUNCH_M02 vars (subsumed by
    launch_m01 / launch_m02)

Verified: local Tier-1-style smoke test launches a `sleep 30` bg
process, disowns it, and exits within 1.08s (the explicit `sleep
1` + overhead). Pre-fix this took ~5s (timeout fallback). The bg
process detached and ran independently. This proves all three
post-`&` statements (disown / sleep / exit) execute as separate
commands — the line-collapse hazard is structurally eliminated.

Refs: QA Tier 2 round 53 finding (Linux SSH hang); architect
option (A) ratified; option (B) `;<newline>` rejected per QA's
clarification (newlines also stripped by `\<newline>` so
semicolons alone don't help).
2026-04-26 23:38:34 -07:00
pingqiu 994ad4e842 G5-5 script: PREBUILT_BIN_DIR Tier 2 fast-path + SRC_DIR safety guard
Architect option (a) ratified round 53. Two changes to sync_and_build:

1. PREBUILT_BIN_DIR fast-path for Tier 2 (cross-node m01+M02):
   When PREBUILT_BIN_DIR is set, skip source-tar + remote-build
   entirely. scp the 3 pre-built binaries (g5-blockmaster,
   g5-blockvolume, g5-m01verify) directly to m01:/tmp/ and onward
   to M02. Mirrors the existing LOCAL_MODE branch pattern.

   Use case: Windows workstation cross-compiles via
     CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o ...
   then sets PREBUILT_BIN_DIR=/path/to/bins. No m01-side source
   tree or `go` install needed. Also works for CI artifact paths.

2. SRC_DIR safety guard (the bug QA hit round 53):
   When iterate.sh is copied away from the repo and run with
   SRC_DIR resolving to "" or "/" (e.g., bash /tmp/iterate.sh
   without overriding SRC_DIR), the prior code called
     `cd "$SRC_DIR" && tar -czf /tmp/g5-src.tgz .`
   which tarred the root filesystem. QA killed it before damage,
   but the unsafety must not exist.

   Guard sequence (refuses with named error before any tar):
     - SRC_DIR empty or "/"        → die
     - SRC_DIR/go.mod missing      → die
     - SRC_DIR/cmd/blockvolume/    → die
     - else                        → safe to tar

   Verified all 4 die paths fire with clear messages: empty, "/",
   non-repo path, PREBUILT_BIN_DIR with missing binary.

Acceptance criteria #1-#7 unaffected; only the build/sync mechanism
changes. The 4 verify_* scenario bodies are untouched.

Refs: QA Tier 2 round 53 finding (SMB-driven iterate.sh attempted
to tar root filesystem); architect option (a) binding.
2026-04-26 23:28:50 -07:00
pingqiu 0769d67fa5 G5-5 script: fix Windows-Git-Bash SSH-launch hang (-T -n + timeout)
QA Tier 2 m01 cross-node verification surfaced: cluster comes up
correctly (master + primary + replica all start, replica logs
"authority is now r1@1; recording supersede" — exactly the
architect-binding role split), but the Windows Git Bash side of
start_replica's SSH session never returns even though the remote
process is detached via setsid+nohup+disown.

Root cause: OpenSSH on Windows Git Bash allocates a PTY for the
remote shell (default behavior when stdin is a terminal); the
local ssh client waits for the PTY to detach, which never happens
even after setsid. Standard Git Bash quirk; well-documented but
not previously hit by V3 because prior cross-node scripts used
short-lived SSH calls only.

Two-layer fix:

1. Add -T (no PTY) and -n (close local stdin) to all SSH commands
   via shared SSH_OPTS variable. -T is the primary fix; -n was
   already added by prior edit but is insufficient alone.

2. Wrap launch-and-detach SSH calls (start_master/_primary/_replica)
   with `timeout 15 --preserve-status` as defense-in-depth. If SSH
   still hangs (rare with -T -n applied), the script moves on after
   15s. Remote process is already disown'd so the only stale state
   is a local ssh client process — harmless. Falls back to no-op
   wrapper if `timeout` isn't installed (Git Bash without coreutils).

Also tightens remote launch heredoc:
  - explicit `disown $!` after backgrounding to detach from job table
  - explicit `exit 0` to force the wrapping shell to exit cleanly
    even if any prior command had a non-zero status

Tested: bash -n syntax clean; timeout available on local box; no
local-mode regression (LOCAL_MODE=1 path uses bash -c, not ssh).

Refs: QA Tier 2 round 53 finding; environmental, not a product bug
(daemon comes up correctly on cross-node hardware per the same
session's logs).
2026-04-26 22:58:00 -07:00
pingqiuandClaude Opus 4.7 71f93f6cd8 G5-5 script: two-tier (LOCAL_MODE) + architect findings + SSH detach
Architect round-52 findings absorbed:
  - iscsi-listen 0.0.0.0 → 127.0.0.1 (T2 iSCSI loopback-only rule)
  - remote SSH bash blocks: set -euo pipefail + DEV non-empty assert
    + primary.H advancement check (catches silent dd failure masking)
  - RecoveryDecision empty no longer acceptable: must observe
    explicit catch_up transition or fail
  - (walstore.OpenReadOnly already correct per sw earlier commit)

Two-tier mode added:
  - LOCAL_MODE=1: single Linux host (e.g. WSL); both processes on
    localhost; iSCSI/race/full-suite skip if iscsiadm/Go-too-old
  - LOCAL_MODE=0 (default): m01 cross-node Tier 2

Tier 1 verified PASS on WSL (cluster bring-up + role split; iSCSI
tests cleanly skip).

SSH detach fixes:
  - pkill -f '[g]5-block' (regex character class avoids self-match)
  - setsid nohup ... & (replaces & disown; full process group break)
  - ssh -n (no stdin; helps SSH session cleanup on Windows Git Bash)

Tier 2 (m01) status: cluster comes up correctly end-to-end (master +
primary + replica all running; replica logs role-split supersede),
but SSH session for start_replica step doesn't return cleanly from
Windows Git Bash — known SSH-from-Windows quirk. Tier 2 should run
from a Linux SSH host OR with ProxyJump to avoid Windows-side hang.

Tier 1 evidence is sufficient for criteria #1 (cluster ready, role
split). Criteria #2/#3/#4 require iSCSI which neither WSL (no
open-iscsi) nor Tier 2 (Windows-SSH hang) currently runs end-to-end.
Carry: Tier 2 on Linux-host SSH OR install open-iscsi on WSL.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:49:12 -07:00
pingqiu 1caaf9c291 G5-5 script: LOCAL_MODE Tier 1 (localhost) for fast dev iteration
Add two-tier test mode to iterate-m01-replicated-write.sh:
  Tier 1 (LOCAL_MODE=1): both processes on localhost, no SSH/scp
    - drives faster dev iteration (no cross-node sync overhead)
    - iSCSI tests skip with explicit message if iscsiadm not present
    - intended for WSL/Linux dev workstation iteration before
      escalating to cross-node m01/M02 verification
  Tier 2 (default, LOCAL_MODE=0): m01 (192.168.1.181) + M02
  (192.168.1.184) cross-node — deployment-realism close evidence

Implementation:
  - SSH_M01/SSH_M02 redefined as `bash -c` in LOCAL_MODE
  - sync_and_build skips tar/scp in LOCAL_MODE; builds locally
  - master subscribe target switched to 127.0.0.1 vs 192.168.1.181
  - HAS_ISCSI sentinel set per-mode for skip messaging
2026-04-26 22:12:31 -07:00
pingqiuandClaude Opus 4.7 94edc46197 G5-5 round-52 fixes: read-only opener no goroutines + script fail-closed
Addresses architect/QA review round 52 findings:

MEDIUM — OpenReadOnly inherited writer machinery:
  Original implementation reused openInitialized which started
  flusher + committer + admission goroutines and persisted the
  superblock back through Close. Those writes target the fd
  opened O_RDONLY — silent OS-layer failure but a "read-only
  verifier" leak.

  Rewrite: WALStoreReader is now a minimal handle (fd + sb + dm)
  with its own Read/Close paths. No openInitialized call, no
  background goroutines, Close only releases the fd. Same
  WAL-then-extent merge semantic for Read(lba); recoverWAL is
  invoked directly to populate the dirty map (it's a pure read
  pass over WAL frames — no fd writes).

  Pinned by new TestOpenReadOnly_NoBackgroundGoroutines that
  snapshots runtime.NumGoroutine() before/after Open+Read+Close
  and asserts no growth (tolerance 1 for runtime jitter; flusher
  + committer alone would add 2).

HIGH — verify_byte_equal could false-pass on silent write failure:
  Same hardening pattern already applied to verify_network_catchup
  + verify_restart_catchup (user-applied edits) now extended to
  verify_byte_equal:
    - remote SSH heredoc uses `set -euo pipefail`
    - DEV non-empty assertion before dd
    - primary.H captured before + after, asserted strictly greater
      (catches silent-write-failure masking before the byte-equal
      check ever runs)
    - explicit echo "WROTE-LBA-0-PATTERN-AB" stamped on success
      so the surrounding script can grep for the marker if needed

BLOCKER from round 51 (--iscsi-listen 0.0.0.0:) was already
resolved in the prior commit (file edit set 127.0.0.1).

Tests: core/storage 3/3 PASS (incl. new goroutine fence);
core/host/volume + cmd/blockvolume + smartwal all green.
Script syntax-checked clean (bash -n).

Refs: sw-block/design/v3-phase-15-g5-5-mini-plan.md v0.3 §6
risks (architect REVIEW round 52 findings)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:11:39 -07:00
pingqiuandClaude Opus 4.7 702c661f87 G5-5 implementation: instrumentation + verifier + m01 orchestration
Per architect-ratified mini-plan v0.3 §1 file map. Three additions
(no engine/adapter behavior changes per architect §6 binding):

1. /status/recovery endpoint (opt-in, loopback-only, default off)
   - core/host/volume/status_server.go: handler + EnableRecoveryEndpoint()
   - core/host/volume/projection_bridge.go: AdapterProjectionView.EngineProjection()
     accessor returns the underlying engine.ReplicaProjection (Mode/R/S/H/
     RecoveryDecision/Reason). Surfaces existing engine state via HTTP;
     no engine code change.
   - cmd/blockvolume/main.go: --status-recovery CLI flag (default off);
     calls status.EnableRecoveryEndpoint() when set
   - core/host/volume/status_server_test.go: 3 new tests
     (Disabled→404, Enabled→200+fields, WrongVolume→404)

2. core/storage.OpenReadOnly + WALStoreReader
   - Read-only walstore opener for hardware byte-equal verification.
     Opens O_RDONLY, runs Recover() to populate dirty map, exposes
     Read(lba) only (no Write/Sync surface). Caller must ensure no
     concurrent writer.
   - core/storage/walstore_readonly.go + walstore_readonly_test.go
     (round-trip write→close→OpenReadOnly→Read passes; missing-file
     fence)

3. cmd/m01verify standalone helper (build-tag m01verify)
   - Separate cmd subpackage so it doesn't collide with blockvolume's
     main(). Builds only with `go build -tags m01verify`.
   - Opens replica's walstore via storage.OpenReadOnly, calls Read(lba)
     per LBA in target range, SHA-256 vs --expected-pattern (single hex
     byte) or --expected-file (binary payload). Prints OK / MISMATCH +
     exit 0/1.
   - Architect REVISE round 51: NO raw .extent peek; storage abstraction
     is the only authoritative read path.

4. scripts/iterate-m01-replicated-write.sh — full G5-5 orchestration
   - Replaces v0.1 skeleton's TODO scenario bodies with real verify
     steps matching mini-plan v0.3 §2 acceptance criteria #1-#6.
   - 6 verify functions: cluster_ready, byte_equal (kernel iSCSI write
     + m01verify storage-aware compare), network_catchup (iptables
     drop + /status/recovery R/H polling), restart_catchup (SIGTERM
     replica + restart same --durable-root + R/H polling), race_stress
     (TestG54_BinaryWiring x10 -race on m01), full_suite (go test ./...).
   - Build phase compiles all 3 binaries on m01 (master + volume + verify)
     and scp blockvolume + m01verify to M02. SMB share path used in
     prior smoke is replaced by direct scp for simpler dependency.

Acceptance gates per mini-plan v0.3 §2:
  #1-#6 covered by script verify steps; m01 hardware run is QA's
  responsibility per `v3-batch-process.md §14` (sw drafts, QA verifies).
  #7 (v3-dev-roadmap.md update at gate-close) deferred to §close.

Full V3 regression: 23/23 packages green from local Windows run
(includes G5-4 binary integration test still passing at 16.4s; new
status_server tests pass; new walstore_readonly tests pass; m01verify
builds clean under -tags m01verify).

Hard binding preserved: zero engine/adapter behavior changes. The
/status/recovery endpoint surfaces an already-computed projection;
walstore.OpenReadOnly is a new read-only wrapper around existing Recover
+ Read; no semantic changes to either.

Refs: sw-block/design/v3-phase-15-g5-5-mini-plan.md v0.3

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 21:44:17 -07:00
pingqiuandClaude Opus 4.7 be9823b872 G5-4: bind T4 replication stack into cmd/blockvolume
Mirror T4d-4 part B's WithEngineDrivenRecovery() (component framework
binding at core/replication/component/cluster.go:357-369) into the
production binary. Constructs ReplicationVolume + ReplicaListener
per volume and wires both into the host lifecycle, so replicas can
accept incoming WAL traffic and primaries can fan out writes.

Architect bindings (mini-plan v0.4 §7.1 round 50):

  Replica readiness — frontend.Projection.Healthy is reused with
  role-aware semantics: primary reaches Healthy=true via the existing
  caught-up + fence-acked path (engine.ModeHealthy); replica role
  (assigned to SUPPORTING; engine apply skips OnAssignment via
  recordOtherLine) keeps Healthy=false indefinitely. Frontend bind
  (--iscsi-listen / --nvme-listen) is operator-controlled per role:
  not passed for replicas. G5-4.5 integration test uses precise
  assertion names (replica MUST NOT report Healthy=true).

  --ctrl-addr reuse REJECTED — verified ReplicaListener should bind
  on --data-addr instead. transport executor's Probe + Ship paths
  dial peer.DataAddr (executor.go:303); listener must bind on the
  address master mints into AssignmentFact.peers[*].DataAddr — i.e.,
  --data-addr. --ctrl-addr stays reserved for future control-plane
  split (no current binder; verified no conflict with NVMe / iSCSI
  / status: each has its own dedicated --*-listen / --status-addr
  flag). Mini-plan v0.4 said "reuse --ctrl-addr"; correct answer
  found during code is --data-addr. PR description carries this
  finding for ratification.

Files changed:
  - core/host/volume/host.go: SetReplicationVolume(rv) + RWMutex
    around h.replication so binary can wire post-New (storage opens
    after host construction).
  - core/frontend/durable/provider.go: EnsureStorage(volumeID) opens
    LogicalStorage role-agnostically (without waiting for Healthy);
    Backend(volumeID) accessor returns the same StorageBackend
    instance dp.Open returns later. Both used by binary main.go.
  - cmd/blockvolume/main.go: after EnsureStorage + RecoverVolume,
    construct ReplicationVolume(volumeID, store) + h.SetReplicationVolume,
    SetWriteObserver on the backend for fan-out, ReplicaListener on
    --data-addr + Serve. Cleanup chain (LIFO): listener.Stop +
    rv.Close BEFORE durableProv.Close (storage borrowed by both).
  - cmd/blockvolume/g5_4_l2_replication_test.go: NEW. L2 subprocess
    integration test — real cmd/blockmaster + 2× cmd/blockvolume over
    TCP with --expected-slots-per-volume 2; asserts primary reaches
    Healthy=true, replica does NOT (role split per architect
    binding), replica's --data-addr accepts TCP (listener bound).

Acceptance criteria status (mini-plan v0.4 §4):
  #1 binary constructs ReplicationVolume   ✅ verified by code review
  #2 in-process role-appropriate ready     ✅ G5-4.5 PASS
  #3 byte-equal primary→replica            ⏸ deferred to G5-5 m01
     (in-process test would need iSCSI/NVMe Go client to drive
     frontend writes; subprocess pin for wiring + role split is in;
     m01 hardware has the kernel iSCSI client tooling)
  #4 stop-restart catch-up convergence     ⏸ deferred to G5-5 m01
     (depends on #3 frontend write driver)
  #5 no regressions                        ✅ full V3 suite green
  #6 10x -race stress                      ⏳ pending m01 verification
  #7 invariant ledger inscription          ✅ 5 INV-BIN-WIRING-* in
     v3-invariant-ledger.md (companion commit in seaweedfs repo)

Refs: sw-block/design/v3-phase-15-g5-4-mini-plan.md v0.4

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 17:03:42 -07:00
pingqiuandClaude Opus 4.7 2d86f3ba5b G5-1 QA scenarios: 2 distinct-from-sw component tests + 1 known-gap skip
Per architect round-49 G5 v0.3 ratification: G5-1 cleared to start
immediately (no architect dependency; component framework binds T4d-4
part B WithEngineDrivenRecovery directly).

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

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

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

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

22 packages green; full component package smoke passes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 15:58:43 -07:00
pingqiuandClaude Opus 4.7 02fdb71c7d blockmaster: --expected-slots-per-volume flag (was hardcoded 3)
cmd/blockmaster/main.go hardcoded ExpectedSlotsPerVolume: 3 in the
TopologyControllerConfig. The TopologyController's
validateVolumeTopology rejects every observation snapshot whose
slot count differs from this value, returning an error from
SubmitObservedState that propagates back to the observation host
without a master-log line.

Result with a 2-node smoke topology (m01-primary + m02-replica):
master is silent, no assignments minted, volumes timeout at
durable open with frontend.ErrNotReady — the symptom QA hit
during G5-4 cross-node bring-up.

Fix: add --expected-slots-per-volume CLI flag, default 3
(production RF=3 unchanged). 2-node smoke clusters pass
--expected-slots-per-volume 2.

Long-term refactor (separate ticket): the validator should
compare snapshot slot count against the topology's per-volume
slot count, not a single global config — that's the real
per-volume RF model.

Refs: sw-block/design/v3-phase-15-g5-m0102-bringup-answer.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 10:37:13 -07:00
pingqiuandClaude Opus 4.7 6ce708bb64 G5-4 m01 hardware first-light harness — DRAFT v0.1 skeleton
QA-authored skeleton mirroring T2 iterate-m01-nvme.sh pattern; awaiting
G5 mini-plan ratification for scenario bodies (marked TODO(G5-arch-ratify)).

Architecture (per QA infra verification 2026-04-26):
  - primary blockvolume on m01 (192.168.1.181)
  - replica blockvolume on M02 (192.168.1.184)
  - blockmaster on m01 (single master, both nodes connect)
  - build on m01 (Go 1.26.2 installed); scp blockvolume binary to M02
    (Go NOT installed there — same pattern T2 uses for iSCSI target)

Substrate matrix: walstore + smartwal × 4 scenarios (8 total).
  Default extent: 1 GiB at 4 KiB blocks (262144 blocks).

Scenario stubs (TODO bodies await G5-4 architect ratification per
g5-kickoff.md §3 / §4 #1):
  1. ShortDisconnect_DeltaCatchUp — iptables block + drive writes +
     unblock + verify engine catch-up to delta-only convergence
  2. LongDisconnect_RebuildEscalation — fill retention window +
     verify WAL recycled → rebuild path
  3. MidStreamDisconnect_Recovery — engine retry budget under
     intermittent fault
  4. SteadyStateLiveShip_Throughput — sustained write load (relevant
     to G5-2 walstore flusher cadence verification)

Framework gaps surfaced for sw G5-4 work (in skeleton TODO comments):
  - Workload driver decision (iSCSI? gRPC admin? test-only RPC?)
  - Replica state inspector (extend --status-addr endpoint?)
  - Byte-exact verifier across nodes

Diagnostics: master + primary + replica logs + dmesg from both nodes
collected on any scenario failure to ARTIFACT_DIR (default:
seaweedfs/sw-block/design/g5-artifacts/).

Status: ⏸ DRAFT skeleton — no scenarios runnable yet. Ready for
sw + architect review of structure; scenario bodies land in G5-4 PR.

Refs: g5-kickoff.md §3 batch G5-4 + §7a infra verification.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 09:38:44 -07:00
pingqiuandClaude Opus 4.7 1be5da483d nvme test fixture: atomic.Pointer for lastWrite (race under TestT2A_ConcurrentQueueStress)
writeCountingBackend.lastWrite was a plain []byte field. The
chunked-R2T integrity tests drive Writes serially (assumption
documented in the original code), but TestT2A_ConcurrentQueueStress
shares one writeCountingBackend across 8 IO queues, violating that
assumption — m01 -race reported a write-write race on the field.

Race report (m01, T4d-4 verification):
  WARNING: DATA RACE on writeCountingBackend.lastWrite
  Both goroutines: nvme_test.(*writeCountingBackend).Write
  Stack: dispatchIO → handleWrite → IOHandler.Handle → ...

Fix: replace plain field with atomic.Pointer[[]byte]. Each Write
Stores a fresh copied slice (never mutated after store); readers
Load() to observe a stable snapshot. Semantics preserved for the
chunked-R2T integrity check sites.

Production code untouched. Production session model already
correctly synchronized (per QA's race triage during T4d closure).

Refs §8B.4 Discovery Bridge: QA-owned NVMe test fixture lastWrite
race. Architect-approved 2026-04-26 (pingqiu). Verify on m01:
  go test -race -count=10 -run TestT2A_ConcurrentQueueStress \
    ./core/frontend/nvme/

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 00:13:53 -07:00
pingqiuandClaude Opus 4.7 4d73c3978e T4d-4 part C: full L2 matrix + 2 engine bug fixes (HARD GATE #3)
HARD GATE #3 surfaced 2 real bugs in engine-driven recovery flow that
synthetic OnSessionClose injection didn't expose. Both fixed here.

Bug #1 — catch-up exhaustion missed escalation when Decision was
re-classified mid-flight:
  Symptom: stray auto-probe arriving between catch-up retries
  re-classified Recovery.Decision (R<S → Rebuild). Exhaustion-branch
  checked stale Decision and fell through to terminal-degraded
  instead of round-47 escalation.
  Fix: key on st.Session.Kind == SessionCatchUp (truth = what
  session actually failed), not on mutable Recovery.Decision.

Bug #2 — WALRecycled set Decision=Rebuild but never emitted
StartRebuild; subsequent probe could downgrade:
  Symptom: WALRecycled escalation only emitted PublishDegraded; no
  rebuild command. A subsequent probe with R>=S could re-classify
  back to CatchUp before any rebuild fired.
  Fix: new RecoveryTruth.RebuildPinned sticky bool. Set by both
  WALRecycled escalation AND catch-up exhaustion. decide() honors
  it as override — forces Decision=Rebuild + emits StartRebuild
  regardless of R/S/H. Cleared by successful rebuild
  SessionCompleted (or identity reset).
  WALRecycled also now emits StartRebuild immediately (in addition
  to PublishDegraded for diagnostic surface).

Bug #3 (architect-required rule) — already correct:
  Rebuild's MaxRetries=0 routes the first rebuild failure to the
  existing terminal-degraded branch. No code change needed.

New invariants pinned:
  INV-REPL-REBUILD-DECISION-STICKY — once escalated to rebuild
    (WALRecycled or exhaustion), probe re-classification cannot
    downgrade to CatchUp before rebuild completes.
  INV-REPL-REBUILD-EMITTED-ON-WAL-RECYCLED — WALRecycled escalation
    emits StartRebuild immediately, not just PublishDegraded.

Full L2 tests (HARD GATE #3) — all PASS through real
engine→adapter→executor wiring (NOT synthetic injection):
  - TestT4d4_FullL2_CatchupRetryExhausted_EscalatesToRebuild
  - TestT4d4_FullL2_WALRecycled_EscalatesImmediate
  - TestT4d4_FullL2_LastSentMonotonic_AcrossRetries (QA #8 full form)

Files:
  - core/engine/state.go — RebuildPinned field with invariant doc
  - core/engine/apply.go — sticky-rebuild gate in decide();
    WALRecycled emits StartRebuild + pins; exhaustion uses
    Session.Kind + pins; rebuild SessionCompleted clears pin
  - core/engine/recovery_test.go — fixtures set Session.Kind:
    SessionCatchUp (was relying on old Decision-based check)
  - core/replication/component/t4d4_full_l2_matrix_test.go — NEW,
    3 HARD GATE #3 tests via engine-driven flow with substrate
    fault injection wraps

Verified: full V3 suite green; m01 -race ×20 stress on the 3 HARD
GATE tests, no flakes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 23:36:47 -07:00
pingqiuandClaude Opus 4.7 028ea64fc6 T4d-4 part B: engine-driven recovery wiring + rebuild-on-exhaustion + G5-DECISION-001 serializability
Per T4d mini-plan v0.5 §2.4 (architect round-47 expanded scope).
Closes 3 of 4 HARD CLOSE GATE items (#1 #2 #4); #3 full L2 matrix
+ QA #8 LastSentMonotonic full form deferred to part C with
substrate fault injection.

ROUND-47 ENGINE CHANGE — catchup-exhaustion escalates to rebuild:
- core/engine/apply.go applySessionFailed: catch-up budget exhaustion
  now DIRECTLY emits StartRebuild (Decision flips to Rebuild,
  StartRebuild command emitted with current Recovery.H as TargetLSN).
  Pre-round-47: cleared Decision + emitted PublishDegraded; rebuild
  only fired if a fresh probe arrived. Round-47: rebuild path becomes
  engine-driven end-to-end without probe dependency.
- Rebuild has MaxRetries=0 per DefaultRuntimePolicyFor; rebuild
  failure terminates (Decision cleared, PublishDegraded emitted).
  Pinned by INV-REPL-CATCHUP-EXHAUSTION-ESCALATES-TO-REBUILD +
  INV-REPL-REBUILD-FAILURE-TERMINAL.
- Existing TestSessionFailed_NonRecycled_RetriesUntilBudget updated
  for round-47 escalation (asserts StartRebuild emit on attempt #4
  + Decision=Rebuild + DecisionReason="catchup_budget_exhausted").

WITHENGINEDRIVENRECOVERY() REAL — round-47 HARD GATE #1 + #2:
- core/replication/component/cluster.go: WithEngineDrivenRecovery()
  now installs ONE VolumeReplicaAdapter per replica at Start.
  Adapters are wired to executors via the constructor's
  executor-callback registration (existing adapter ctor behavior).
- New PrimaryNode.adapters field + Cluster.Adapter(idx) accessor.
- New Cluster.DriveAssignment / Cluster.DriveProbeResult helpers
  for test scenarios driving engine state through real adapter.
- Stub warning text + log message removed; engine-driven recovery
  is now the real path when opted in.

G5-DECISION-001 SERIALIZABILITY — round-47 obligation:
- core/engine/g5_decision_001_serializability_test.go pins that
  engine.ReplicaState (+ all nested truth structs) round-trips
  through encoding/json cleanly. T4d-4 obligation: keep struct
  serializable so G5 can choose Path A (persist recovery state
  across primary restart) without structural rewrite.
- 2 tests: full-state round-trip + zero-value round-trip
- T4d-4 does NOT implement persistence — just maintains the
  serializability property.

NEW TESTS (9):
core/engine/recovery_test.go (2 new + 1 updated):
- TestT4d4_CatchupExhaustionEscalatesToRebuild (round-47 #4 pin)
- TestT4d4_RebuildExhaustionIsTerminal (rebuild MaxRetries=0
  termination)
- (existing) TestSessionFailed_NonRecycled_RetriesUntilBudget
  updated for round-47 escalation semantic

core/engine/g5_decision_001_serializability_test.go (2):
- TestG5Decision001_ReplicaState_RoundTripJSON
- TestG5Decision001_ReplicaState_ZeroValueStable

core/replication/component/t4d4_engine_driven_test.go (5):
- TestT4d4_WithEngineDrivenRecovery_IsReal (HARD GATE #1)
- TestT4d4_AdapterWithoutWithEngineDrivenRecovery_IsNil (fence)
- TestT4d4_DriveAssignment_EngineEmitsProbeReplica
- TestT4d4_RoundTrip_AssignmentToProbeToCatchUp_EngineDriven
- TestT4d4_CatchupBudgetExhausted_EngineEmitsRebuild

Existing test updated for round-47:
- core/adapter/adapter_test.go
  TestPreparedNeverStarted_FailsClosedOnImmediateStartError:
  set rebuildErr matching catchUpErr; assert chain ends at
  Degraded after retry+escalate+rebuild-terminal (was: assert
  PhaseFailed after first attempt — round-47 makes that
  intermediate not terminal).

NOT in part B (deferred to part C):
- HARD GATE #3: Full L2 matrix incl QA #8 LastSentMonotonic full form
  — needs substrate fault injection wrapping engine-driven flow
- Windows TempDir cleanup race + sessionID coordination + test rename

Forward-carry status:
- Round-47 engine change preserves all prior round-43/44/46
  invariants (lane purity, stale-skip, no per-LBA regression)
- T4d-1 typed-kind contract: forward-carries
- T4d-2 lane-pure apply gate: forward-carries
- T4d-3 R+1 threading: forward-carries
- T4d-4 part A (RecoveryMode + Stop lifecycle): forward-carries
- 22 packages green; 0 failures

Refs: T4d mini-plan v0.5 §2.4 (architect-ratified expanded scope);
round-47 architect ruling (catchup-exhaustion escalates to rebuild +
G5-DECISION-001); G-1 sign 80036404c (G-1 v0.2).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 23:05:00 -07:00
pingqiuandClaude Opus 4.7 e8aec8b954 T4d-4 part A: RecoveryMode interface method + Stop lifecycle (BUG-005 non-repeat) + framework wrap fix
Per T4d mini-plan v0.4 §2.4 expanded scope. Part A of three: smaller
substrate cleanups + lifecycle hardening land first; Path B fold
(ReplicationVolume↔adapter wiring + WithEngineDrivenRecovery real)
follows as part B; Windows cleanup + L2 matrix as part C.

T4c §I row 6 closure (RecoveryMode interface method):
- core/storage/logical_storage.go — add RecoveryMode() to
  LogicalStorage interface (returns substrate's tier-1 sub-mode
  per memo §5.1 / §13.0a)
- core/storage/store.go BlockStore.RecoveryMode() →
  RecoveryModeStateConvergence (in-memory; ScanLBAs synthesizes)
- core/storage/walstore.go WALStore.RecoveryMode() →
  RecoveryModeWALReplay (V2-faithful per-LSN)
- core/storage/smartwal/store.go Store.RecoveryMode() →
  RecoveryModeStateConvergence (per-LBA dedup)
- core/transport/catchup_sender.go — replace duck-typed
  CheckpointLSN probe with e.primaryStore.RecoveryMode() interface
  call. Forwards cleanly through component framework wraps via
  embedded LogicalStorage.
- core/replication/component/faults.go godoc — replace stale
  "MASKED by wrap" limitation note with T4d-4 closure note;
  AssertSawRecoveryMode now works correctly under wraps

T4d-4 lifecycle (BUG-005 non-repeat):
- core/replication/volume.go — Stop() canonical entry point added
  (delegates to existing Close); semantic clarity over Close().
  Both methods are equivalent in T4d-4; Stop() is the named entry
  for "stop volume lifecycle activity" while Close() retained for
  backward compatibility. Future expansions (drain pending I/O,
  stop background goroutines) land in Stop().
- INV-REPL-LIFECYCLE-HANDLE-BORROWED-001 pinned by
  TestReplicationVolume_Stop_DoesNotCloseBorrowedStore: store is
  STILL usable after volume.Stop (substrate handle is borrowed,
  never closed by us — BUG-005 discipline)
- TestReplicationVolume_Stop_Idempotent: second + later Stop calls
  are no-ops returning nil
- TestReplicationVolume_Stop_TearsDownPeers: empty-set lifecycle pin

Tests added (5 new):
- TestReplicationVolume_Stop_Idempotent
- TestReplicationVolume_Stop_DoesNotCloseBorrowedStore
- TestReplicationVolume_Stop_TearsDownPeers
- TestStorageRecoveryMode_BlockStore_StateConvergence
- TestStorageRecoveryMode_Walstore_WALReplay
- TestStorageRecoveryMode_LogicalStorageInterface_HasMethod
  (compile-time fence pinning RecoveryMode is on the interface,
  not just on substrate impls)

NOT in part A (deferred to part B / C):
- ReplicationVolume↔adapter wiring (Path B fold, part B)
- WithEngineDrivenRecovery real binding (Path B fold, part B)
- Full L2 integration matrix (part C)
- Windows TempDir cleanup race (part C)
- Test rename per kickoff §5 (part C)
- sessionID coordination (T4c §I row 5; part C — minor)

22 packages green; 0 failures. Forward-carries: T4c-2 + T4d-1 +
T4d-2 + T4d-3 invariants all green; new RecoveryMode plumbing
preserves T4c-2 INV-REPL-RECOVERY-MODE-OBSERVABLE.

Refs: T4d mini-plan v0.4 §2.4 (architect-ratified expanded scope);
T4c §I row 6 (substrate RecoveryMode method); kickoff §2.1 (BUG-005
non-repeat lifecycle); G-1 sign 80036404c (G-1 v0.2 + planning
artifacts).

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