Commit Graph
7 Commits
Author SHA1 Message Date
pingqiu 13e13ee5f0 engine: act on durable ack lag policy 2026-05-02 11:42:24 -07:00
pingqiu 0575e24f77 engine: record durable ack progress facts 2026-05-02 11:19:20 -07:00
pingqiu 56a57155d8 engine: introduce frontier hint alias for recovery commands 2026-05-02 00:40:58 -07:00
pingqiuandClaude Opus 4.7 4d73c3978e T4d-4 part C: full L2 matrix + 2 engine bug fixes (HARD GATE #3)
HARD GATE #3 surfaced 2 real bugs in engine-driven recovery flow that
synthetic OnSessionClose injection didn't expose. Both fixed here.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 10:15:41 -07:00
wzcheng99andClaude Opus 4.7 dec084485b P14 S1: proactive R>=H fence with ack-gated healthy publication
Adds an explicit FenceAtEpoch command + FenceCompleted/FenceFailed
event pair on the caught-up recovery branch. A replica with R >= H
under a newer identity epoch is no longer declared healthy until the
replica's lineage gate has been bumped to match Identity.Epoch via a
FenceCompleted — closing the window where stale old-epoch traffic
could still land on the replica while the projection already reads
healthy.

Contract surface:
  * Caught-up path emits ONLY FenceAtEpoch — no catch-up / no rebuild.
    Fence is a command+event pair, not a session lifecycle.
  * PublishHealthy held until FenceCompleted advances FencedEpoch.
    Publication and DeriveProjection both gate on this so the
    operator-visible mode reflects the ack-gated contract, not
    just the command stream.
  * FenceFailed is fail-closed: FencedEpoch is NOT advanced; retry
    is probe-driven (next successful probe re-runs decide() and
    re-emits FenceAtEpoch).
  * Session completion (catch-up / rebuild) implicitly fences,
    because mutating traffic at the current epoch already bumped
    the replica's gate.
  * Stale FenceCompleted (epoch < Identity.Epoch, or same epoch
    with older endpointVersion) is rejected without mutating state.
  * FencedEpoch is engine-internal; NOT exposed in ReplicaProjection.

Adapter-side fence dispatch:
  * fenceInFlight keyed by fence LINEAGE
    (replicaID, epoch, endpointVersion), NOT by replicaID alone.
    This prevents a newer-epoch fence from being starved by an
    older in-flight fence — both occupy distinct slots, the old
    one is dropped by the engine as stale when its callback lands,
    and the newer one drives publication to healthy without
    waiting for an unrelated later probe.

Proof tests:
  * engine: TestFence_CaughtUpPath_UsesNoDataRecovery
  * engine: TestFence_HealthyOnlyAfterFenceComplete
  * engine: TestFence_FailureLeavesFencedEpochUnchanged
  * engine: TestFence_StaleOldEpochRejectedAfterFenceOnCaughtUp
  * adapter: TestFullRoute_CaughtUp_NotHealthyUntilFenceComplete
  * adapter: TestFence_NewerEpochNotStarvedByOlderInFlightFence

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 16:29:23 -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