Commit Graph
15 Commits
Author SHA1 Message Date
Ping Qiu 24f2b40dd1 docs: relocate V3 recovery design docs to seaweedfs/sw-block/design/ (#17)
Per repository policy: dev/design docs live in
seaweedfs/sw-block/design/, not in seaweed_block/docs/. Companion
to the seaweedfs commit at 04b9d1ea5 which adds the same content
under v3-recovery-* prefix.

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

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

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

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

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

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

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

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

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

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

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

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

Branch hygiene: stacked off `g7-redo/recycle-pin-hookup` for context
linkage, but architect-tagged "可与 wiring 并行" — separate concurrent
PR. Depends on neither wiring nor recycle-pin-hookup at code level.
2026-04-29 16:23:57 -07:00
Ping Qiu 5b64dfd3c5 recovery: WAL recycle gate consumes MinPin (priority 2.5) (#14)
Closes architect priority 2.5 per docs/recovery-wiring-plan.md §6.
Pinned by INV-RECYCLE-GATED-BY-MIN-ACTIVE-PIN. Depends on wiring
(stack-on-wiring per architect Option A 2026-04-29).

Substrate gate (`core/storage`):
  + RecycleFloorSource interface — externally-supplied
    `MinPinAcrossActiveSessions() (uint64, bool)`. Substrate stays
    orthogonal to engine: structural typing means
    `core/recovery.PeerShipCoordinator` satisfies it without import.
  + RecycleFloorGate optional interface — substrate impl that
    accepts a source via `SetRecycleFloorSource`. Cmd / wiring
    type-asserts on it; smartwal can opt in later.

walstore (`core/storage/walstore.go`):
  + recycleFloorSrc field, mu-guarded.
  + persistCheckpoint clamps proposed `highestLSN` to floor when
    source reports active session. Existing no-regress guard
    (`if highestLSN <= s.checkpointLSN`) handles transient
    floor-below-checkpoint races.
  + SetRecycleFloorSource setter.

memorywal (`core/storage/memorywal/store.go`):
  + recycleFloorSrc field, mu-guarded.
  + AdvanceWALTail clamps proposed `newTail` to floor when source
    reports active session. Same shape as walstore.
  + SetRecycleFloorSource setter.

Coordinator assertion (`core/recovery/peer_ship_coordinator.go`):
  + `var _ storage.RecycleFloorSource = (*PeerShipCoordinator)(nil)`
    — compile-time pin so future signature drift breaks the build,
    not the runtime gate.

Daemon wiring (`cmd/blockvolume/main.go`):
  + In dual-lane mode, install gate via `RecycleFloorGate` type
    assertion. Skipped silently when substrate doesn't support it
    (BlockStore today). Diagnostic stderr line for operators.

Component fixture (`core/replication/component/cluster.go`):
  + Cluster.Start installs the gate when dualLane is set, so
    component-level dual-lane tests exercise the recycle path
    against the same coordinator they install on executors.

Tests (12 new):
  + walstore_recycle_pin_test.go (6) — nil source / inactive /
    active clamp / floor-above-proposed (no clamp) / no-regress
    when floor < current checkpoint / disable via Set(nil).
  + memorywal/store_recycle_pin_test.go (6) — nil source / inactive
    / active clamp + scan-gate inequality / floor-above-proposed /
    disable / RecycleFloorGate interface satisfaction.

Verified: `go test ./core/... ./cmd/... -count=1` all green
(transport, host, recovery, storage{,/memorywal,/smartwal},
replication{,/component}, blockvolume).

inv-test-map.md updated: row flips from "logic only; recycle
integration is next milestone" to "coord + walstore + memorywal
substrate integration" with the 12 new tests cited.
2026-04-29 16:23:37 -07:00
Ping QiuandClaude Opus 4.7 d8b30f5956 G7-redo wiring: cmd flag + replication factory + transport + component fixture (dual-lane reachable from binary) (#13)
* docs: wiring plan for core/recovery → core/transport + cmd

Strategy doc for the next PR (g7-redo/wiring): how to land the
dual-lane recovery package alongside (NOT replacing) the existing
single-lane core/transport path per architect ruling.

Sections:
- Strategy: --recovery-mode flag (legacy / dual-lane); default
  legacy until one milestone of dual-lane GREEN observed.
- Surface inventory: 6 files in core/transport, 1-2 in cmd, 0 in
  core/recovery (it stays untouched).
- Lifecycle alignment: PeerShipCoordinator is the single source of
  truth for "is replica P in a rebuild session" when dual-lane
  active; legacy's BlockExecutor.activeSession is internal to the
  legacy path. Mode is exclusive.
- Wire-format collision (frameSessionStart=0x01 vs MsgShipEntry=
  0x01): three options analyzed; recommend separate ports per mode.
- Coordinator scope: per-volume, NOT per-replica (so MinPin sees
  all replicas for a meaningful min).
- Priority 2.5 (WAL recycle consumes MinPin): new RecycleFloorSource
  interface in core/storage; coordinator already implements it
  exactly; recommend split into g7-redo/recycle-pin-hookup PR after
  this one.
- Test plan: dual-lane integration tests + recycle-pin unit test.
  Existing legacy tests unchanged.
- Rollback: default flip is one-line; legacy removal is a separate
  later PR.

4 open questions for architect (wire collision option, 2.5 split,
default flip timing, legacy removal timing).

Out of scope: §3.2 #3 interleave, retry budget (parallel PR),
liveShipTargetLSNSentinel removal (waits for legacy removal).

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

* transport: dual-lane wiring (BlockExecutor + StartRebuild branch)

First wiring step per docs/recovery-wiring-plan.md §1-§3. Adds the
parallel-flag plumbing for routing StartRebuild through the
core/recovery package's PrimaryBridge while leaving the legacy
single-lane path completely untouched on the default constructor.

Architect ACK on §11 Resolution 1 (separate ports, Option A) drives
the design: dual-lane uses a separate listen address from the
legacy port; this commit only does the primary-side dial; replica's
listen loop is illustrated in dual_lane_test.go and will be hoisted
into cmd/blockvolume in a follow-up.

What lands:

core/transport/executor.go
  + DualLaneConfig struct (Bridge / DialAddr / ReplicaID).
  + dualLane *DualLaneConfig field on BlockExecutor.
  + NewBlockExecutorWithDualLane(primaryStore, replicaAddr,
    dualLaneAddr, coord, replicaID) constructor.
  + Bridge captures executor's onStart/onClose via closures so
    SetOnSession*Callback continues to work post-construction.

core/transport/rebuild_sender.go
  + StartRebuild branches on e.dualLane != nil.
  + startRebuildDualLane: dial dual-lane port, call
    bridge.StartRebuildSession, immediately FinishLiveWrites
    (legacy semantic — no live writes during rebuild). Logs the
    same "executor: rebuild start" marker QA helpers scrape, with
    "(dual-lane)" suffix for trace clarity.

core/transport/dual_lane_test.go
  + runDualLaneListener test helper (illustrates what cmd will do
    in production: net.Listen + accept loop spawning
    recovery.ReplicaBridge.Serve per conn).
  + TestDualLane_BlockExecutor_StartRebuild — full path:
    OnSessionStart fires, OnSessionClose fires with achievedLSN ==
    primaryH, replica's substrate matches primary byte-for-byte,
    coordinator returns to PhaseIdle.
  + TestDualLane_LegacyConstructorIsNotDualLane — guard that
    the existing NewBlockExecutor stays legacy (dualLane == nil).

Validation: 2 new tests pass; all existing core/transport tests
unchanged; full repo `go test ./...` green.

OUT OF SCOPE for this PR (per wiring plan §10):
  - cmd/blockvolume flag wiring (next commit).
  - WAL recycle path consuming MinPinAcrossActiveSessions
    (architect priority 2.5 — separate g7-redo/recycle-pin-hookup
    PR per §11 Resolution 2).
  - Removing core/transport/replica.go::liveShipTargetLSNSentinel
    lane shim (waits for legacy removal milestone).
  - §3.2 #3 single-queue real-time interleave (architect priority #2).

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

* wiring: cmd flag + replication factory + listener (dual-lane reachable from binary)

Second wiring step per docs/recovery-wiring-plan.md. After this commit,
the daemon binary actually exposes the dual-lane recovery path: a flag
selects mode, the replication volume injects the right BlockExecutor
factory per peer, and a separate listener binds at port+1 for inbound
recover-session conns.

cmd/blockvolume/main.go
  + --recovery-mode=legacy|dual-lane flag (default legacy).
  + Validation: rejects unknown values at parse time.
  + In dual-lane mode, after constructing replVolume:
      - new per-volume recovery.PeerShipCoordinator,
      - SetDualLaneExecutorFactory wires per-peer
        NewBlockExecutorWithDualLane closures,
      - separate listener at deriveDualLaneAddr(data-addr) running
        recovery.ReplicaBridge.AcceptDualLaneLoop in its own goroutine,
      - graceful close via deferred cancel + ln.Close at daemon shutdown.
  + deriveDualLaneAddr helper: host:port → host:port+1 (deployment
    convention, wiring plan §4 Option A).

cmd/blockvolume/dual_lane_addr_test.go
  + Pins the port+1 convention: IPv4, IPv6, port=0 boundary,
    overflow at 65535, malformed inputs.

core/replication/volume.go
  + dualLaneExecutorFactory type (factory takes replicaID alongside
    addr — the legacy 2-arg signature does not).
  + newDualExec field, nil-default = use legacy newExec.
  + UpdateReplicaSet branches on which factory is set per peer.
  + SetDualLaneExecutorFactory exported setter for cmd to inject the
    per-volume coordinator-capturing closure. MUST be called before
    UpdateReplicaSet (existing peers do not retroactively re-construct).

core/recovery/integration_stub.go
  + Hoist AcceptDualLaneLoop helper from the test file to a public
    method on ReplicaBridge. Production cmd uses this directly;
    test wrapper now just calls it.

core/transport/dual_lane_test.go
  + Refactor runDualLaneListener to use the new public helper instead
    of an inline accept loop. Lifecycle simplified (ctx cancel + ln
    close → loop returns).

Validation: cmd/blockvolume tests + full repo go test ./... PASS.
Default --recovery-mode=legacy keeps existing G5-* / G6 behavior
identical.

Out of scope (still): WAL recycle path consuming MinPin (g7-redo/
recycle-pin-hookup, separate PR per architect §11 Resolution 2),
removing legacy lane shim, §3.2 #3 interleave.

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

* component: dual-lane engine-driven happy path (wiring step 3)

Closes the wiring milestone per docs/recovery-wiring-plan.md §7 +
architect "P0 = component layer dual-lane full chain" (2026-04-29).

Full chain pinned: master fact → adapter.OnAssignment → engine
ingest Identity → emits ProbeReplica → executor.Probe → adapter
ingests RecoveryFacts → engine.decide() picks rebuild (R<S) →
emits StartRebuild → adapter dispatches to dual-lane-mode
BlockExecutor → recovery.PrimaryBridge.StartRebuildSession →
sender goroutine over the replica's separate dual-lane port →
recovery.Receiver applies base lane + barrier → SessionClosedCompleted
flows back through executor.OnSessionClose → adapter →
engine.Trace records the event.

Cluster builder additions:
  + WithDualLaneRecovery() — composable with WithEngineDrivenRecovery.
  + Coord() — exposes the per-volume PeerShipCoordinator for assertion.
  + DualLaneReplicaAddr(i) — diagnostic.
  + ReplicaNode.DualLaneAddr — populated when dual-lane mode set.
  + Start() branches: per-replica dual-lane listener bound on
    127.0.0.1:0 alongside the legacy listener; per-volume coord
    instantiated before executors so each NewBlockExecutorWithDualLane
    captures the same instance.

Substrate: MemoryWAL (new factory in cluster.go) — NOT BlockStore
or walstore. Architect-bound rationale for using memorywal rather
than walstore here:
  - V2-faithful per-LSN replay (RecoveryModeWALReplay, write-time
    LSN through ScanLBAs) — matches the dual-lane recovery contract
    the test asserts.
  - In-memory; no /tmp churn between tests; no flusher/checkpoint
    timing surprises in scenario assertions.
  - Already part of the contract test table (BlockStore / WALStore /
    MemoryWAL all pass the same 12 tests), so substrate parity is
    covered separately.

Tests pinned (both PASS, runs in ~30ms each on memorywal):
  TestDualLane_EngineDrivenRebuild_HappyPath:
    - Engine emits StartRebuild after probe-result ingest.
    - Trace records SessionClosedCompleted within 5s deadline.
    - coord.Phase("r-0") == PhaseIdle post-session.
    - Replica's substrate matches primary byte-for-byte across the
      rebuilt range (12 LBAs).
  TestDualLane_CoordReleasesPinFloorAfterSession:
    - Pin floor released; MinPinAcrossActiveSessions reports
      anyActive=false post-session.
    - PinFloor("r-0") == 0 after coord.EndSession.
    - INV-SESSION-TEARDOWN-IS-EXPLICIT.

Out of scope (still):
  - Hardware integration (separate phase).
  - WAL recycle path consuming MinPin (g7-redo/recycle-pin-hookup,
    architect §11 Resolution 2).
  - §3.2 #3 single-queue real-time interleave (architect priority #2).
  - Multi-replica fanout under dual-lane (single replica here for
    focus).

Full repo `go test ./...` PASS.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 16:23:07 -07:00
Ping QiuandClaude Opus 4.7 e1403b548e G7-redo: BaseBatchAck wire + pin_floor advancement (was #12; rebased onto phase-15 post-#11) (#16)
* recovery: BaseBatchAck wire + pin_floor advancement (#3)

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

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

What lands:

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 16:22:19 -07:00
Ping QiuandClaude Opus 4.7 107ef82c43 G7-redo POC: dual-lane recovery package + memorywal substrate + pin-floor wire design (#11)
* G7-redo POC: dual-lane recovery package — mechanism + e2e

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 16:19:50 -07:00
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 63ea717a75 P14 S2 fix²: close-safe delivery, catch-up ordering, pointer-form bypass
Addresses five architect findings across two review rounds, all on
the authority package introduced in 5c663b8. The core S2 boundary
(Publisher is the sole minter, identity keyed by (VolumeID,
ReplicaID), Directive is the only policy seam) stays unchanged;
this commit tightens correctness of delivery and the strength of
the non-forgeability proof.

1. Close-safe delivery (High). apply()'s fan-out ran outside
   pub.mu and could race with cancel()/Run-exit closing the same
   channel. The former deliverLatest free function was not
   close-aware — a concurrent close would produce send-on-closed
   panics, and its drain-retry loop on a closed channel (where
   receive is permanently ready with zero value) would spin
   forever.

   Fix: subscription now owns a sync.Mutex + closed flag. New
   methods subscription.deliver() and subscription.close() both
   acquire s.mu; deliver() returns early if closed, and close()
   is idempotent. The deliverLatest free function is gone;
   apply() calls s.deliver(next). cancelSubscription and
   closeAllSubscriptions call target.close() instead of closing
   target.ch directly.

   Regression: TestPublisher_CancelDuringDeliveryDoesNotPanic
   stress-runs 50 concurrent subscribe/cancel goroutines against
   200 concurrent Refresh asks on the same (vid, rid). Asserts no
   panic and no hang within 5 s.

2. Catch-up ordering race (High). Subscribe() registered the new
   subscriber in p.subs under pub.mu, then released the lock and
   did a blocking sub.ch <- st.info. A concurrent apply() could
   deliver a newer fact first; the delayed catch-up would then
   enqueue the older fact, producing stale/out-of-order delivery
   on a route that must converge to current authority truth.

   Fix: the catch-up send now happens INSIDE the pub.mu critical
   section, immediately after the subs-map insert. Because sub.ch
   is cap=1 and the fresh subscription is invisible to any other
   goroutine until pub.mu is released, the catch-up send is
   guaranteed non-blocking. Any later apply() either runs before
   us (catch-up state IS current) or sees us in the subs map and
   drains our stale catch-up via deliver(). Strict ordering.

   Regression:
   TestPublisher_LateSubscriberReceivesLatestUnderConcurrentPublish
   runs 200 iterations of (concurrent Reassign + fresh Subscribe +
   drain); asserts drained epoch <= current authoritative epoch
   every iteration.

3. AST non-forgeability proof gap — deferred-mutation bypass
   (Medium). The earlier AST walker explicitly skipped short
   declarations (x := adapter.AssignmentInfo{}), so the pattern
     x := adapter.AssignmentInfo{}
     x.Epoch = userInput
   bypassed both checks: the literal is zero-valued so check (a)
   did not trigger, and the short-decl path was ignored in (b).

   Fix: auditNonForgeability now handles the AssignStmt branch
   with Tok == token.DEFINE; any RHS that is a composite literal
   of AssignmentInfo type is flagged as the deferred-mutation
   bypass shape, regardless of field values. Also added the
   long-decl-with-value case: var x = adapter.AssignmentInfo{}.

   Regression (two synthetic-source tests that exercise the audit
   function directly):
   - TestNonForgeability_CatchesShortDeclBypass
   - TestNonForgeability_CatchesVarDeclBypass

4. AST non-forgeability proof gap — pointer form (Medium,
   subsequent round). After the short-decl fix, the architect
   noted the same bypass in pointer form was still outside the
   proof:
     x := &adapter.AssignmentInfo{}
     x.Epoch = userInput
   The AST walker only recognized a bare *ast.CompositeLit on the
   RHS, missing the UnaryExpr(&, CompositeLit) wrapper.

   Fix: new helper unwrapAddrOfCompositeLit recognizes both
   X{...} and &X{...}. Both GenDecl-with-value and AssignStmt
   branches use it.

   Regression:
   - TestNonForgeability_CatchesPointerShortDeclBypass
   - TestNonForgeability_CatchesPointerVarDeclBypass

5. Doc drift (Low). Two doc blocks still described the pre-fix²
   state: docs/p14-s2-design.md said "simple 'forbidden
   constructor' grep" and docs/p14-s2-closure.md listed
   Unsubscribe as a Publisher method. Both updated to reflect the
   AST-based whole-repo walker (covering value and pointer
   forms) and the per-subscription cancel API with no key-wide
   unsubscribe verb. Test count in closure.md bumped to 26 and
   pointer-form test names added to the verification list.

No changes to engine, adapter, transport, ops, storage, or
sparrow. Authority tests: 26 pass. Full module: 12 packages pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 22:29:47 -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
wzcheng99andClaude Opus 4.7 5c663b8c83 P14 S2: bounded authority publication route for assignment truth
Introduces the core/authority/ package — the system-owned publication
route where Epoch and EndpointVersion are authored, not relayed. The
publisher is the only production code that constructs an
adapter.AssignmentInfo with a non-zero Epoch.

Contract boundaries (load-bearing):
  * S2 owns publication of authority truth.
  * S2 does NOT own failover policy.
  * Engine and adapter remain consumers, not producers.

Design:
  * Publisher.Run consumes AssignmentAsk values from an injected
    Directive and fans out AssignmentInfo to subscribers keyed by
    (VolumeID, ReplicaID) — not by ReplicaID alone, which would
    multiplex different volumes that share a replica name.
  * AssignmentAsk carries no Epoch and no EndpointVersion. The
    publisher mints both from the intent enum (Bind | RefreshEndpoint
    | Reassign). Retirement (Remove) is deliberately deferred.
  * No public verb accepts a preformed AssignmentInfo. The former
    PublishAssignment relay verb was removed from the design before
    code — the publisher is a minter, not a pass-through.
  * Directive is the seam where P14 S3's failover policy will later
    plug in without reaching into the publisher. S2 ships only
    StaticDirective.
  * Bridge forwards publisher output to adapter.OnAssignment — the
    adapter remains the one and only consumer entry point; no second
    mutation ingress was added.

Tests (core/authority/authority_test.go):
  * Intent semantics: Bind mints epoch=1 ev=1; RefreshEndpoint keeps
    epoch and bumps ev (no-op on unchanged addrs); Reassign bumps
    epoch and resets ev=1; each invalid precondition is rejected.
  * Fan-out keyed by (VolumeID, ReplicaID): two subs on the same key
    both receive; a sub on a different volume for the same replica
    name does NOT receive — regression for the narrow-key bug.
  * Late-subscriber catch-up via LastPublished.
  * Run loop drives Directive until ctx cancel; rejected asks are
    logged and loop continues.
  * Bridge forwards to AssignmentConsumer.
  * Closure target integration test: Publisher -> Bridge -> real
    VolumeReplicaAdapter reaches Mode == ModeHealthy without any
    harness.assign call.
  * Non-forgeability structural test walks core/ and fails if any
    production file outside an explicit allowlist (authority /
    calibration / conformance / schema) constructs an AssignmentInfo
    with a non-zero Epoch.

Docs:
  * docs/p14-s2-audit.md — scoped audit of existing producers /
    publishers / consumers / hidden-operator-path smells / V2 port
    candidates.
  * docs/p14-s2-design.md — bounded design: load-bearing boundaries,
    closure target, package layout, AssignmentAsk shape, authoring
    rules table, publication API, Bridge model, V2 port plan,
    explicit non-goals and acceptance criteria.
  * docs/p14-s2-closure.md — what S2 closed, what stayed out, S2/S3
    boundary table, verification recipe.

No changes to engine, adapter, transport, ops, storage, or sparrow
wiring. The authority route is additive.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 17:13:12 -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 74c4f88cca docs: add engine surface taxonomy
## What this adds

`docs/surface.md` is a taxonomy reference for the semantic core. It
names every event, command, truth domain, and operator enum the
engine currently exposes, so reviewers and contributors can see the
full surface without re-reading the code.

## Counts (verified against current sources)

| Dimension | Count |
|---|---|
| Events | 12 |
| Commands | 6 |
| Truth domains | 5 |
| Operator `Mode` | 4 |
| `RecoveryDecision` | 4 |
| `SessionKind` | 3 |
| `SessionPhase` | 5 |
| `ProbeStatus` | 4 |
| `ContactKind` | 5 |

## Why no single state diagram

The doc explicitly argues against drawing a unified diagram and
names what replaces it:

- the reducer itself as the transition specification
- invariants (C8 / C9 / C10 / C12 + the same-observation batch rule)
- conformance YAML cases
- per-run trace output

Plus a list of per-dimension sub-diagrams that DO fit on one page
for local review.

## Linked from README

Single line under "Repo Layout" pointing to the new doc.
2026-04-14 12:43:17 -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