Commit Graph
25 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
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 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 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
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 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
wzcheng99andClaude Opus 4.7 29e3d0de0c T3b: DurableProvider + Recovery + iSCSI SYNC_CACHE + NVMe Flush + cmd wire
Atomic per T3b mini plan §3 stop rule #1 — all 5 deliverables one commit.

## Scope delivered (mini plan §0)

### 1. DurableProvider (G-int.4)

New core/frontend/durable/provider.go:
  - `ImplName` ("smartwal" | "walstore"); production default smartwal
    per PM direction
  - `ProviderConfig` with StorageRoot + Impl + geometry + OpenTimeout
  - `NewDurableProvider` validates selector; mkdir storage root
  - `Open(ctx, volumeID)` caches handle per volumeID; opens existing
    file (verifying magic vs selector) or creates fresh
  - `RecoverVolume(ctx, volumeID)` runs LogicalStorage.Recover on
    the cached storage, flips backend operational bit per report
  - `Close()` tears down in correct order (backend close → storage
    close); idempotent
  - ImplKind mismatch detection: peeks 4-byte magic BEFORE storage
    Open so the error message names selector vs on-disk kind
    (ErrImplKindMismatch). Never silently coerces (Addendum A #2).
  - testback.StaticProvider unchanged (audit §11 G-int.4).

### 2. Recovery wrapper (G-int.5)

New core/frontend/durable/recovery.go:
  - Pure function `Recover(storage, volumeID) RecoveryReport`
  - Report carries VolumeID, RecoveredLSN, Evidence string, Err
  - Zero side-effects on backend — Provider (or cmd) flips
    SetOperational based on report
  - Option 3 from audit §10.5 honored: no local epoch mirror;
    per-I/O adapter fence check remains sole authority-drift guard
  - §3.2 boundary: no new publication path; readiness surfaces
    via existing /status + adapter's SetOperational

### 3. iSCSI SYNC_CACHE wire

core/frontend/iscsi/scsi.go:
  - SYNCHRONIZE_CACHE(10) [0x35] + SYNCHRONIZE_CACHE(16) [0x91]
    dispatch to backend.Sync(ctx) (formerly no-op Good)
  - Sync errors map to CHECK CONDITION / MEDIUM_ERROR /
    WRITE_ERROR (SPC-5 §D.2.14). Stop rule §3.6 (error-faithful
    Sync wire): swallowing to Good is forbidden.

core/frontend/iscsi/errors.go:
  - Added `ASCWriteError = 0x0C` (SPC-5 ASC table)

### 4. NVMe Flush wire

core/frontend/nvme/io.go + session.go:
  - `ioFlush` opcode (0x00) handler dispatches to backend.Sync via
    IOHandler.Handle
  - Session dispatchIO routes Flush through the handler (was:
    direct Success enqueue)
  - Sync errors map via mapBackendError; ErrStalePrimary → ANA
    Transition, generic → Internal Error

### 5. cmd/blockvolume wire

Added flags:
  - --durable-root PATH      enables DurableProvider; empty = memback
  - --durable-impl NAME      "smartwal" (default) | "walstore"
  - --durable-blocks N       first-create geometry
  - --durable-blocksize N    first-create block size

Startup sequence (when --durable-root is set):
  1. Build DurableProvider
  2. Open the served volumeID (creates storage if absent)
  3. RecoverVolume → flips adapter operational bit per outcome
  4. Use the provider for both iSCSI and NVMe target wiring
  5. On shutdown, Close the provider (backend + storage) in order

memback path unchanged when --durable-root is empty.

### 6. Adapter lifecycle design note

Backend.Close() does NOT tear down underlying LogicalStorage
(already was the T3a contract). Provider.Close() is the only
teardown path for storage; both are idempotent.

## Acceptance (mini plan §2)

  #1 `TestT3b_DurableProvider_ImplementsProvider`              ✅ both impls
  #2 `TestT3b_DurableProvider_Open_SelectsImpl_Matrix`         ✅ (file magic verified on disk)
  #3 `TestT3b_DurableProvider_Open_StartsNotOperational`       ✅ Read/Write/Sync → ErrNotReady
  #4 `TestT3b_DurableProvider_Open_ImplKindMismatch_FailsFast` ✅ ErrImplKindMismatch named
  #5 `TestT3b_Recovery_CleanRecover_FlipsOperational`          ✅ + `*UnopenedVolume*` + pure-fn tests
  #6 `TestT3b_ISCSI_SyncCache_DispatchesToBackend`             ✅ SYNC_CACHE(10) + (16)
  #7 `TestT3b_NVMe_Flush_DispatchesToBackend`                  ✅ ioFlush → backend.Sync
  #8 `TestT3b_DurableProvider_Lifecycle_*`                     ✅ close isolation + double-close idempotent
  #9 Full regression                                            ✅ 17/17 core packages ok
 #10 Boundary guard                                             ✅ core/frontend/durable/ auto-covered

## Regression

  go test ./core/... -count=1 → 17/17 packages ok
  - core/frontend/durable: 0.5s (16 T3a + 13 T3b subtests all green)
  - core/frontend/iscsi: 31.5s
  - core/frontend/nvme: 61.3s
  - core/host: 122.8s (no regression)
  - all others sub-second or unchanged

## Stop rules honored

  #1 atomic (5 deliverables one commit) ✅
  #2 no OnDegraded reinstated ✅
  #3 no local epoch mirror ✅
  #4 no new publication path ✅
  #5 Provider.Impl is config-driven string; no compile branch ✅
  #6 iSCSI + NVMe Sync errors map faithfully ✅
  #7 no scenarios / no perf landed in T3b ✅

## Ledger rows queued ACTIVE at T3b close

  - INV-DURABLE-PROVIDER-SELECT-001
  - INV-DURABLE-RECOVERY-READSIDE-001
  - INV-DURABLE-SYNC-WIRED-001

Existing (T3a / T1) rows stay ACTIVE:
  - INV-DURABLE-OPGATE-001, INV-DURABLE-IMPL-IDENTITY-001
  - INV-FRONTEND-002.{EPOCH,EV,REPLICA,HEALTHY}

## Out of T3b (per mini plan)

  - 4 G6 scenarios → T3c
  - m01 iSCSI + NVMe fs-workload smoke → T3c
  - Perf baseline → T3c
  - T3 closure report + T3-end three-sign → T3c

## References

  sw-block/design/v3-phase-15-t3a-mini-plan.md (CLOSED 10cd117)
  sw-block/design/v3-phase-15-t3b-mini-plan.md (this batch)
  feedback_porting_discipline.md (port-model discipline)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 17:55:50 -07:00
wzcheng99 e00d725cb5 T2 ckpt 8 follow-up: enforce --nvme-ns + --nvme-subsysnqn on the wire
Two architect-review findings (round-7) closed:

Finding 1: --nvme-ns was a dead flag.
  cmd/blockvolume accepted --nvme-ns N but built TargetConfig with
  zero-value Handler, so the IOHandler always defaulted to NSID=1.
  An operator running --nvme-ns 7 got a target that still rejected
  every command targeting NSID=7.

  Fix (cmd/blockvolume/main.go):
    Handler: nvme.HandlerConfig{NSID: uint32(f.nvmeNS)}
    threaded through TargetConfig so the configured value reaches
    the per-session handler.

Finding 2: --nvme-subsysnqn was advertised but not enforced.
  Target.SubsysNQN was metadata-only; the wire-level Fabric Connect
  accepted any host's SubNQN. A host could connect with an
  arbitrary subsystem name and still get IO service — multi-target
  routing and operator intent ambiguous.

  Fix (core/frontend/nvme/session.go + target.go + errors.go):
    - Session.expectedSubNQN field, plumbed via newSession().
    - Target.handleConn passes t.cfg.SubsysNQN into newSession.
    - handleFabric rejects mismatched SubNQN with
      SCT=Command Specific (1) + SC=ConnectInvalidParameters (0x80)
      per NVMe-oF spec §3.3.1. New SC constants in errors.go:
      SCConnectInvalidParameters / SCConnectControllerBusy /
      SCConnectInvalidHost.
    - Empty Session.expectedSubNQN preserves "no enforcement"
      contract for in-process L1 tests that don't pin a subsystem
      identity. cmd/blockvolume always sets SubsysNQN (already
      required at startup), so production is always enforced.

core/frontend/nvme/identity_enforcement_test.go (NEW, sw regression)
  4 tests pin both fixes:
    - TestT2NVMe_HandlerHonorsConfiguredNSID:
        handler-level — IOHandler with NSID=7 rejects NSID=1
        commands with Generic/InvalidField, backend not invoked.
    - TestT2Process_NVMe_TargetHandlerNSIDConfigPropagates:
        wire-level — Target with HandlerConfig.NSID=7 rejects
        client Write at NSID=1; status decode confirms wire bits
        SCT=0 SC=0x02. Backend not invoked.
    - TestT2Process_NVMe_ConnectWithWrongSubNQN_Rejected:
        low-level capsule write with wrong SubNQN; assert
        wire status SCT=1 SC=0x80 (ConnectInvalidParameters).
    - TestT2NVMe_EmptySubsysNQN_AcceptsAnyConnect:
        regression for the in-process L1 path — empty target
        SubsysNQN admits any Connect (preserves L1 test setup).

Tests green (no regressions):
  core/frontend/nvme: 26 tests (was 22; +4 enforcement regressions)
  All other packages: unchanged.

Sign-off impact: T2B-NVMe-provisional unchanged (still QA + sw lead);
follow-up tightens identity wiring per architect feedback before
T2-closed L2-OS work begins.
2026-04-21 21:28:26 -07:00
wzcheng99 ee12558f58 T2 checkpoint 8: cmd/blockvolume --nvme-* wiring + NVMe L2-harness green
cmd/blockvolume/main.go
  New flags symmetric with iSCSI:
    --nvme-listen <addr>      (loopback-only bind enforced;
                               empty disables)
    --nvme-subsysnqn <nqn>    (required when --nvme-listen set)
    --nvme-ns <id>            (default 1)
  When --nvme-listen is set:
    - implicitly auto-enables --t1-readiness with same stderr
      notice ("blockvolume: nvme enabled: t1-readiness auto-enabled")
      → kept symmetric with iSCSI per QA checkpoint-7 note;
      closure report doesn't have to explain asymmetry.
    - constructs memback.NewProvider wrapping the volume's
      AdapterProjectionView (same readiness bridge as iSCSI;
      sketch §10 "Readiness bridge shared, not duplicated").
    - emits nvme-listening JSON ready line with nvme_addr + subsys_nqn.

  Refactored enforceIscsiLoopbackBind → enforceFrontendLoopbackBind
  (parameterized on kind="iscsi"|"nvme") so both protocols use
  one guard. Identical loopback-only safety policy.

core/frontend/nvme/t2_l2_nvme_harness_test.go (QA-owned, test-spec §6)
  // T2 L2 EVIDENCE CLASS: L2-harness

  T2.L2.n1 TestT2Process_NVMe_AttachWriteRead (13.6s):
    real blockmaster + blockvolume subprocesses with
    --nvme-listen on a reserved loopback port; Go NVMe/TCP
    initiator does ICReq → fabric Connect → Write 512B at LBA
    0 → Read at same location, bytes match over real wire
    (capsule + R2T + H2CData + C2HData round trip).

  T2.L2.n4 TestT2Process_NVMe_ReopenAfterMove_ServesNewLineage (17.2s):
    same harness; pre-move Connect+Write+disconnect, then primary
    volume restarts with new data/ctrl addrs (same status+nvme
    addrs). Master mints IntentRefreshEndpoint → EV advances.
    Fresh Connect to the same NVMe addr gets a backend at the
    new lineage and Write+Read round-trip succeed. Explicit
    NON-CLAIM: pre-move bytes not expected to persist.

  NOT included per checkpoint-5 scope (C5.3 applied to NVMe):
  T2.L2.n2 / n3 (stale Write / Read after move). L2-OS REQUIRED
  critical cells; harness can't substitute for kernel ANA
  Transition handling. Tracked for L2-OS on m01.

Tests green (no regressions):
  core/frontend/nvme:    22 tests (errors 7 + boundary 1 + io 9 +
                         L1 route 3 + L2-harness 2)
  core/frontend/iscsi:   31 unchanged
  All other packages:    unchanged.

Sign-off tier: T2B-NVMe-provisional
  Acceptance:
    - L0 6/6 green (n1-n6)
    - L1 3/3 green (n1-n3 component route)
    - L2-harness 2/2 green (n1 + n4)
    - cmd/blockvolume --nvme-* product-host wiring landed
    - loopback default + NQN required match T2 safe defaults
    - i2 stale Write / i3 stale Read deferred to L2-OS
  Sign-off: QA Owner + sw lead (§8B.9 provisional tier)
  Downstream unlock: none; T2A-iSCSI-product-ready and
                     T2B-NVMe-product-ready remain L2-OS work
                     (m01 enablement).
2026-04-21 21:12:35 -07:00
wzcheng99 28e9636edb T2 checkpoint 6: NVMe/TCP minimal slice — L0 green + boundary guard
Checkpoint 6 mirrors iSCSI checkpoints 1+2 for the NVMe/TCP
protocol. L1/L2 for NVMe come in later checkpoints.

cmd/blockvolume/main.go
  Small follow-up on T2A-iSCSI-provisional sign-off note:
  emit a stderr line "iscsi enabled: t1-readiness auto-enabled"
  when --iscsi-listen implicitly flips the readiness bridge on.
  Keeps operators from misreading the auto-enable as silent.

core/frontend/nvme/errors.go (NEW)
  NVMe status vocabulary for T2:
    SCT types (Generic, CommandSpecific, MediaDataInteg, PathRelated,
               VendorSpecific)
    Generic SCs: Success, InvalidOpcode, InvalidField, InternalError,
                 LBAOutOfRange, CapacityExceeded, NamespaceNotReady.
    PathRelated SCs: ANA PersistLoss / Inaccessible / Transition.

  StatusError type carrying (SCT, SC, Reason) with Error() and
  EncodeStatusField() that packs SCT/SC into the 16-bit CQE
  status field (SC<<1 | SCT<<9 per NVMe base spec §4.6.1).

  Canonical constructors:
    NewStaleLineage()   -> SCT=3 (PathRelated) + SC=0x03 (ANA Transition)
                           — semantic match for authority-move
                           transition; Linux nvme driver treats this
                           as a path-retry condition.
    NewBackendClosed()  -> SCT=3 + SC=0x02 (ANA Inaccessible)
                           — distinct from stale-lineage so logs
                           disambiguate the two fail modes.
    NewInvalidField(sc, reason) -> SCT=0 + caller SC.

  Symmetric with iscsi/errors.go's ALUA 0x04/0x0A vs 0x04/0x00
  distinction (see earlier checkpoint 2 note).

core/frontend/nvme/io.go (NEW)
  IOHandler dispatches NVMe IO Read/Write/Flush to a
  frontend.Backend. Opcode set intentionally minimal for L0 scope;
  Identify / SetFeatures / fabric admin land with capsule framing
  in a later checkpoint.

  IOCommand is the normalized form (Opcode, NSID, SLBA, NLB, Data).
  IOResult.AsError() returns nil on Success or a *StatusError.

  mapBackendError: ErrStalePrimary -> ANA Transition;
                   ErrBackendClosed -> ANA Inaccessible;
                   other -> Internal Error (fail-closed).

  LBA-range + NSID + short-data validation BEFORE backend call
  (fail closed). NLB=0 is invalid in our one-based form (zero-based
  on wire, one-based in IOCommand for readability).

core/frontend/nvme/io_test.go (QA-owned, test-spec §4 n1..n4)
  T2.L0.n1 CommandReadWrite_UsesFrontendBackend: Read + Write
    route through RecordingBackend, single invocation, exact
    offset + data.
  T2.L0.n2 StaleWrite_ReturnsProtocolFailure: non-Success,
    SCT=3 SC=3 (ANA Transition).
  T2.L0.n3 StaleRead_ReturnsProtocolFailure: non-Success,
    zero data bytes (MUST NOT leak stale bytes), ANA Transition.
  T2.L0.n4 InvalidInput_FailsClosed: table-driven — LBA past
    end, LBA overflow, short data, NLB=0, unknown NSID. Each
    fails at handler, backend never invoked.

  Plus sw-added regressions:
    BackendClosed_DistinctFromStale pins the ANA Transition vs
    ANA Inaccessible distinction.
    UnknownOpcode_ReturnsInvalidOpcode (fail-closed on 0x7f).
    Flush_SuccessInT2Scope (no-op).
    IOResult.AsError_NilOnSuccess + SupportsErrorsAs.

core/frontend/nvme/boundary_guard_test.go (QA-owned, test-spec n5+n6)
  T2.L0.n5 + n6 AST guard: full-parse + alias-resolution (same
  shape as iSCSI's boundary guard). Extends PCDD-STUFFING-001
  coverage to core/frontend/nvme. No core/authority, no
  core/adapter, no authority-minting composite literal, no
  dot-import bypass.

Tests green (no regressions):
  core/frontend/nvme:   17 tests (errors 7 + boundary 1 + io 9)
  core/frontend/iscsi:  unchanged (31)
  All other packages:   unchanged.

Sign-off tier: T2B-NVMe checkpoint 6 (L0 foundation). L1 + L2
arrive in checkpoints 7-8; T2B-NVMe-provisional pending L2-harness
(checkpoint 8).
2026-04-21 19:54:10 -07:00
wzcheng99 15e049d79a T2 checkpoint 5: cmd/blockvolume --iscsi-* wiring + L2-harness green
cmd/blockvolume/main.go
  New flags per assignment §3.2:
    --iscsi-listen <addr>   (empty disables; loopback-only bind
                             enforced at startup per C5.4
                             "Defaults must be safe")
    --iscsi-iqn <iqn>       (required when --iscsi-listen set)
    --iscsi-lun <id>        (default 0)
  When --iscsi-listen is set:
    - implicitly auto-enables --t1-readiness (iSCSI needs a
      Healthy adapter projection to open a memback backend)
    - enforces loopback bind (mirrors StatusServer's guard;
      non-loopback or empty-host addrs rejected with clear
      error). T2 iSCSI is unauthenticated — real-NIC binds
      land with T8 security.
    - constructs memback.NewProvider wrapping the volume host's
      AdapterProjectionView, then iscsi.NewTarget on that
      provider. Per-op lineage fence + supersede fence still
      apply at SCSI command granularity.
    - emits iscsi-listening JSON ready line with iscsi_addr
      and iqn (same pattern as status-listening).

core/frontend/iscsi/t2_l2_iscsi_harness_test.go (QA-owned, test-spec §6)
  // T2 L2 EVIDENCE CLASS: L2-harness

  T2.L2.i1 TestT2Process_ISCSI_AttachWriteRead (13.5s):
    real blockmaster + blockvolume subprocesses with
    --iscsi-listen on a reserved loopback port; Go initiator
    logs in, WRITE(10) 512 bytes at LBA 0, READ(10) at same
    location returns identical bytes over real TCP+PDU framing.

  T2.L2.i4 TestT2Process_ISCSI_ReopenAfterMove_ServesNewLineage (17.2s):
    same harness; pre-move session writes then logs out; primary
    volume restarts with new data/ctrl addrs (same status+iscsi
    addrs). Master mints IntentRefreshEndpoint → EndpointVersion
    advances. Fresh login on the same iSCSI addr serves the new
    lineage (post-move WRITE + READ round-trip succeed under
    the new Identity). Explicit NON-CLAIM: pre-move bytes not
    expected to persist (memback is Identity-scoped; G8
    territory).

  NOT included per checkpoint-5 scope (C5.3): stale WRITE / READ
  after move. Those are L2-OS REQUIRED critical cells; running
  them at L2-harness would be a spec violation (§G3 initiator-
  evidence rule + test-spec §6 L2-OS requirement). Tracked for
  L2-OS on m01.

Tests green (no regressions):
  core/frontend/iscsi:     31 tests (prior 29 + L2.i1 + L2.i4 L2-harness)
  core/frontend, memback, testback, host/volume: unchanged.

Sign-off tier: T2A-iSCSI-provisional
  (QA Owner + sw lead; per §8B.9).
  L2-OS → product-ready → architect+PM sign is a later checkpoint.

NVMe/TCP slice (checkpoint 6) may now proceed in parallel.
2026-04-21 17:42:03 -07:00
wzcheng99 f5c557074d T1 product closure: readiness bridge + supersede fence + L2 authority move
Addresses three architect review rounds on T1 frontend contract:

Round 1 (L0/L1 only) → Round 2 (real adapter path + product loop):
  - AdapterProjectionView reads engine.ReplicaProjection.Mode
    (engine.ModeHealthy is the real readiness source, not
    manufactured AssignmentInfo receipt)
  - HealthyPathExecutor drives engine through Probe + Fence +
    PublishHealthy so Mode actually reaches ModeHealthy
  - cmd/blockvolume: --t1-readiness + --status-addr flags;
    volume.StatusServer exposes frontend.Projection over HTTP
  - memback negative offset: returns ErrInvalidOffset, no panic
  - Boundary guard: full AST parse + alias resolution

Round 3 (cross-replica supersede + real authority move in L2):
  - SupersedeProbe seam on AdapterProjectionView; Host.IsSuperseded
    compares lastOther (replicaId, epoch, ev) vs self-lineage →
    Healthy=false when another replica holds newer authority
  - L2 now drives a product-route authority move: r1 restarts
    with new data/ctrl addrs → master mints IntentRefreshEndpoint
    → EndpointVersion advances → old backend ErrStalePrimary →
    fresh Open captures new lineage
  - StatusServer restricted to loopback (bind + client check)

Round 4 (proof coverage + robustness):
  - Real Host.recordOtherLine → IsSuperseded → View integration
    test (no more stubProbe-only coverage for supersede claim)
  - L2 closure claim sharpened: PROVES IntentRefreshEndpoint
    stale reject; DOES NOT PROVE cross-replica primary change
    (deferred to T6/G8)
  - Reserve loopback port via :0 instead of hardcoded 7165
  - Boundary guard: forbid dot-import of core/adapter and
    core/authority (bare-literal bypass closed)

Tests (all green):
  core/frontend L0: 7 + negative-offset regression + 3 meta
  core/frontend L1: 1 (real adapter + AdapterProjectionView)
  core/frontend L2: 1 (product route + authority move + stale
    reject + new open, 17-21s)
  core/host/volume: 4 AdapterProjectionView + 3 supersede
    integration + 5 StatusServer loopback

Closure: INV-FRONTEND-001 / INV-FRONTEND-002 Unit+Component+
Integration; PCDD-STUFFING-001 Unit with dot-import guard.
Cross-replica primary-change facet explicitly remains
Unit/Component only (routed to G8/T6 for L2 promotion).
2026-04-21 15:53:14 -07:00
wzcheng99 55793d49bc T0 closure: blockmaster/blockvolume hosting + D1-D5 tests
Product binaries (cmd/blockmaster, cmd/blockvolume) and
core/host wiring for volume-scoped assignment delivery,
durable authority with Windows rename retry, and the T0
closure test set (D1 L2 subprocess, D2 G1 adversarial,
D3 concurrent write-reload regression, D4 hosting-smoke
scenario + Go-native replay, D5 --topology flag).

Diagnostic surfaces: ObservationStore.SupersededCount
(PCDD-DELAYED-HB-001 evidence, not authority input) and
SetNowForTest clock seam on Store/Host, guarded by grep
test ensuring the identifier stays out of production files.
2026-04-21 02:02:52 -07:00
wzcheng99andClaude Opus 4.7 c699d358b0 P14 cleanup: CodeRabbit nits on the S5-S8 PR
Three review follow-ups from PR #10 CodeRabbit feedback. All
style/robustness; no correctness changes.

1. core/authority/authority.go — drop dead-scaffolding locals
   (prevForRollback / hadPrev) around the durable-write path.
   State mutation is deliberately sequenced after store.Put, so
   there is nothing to roll back on Put failure. Replace the
   phantom locals with a comment stating the invariant.

2. cmd/sparrow/s7_restart_smoke_test.go — use exec.CommandContext
   with a 60s test-level deadline for both the go build and the
   two subprocess runs, so a hung child dies when go test times
   out instead of lingering.

3. cmd/sparrow/s7_bootstrap_test.go — replace
   `dir + string(os.PathSeparator) + ...` with filepath.Join for
   cross-platform correctness.

Not addressed (explicitly CodeRabbit-flagged "recommended not
essential"): double-reload at boot (bootstrap.go). Would require a
new Publisher WithPreloaded option; skipped to keep this commit
tight and not reopen S5 surfaces.

go test ./core/authority ./cmd/sparrow -count=1 green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 02:22:08 -07:00
wzcheng99andClaude Opus 4.7 0562aeb878 P14 S7: real-route restart closure (L1 component + L2 subprocess smoke)
Proves the S4-S6 control loop composes under restart and real-route
pressure: durable authority reload -> observation replay -> controller
recompute -> VolumeBridge delivery -> VolumeReplicaAdapter.

Restart sequence pinned (sketch §5, adapter-BEFORE-bridge per round-3):
lock -> store -> pub(reload) -> ctrl(reloaded reader) -> host(same
reader) -> adapter -> VolumeBridge -> pub.Run + host.Start.

Desired state is recomputed, not persisted (sketch §6). No DesiredStore,
no StuckStore, no bootstrap-mint shortcut. Stale pre-restart observation
rejected via existing basisMatchesLine, not a new bootstrap predicate.

L1 (core/authority/restart_route_test.go, 8 tests + 4 stale sub-cases):
row 1 reloaded authority via bridge to adapter; row 2 recompute (hard
precondition + same-observation replay); row 3 stale observation (4
sub-cases via snapshottingReader host-reader freeze — test simulation
shape per sketch §9, not a heartbeat-wire claim); row 4a old slot NOT
revived from durable (S5 one-record-per-volume contract); row 4b
live-route monotonic guard rejects bridge-delivered old slot from
in-memory publisher; row 5 unsupported evidence via ConflictingPrimaryClaim;
row 6 fence path bounded (Fence command reaches executor via real route;
withheld callback does not produce spurious Healthy); row 7 per-volume
isolation on restart.

L2 component (cmd/sparrow/s7_bootstrap_test.go): rows 8/9/10a via
in-process Bootstrap two-run, asserting directly on ReloadedRecords,
ReloadSkips, VolumeAuthorityLine. No backward mint across restart.

L2 subprocess (cmd/sparrow/s7_restart_smoke_test.go): row 10b via real
sparrow binary spawn twice against the same store dir. Asserts exit 0
on both runs, lock released between runs, second-run structured stdout
reports the durable line the first run wrote, backwardMint=false.

cmd/sparrow additions:
- --s7-restart-smoke flag (test-only, undocumented in --help)
- runS7RestartSmoke entry with pinned JSON pass-line schema
- parseFlags rules: requires --authority-store, mutually exclusive with
  --s5-bootstrap

Helpers: restartRoute / simulateRestart (single pinned construction
seam; no direct adapter.OnAssignment anywhere; uses VolumeBridge, not
hand-rolled Bridge goroutines); restartExecutor (fence-mode configurable
pre-loop); snapshottingReader.forceSet for stale-basis simulation.

Engine/adapter/transport: no changes. Row 4 honesty split (round-5c):
durable restart discards old-slot state by S5 design, so "old-slot
rejected on restart" is proved by ABSENCE; the monotonic-guard proof
belongs to a pre-restart live-route test where in-memory per-replica
keys legitimately exist. Row 6 explicitly defers the full timeout-
expiry quantitative bound to the adapter's own tests (sketch §10.1
Path B forbids S7 from reconfiguring the fence path).

Residual: Windows TempDir teardown can race with lock-file release;
logged as residual per sketch §8.5 scope — durable-store write/reload
errors remain hard failures.

go test ./core/authority ./cmd/sparrow ./core/adapter -count=1 green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 23:10:24 -07:00
wzcheng99andClaude Opus 4.7 47eb1f6f8d P14 S5: durable authority institution + live sparrow bootstrap
Introduces the P14 S5 durable-authority layer: Publisher state
survives control-plane restart via an atomic-rename file-per-
volume store, guarded by a cross-platform OS-level single-owner
lock, with startup wiring in cmd/sparrow that acquires the lock
and reloads durable truth before live publication begins.

Load-bearing boundaries held (sketch §3):
  * durable authority store may preserve and reload truth, but
    it may NEVER mint truth. Publisher is the sole minter of
    Epoch / EndpointVersion; the store persists values already
    minted and reloads them verbatim at boot.
  * AST boundary guards (from S5 sketch §12) enforced at test
    scope: no non-authority code constructs a DurableRecord with
    non-zero Epoch/EndpointVersion, no non-authority code calls
    store.Put.

Core store and interface (core/authority/):

  * authority_store.go — DurableRecord shape (per-volume current
    line; no per-slot history, no append log, no wall-clock
    freshness field); AuthorityStore interface with Load /
    LoadWithSkips / Put / Close; SHA-256-checksummed JSON
    envelope; per-record ErrCorruptRecord; index-level failure
    distinguished from per-record skip.
  * authority_store_file.go — file-per-volume FileAuthorityStore
    with fsync + atomic rename on write; stale-tempfile cleanup
    on Load; INJECTIVE filename encoding (every non-[a-zA-Z0-9-]
    byte including '_' escapes as "_XX" — closes the earlier
    "_002f" vs "/" aliasing gap).
  * authority_bootstrap.go — AcquireStoreLock returning a
    StoreLock whose OS-level file lock is dropped on handle
    close, cross-platform crash-safe.
  * authority_bootstrap_unix.go (build !windows) — syscall.Flock
    with LOCK_EX|LOCK_NB.
  * authority_bootstrap_windows.go (build windows) —
    syscall.CreateFile with dwShareMode=0 exclusive share;
    ERROR_SHARING_VIOLATION / ERROR_ACCESS_DENIED map to
    ErrStoreLockHeld. Purely stdlib; no x/sys dependency.

Publisher integration (core/authority/authority.go):

  * WithStore(store) functional option on NewPublisher. Nil /
    omitted keeps existing in-memory behavior.
  * Synchronous reload at construction: verifies records,
    populates p.state, seeds p.writeSeqByVolume from max stored
    WriteSeq. Per-record corrupt skips surface via LoadErrors()
    (per-volume fail-closed; process continues).
  * Synchronous write-through in apply(): DurableRecord built
    under pub.mu, store.Put invoked before in-memory commit. On
    Put failure the in-memory state is NOT mutated, subscribers
    are NOT notified, and the caller gets a wrapped error — on-
    disk and in-memory stay lock-step.
  * Index-level load failure panics at construction (honors the
    sketch §10 fail-the-whole-boot rule); the Bootstrap helper
    converts this to a clean error return via a pre-check.

Live sparrow entry point (cmd/sparrow/):

  * bootstrap.go — Bootstrap(storeDir, directive) helper that
    performs the full startup sequence (lock → store → index
    pre-check → NewPublisher with reload → log outcomes). Also
    exposes BootstrapFromStore seam so tests can inject a mock
    store to exercise the pre-check cleanup branch portably.
  * s5_bootstrap.go — runS5Bootstrap mode invoked via
    "sparrow --authority-store <dir> --s5-bootstrap". Acquires
    lock, reloads, runs Publisher briefly, emits report, exits
    cleanly. This is the one real non-test caller of the
    durable route. The default demo path stays in-memory by
    design (the Bind/Reassign smoke sequence is not restart-
    clean, and forcing it to be would smuggle durability-aware
    branches into SMOKE test code).
  * main.go — --authority-store and --s5-bootstrap flags
    rejected at parseFlags unless paired; --s5-bootstrap
    dispatches to runS5Bootstrap. Default modes unchanged.

Proof (core/authority/ + cmd/sparrow/):

  * authority_store_test.go — round-trip, latest-wins per-volume,
    corrupt-record per-volume fail-closed, atomic-write-no-torn
    (orphan tempfile cleanup), process lock exclusivity +
    idempotent release + survives stale lockfile on disk,
    unreadable-index boot fails closed, wall-clock-NOT-consulted
    on reload, AST boundary guards (store never mints, only
    core/authority calls store.Put), filename encoding
    injectivity + no-filesystem-unsafe-output, envelope shape.
  * authority_restart_test.go — reload reproduces current line,
    stale pre-failover record rejected, Publisher advances from
    reloaded truth (not zero), Controller sees reloaded line at
    boot, Put-failure rolls in-memory back, empty-store reload
    yields fresh state, store-backed Publisher runs normal
    Bridge route.
  * cmd/sparrow/bootstrap_test.go — live Bootstrap tests: fresh
    dir acquires lock + reloads, existing-record reloads into
    Publisher state, corrupt record logged at startup (not
    stranded in LoadErrors), lock contention refuses second
    bootstrap, empty dir errors, Close idempotent,
    ParseFlags_AuthorityStoreRequiresS5Bootstrap flag validation,
    RepeatedRunsAreRestartClean (two runS5Bootstrap invocations
    on same dir with seeded record between — architect round-7
    regression), PreCheckFailure_ReleasesLockAndClosesStore
    (mock-injected index failure → lock released, store closed,
    error returned — architect round-8/9 regression).
  * observation_test.go — E2E SystemFedSnapshotReachesController
    poll-loop fixed: was racing on first non-empty submission
    (initial pending) instead of waiting for supported; now
    polls until supported-v1 with 3 slots is observed.

No changes to engine, adapter, transport, ops, storage.
Authority package: 112 tests. cmd/sparrow: 19 tests. Full module:
12 packages pass.

Design docs in sw-block/design/ external repo:
  * v3-phase-14-s5-assignment.md
  * v3-phase-14-s5-durable-authority-institution.md
  * v3-phase-14-s5-sketch.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 18:48:25 -07:00
wzcheng99andClaude Opus 4.7 3d53563ca9 P14 S2 fix: per-subscription cancel, lossless-latest delivery, AST non-forgeability
Addresses three architect findings on the first S2 drop:

1. High: Unsubscribe(vid, rid) was key-wide — one Bridge exiting
   silently closed channels for all other peers on the same
   (VolumeID, ReplicaID). Replaced with per-subscription cancel:
   Subscribe now returns (ch, cancel func). Each cancel closes only
   its own subscription. Publisher owns a nextSubID counter and
   tracks subscriptions as []*subscription per key. Cancel is
   idempotent and safe against concurrent Run-exit teardown via a
   "whoever finds it closes it" protocol.

   Regression test: TestPublisher_IndependentUnsubscribe_OtherPeersUnaffected.

2. High: silent drop on full subscriber buffer could leave the
   adapter on stale authority truth until an unrelated later ask
   happened — unacceptable for an authority route. Per-subscription
   channels are capacity 1 with overwrite-latest semantics: on full,
   the publisher drains the stale pending value and retries send,
   so the subscriber always reads the LATEST authoritative state
   next. Intermediate states may be coalesced (correct for authority
   truth; the engine cares about current identity, not interstitial
   history).

   Regression test: TestPublisher_DeliveryConvergesToLatestOnSlowConsumer.

3. Medium: the non-forgeability structural test was a regex-based
   grep over core/ only, and caught only composite-literal Epoch
   assignments. Rewritten as an AST-based walker that (a) covers
   the whole repo (cmd/ and future production packages included,
   not just core/) and (b) catches both composite-literal mints
   with non-zero Epoch/EndpointVersion AND local variable
   declarations of type AssignmentInfo — the classic bypass shape
   for deferred mutation: `var x AssignmentInfo; x.Epoch = input`.

   The stronger check surfaced three pre-existing hidden operator
   paths in cmd/sparrow/main.go that minted AssignmentInfo with
   hard-coded epochs 1/2/3 directly. All three demo sites are now
   routed through a shared authority.Publisher: healthy demo issues
   IntentBind, catch_up and rebuild demos issue IntentReassign.
   No sparrow demo code constructs AssignmentInfo directly anymore.

Other:
  * Run now closes every live subscription channel on exit, so
    Bridges observe end-of-stream cleanly. Tested by
    TestPublisher_RunClosesLiveSubscriptionsOnExit.
  * Publisher.apply() releases the publisher lock before fan-out,
    preventing a slow consumer from stalling the authoring loop.

Docs updated:
  * docs/p14-s2-design.md — Publication API now documents
    per-subscription cancel, removes the stale Unsubscribe(vid,rid)
    verb, adds the "lossless for current fact" delivery semantic.
  * docs/p14-s2-closure.md — test list updated (20 tests), Changed
    section records the sparrow migration.

No changes to engine, adapter, transport, ops, storage.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 21:20:09 -07:00
Ping Qiu 2f07922234 P8-P12: local data process, lineage protocol, data-sync, recovery-execution, single-node surface, replicated durable slice
* storage: local data process — admission, flusher, and experimental extent-direct backend

Names the local data process (read / write / flush / checkpoint /
recover on one node) as a bounded institution with an explicit
crash model and carry-forward boundaries. Adds WAL admission
backpressure, a background flusher that drains WAL entries into
the extent, and an experimental metadata-only backend alongside
the regular WAL+extent backend. Both backends implement the same
LogicalStorage interface and pass the shared contract test suite.

Admission controller ports the battle-tested watermark algorithm
from the in-production engine: 0.7 soft / 0.9 hard, counting
semaphore for concurrent writers, deadline governing the whole
Acquire call, flusher wakeup via a dedicated urgent-notify seam.
Defaults intentionally absent at the admission layer — callers
set them explicitly, same contract as the source.

Flusher processes the entire dirty-map snapshot per cycle; the
on-disk checkpoint is bumped to the highest LSN verified-and-
flushed. Compare-and-delete cleanup preserves concurrent writes
that bumped an LBA's LSN after the snapshot was taken.

The experimental backend (core/storage/smartwal) writes data to
the extent first and appends only a small metadata record to a
ring. Reads bypass the ring entirely. A group committer batches
concurrent fsyncs.

Adopting the extent-direct backend as the default would be a
separate decision; this change only makes it available behind the
same interface.

Docs: docs/local-data-process.md names the institution, its crash
windows per backend, and the explicit carry-forward list.

* protocol: close recovery around explicit lineage at every layer

Every recovery start now carries (epoch, endpointVersion, sessionID,
targetLSN) — a single tuple that travels from engine decision through
adapter command, transport wire, replica ingress, and back via ack.
Each layer rejects messages whose lineage doesn't match the contract
it currently believes is active, so stale work cannot leak between
layers.

Engine: probe / catch-up / rebuild commands carry epoch +
endpointVersion. ProbeFailed and RecoveryFactsObserved are now
treated as lineage-bearing observations and dropped if stale.
Same-observation reorder fix is preserved and extended so reversed
probe/facts arrival still converges. Zero-valued epoch /
endpointVersion are rejected at event ingestion with a clear trace
key, not silently at the wire.

Adapter: each Start* command mints a fresh process-wide sessionID
and feeds it synchronously through the executor and engine, so
every outbound mutation can carry it.

Transport: invalidated sessions are canceled — the active session
holds its conn, and InvalidateSession closes the conn directly so a
goroutine parked in ReadMsg unblocks immediately. Recovery conns
have explicit deadlines on every write/read. Mutating wire frames
(ShipEntry, RebuildBlock, RebuildDone, BarrierReq) carry the full
lineage tuple. Replica ingress rejects stale lineage and closes the
connection without partial application.

Rebuild: blocks now apply with the engine's frozen targetLSN
instead of a placeholder, so a future LSN-aware ApplyEntry guard
won't silently drop rebuild data. The primary returns success only
after reading BarrierResp from the replica with the actually
achieved frontier — never on EOF, timeout, or a non-terminal phase
ack.

Tests: adversarial coverage at every layer — stale transport-epoch
events at the engine, stale callback drops at the adapter, mid-
session invalidation interrupting a blocked ack read at the
transport, stale wire-lineage rejection at the replica, and a
calibration handoff/stale-probe scenario.

README adds a roadmap table naming what each upcoming phase closes
and what it does not, so the project's bounded-closure model is
visible to readers.

* transport: institutionalize the data-sync layer

Names the bounded data-sync institution: catch-up byte movement,
rebuild byte movement, barrier exchange, achieved-frontier report,
and the lineage gate that fails closed on stale or overlapping
traffic. The institution does not own recovery classification,
session lifecycle policy, failover decisions, or operator
publication — those belong to later phases.

Splits transport into per-responsibility files so the boundaries
are visible on the page:

  executor.go         — session lifecycle + probe (observation only)
  catchup_sender.go   — primary-side catch-up byte movement
  rebuild_sender.go   — primary-side rebuild byte movement
  barrier.go          — typed BarrierResponse and helpers
  replica.go          — per-message-type handlers, lineage gate

Catch-up and rebuild each keep their own ship loop. The two
protocols look similar today but have different terminators (barrier
vs RebuildDone) and shouldn't share a hidden implementation that
would mask their divergence later.

BarrierResponse replaces the bare 8-byte uint64 wire reply with a
typed struct {AchievedLSN uint64}. The replica reports what Sync()
actually returned; the primary returns that value verbatim. Short
or unexpected payloads now fail closed instead of silently
fabricating a frontier.

Replica handler dispatch extracted into named per-message methods
(handleShipEntry, handleProbeReq, handleRebuildBlock,
handleRebuildDone, handleBarrierReq), each fronted by the same
acceptMutationLineage gate.

Five new fail-closed tests prove the institution's negative space:

  - overlapping sessions: higher lineage bumps active state, older
    session's in-flight frames are rejected
  - primary mid-rebuild crash: subsequent higher-lineage session
    converges, achieved frontier reflects the new session
  - replica disconnects before BarrierResp: primary surfaces failure
    with no fabricated AchievedLSN
  - stale Ship after newer Rebuild: cross-message-type lineage
    rejection
  - probe during rebuild: probe is observation, does not disturb
    activeLineage

Plus a typed-barrier roundtrip + short-payload-fails-closed test.

docs/data-sync-institution.md names what this layer owns, what it
does not, and the explicit carry-forward to later phases.

* chore: remove committed artifact .commitmsg

* engine, adapter, transport: close recovery-execution lifecycle

Admits one bounded recovery-execution institution around
engine-issued recovery commands: engine command → prepared →
real started or bounded timeout → cancel/invalidate/fail/complete
→ terminal close truth. Every stale or delayed callback fails
closed under lineage without reviving dead semantic truth.

Scaffolding (admitted earlier in this working session):

  - SessionPrepared event splits "we accepted the contract" from
    "runtime actually began execution". A dial failure or
    invalidate-before-start no longer looks identical to a real
    running session.
  - OnSessionStart callback + SetOnSessionStart on CommandExecutor
    tie SessionStarted to real execution start, not command
    issuance. Transport emits it via signalSessionStart after
    attachConn succeeds, with a registry recheck so an invalidate
    between attach and signal drops the callback.
  - startTimeout watchdog in the adapter arms on Start* only, fires
    only if engine-state still matches (sessionID == q.sessionID
    AND Phase == PhaseStarting), clears on real start or terminal
    close. An old timer racing a newer session records fire_noop,
    not a spurious failure.

Closure (this pass):

Engine trace detail enriched so ignored transitions name the
current phase ("current phase=failed") and session ID mismatch
traces distinguish older-session vs newer-session vs no-active-
session via phaseMismatchDetail(). Operators debugging a stale
callback can tell at a glance why it was rejected.

Adapter watchdog now records structured lifecycle events via
WatchdogLog(): arm, clear_started, clear_closed, supersede, fire,
fire_noop. Not an operator surface — execution evidence for tests
and diagnostic dumps.

New tests covering the required proof set:

  engine/apply_test.go:
    - TestV3_Terminal_DelayedFailureAfterCompletionIgnored
    - TestV3_Terminal_DuplicateCompletedIgnored
    - TestV3_Terminal_DuplicateFailedIgnored
    - TestV3_Terminal_InvalidPhaseTransitionsLeaveStateUnchanged

  adapter/watchdog_test.go (new):
    - TestWatchdog_ClearedByRealStart
    - TestWatchdog_ClearedByImmediateClose
    - TestWatchdog_OldTimerCannotFailNewSession
    - TestWatchdog_InvalidateBeforeStart_NoFalseStartNoFalseSuccess

  transport/transport_test.go:
    - TestTransport_Lifecycle_LateCompletionAfterInvalidateDropped

docs/recovery-execution-institution.md updated with per-scenario
proof table, separate watchdog contract table, and an explicit
"What is NOT proven here" section naming carry-forward for
multi-replica coordination, policy-driven invalidation, operator
surfaces.

Non-identity invalidation remains out of scope: the engine still
emits InvalidateSession only from identity-truth handlers
(assignment, removal). A SessionInvalidated reducer exists without
an emitter as forward-compatibility for the topology phase.

* ops: bounded single-node product surface

Makes the existing inspection endpoints read as one coherent
single-node product surface: self-describing, bounded, and
tested against its honesty rules.

Added two endpoints so the surface is product-shaped rather than
four scattered reads:

  GET /          surface map — scope + endpoints + read-only note
  GET /diagnose  bounded summary over projection + trace tail +
                 watchdog counters; full fidelity stays at the
                 dedicated endpoints

Every field exposed by /diagnose is derivable from the existing
State.Snapshot() — projection, trace, watchdog log. The surface is
a mirror over accepted lower truth, never a new authority path.

No HTTP mutation surface. Any mutation verb on any path still
returns 501. The surface-index test rejects cluster-shaped
vocabulary ("cluster", "failover", "promotion", "topology
authority", "rf3") in the self-description — an early draft of
the root endpoint's note used "Cluster-shaped control" and the
test caught it; the note was reworded positively.

Proof (core/ops/surface_test.go):

  - TestSurfaceIndex_SelfDescribing: GET / lists exactly the paths
    the mux wires, each with a non-empty Owns description.
  - TestSurfaceIndex_WordingIsSingleNode: the surface declares
    itself single-node and contains no cluster-shaped vocabulary.
  - TestDiagnose_EmptyStateIsHonest: an empty-state /diagnose
    returns zero/empty values, never fabricated fields.
  - TestDiagnose_OnlyReadsLowerTruth: the /diagnose field set is
    restricted to fields derivable from Snapshot(); any future
    addition that isn't sourced from lower truth trips this test.
  - TestSurfaceMutations_IncludesRootAndDiagnose: every mutation
    verb on / and /diagnose returns 501.

New docs/single-node-surface.md names what the surface owns, what
it does not, and the explicit carry-forward: replicated status to
P12, topology/failover control to P14, operator governance surface
to P15.

README gets a "Single-node product surface" section linking to
the new doc. docs/bootstrap-validation.md updated to reference
/ and /diagnose, and to drop the "Phase 05" label — the doc is
now positioned as the CLI/endpoint reference, with the
product-shape view living in single-node-surface.md.

Also rolls in a small docs/recovery-execution-institution.md note
clarifying that the adapter watchdog's engine-state pre-check is
advisory; the engine phase guards remain the authoritative last
gate. This keeps a dual-layer guard visible to future maintainers
so they don't collapse the two into one convenience check.

* adapter: bounded replicated durable slice — handoff mechanism + fencing proof

Proves the first product capability beyond single-node operation:
given an external reassignment (epoch+1), the engine clears any
in-flight session, invalidates stale lineage, re-probes the
replica, decides catch-up or rebuild, and converges — while the
old primary's stale execution is rejected at every layer by the
lineage gate.

No new engine or transport mechanism was required. The lower
institutions (lineage gate, session lifecycle, data sync) compose
into a working handoff. P12's deliverable is the product-level
proof that this composition works.

Added adapter.OnRemoval(replicaID, reason) so the old primary's
demotion is expressible from outside the package.

Four multi-adapter handoff tests — two real adapters + two real
transport executors sharing one replica listener, no mocks:

  TestHandoff_OldPrimaryToNewPrimary_Converges
    A (epoch=1) reaches healthy; B (epoch=2) probes, recovers,
    converges. Replica data matches B.

  TestHandoff_StaleOldPrimaryTraffic_Rejected
    After B's epoch=2 traffic establishes lineage on the replica,
    stale epoch=1 frames are rejected at the data plane.

  TestHandoff_RejoinAfterNewPrimary_DataConsistent
    Every LBA the new primary wrote is byte-identical on the
    replica after handoff.

  TestHandoff_OldPrimaryDemoted_NoResurrection
    After ReplicaRemoved, late callbacks from the old executor
    cannot resurrect a healthy projection.

Durability claim (explicitly bounded): all writes the new primary
successfully barrier-ack'd are durable on the replica. Writes
in-flight on the old primary at reassignment that weren't ack'd
may be lost. The new primary's truth is authoritative.

Known limitation documented: if the new primary finds the replica
already caught up (R >= H), no mutating traffic establishes the
new epoch on the replica. Stale old-epoch traffic with a higher
sessionID could land. Low practical risk; deferred to P14 as a
proactive-fence concern.

docs/replicated-slice.md names what P12 proves (one bounded
failover/rejoin mechanism), what it doesn't (who decides primary,
when to fail over), and the carry-forward to P13/P14/P15.

* P8-P12: reconcile working tree with accepted phase closures

Reconciles the working tree so all accepted P10, P11, and P12
closures are present and consistent — no regressions, no stubs,
no doc/code mismatches.

P10 watchdog observability restored:
  - armStartWatchdog/clearStartWatchdog record structured events
    (arm, clear_started, clear_closed, supersede, fire, fire_noop)
    into the adapter's watchdogLog field
  - WatchdogLog() returns real data, not a nil stub
  - clearStartWatchdog takes a WatchdogKind reason parameter so
    clear-by-start is distinguishable from clear-by-close
  - watchdog_test.go assertions are full strength — no skip-if-nil
    guards

P10 engine trace detail restored:
  - phaseMismatchDetail() helper distinguishes older-session,
    newer-session, and no-active-session cases
  - all session lifecycle handlers use enriched traces:
    "current phase=failed" instead of "not in active phase"
  - four terminal-lifecycle proof tests restored:
    DelayedFailureAfterCompletion, DuplicateCompleted,
    DuplicateFailed, InvalidPhaseTransitionsLeaveStateUnchanged

P11 single-node product surface restored:
  - GET / (self-describing surface map) and GET /diagnose (bounded
    summary) re-added to handlers.go and server.go
  - surface_test.go recreated with all five honesty proofs
  - server_test.go mux and mutation paths include / and /diagnose
  - README endpoint list names all six read-only endpoints
  - README "Single-node product surface" and "Replicated durable
    slice" sections restored with doc links
  - bootstrap-validation.md endpoint table and example curl block
    include / and /diagnose; header repositioned as CLI/endpoint
    reference with link to single-node-surface.md

P12 fixes preserved:
  - replicated-slice.md route statement narrowed to distinguish
    recovery-needed handoff (fenced) from R>=H (NOT fenced)
  - TestHandoff_OldPrimaryDemoted_NoResurrection strengthened:
    uses SetStepDelay to keep session active during removal, then
    injects late OnSessionStart + OnSessionClose(success) — both
    rejected
  - "stops receiving assignments" wording corrected to "receives
    explicit ReplicaRemoved"
  - adapter.OnRemoval() public API added
  - transport.BlockExecutor.SetStepDelay() exposed for test control
2026-04-16 15:23:29 -07:00
Ping Qiu 7f9232af28 storage: persistence backend with crash-safe acked writes
Adds a single-node persistence layer behind a `LogicalStorage` seam
that admits multiple implementations. The semantic engine, adapter,
and calibration are unchanged — storage is execution machinery, not
authority.

## Interface

`core/storage/logical_storage.go` defines `LogicalStorage`. Both
`BlockStore` (in-memory, existing) and the new `WALStore` satisfy
it (compile-time assertions). Methods cover Write/Read/Sync/Recover,
Boundaries (R/S/H), frontier control (AdvanceFrontier /
AdvanceWALTail / ApplyEntry / AllBlocks), and lifecycle (Close).

## WALStore — default crash-safe backend

`core/storage/walstore.go` plus supporting files
(`wal_entry.go`, `wal_writer.go`, `superblock.go`, `dirty_map.go`,
`recovery.go`, `group_commit.go`).

- Single preallocated file: superblock + circular WAL + extent
- Per-record CRC32 + EntrySize trailer detects torn writes
- Group committer batches concurrent Sync callers into one fsync
- Defensive past-head scan on Recover picks up writes that landed
  after the last superblock update
- Idempotent recovery

## smartwal subpackage — experimental alternative

`core/storage/smartwal/` (record / ring / superblock / store /
recovery / tests / README).

- 32-byte metadata records in a slot-based ring
- Data goes directly to extent; reads always hit extent (no dirty
  map needed for the read path)
- Last-writer-wins per LBA on recovery; CRC verified against
  extent block
- Distinct magic byte from WALStore so files cannot be confused
- Subpackage layout signals opt-in / experimental status; default
  remains WALStore

## Crash consistency for acked writes

`TestWALStore_AckedWritesSurviveSimulatedCrash` and
`TestSmartWAL_AckedWritesSurviveSimulatedCrash` both bypass `Close()`
by dropping the file handle directly — no implicit fsync, no
housekeeping. After reopen + Recover, every block whose Write was
followed by a successful Sync is recoverable; pre-Sync writes may
or may not be present but never corrupt acked data.

## sparrow `--persist-demo`

Reproducible single-node demo: Write 4 blocks, Sync, Close, reopen,
Recover, Read back. Removes prior demo file in the target dir
before Round 1 so repeated invocations / CI runs work cleanly. Text
and `--json` output. Exit codes documented in
`docs/bootstrap-validation.md`.

## Contract test infrastructure

`core/storage/contract_test.go` runs 11 contract assertions against
each registered implementation via a factory table. Adding a third
implementation is one entry in the table.

## Documentation

`docs/persistence.md` describes the WAL+extent design, crash-
consistency guarantees, what's NOT covered, file layout, on-disk
record format, and the **Execution-layer scope decision**:
`LogicalStorage` is the accepted persistence seam;
`DataCommunicator` / `RecoveryExecutor` / `ProgressFeed` are
deliberately deferred peer institutions. **Backing-store options**
section documents the path to raw block device, O_DIRECT, FUA, and
SPDK with concrete perf budgets — all preserve the seam.

## Required adjustments to existing code

`BlockStore.Sync` changed from `() uint64` to `() (uint64, error)` so
in-memory and on-disk implementations share one signature. Callers
that ignored the return updated to discard explicitly. Replica
barrier handler now propagates real fsync errors.

## Tests

| Package | Count |
|---|---|
| `core/storage` | 26 (11 contract × 2 backends + 4 WALStore-specific) |
| `core/storage/smartwal` | 16 (11 contract + 5 SmartWAL-specific) |
| `cmd/sparrow` | 14 (added repeatability check for the demo) |

Full repo green except a pre-existing flake on
`TestTransport_Rebuild_DoesNotCorruptLBA0` (unrelated; addressed on
a separate branch).
2026-04-14 12:22:16 -07:00
Ping Qiu aff28bc936 calibration: first scenario pass (C1-C5)
Adds the first calibration pass: five scenario families (C1-C5)
that drive the accepted route and record expected-versus-observed
evidence as machine-readable artifacts.

## Scenarios

| ID | Family | What it proves |
|---|---|---|
| `CAL-C1-healthy-repeat` | C1 | Repeated probes on a caught-up replica do not trigger spurious recovery |
| `CAL-C2-short-gap-catchup` | C2 | Short retained gap chooses catch-up; closes to healthy; data integrity preserved |
| `CAL-C3-long-gap-rebuild` | C3 | Long gap beyond retained window chooses rebuild; closes to healthy; data integrity preserved |
| `CAL-C4-terminal-close-only` | C4 | Healthy publication appears in the trace ONLY after `event: SessionClosedCompleted` (ordered check, not presence-only) |
| `CAL-C5-order-stable` | C5 | Five same-replica delivery perturbations produce identical Decision, FinalMode, recoverySignature, and CloseEventCount |

## What changed

- `core/calibration/` — new package
  - `result.go`, `harness.go`, `scenarios.go`, `report.go`, `scenarios_test.go`
- `cmd/sparrow/calibrate.go` — wires `--calibrate` and `--calibrate --json`
- `docs/calibration/scenario-map.md` and `divergence-log.md` — evidence templates seeded with the first-pass results
- `README.md` and `docs/bootstrap-validation.md` — `--calibrate` advertised

## Evidence dimensions C5 compares across runs

1. `Decision` (derived from command path)
2. `FinalMode`
3. `recoverySignature` = (NCatchUp count, NRebuild count)
4. `CloseEventCount` (count of `SessionClosedCompleted` events in trace)
5. `DataIntegrityOK`

Each has a distinct sentinel in the JSON artifact when it drifts.

## Tests

- 14 calibration tests (5 per-scenario + 8 compare + 1 meta-test for the recovery-signature check)
- Stable under `-count=10` stress
- Full repo green
2026-04-14 12:13:27 -07:00
Ping Qiu bdc4845014 phase 05: bootstrap/inspection/validation surfaces on the sparrow
Extends the accepted sparrow (Phase 04) with narrow dev/test flags
and a read-only HTTP inspection surface so outside readers and
testers can start, inspect, and validate the runnable slice without
deep design-doc archaeology.

No new standalone operator CLI — `weed shell` remains the eventual
production interface; this work is a standalone-repo sparrow
improvement, not a competing CLI.

## What changed

- `cmd/sparrow/main.go` — flag handling; `startHTTPOps` binds
  synchronously and surfaces errors honestly
- `cmd/sparrow/scope.go` — authoritative `ScopeStatement` + `Version`
- `core/ops/` — new package: `state.go`, `server.go`, `handlers.go`
- `docs/bootstrap-validation.md` — operator-facing surface reference
- `README.md` — Operations section

## Sparrow flags (all opt-in, default unchanged)

| Flag | Effect |
|---|---|
| `--json` | machine-readable JSON summary |
| `--runs N` | repeat the full demo N times |
| `--http ADDR` | read-only HTTP ops server, stays up after demos |
| `--help` | authoritative supported/unsupported scope |
| `--version` | version string |

## Exit codes

| Code | Meaning |
|---|---|
| 0 | all-pass |
| 1 | any fail (validation use) |
| 2 | usage / flag error |
| 3 | runtime setup failure (currently: `--http` bind failed) |

## HTTP ops surface (behind `--http`)

| Method | Path | Returns |
|---|---|---|
| GET | `/status` | version, uptime, scope, current demo |
| GET | `/projection` | latest `ReplicaProjection` as JSON |
| GET | `/trace` | latest adapter trace as JSON array |
| POST/PUT/PATCH/DELETE | any path | 501 + structured "not supported" body |

## Anti-pattern guards held

- ops package never calls `engine.Apply` directly
- ops reads state only through `adapter.Projection()` / `.Trace()`
- no ops handler chooses recovery semantics or redefines `targetLSN`
- `ScopeStatement` shown by `--help` and `/status` is the same constant
- no new standalone operator CLI binary

## Honest bind

`startHTTPOps` calls `net.Listen` synchronously and returns an error
if the port cannot be bound. `--http` never falsely claims
"listening" when it is not. The bound address shown to the user is
the actual listener address (useful for `--http :0` random-port).

## Tests

| Package | Count |
|---|---|
| `cmd/sparrow` | 12 (flag parsing, scope content, repeatable runs, HTTP bind happy path, HTTP bind port-conflict failure, end-to-end exit-code 3 on bind failure) |
| `core/ops` | 26 (handlers, 501 on every verb × path, state) |

Pre-existing flake `TestTransport_Rebuild_DoesNotCorruptLBA0` is
unrelated; `fix/rebuild-race` branch addresses it separately.
2026-04-14 00:16:53 -07:00
Ping Qiu 60103e5f7b Block semantic engine + runnable block sparrow (#1)
* V3 mini engine: Phase 01 + 02 + 03 initial implementation

Phase 01 — Semantic Core (engine/):
- 5 truth domains, 11 events, 6 commands, deterministic Apply()
- Stale rejection, terminal truth, wrong-replica guard
- 17 conformance tests

Phase 02 — Reference Runtime (schema/ + runtime/ + conformance/):
- YAML case loader with strict validation
- Replay runner with expectation checker
- 7 cases, 7 determinism proofs, 5 loader tests

Phase 03 — Adapter (adapter/):
- Single route: observation -> engine -> command -> executor
- CommandExecutor with SetOnSessionClose callback
- Command dispatch outside lock, session ID owned by adapter
- 8 constraint tests (C8/C9/C10/C12 + callback + full route)

44 tests total, all passing.

* Phase 04: runnable block sparrow with real TCP transport

First public runnable slice of seaweed-block. Demonstrates three
recovery paths end-to-end through a deterministic semantic engine:

  1. Healthy: replica caught up (R >= H), no recovery needed
  2. Catch-up: short gap (R >= S, R < H), ship blocks via TCP
  3. Rebuild: long gap (R < S), full base copy via TCP

Package structure (renamed v3mini/ -> core/):
  core/engine     - deterministic Apply(state, event) reducer
  core/adapter    - single-route adapter with async callback wiring
  core/schema     - YAML conformance case loading (strict fields)
  core/runtime    - replay runner for conformance oracle
  core/conformance - 7 YAML cases + determinism + loader tests
  core/storage    - in-memory block store with LSN tracking
  core/transport  - TCP protocol, replica listener, block executor
  cmd/sparrow     - runnable demo binary

51 tests, all passing. Sparrow runs via: go run ./cmd/sparrow

Key design rules enforced:
  - Engine decides, executor executes (C12)
  - Same facts produce same decision (C8)
  - Timer only triggers probe, never recovery (C9)
  - No transport state in engine (C10, recursive reflect guard)
  - Terminal truth only from SessionClosedCompleted
  - Executor honors engine-issued targetLSN exactly
  - Session close callback wired from executor to adapter to engine
  - Command dispatch outside adapter mutex (no deadlock risk)
  - Rebuild uses AdvanceFrontier (no LBA 0 corruption)
  - Catch-up reports barrier-confirmed achievedLSN, not intent

* fix: address CodeRabbit/Gemini review findings

1. Max payload limit in ReadMsg (16MB cap, prevents memory exhaustion)
2. Session ID race fix: capture IDs under lock in buildSessionEvents,
   pass via map to executeCommand — no re-locking needed
3. Barrier response error handling in replica listener
4. Demo 1 uses waitForMode polling instead of fixed sleep
5. ApplyEntry validates data size matches blockSize
6. Rebuild test timing: small delay for replica Sync after MsgRebuildDone
2026-04-13 12:46:57 -07:00