mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
59bf6f06b52061ba7e76b4fbec25c8e0f80521c7
25
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
5c4f995c55 |
v0.2 alpha: Day-1 activation and first-volume loop (#48)
Package the Kubernetes alpha into a script-based Day-1 activation loop: activate the stack, create the first PVC-backed volume, verify writer/reader data, collect product-owned observation evidence, render a local read-only report, and clean up. Includes multi-node-safe activation defaults, first-volume example automation, read-only ops report output, README/quickstart/release note updates, and review-driven hardening for fail-fast configuration, promotion evidence, inventory fail-closed behavior, and test guards. Validated by Day-1 activation run 20260517-205252-04e9 and read-only report run 20260517-212358-bfba. Local targeted tests passed. |
||
|
|
6a5d54678c |
docs(core): drop internal phase/gate prefixes from production comments
Strip T4a/T4b/T4c/T4d, G3+/G5-5/G5-5A/G5-5C/G6/G7-redo, P14/P15, and "architect round-NN" prose from godoc and in-body comments across the core/ tree. Preserve stable invariant identifiers (INV-* names) since they're searchable across the codebase. Files: core/engine/apply.go, core/host/master/services.go, core/replication/component/cluster.go, core/replication/probe_loop.go, core/storage/walstore.go, core/storage/walstore_recovery.go, core/transport/executor.go, core/transport/replica.go. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
8e508527b0 | G9C: require post-close durable ack for recovered replica ready | ||
|
|
41e2cab069 | engine: build flow control facts from progress gauges | ||
|
|
db595eb843 | engine: add primary flow control policy | ||
|
|
13e13ee5f0 | engine: act on durable ack lag policy | ||
|
|
a3c8ede5e1 | engine: add progress lag policy | ||
|
|
0575e24f77 | engine: record durable ack progress facts | ||
|
|
ee5387bbc5 | engine: route recovery decisions through progress facts | ||
|
|
544d1307b9 | engine: add replica progress fact classifier | ||
|
|
aead4f466e | engine: keep recovery frontier monotonic on session close | ||
|
|
56a57155d8 | engine: introduce frontier hint alias for recovery commands | ||
|
|
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. |
||
|
|
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.
|
||
|
|
602fc0d8ca |
G5-5C #4: engine boundary tests — dispatch / Case 1 reconnect / lineage stale-event drop / stale-ack guard
Architect Batch #4 review 2026-04-27 ruled the four §2 invariants (#4 / #11 / #12 / #13) belong at the engine layer, not core/replication/ — "single owner per invariant, don't double-assert in adapter and engine". Batch 3 already covered the runtime concerns (lifecycle, cooldown, lock ordering, peer-instance teardown); Batch #4 covers the truth-layer translations engine performs from probe results into recovery commands. Tests (5 tests, 9 subcases, 9/9 PASS): §2 #4 dispatch (catch-up vs rebuild) — TableDriven: - caught_up: R≥H → DecisionNone, no recovery cmd - gap_within_wal: R<H, R≥S → DecisionCatchUp + StartCatchUp - gap_exceeds_wal: R<S → DecisionRebuild + StartRebuild - rebuild_pinned: pin overrides catch-up → StartRebuild Mutual exclusion checked on each row (the OTHER cmd must NOT emit). No real retention/WAL logic dragged in; pure (R,S,H) input → cmd output table. §2 #11 reconnect Case 1 (identity unchanged): Admit at (epoch=1, EV=1) → catch-up running → session fails → fresh ProbeSucceeded at SAME (epoch=1, EV=1) → engine still in CatchUp at the same lineage. Identity.{Epoch,EndpointVersion} pinned unchanged. No StartRebuild emitted (no master re-emit needed for Case 1 — pinned by §1.F). §2 #12 lineage-bump during in-flight recovery: In-flight session 42 at epoch=1 → AssignmentObserved at epoch=2 resets Session/Recovery/Reachability via identityChanged path → late SessionClosedCompleted carrying old SessionID=42 must be DROPPED. Asserts: Recovery.R does NOT advance, Session.Phase does NOT promote to Completed, no PublishHealthy emit. Distinct from batch 3's volume-layer Case 2 test (peer-instance replacement); this asserts the engine truth layer drops stale-SessionID events. §2 #13 stale-ack guard (single owner = engine): StaleSessionAck_DoesNotPromoteHealth — SessionCompleted with AchievedLSN=50 < TargetLSN=100; Recovery.R advances to 50 but decide() leaves Decision in CatchUp (R<H), so Healthy gate refuses to flip. PublishHealthy NOT emitted. StaleSessionAck_FullAchievedDoesPromote — counterpart confirming AchievedLSN=H DOES promote (so prior test isn't trivially passing via "Healthy never promotes"). PublishHealthy emit confirmed. Also addresses architect's lock-order reminder #1 from Batch 3 review: volume.go ConfigureProbeLoop's peersFn comment now states explicitly "HARD RULE: code on the probe path MUST NOT re-enter v.mu while holding peer.mu" so any future "peer callback into volume" code is blocked at review. Full ./core/engine/ + ./core/replication/ regression: PASS. Per architect ruling, §2 #14 backoff progression is mathematically pinned at the peer layer (batch 2); no further integration-layer re-assertion needed. Next batch (G5-5C #5): cmd/blockvolume flag wiring + production probeFn that calls executor.Probe + adapter.OnProbeResult. |
||
|
|
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> |
||
|
|
028ea64fc6 |
T4d-4 part B: engine-driven recovery wiring + rebuild-on-exhaustion + G5-DECISION-001 serializability
Per T4d mini-plan v0.5 §2.4 (architect round-47 expanded scope).
Closes 3 of 4 HARD CLOSE GATE items (#1 #2 #4); #3 full L2 matrix
+ QA #8 LastSentMonotonic full form deferred to part C with
substrate fault injection.
ROUND-47 ENGINE CHANGE — catchup-exhaustion escalates to rebuild:
- core/engine/apply.go applySessionFailed: catch-up budget exhaustion
now DIRECTLY emits StartRebuild (Decision flips to Rebuild,
StartRebuild command emitted with current Recovery.H as TargetLSN).
Pre-round-47: cleared Decision + emitted PublishDegraded; rebuild
only fired if a fresh probe arrived. Round-47: rebuild path becomes
engine-driven end-to-end without probe dependency.
- Rebuild has MaxRetries=0 per DefaultRuntimePolicyFor; rebuild
failure terminates (Decision cleared, PublishDegraded emitted).
Pinned by INV-REPL-CATCHUP-EXHAUSTION-ESCALATES-TO-REBUILD +
INV-REPL-REBUILD-FAILURE-TERMINAL.
- Existing TestSessionFailed_NonRecycled_RetriesUntilBudget updated
for round-47 escalation (asserts StartRebuild emit on attempt #4
+ Decision=Rebuild + DecisionReason="catchup_budget_exhausted").
WITHENGINEDRIVENRECOVERY() REAL — round-47 HARD GATE #1 + #2:
- core/replication/component/cluster.go: WithEngineDrivenRecovery()
now installs ONE VolumeReplicaAdapter per replica at Start.
Adapters are wired to executors via the constructor's
executor-callback registration (existing adapter ctor behavior).
- New PrimaryNode.adapters field + Cluster.Adapter(idx) accessor.
- New Cluster.DriveAssignment / Cluster.DriveProbeResult helpers
for test scenarios driving engine state through real adapter.
- Stub warning text + log message removed; engine-driven recovery
is now the real path when opted in.
G5-DECISION-001 SERIALIZABILITY — round-47 obligation:
- core/engine/g5_decision_001_serializability_test.go pins that
engine.ReplicaState (+ all nested truth structs) round-trips
through encoding/json cleanly. T4d-4 obligation: keep struct
serializable so G5 can choose Path A (persist recovery state
across primary restart) without structural rewrite.
- 2 tests: full-state round-trip + zero-value round-trip
- T4d-4 does NOT implement persistence — just maintains the
serializability property.
NEW TESTS (9):
core/engine/recovery_test.go (2 new + 1 updated):
- TestT4d4_CatchupExhaustionEscalatesToRebuild (round-47 #4 pin)
- TestT4d4_RebuildExhaustionIsTerminal (rebuild MaxRetries=0
termination)
- (existing) TestSessionFailed_NonRecycled_RetriesUntilBudget
updated for round-47 escalation semantic
core/engine/g5_decision_001_serializability_test.go (2):
- TestG5Decision001_ReplicaState_RoundTripJSON
- TestG5Decision001_ReplicaState_ZeroValueStable
core/replication/component/t4d4_engine_driven_test.go (5):
- TestT4d4_WithEngineDrivenRecovery_IsReal (HARD GATE #1)
- TestT4d4_AdapterWithoutWithEngineDrivenRecovery_IsNil (fence)
- TestT4d4_DriveAssignment_EngineEmitsProbeReplica
- TestT4d4_RoundTrip_AssignmentToProbeToCatchUp_EngineDriven
- TestT4d4_CatchupBudgetExhausted_EngineEmitsRebuild
Existing test updated for round-47:
- core/adapter/adapter_test.go
TestPreparedNeverStarted_FailsClosedOnImmediateStartError:
set rebuildErr matching catchUpErr; assert chain ends at
Degraded after retry+escalate+rebuild-terminal (was: assert
PhaseFailed after first attempt — round-47 makes that
intermediate not terminal).
NOT in part B (deferred to part C):
- HARD GATE #3: Full L2 matrix incl QA #8 LastSentMonotonic full form
— needs substrate fault injection wrapping engine-driven flow
- Windows TempDir cleanup race + sessionID coordination + test rename
Forward-carry status:
- Round-47 engine change preserves all prior round-43/44/46
invariants (lane purity, stale-skip, no per-LBA regression)
- T4d-1 typed-kind contract: forward-carries
- T4d-2 lane-pure apply gate: forward-carries
- T4d-3 R+1 threading: forward-carries
- T4d-4 part A (RecoveryMode + Stop lifecycle): forward-carries
- 22 packages green; 0 failures
Refs: T4d mini-plan v0.5 §2.4 (architect-ratified expanded scope);
round-47 architect ruling (catchup-exhaustion escalates to rebuild +
G5-DECISION-001); G-1 sign
|
||
|
|
3351a66ff2 |
T4d-3: R+1 threading + import-discipline fence (G-1 v0.2 PORT items 1-5; CARRY-T4D-LANE-CONTEXT-001 Option B)
Per T4d mini-plan v0.3 §2.3 + G-1 v0.2 (architect+QA-signed
2026-04-25). Refs G-1 sign: pending hash (G-1 doc lives in
seaweedfs sw-block/design/v3-phase-15-t4d-3-g1-v2-read.md v0.2);
QA approval round-46 cleared T4d-3 start.
PORT items landed (G-1 v0.2 §3, items 1-5):
Item 1 — start boundary: engine.StartCatchUp gains FromLSN field;
engine emits Recovery.R + 1 (decide path + retry-loop re-emit).
Pinned by INV-REPL-CATCHUP-FROMLSN-IS-REPLICA-FLUSHED-PLUS-1 +
INV-REPL-CATCHUP-FROMLSN-FROM-ENGINE-STATE-NOT-PROBE.
Item 2 — per-call deadline: preserved unchanged (T4c-2 INV-REPL-
CATCHUP-DEADLINE-PER-CALL-SCOPE forward-carries).
Item 3 — last-sent monotonic + completion: preserved unchanged
(T4c-2 invariants forward-carry; barrier ack remains completion
truth).
Item 4 — retry budget: engine retry-loop reuses ORIGINAL Recovery.R
+ 1 on re-emit per G-1 §6.2 architect Option A (no inter-attempt
re-probe; apply gate handles over-ship). Pinned by
TestT4d3_CatchUp_RetryReusesOriginalRPlus1.
Item 5 — retention-miss escalation: T4d-1 typed-kind contract
already in place; engine branches on FailureKind. Forward-carry.
V3-NATIVE items (no V2 source per G-1 v0.2 §4):
- Engine-owned retry loop (Q1) — already in place at T4c-3
- Unified recovery command model — T4c-pre-B
- Lane-aware apply gate integration — T4d-2
- BarrierResponse.AchievedLSN as completion truth — T4c-2
- Package-boundary discipline — pinned by new
TestT4d3_Catchup_TransportNeverImportsSubstrateInternals
(parses transport .go files via go/parser; fails if any
substrate-internal package import surfaces)
Signature ripple (10 files):
- engine.StartCatchUp{FromLSN uint64} added (no removals)
- adapter.CommandExecutor.StartCatchUp interface +1 param
- transport.BlockExecutor.StartCatchUp + doCatchUp +1 param
- 4 test executor stubs (mockExecutor, closureExecutor,
policyClosureExecutor, restartExecutor) + production
HealthyPathExecutor + noopExecutor + ops nopExecutor
- transport.recovery_session.go bridge passes fromLSN=1 (legacy
StartRecoverySession path; forward-carry to T4e for explicit
fromLSN field on StartRecovery)
- adapter.adapter_test.go bridge passes fromLSN=1
- 5 transport test call sites + 3 component integration test sites
- component framework CatchUpReplica helper passes fromLSN=1
(transitional shim; tests needing explicit R+1 use direct
executor invocation per G-1 §7)
NEW TESTS (G-1 §7 test parity matrix):
- core/engine/t4d3_rplus1_test.go (3 tests):
- TestT4d3_CatchUp_Engine_RPlus1_FromOwnState_NotProbeDirectly
(pins INV-REPL-CATCHUP-FROMLSN-FROM-ENGINE-STATE-NOT-PROBE)
- TestT4d3_CatchUp_RetryReusesOriginalRPlus1 (G-1 §6.2 Option A)
- TestT4d3_StartCatchUpStruct_HasFromLSNField (compile fence)
- core/transport/t4d3_rplus1_test.go (3 tests):
- TestT4d3_CatchUp_ScansFromReplicaR_NotGenesis (substrate
receives caller-supplied fromLSN; sender does NOT add +1)
- TestT4d3_CatchUp_StartCatchUpSignature_FromLSNRequired
- TestT4d3_CatchUp_NonEmptyReplica_BlockStoreOverShipsExpected
(round-46 ADDITION 2 substrate-bound naming — opposing-
assertion regression fence per §9 caveat)
- core/transport/import_discipline_test.go (1 test):
- TestT4d3_Catchup_TransportNeverImportsSubstrateInternals
(Q3 INV-REPL-TRANSPORT-STORAGE-CONTRACT-ONLY; parses transport
sources, fails on substrate-internal imports)
- core/replication/component/t4d3_scenarios_test.go (4 tests):
- TestT4d3_CatchUp_NonEmptyReplica_ShortGap_BandwidthBounded_
Walstore (substrate-bound bandwidth observation)
- TestT4d3_CatchUp_NonEmptyReplica_ShortGap_BandwidthBounded_
Smartwal (mirror)
- TestT4d3_RetryAfterReplicaAdvanced_OverScansHandledByApplyGate
(round-46 ADDITION 1 — pins §6.2 Option A safety claim:
over-scan + apply gate per-LBA stale-skip; assertions cover
byte-exact convergence + no per-LBA regression + coverage
union completeness)
- TestT4d3_RecoveryTargetLSN1_KnownGap (CARRY-T4D-LANE-CONTEXT-
001 Option B close — SKIPPED with explicit forward-binding
for the T4e or beyond fix; gate API itself is already
lane-pure, only caller's signal source needs upgrading)
CARRY-T4D-LANE-CONTEXT-001 close (round-46 architect HARD CLOSE
CONDITION): Option B chosen (NOT Option A) because true handler/
session-context lane signal is a much larger refactor (separate
listener ports OR per-connection lane tag via session-registration
handshake OR new MessageType — all wire/transport-architectural
changes). Architect listed Option B as acceptable. The skip-marked
test documents the H=1 known gap; godoc cites
CARRY-T4D-LANE-CONTEXT-001 explicitly for catalogue cross-reference.
NOT in T4d-3 scope (deferred):
- Engine-driven recovery wiring through ReplicationVolume↔adapter
(G-1 §4 Item A integration scope) — engine retry-loop is
unit-tested; full ReplicationVolume↔adapter binding is a
follow-up task. Rationale: this commit is large enough; landing
the R+1 threading + import discipline as one piece + adding
end-to-end engine-driven recovery wiring as another keeps
reviewability tractable. T4d-4 owns the lifecycle integration;
the engine-driven-recovery wiring fits naturally there OR as a
T4d-3-followup.
Forward-carry status:
- T4d-1 typed-kind contract: forward-carries unchanged
- T4d-2 lane-pure apply gate: forward-carries; round-46 lane
discipline still honored (gate doesn't sniff lineage)
- All round-43/44 stale-skip invariants: forward-carry green
- T4c-2 6 catch-up invariants: forward-carry under R+1 threading
(verified via T4c muscle tests still passing)
- 22 packages green; 0 failures
Tests added: 11 (per G-1 §7 matrix).
Refs: T4d mini-plan v0.3 §2.3 (architect-ratified); G-1 v0.2
QA-signed (CARRY-T4D-LANE-CONTEXT-001 close condition Option B);
round-46 architect ruling (lane-pure gate); kickoff §9 (Q1/Q2/Q3).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
5ca1d1193e |
T4d-1: structured RecoveryFailureKind end-to-end + AppliedLSNs interface (Option C hybrid)
Per T4d mini-plan v0.3 §2.1 (architect-ratified). Closes T4c §I forward-carry "structured RecoveryFailureKind" + lands the LogicalStorage AppliedLSNs() addition T4d-2 needs at session start. ARCHITECTURAL CONTRACT (v0.3 boundary discipline): - core/engine MUST NOT import core/storage - storage owns substrate-side StorageRecoveryFailureKind + RecoveryFailure - transport extracts substrate kind via errors.As, maps to engine kind - adapter.SessionCloseResult.FailureKind = engine.RecoveryFailureKind - engine.SessionClosedFailed.FailureKind = engine.RecoveryFailureKind - Reason / FailReason text remains DIAGNOSTIC ONLY — engine MUST NOT parse Storage side (core/storage/recovery_contract.go): - StorageRecoveryFailureKind enum (Unknown / WALRecycled / SubstrateIO) - RecoveryFailure typed-error struct with Unwrap() preserving errors.Is(_, ErrWALRecycled) compatibility for migration window - NewWALRecycledFailure / NewSubstrateIOFailure helpers - ErrAppliedLSNsNotTracked sentinel for substrates without per-LBA applied-LSN metadata LogicalStorage interface gains AppliedLSNs() method (Option C hybrid per kickoff §2.5 #1 architect ratification): - BlockStore: explicit (nil, ErrAppliedLSNsNotTracked) — in-memory, no per-LBA tracking; gate falls back to session-only map - walstore: dirty-map snapshot reduction (PARTIAL VIEW per kickoff §2.5 #3 caveat — only in-WAL LBAs reported; flushed LBAs lose per-LBA LSN tracking; defense-in-depth, gate is authoritative) - smartwal: ring.scanValid() per-LBA last-writer-wins reduction Substrate ScanLBAs error wrapping: - walstore: NewWALRecycledFailure(ErrWALRecycled, "fromLSN=... checkpointLSN=...") at retention boundary - smartwal: NewWALRecycledFailure(ErrWALRecycled, "fromLSN=... oldestPreserved=...") at retention boundary Engine side (core/engine/events.go + apply.go): - New engine-owned RecoveryFailureKind enum (Unknown / WALRecycled / Transport / SubstrateIO / TargetNotReached / StartTimeout / SessionInvalidated) - SessionClosedFailed gains FailureKind field (typed branch) - applySessionFailed branches on e.FailureKind, NOT on Reason text - Substring helpers REMOVED: isWALRecycledFailure / isStartTimeoutFailure / containsAny — engine no longer parses Reason Transport side (core/transport/recovery_session.go + executor.go finishSession): - New classifyRecoveryFailure helper at the boundary: errors.As to extract *storage.RecoveryFailure, map StorageRecoveryFailureKind → engine.RecoveryFailureKind; fallbacks for errSessionInvalidated + target-not-reached error message (transport-internal, acceptable) - finishSession populates SessionCloseResult.FailureKind via classifier Adapter side (core/adapter/normalize.go + adapter.go): - SessionCloseResult gains FailureKind engine.RecoveryFailureKind - NormalizeSessionClose copies FailureKind into SessionClosedFailed - adapter dispatch failure paths (start_catchup_failed / start_rebuild_failed / start_recovery_failed) tag Transport kind - Watchdog timeout path tags StartTimeout kind (engine bypasses retry for this kind per existing T4c-3 design) Tests (10 new, mini-plan §2.1 budget met): - Storage: TestStorageRecoveryFailure_WALRecycled_ErrorsIsCompatible, TestStorageRecoveryFailure_WALRecycled_ErrorsAsExposesKind, TestStorageRecoveryFailure_SubstrateIO_ErrorsAsExposesKind, TestStorageRecoveryFailureKind_StringForms, TestBlockStore_AppliedLSNs_ReturnsErrAppliedLSNsNotTracked, TestStorageRecoveryFailureKind_Walstore_RecycleWrappedAsKind, TestWalstore_AppliedLSNs_ReportsDirtyMapEntries, TestStorageRecoveryFailureKind_Smartwal_RecycleWrappedAsKind, TestSmartwal_AppliedLSNs_ReportsRingEntries - Adapter: TestAdapter_SessionCloseResult_TypedKindEndToEnd (×6 subtests, one per kind), TestAdapter_SessionCloseResult_ SuccessIgnoresFailureKind - Engine: TestSessionFailed_WALRecycled_EscalatesToRebuild (rewritten — typed branch), TestSessionFailed_WALRecycled_ NoSubstringMatchUsed (negative pin: text-only without typed kind must NOT escalate), TestEngine_SessionFailed_NoMoreSubstringMatch (source-grep fence with comment-stripping helper to avoid false-positive on godoc mentions of removed helpers) Existing tests preserved: - T4c-2 / T4c-3 tests pass under new contract (existing close-result builders default FailureKind to Unknown which falls into the Transport-kind retry path — matches their pre-T4d-1 substring- match behavior on non-recycled failures) INV-REPL-CATCHUP-RECYCLE-ESCALATES updated: pinning method changed from substring to typed kind (per T4d mini-plan §2.1). go test ./... -count=1 → all 22 packages green. Refs: T4d mini-plan v0.3 (architect-ratified 2026-04-25); kickoff §9.3 #1 (Q1 engine-owned recovery decisions); kickoff §2.5 #1 (Option C hybrid AppliedLSNs); memory feedback_engine_no_storage_ import.md (round-45 architect lock). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
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>
|
||
|
|
3b54576e2f |
T4c-2: catch-up muscle port + state machine + ScanLBAs interface seam
Per design memo §7a + G-1 V2 read signed at v3-phase-15-t4c-2-g1-v2-read.md. Round-35 architect collapse: T4c-2 covers walstore wal_replay inner-loop muscle port (V2-faithful, narrow G-1 scope), smartwal state_convergence production promotion, peer state machine extensions (CatchingUp / NeedsRebuild), and observability surfacing. Storage substrate (G-1 §3 row #4 — interface seam): - Unified RecoveryEntry + ErrWALRecycled + RecoveryMode types in core/storage/recovery_contract.go (memo §5.1, §13.0a) - LogicalStorage.ScanLBAs interface method added; substrate dispatch is via interface, not type-switch - walstore POC promoted: walstore_recovery_poc.go → walstore_recovery.go; ScanFrom → ScanLBAs; uses unified storage.RecoveryEntry - smartwal POC promoted: recovery_poc.go → recovery_scan.go; ScanFrom → ScanLBAs; type alias to storage.RecoveryEntry - BlockStore implements ScanLBAs (state-convergence-equivalent synthesis since in-memory has no WAL retention; uses walHead as scan-time LSN so caller's targetLSN cap doesn't accidentally skip every entry) Catch-up sender muscle port (G-1 §3 narrow-scope inner loop): - core/transport/catchup_sender.go body rewritten: replaces AllBlocks-walk with primaryStore.ScanLBAs(0, fn) + per-entry ShipEntry write - INV-REPL-CATCHUP-CALLBACK-RETURN-NIL-CONTINUES honored: callback skips entries past targetLSN by returning nil (not error) - INV-REPL-CATCHUP-LASTSENT-MONOTONIC honored: lastSent only advances after successful frame write - INV-REPL-CATCHUP-DEADLINE-PER-CALL-SCOPE honored: SetDeadline at entry, cleared at exit (deferred) - INV-REPL-CATCHUP-TARGET-NOT-REACHED-VS-RECYCLED-DISTINGUISHED: ErrWALRecycled wrapped as tier-class change; target-not-reached surfaces as separate stream-level error - INV-REPL-CATCHUP-COMPLETION-FROM-BARRIER-ACHIEVED-LSN (§4.2 binding): completion judged from BarrierResponse.AchievedLSN, not from a separate MsgCatchupDone marker; recovery_mode label surfaces in success log per memo §5.1 Engine (G-1 §4.1, §4.3): - RecoveryRuntimePolicy.MaxRetries field added; per-kind defaults match V2 maxCatchupRetries=3 (wal_delta), 0 (full_extent), 1 (partial_lba) - applySessionFailed maps ErrWALRecycled in failure reason → recovery.Decision = Rebuild (G-1 §4.3 Option B); engine→storage decoupling preserved by string-match on the sentinel text rather than importing storage package Peer state machine (memo §2.2): - ReplicaCatchingUp + ReplicaNeedsRebuild states added - SetState method with table-driven replicaStateTransitionAllowed gate; rejects illegal transitions (NeedsRebuild is terminal in T4c per memo) Tests (15 new): - core/transport/catchup_sender_test.go (8 tests: 2 V2-mirror + 6 invariant pins for §5.1-§5.5 + §4.2 binding + sentinel + mode-label) - core/replication/peer_state_machine_test.go (4 tests: allowed transitions, rejected transitions, NeedsRebuild terminal, String forms) - core/engine/recovery_test.go (3 new: MaxRetries per-kind defaults pin, WAL-recycled escalation pin, non-recycled non-escalation pin) go test ./... -count=1 → all 21 packages green. Catalogue invariants queued for §3.3 inscription at T4c batch close: INV-REPL-CATCHUP-CALLBACK-RETURN-NIL-CONTINUES, INV-REPL-CATCHUP-LASTSENT-MONOTONIC, INV-REPL-CATCHUP-DEADLINE-PER-CALL-SCOPE, INV-REPL-CATCHUP-TARGET-NOT-REACHED-VS-RECYCLED-DISTINGUISHED, INV-REPL-CATCHUP-RECYCLE-ESCALATES, INV-REPL-CATCHUP-COMPLETION-FROM-BARRIER-ACHIEVED-LSN, INV-REPL-PEER-STATE-CATCHINGUP, INV-REPL-RECOVERY-MODE-OBSERVABLE. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
eadc113697 |
T4c-pre-B: unified StartRecovery command + per-kind runtime policy
Per design memo §7a (architect rounds 29-30): introduce semantic unification at the command boundary — one StartRecovery covers catch-up / rebuild / partial-LBA — without unifying runtime behavior. RecoveryRuntimePolicy carries per-content-kind envelope (timeout / progress cadence / cancellation mode); engine populates via DefaultRuntimePolicyFor at emit time. - core/engine: StartRecovery + RecoveryContentKind (wal_delta / full_extent / partial_lba) + DurationClass + CancellationMode + RecoveryRuntimePolicy + DefaultRuntimePolicyFor. - core/adapter: CommandExecutor.StartRecoverySession; adapter dispatch wired (queue + execute + start watchdog). - core/transport: BlockExecutor.StartRecoverySession bridges wal_delta → catch-up sender, full_extent → rebuild sender; partial_lba returns explicit Stage-2 error; validateRecoveryPolicy enforces non-empty envelope + wal_delta+CancelOnTimeout requires Timeout > 0. - Test executors (authority, host/volume, ops) updated with stub StartRecoverySession. - 10 new engine tests (command shape, per-kind defaults, label strings, cadence/timeout consistency); 8 new transport tests (policy validation, dispatch contract — partial_lba rejected, unknown kind rejected, policy-validates-before-dispatch). Legacy StartCatchUp / StartRebuild retained as engine emit shape; T4c-3 muscle port migrates engine emission to StartRecovery. go test ./... -count=1 → all 21 packages green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
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>
|
||
|
|
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
|
||
|
|
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 |