mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
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.
This commit is contained in:
1 parent
1c453375cf
commit
24f2b40dd1
4 files changed
-680
No files matched your search
@@ -1,124 +0,0 @@
|
||||
# Recovery Execution Institution
|
||||
|
||||
The recovery-execution institution is the bounded layer that turns
|
||||
engine-issued recovery commands into real runtime lifecycle facts.
|
||||
It owns session preparation, real execution start, cancellation,
|
||||
timeout wiring, and terminal close callbacks. It does not own
|
||||
recovery classification, failover decisions, topology authority,
|
||||
or operator-facing publication.
|
||||
|
||||
This doc names what the institution owns, what it does not, and
|
||||
what is explicitly carried forward to later phases.
|
||||
|
||||
## Files
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `core/adapter/adapter.go` | Command preparation, lifecycle callback ingress, single route from engine commands to runtime execution |
|
||||
| `core/adapter/executor.go` | `CommandExecutor` contract, including `SetOnSessionStart` and `SetOnSessionClose` |
|
||||
| `core/adapter/normalize.go` | Runtime lifecycle facts to engine events: `SessionPrepared`, `SessionStarted`, `SessionClosed*` |
|
||||
| `core/engine/apply.go` | Semantic lifecycle reducer for prepare / start / fail / complete / invalidate |
|
||||
| `core/transport/executor.go` | Runtime session registry, conn ownership, invalidation, start/close signaling |
|
||||
| `core/transport/catchup_sender.go` | Catch-up execution path; emits start only after real execution path begins |
|
||||
| `core/transport/rebuild_sender.go` | Rebuild execution path; same lifecycle rule as catch-up |
|
||||
|
||||
## What the Institution Owns
|
||||
|
||||
1. **Command admission into execution** — engine-issued `StartCatchUp`,
|
||||
`StartRebuild`, and `InvalidateSession` become runtime actions
|
||||
through one adapter route.
|
||||
2. **Prepared versus running split** — `SessionPrepared` is emitted
|
||||
when the adapter binds lineage and queues runtime work; `SessionStarted`
|
||||
is emitted only when the runtime actually begins execution.
|
||||
3. **Bounded start timeout** — a prepared session that never reaches
|
||||
real execution is failed by the adapter's bounded start-timeout
|
||||
watchdog instead of remaining indefinitely in `starting`.
|
||||
4. **Lifecycle callbacks** — the executor reports real start and
|
||||
terminal close through `SetOnSessionStart` and `SetOnSessionClose`.
|
||||
5. **Session invalidation** — `InvalidateSession` removes the active
|
||||
session, closes its conn, and prevents stale delayed callbacks from
|
||||
becoming current truth.
|
||||
6. **Fail-closed start / close behavior** — start failure, timeout,
|
||||
or invalidation must not fabricate `running` or `healthy`.
|
||||
7. **Runtime-local ownership only** — the executor may own conn state,
|
||||
deadlines, and cancellation wiring, but not recovery policy.
|
||||
|
||||
## What the Institution Does NOT Own
|
||||
|
||||
The following belong to later phases. The recovery-execution institution
|
||||
must not silently absorb them:
|
||||
|
||||
| Concern | Owner | Why not here |
|
||||
|---|---|---|
|
||||
| Choosing catch-up vs rebuild | engine | semantic policy, not execution lifecycle |
|
||||
| Widening `targetLSN` or rewriting recovery meaning | engine | execution must honor the frozen command contract |
|
||||
| Cross-session retry policy and backoff strategy | later P10 / P12 work | broader lifecycle policy than the current bounded institution |
|
||||
| Live WAL streaming during rebuild | P10 / P12 | needs richer lifecycle orchestration than the current single-run route |
|
||||
| Multi-replica coordination | P12 | replicated contract, not one replica's runtime lifecycle |
|
||||
| Promotion / failover selection | P14 | topology authority |
|
||||
| Epoch minting / endpoint authority | P14 | topology authority produced above the executor |
|
||||
| Operator-facing health / repair controls | P15 | governance surface |
|
||||
|
||||
## Fail-Closed Contract
|
||||
|
||||
The current recovery-execution institution proves these boundaries:
|
||||
|
||||
| Scenario | Property proven |
|
||||
|---|---|
|
||||
| Session prepared but not yet started | projection stays `starting`; no fabricated `running` without a real start callback |
|
||||
| Prepared session exceeds bounded start timeout | adapter emits `SessionClosedFailed(start_timeout)`; prepared does not hang forever |
|
||||
| Immediate executor start error | adapter converts the failure into `SessionClosedFailed`; lifecycle fails closed without a `started` event |
|
||||
| Delayed start after timeout | same-session `SessionStarted` is ignored once the session has already failed |
|
||||
| Delayed success close after timeout | same-session `SessionClosedCompleted` is ignored; late success cannot revive a failed session |
|
||||
| Delayed stale start callback after newer assignment | old `SessionStarted` is rejected; it cannot advance the new session |
|
||||
| Delayed stale close callback after newer assignment | old `SessionClosed*` is rejected; it cannot make the new session healthy or failed |
|
||||
| Transport dial failure | executor emits failed close but no `SessionStarted`; command issuance alone does not count as running |
|
||||
| Session invalidation mid-run | invalidated session does not emit terminal close; runtime cancellation is semantically dead |
|
||||
|
||||
The key truth split is:
|
||||
|
||||
- `SessionPrepared` means the engine accepted one bounded recovery contract.
|
||||
- `SessionStarted` means runtime execution actually began.
|
||||
- `SessionClosedCompleted` / `SessionClosedFailed` are the only terminal lifecycle truth.
|
||||
|
||||
## Watchdog Guard Note
|
||||
|
||||
One non-blocking implementation note is important for future maintainers:
|
||||
|
||||
1. the adapter watchdog's read of engine state before firing is advisory, not authoritative
|
||||
2. after that pre-check, engine state may still move before the watchdog calls back into the adapter
|
||||
3. the final authoritative guard remains the engine's phase checks in `applySessionFailed`
|
||||
|
||||
This dual layer is intentional:
|
||||
|
||||
1. the watchdog should suppress obviously stale timeout fires where it can
|
||||
2. the engine must remain the last semantic guard against late timeout/start/close races
|
||||
|
||||
Do not simplify this into one convenience check unless the replacement preserves
|
||||
both properties explicitly.
|
||||
|
||||
## Reading Order
|
||||
|
||||
For someone new to this institution:
|
||||
|
||||
1. `core/adapter/executor.go` — lifecycle contract surface
|
||||
2. `core/adapter/adapter.go` — command preparation and callback ingress
|
||||
3. `core/engine/apply.go` — semantic lifecycle reducer
|
||||
4. `core/transport/executor.go` — session registry and invalidation
|
||||
5. `core/transport/catchup_sender.go` and
|
||||
`core/transport/rebuild_sender.go` — where real execution start is admitted
|
||||
6. `core/adapter/adapter_test.go` and
|
||||
`core/transport/transport_test.go` — lifecycle proof set
|
||||
|
||||
## Carry-Forward
|
||||
|
||||
Items the recovery-execution institution leaves explicitly to later phases:
|
||||
|
||||
- **Later P10 work** — per-session timeout classification, retry/backoff policy,
|
||||
richer execution-phase observability, and live-WAL-during-rebuild orchestration.
|
||||
- **P12 (bounded replicated failover contract)** — rejoin contract,
|
||||
multi-replica lifecycle coordination, and bounded takeover guarantees.
|
||||
- **P14 (topology / failover policy)** — epoch authority, promotion,
|
||||
failover selection, and replica placement truth.
|
||||
- **P15 (operator-facing governance surface)** — operator controls for
|
||||
retire / repair / rebalance and their publication semantics.
|
||||
@@ -1,134 +0,0 @@
|
||||
# Recovery INV ↔ Test Mapping (G7-redo POC)
|
||||
|
||||
Each invariant declared by `core/recovery/doc.go` (or by
|
||||
`sw-block/design/v3-recovery-live-line-backlog-spec.md`) maps below to
|
||||
the test function(s) that pin it. File paths are repo-relative;
|
||||
line numbers are the `func TestXxx` declaration line at branch
|
||||
`g7-redo/dual-lane-recovery-poc` HEAD (commits `42f351d` /
|
||||
`dc7f550` / `a5b50db`).
|
||||
|
||||
Status legend:
|
||||
|
||||
- **Layer 1** — receiver-side mechanism (`core/recovery/`, layer-1 files).
|
||||
- **Layer 2** — primary-side orchestration (coordinator + bridge).
|
||||
- **Layer 3** — error taxonomy.
|
||||
- **Substrate** — `core/storage/memorywal` contract conformance.
|
||||
- **Forward** — declared but deliberately untested in this PR; pending later milestone.
|
||||
|
||||
---
|
||||
|
||||
## Layer 1 — receiver-side mechanism
|
||||
|
||||
| INV | Definition | Test(s) | Status |
|
||||
|---|---|---|---|
|
||||
| `INV-DUAL-LANE-WAL-WINS-BASE` | Same LBA: once WAL lane has applied (`bitmap.MarkApplied`), base lane MUST skip subsequent base blocks for that LBA. Symmetric: base-then-WAL → WAL data overwrites via substrate's last-writer-wins LSN ordering. | `TestRebuildSession_WALWinsThenBaseSkips` (`core/recovery/rebuild_session_test.go:29`)<br>`TestRebuildSession_BaseFirstThenWALOverwrites` (`core/recovery/rebuild_session_test.go:54`) | ✅ pinned both directions |
|
||||
| `INV-SESSION-COMPLETE-ON-CONJUNCTION-LAYER1` | `TryComplete` returns `done=true` iff `baseDone ∧ walApplied ≥ targetLSN`. Latched: subsequent calls return `done=true` without state change. NOT including barrier-ack — that is layer-2's system-level confirmation. | `TestRebuildSession_TryComplete_Conjunction` (`core/recovery/rebuild_session_test.go:74`)<br>`TestRebuildSession_TryComplete_LatchesCompleted` (`core/recovery/rebuild_session_test.go:108`) | ✅ pinned (3 negative + 1 positive + latch) |
|
||||
| `INV-BITMAP-NO-INDEPENDENT-LOCK` | `RebuildBitmap` exposes no synchronization; callers (`RebuildSession`) serialize access via session mutex. | `TestRebuildSession_ConcurrentLanes` (`core/recovery/rebuild_session_test.go:130`) | ✅ stress test (4 base + 4 WAL goroutines × 1024 LBAs); needs `-race` on Linux for full proof |
|
||||
|
||||
---
|
||||
|
||||
## Layer 2 — primary-side orchestration
|
||||
|
||||
| INV | Definition | Test(s) | Status |
|
||||
|---|---|---|---|
|
||||
| `INV-PIN-EXISTS-ONLY-DURING-SESSION` | Primary maintains no `pin_floor` in steady state; recycle proceeds per retention. `pin_floor` appears only during an active session. | `TestCoordinator_MinPinAcrossActiveSessions` (`core/recovery/peer_ship_coordinator_test.go:159`) — `anyActive=false` when no sessions; emerges on `StartSession`; vanishes on `EndSession` | ✅ pinned |
|
||||
| `INV-PIN-STABLE-WITHIN-SESSION` | Same session: `pin_floor` is monotonically non-decreasing. To pick a different anchor, invalidate session and start new lineage. | `TestCoordinator_SetPinFloor_Monotonic` (`core/recovery/peer_ship_coordinator_test.go:200`) — regression attempts ignored | ✅ pinned |
|
||||
| `INV-PIN-ADVANCES-ONLY-ON-REPLICA-ACK` | `pin_floor` advances iff replica has emitted `BaseBatchAcked` for an LBA range whose base data is now installed. Primary cannot advance pin on its own. | `TestE2E_PinFloorAdvancesIncrementally` (`core/recovery/e2e_test.go:466`) — K=8 cadence drives multiple acks across 50-LBA backlog; pin advances through coord.SetPinFloor. Wire impl in `g7-redo/pin-floor` branch (`6cb89ee`). | ✅ pinned |
|
||||
| `INV-PIN-COMPATIBLE-WITH-RETENTION` | `pin_floor ≥ retained(S)` always holds. A session demanding a pin below S MUST fail-loud → invalidate → new lineage. | Coord layer: `TestCoordinator_SetPinFloor_RejectsBelowRetention` (`core/recovery/peer_ship_coordinator_test.go:225`) — typed `*Failure(PinUnderRetention)` on `floor < primaryS`; `TestCoordinator_SetPinFloor_ZeroBoundaryDisablesCheck` (`core/recovery/peer_ship_coordinator_test.go:262`) — `S=0` legacy path.<br>Engine retry-budget gate (G7-redo priority #3 [retry] Option A): `TestT4d_PinUnderRetention_BypassesRetryBudget` + `TestT4d_PinUnderRetention_AtBudgetEdge_DoesNotEscalate` (`core/engine/recovery_pin_retention_test.go`) — `RecoveryFailurePinUnderRetention` skips retry, leaves `Attempts` unchanged, emits `PublishDegraded`, does NOT auto-flip Decision (counter-WALRecycled).<br>Boundary mapping: `TestClassifier_RecoveryPinUnderRetention_MapsToEngineKind` (`core/transport/classifier_pin_under_retention_test.go`) — `*recovery.Failure(PinUnderRetention)` → `engine.RecoveryFailurePinUnderRetention` (closes silent fall-through to retryable Transport). | ✅ pinned (coord + engine retry-bypass + boundary mapping) |
|
||||
| `INV-RECYCLE-GATED-BY-MIN-ACTIVE-PIN` | Primary's WAL recycle floor = `min(pin_floor)` over active sessions; no sessions ⇒ pure retention. | `TestCoordinator_MinPinAcrossActiveSessions` (`core/recovery/peer_ship_coordinator_test.go:159`) — coord-level min/release.<br>`TestWALStore_RecycleGate_*` (`core/storage/walstore_recycle_pin_test.go`) — 6 cases: nil source / inactive source / active clamp / floor-above-proposed / no-regress / disable. Substrate `persistCheckpoint` honors gate.<br>`TestStore_RecycleGate_*` (`core/storage/memorywal/store_recycle_pin_test.go`) — 6 cases mirroring walstore on the in-memory substrate; pins gate interface + AdvanceWALTail clamp. | ✅ pinned (coord + walstore + memorywal substrate integration) |
|
||||
| `INV-SESSION-COMPLETE-CLOSURE` | System-level done = layer-1 `TryComplete` ∧ barrier-ack(`achieved == targetLSN`). Both halves required before declaring InSync. | `TestCoordinator_CanEmitSessionComplete` (`core/recovery/peer_ship_coordinator_test.go:79`)<br>`TestE2E_RebuildHappyPath` (`core/recovery/e2e_test.go:33`) — full round-trip<br>`TestE2E_RebuildWithLiveWritesDuringSession` (`core/recovery/e2e_test.go:127`) — closure with live | ✅ pinned (closure predicate + e2e round-trip) |
|
||||
| `INV-LIVE-CAUGHT-UP-IFF-FRONTIER-AT-BARRIER` | "Live caught up" is provable only via probe/barrier comparing `R_repr` against `H` at frozen time, not via shipper liveness. | `TestE2E_RebuildHappyPath` and `TestE2E_RebuildWithLiveWritesDuringSession` — both require barrier achieved ≥ target before passing | ✅ pinned indirectly (no test passes without barrier) |
|
||||
| `INV-SESSION-TEARDOWN-IS-EXPLICIT` | Convergence → InSync → teardown session → drop `pin_floor` → recycle resumes. All transitions are explicit events. | `TestCoordinator_EndSession_Idempotent` (`core/recovery/peer_ship_coordinator_test.go:218`)<br>e2e tests check `coord.Phase == Idle` post-Run | ✅ pinned |
|
||||
| `INV-SINGLE-FLIGHT-PER-REPLICA` | At most one active rebuild session per replica. Concurrent attempts rejected at session start. | `TestCoordinator_SingleFlightPerReplica` (`core/recovery/peer_ship_coordinator_test.go:63`)<br>`TestIntegrationStub_LifecycleCallbacks` (`core/recovery/integration_stub_test.go:22`) — second `StartRebuildSession` errors | ✅ pinned (coord level + bridge level) |
|
||||
|
||||
---
|
||||
|
||||
## Spec `CHK-*` checks (`v3-recovery-live-line-backlog-spec.md`)
|
||||
|
||||
| CHK | Definition | Test(s) | Status |
|
||||
|---|---|---|---|
|
||||
| `CHK-PHASE-NEVER-STEADY-BEFORE-DRAIN` | While recover session active, do NOT transition peer to `SteadyLiveAllowed` until `BacklogDrained ∧ baseDone`. | `TestCoordinator_PhaseTransitionRequiresDrainAndBaseDone` (`core/recovery/peer_ship_coordinator_test.go:10`) — both negative cases (drained-but-not-done, done-but-not-drained) | ✅ pinned |
|
||||
| `CHK-BARRIER-BEFORE-CLOSE` | No `SessionClosedCompleted` without prior successful barrier `AchievedLSN ≥ target`. | `TestCoordinator_CanEmitSessionComplete` (`core/recovery/peer_ship_coordinator_test.go:79`) | ✅ pinned |
|
||||
| `CHK-NO-FAKE-LIVE-DURING-BACKLOG` | During scripted backlog, steady sentinel path either paused or fed from same ordered queue. | `TestCoordinator_RouteLocalWrite` (`core/recovery/peer_ship_coordinator_test.go:114`) — phase=DrainingHistorical → SessionLane; phase=SteadyLiveAllowed → still SessionLane (barrier-pending); only Idle returns SteadyLive | ✅ pinned (with architect-ratified semantics: SteadyLiveAllowed is publication-permission, not routing) |
|
||||
|
||||
---
|
||||
|
||||
## Substrate (memorywal) contract conformance
|
||||
|
||||
| INV / Property | Test(s) | Status |
|
||||
|---|---|---|
|
||||
| `LogicalStorage` contract — Write / Read round-trip | `TestContract_WriteReadRoundTrip` (`core/storage/contract_test.go:91`) — runs across BlockStore / WALStore / **MemoryWAL** | ✅ pinned (3 impls) |
|
||||
| `LogicalStorage` — read-unwritten-LBA returns zeros | `TestContract_ReadUnwrittenLBAReturnsZeros` (`core/storage/contract_test.go:111`) | ✅ pinned (3 impls) |
|
||||
| `LogicalStorage` — Write advances LSN strictly increasing | `TestContract_WriteAdvancesLSN` (`core/storage/contract_test.go:124`) | ✅ pinned (3 impls) |
|
||||
| `LogicalStorage` — Sync returns highest written LSN | `TestContract_SyncReturnsHighestWrittenLSN` (`core/storage/contract_test.go:140`) | ✅ pinned (3 impls) |
|
||||
| `LogicalStorage` — Sync monotonic non-decreasing | `TestContract_SyncMonotonicNonDecreasing` (`core/storage/contract_test.go:160`) | ✅ pinned (3 impls) |
|
||||
| `LogicalStorage` — Boundaries (R/S/H) reflect writes | `TestContract_BoundariesReflectWrites` (`core/storage/contract_test.go:182`) | ✅ pinned (3 impls) |
|
||||
| `LogicalStorage` — ApplyEntry uses supplied LSN | `TestContract_ApplyEntryUsesSuppliedLSN` (`core/storage/contract_test.go:204`) | ✅ pinned (3 impls) |
|
||||
| `LogicalStorage` — AdvanceFrontier bumps H | `TestContract_AdvanceFrontierBumpsH` (`core/storage/contract_test.go:235`) | ✅ pinned (3 impls) |
|
||||
| `LogicalStorage` — AdvanceWALTail moves S | `TestContract_AdvanceWALTailMovesS` (`core/storage/contract_test.go:253`) | ✅ pinned (3 impls) |
|
||||
| `LogicalStorage` — AllBlocks current snapshot | `TestContract_AllBlocksReturnsCurrentSnapshot` (`core/storage/contract_test.go:271`) | ✅ pinned (3 impls) |
|
||||
| `LogicalStorage` — Close idempotent | `TestContract_CloseIsIdempotent` (`core/storage/contract_test.go:286`) | ✅ pinned (3 impls) |
|
||||
| `LogicalStorage` — Recover on fresh store returns 0 | `TestContract_RecoverOnFreshStoreReturnsZero` (`core/storage/contract_test.go:297`) | ✅ pinned (3 impls) |
|
||||
| **MemoryWAL-specific:** ScanLBAs emits write-time LSN | `TestScanLBAs_EmitsWriteTimeLSN` (`core/storage/memorywal/store_test.go:59`) | ✅ pinned |
|
||||
| **MemoryWAL-specific:** 3 writes to same LBA → 3 ScanLBAs entries (V2-faithful per-LSN, NOT state-convergence dedup) | `TestScanLBAs_ThreeWritesSameLBA_EmitsThreeEntries` (`core/storage/memorywal/store_test.go:98`) | ✅ pinned |
|
||||
| **MemoryWAL-specific:** AdvanceWALTail → ErrWALRecycled gate (typed envelope + errors.Is compat) | `TestAdvanceWALTail_RecycledGate` (`core/storage/memorywal/store_test.go:166`) | ✅ pinned (typed `*RecoveryFailure` + `errors.Is(err, ErrWALRecycled)` via Unwrap) |
|
||||
| **MemoryWAL-specific:** AppliedLSNs returns per-LBA highest LSN (BlockStore returns sentinel) | `TestAppliedLSNs_TracksHighestPerLBA` (`core/storage/memorywal/store_test.go:224`) | ✅ pinned |
|
||||
| **MemoryWAL-specific:** RecoveryMode reports WALReplay (not StateConvergence) | `TestRecoveryMode_WALReplay` (`core/storage/memorywal/store_test.go:214`) | ✅ pinned |
|
||||
|
||||
---
|
||||
|
||||
## Layer 3 — failure taxonomy
|
||||
|
||||
| INV | Definition | Test(s) | Status |
|
||||
|---|---|---|---|
|
||||
| Failure retryable matrix (9 kinds) | Wire / Substrate / Contract → retryable; Protocol / Cancelled / SingleFlight / WALRecycled / **PinUnderRetention** / Unknown → not retryable. | `TestFailure_RetryableMatrix` (`core/recovery/failure_test.go:11`) | ✅ pinned (PinUnderRetention added in `g7-redo/pin-floor`) |
|
||||
| Typed `*Failure` envelope: nil-safe Error/Retryable, errors.Is via Unwrap | `TestFailure_NilSafeAndUnwrap` (`core/recovery/failure_test.go:33`) | ✅ pinned |
|
||||
| `AsFailure(err)` extraction works on chains; nil/plain → nil | `TestFailure_AsFailureExtraction` (`core/recovery/failure_test.go:52`) | ✅ pinned |
|
||||
| Wire failure surfaces as typed `Failure(Wire, …)`, retryable=true | `TestIntegrationStub_FailureTypedOnReceiverDown` (`core/recovery/integration_stub_test.go:298`) — replica conn closed early | ✅ pinned |
|
||||
| Ctx cancel surfaces as typed `Failure(Cancelled, AwaitClose)`, retryable=false | `TestIntegrationStub_FailureTypedOnCancellation` (`core/recovery/integration_stub_test.go:352`) | ✅ pinned |
|
||||
| Sender's `defer` always seals + EndSessions, regardless of error path | `TestIntegrationStub_ReceiverFailsEarly_SenderUnblocks` (`core/recovery/integration_stub_test.go:163`) — post-error PushLiveWrite errors; coord back to Idle<br>`TestIntegrationStub_CtxCancelUnblocksSender` (`core/recovery/integration_stub_test.go:230`) — same on ctx cancel<br>`TestE2E_PushLiveWriteAtomicSeal` (`core/recovery/e2e_test.go:365`) — 8 goroutines × 5 pushes; every accepted push present on replica | ✅ pinned (3 angles) |
|
||||
|
||||
---
|
||||
|
||||
## Forward-direction INVs (declared in `doc.go`, deliberately not yet tested)
|
||||
|
||||
| INV | Why deferred | Target milestone |
|
||||
|---|---|---|
|
||||
| `INV-PIN-ADVANCES-ONLY-ON-REPLICA-ACK` | Requires wire ack frame from receiver → primary to drive `coord.SetPinFloor`. | #3 (BaseBatchAck → pin_floor) |
|
||||
| `INV-PIN-COMPATIBLE-WITH-RETENTION` | Requires real substrate's `Boundaries().S` cross-check at session start. | #3 |
|
||||
| `INV-BASE-SPARSE-REQUIRES-SUBSTRATE-CLOSURE` _(or alternate `INV-BASE-FULL-SCAN-NO-SPARSE-ASSUMPTION`)_ | POC chose dense base; sparse omit + substrate basement-clearing is a separate INV pair, one of two must hold. | Sparse base milestone |
|
||||
| `INV-REPL-OVERLAP-HISTORY-NO-REGRESS` | Bitmap-as-WAL-claim refinement — when stale/duplicate LSN arrives that substrate apply gate skips, bitmap may still be marked to prevent base-lane historical refill over newer replica state. Code currently marks bitmap only after successful ApplyEntry. | After apply-gate redesign |
|
||||
| `INV-BACKLOG-LIVE-INTERLEAVE-LSN-SERIALIZED` _(candidate name)_ | Spec §3.2 #3 promise: single ordered queue mixing recover-tagged + post-target traffic by LSN. POC ships sequential (backlog → seal → live). | #2 (single-queue real-time interleave) |
|
||||
| `INV-PRIMARY-SHIP-PHASE` | Operator-visible "primary did not declare InSync on steady-live alone" check; needs engine-level integration to surface. | Wiring PR |
|
||||
|
||||
---
|
||||
|
||||
## Test sweep summary
|
||||
|
||||
```
|
||||
core/recovery/ 36 tests, all PASS (+3 from g7-redo/pin-floor)
|
||||
core/storage/memorywal/ 14 tests, all PASS
|
||||
core/storage/contract_test.go 12 tests × 3 impls = 36 sub-test runs, all PASS
|
||||
────
|
||||
86 test results pinning the above INVs
|
||||
```
|
||||
|
||||
Race-detector status: not run on Windows host (CGO_ENABLED required).
|
||||
Linux CI must run `go test -race ./core/recovery/... ./core/storage/...`
|
||||
to validate `INV-BITMAP-NO-INDEPENDENT-LOCK` under stress.
|
||||
|
||||
---
|
||||
|
||||
## How to keep this current
|
||||
|
||||
When a new INV lands in `core/recovery/doc.go` (or in the spec):
|
||||
|
||||
1. Add a row to the corresponding section.
|
||||
2. Cite the test function + file:line at branch HEAD.
|
||||
3. If forward-only (no test yet), put it in the bottom section with the target milestone.
|
||||
4. Update the "Test sweep summary" counts.
|
||||
|
||||
When a test is renamed or moved, update the line number column. CI
|
||||
gating (future): a small linter could parse this file and assert
|
||||
each cited test actually exists and contains the INV name in a
|
||||
comment — left for a later milestone.
|
||||
@@ -1,238 +0,0 @@
|
||||
# Recovery — `BaseBatchAck` wire + `pin_floor` advancement (design draft)
|
||||
|
||||
**Status**: design draft, not yet implemented. Targets architect priority **#3** in the G7-redo backlog.
|
||||
**Branch target**: `g7-redo/pin-floor` (or extend `g7-redo/dual-lane-recovery-poc` if QA / architect prefer one PR).
|
||||
|
||||
This doc fixes the protocol surface for receiver→primary acknowledgement so `coord.SetPinFloor` has a real driver. Closes the two forward-direction INVs in `docs/recovery-inv-test-map.md` Layer-2 section: `INV-PIN-ADVANCES-ONLY-ON-REPLICA-ACK` and `INV-PIN-COMPATIBLE-WITH-RETENTION`.
|
||||
|
||||
Implementation is intentionally NOT in this doc — only the contract, the cadence, the failure surface, and the test plan.
|
||||
|
||||
---
|
||||
|
||||
## 1. Why this exists
|
||||
|
||||
Today (`g7-redo/dual-lane-recovery-poc`):
|
||||
|
||||
- Coordinator already exposes `SetPinFloor(replicaID, lsn) error` and `MinPinAcrossActiveSessions() (uint64, bool)` — see `core/recovery/peer_ship_coordinator.go`. They are testable but never called by anything: the wire has no path from receiver back to primary that delivers ack progress.
|
||||
- `pin_floor` is therefore frozen at `fromLSN` for the entire session lifetime; recycle is gated indefinitely.
|
||||
|
||||
Without `pin_floor` advancement, two things break under sustained writes / multi-replica:
|
||||
|
||||
1. Primary's WAL retention sits at the lowest active session's `fromLSN` until session ends — recycle stalls.
|
||||
2. Multi-replica `min(pin_floor)` cannot reflect heterogeneous progress; one slow replica blocks WAL recycle for everyone (`INV-RECYCLE-GATED-BY-MIN-ACTIVE-PIN`).
|
||||
|
||||
`#3` adds the incremental ack so primary's recycle floor catches up with the slowest replica's actually-durable frontier.
|
||||
|
||||
---
|
||||
|
||||
## 2. Wire frame
|
||||
|
||||
**Decision: new frame type, NOT piggyback.**
|
||||
|
||||
| Option | Choice | Why |
|
||||
|---|---|---|
|
||||
| New `frameBaseBatchAck` (receiver → primary) | ✅ chosen | Distinct cadence (incremental during base lane, NOT tied to barrier-end). Wire trace audit is unambiguous. |
|
||||
| Piggyback on `frameBarrierResp` | rejected | Barrier fires once at session end. Pin only advances at session close — useless for retention recycle during a long base lane. |
|
||||
| Piggyback on next inbound frame from primary | rejected | Receiver may not have an inbound to piggyback on (primary is also blocked-on-write during base lane). |
|
||||
|
||||
### Frame layout
|
||||
|
||||
```
|
||||
frameBaseBatchAck = 0x07 // next available type after BarrierResp(0x06)
|
||||
|
||||
payload (20 bytes):
|
||||
[8] SessionID uint64 BE
|
||||
[8] AcknowledgedLSN uint64 BE // receiver's durable frontier as of this ack
|
||||
[4] BaseLBAUpper uint32 BE // LBA prefix [0, BaseLBAUpper) durably installed; 0 if no base progress yet
|
||||
```
|
||||
|
||||
`AcknowledgedLSN` is the load-bearing field; `BaseLBAUpper` is advisory (sender uses it for retransmit logic, NOT for pin floor).
|
||||
|
||||
### Lineage / session binding
|
||||
|
||||
`SessionID` in the payload identifies which session this ack belongs to. Receiver sends only on the same conn that it accepted SessionStart on (no fan-out, no cross-conn acks). Primary's sender validates `SessionID` matches its current session before calling `coord.SetPinFloor`; mismatched session → `FailureProtocol`.
|
||||
|
||||
Lineage's `Epoch` and `EndpointVersion` are NOT in the ack payload — the conn already implies them (same conn established the session). Saves 16 bytes per ack and removes a redundant validation step.
|
||||
|
||||
---
|
||||
|
||||
## 3. Cadence — when does receiver send `BaseBatchAck`?
|
||||
|
||||
Receiver-side rule (per session):
|
||||
|
||||
```
|
||||
After every K base-lane blocks applied → enqueue ack
|
||||
After every T milliseconds elapsed → enqueue ack (whichever first)
|
||||
On MarkBaseComplete → MUST send a final ack
|
||||
On TryComplete returns done → MUST send a final ack just before BarrierResp
|
||||
```
|
||||
|
||||
POC defaults:
|
||||
- `K = 256` blocks (~1 MiB at 4 KiB blocks)
|
||||
- `T = 100ms`
|
||||
|
||||
Both are tunable via `Receiver` constructor params (test override) or session config (production). The cadence is the receiver's call — sender MUST tolerate any cadence including "zero acks until end" (legacy/fallback path).
|
||||
|
||||
`AcknowledgedLSN` for each ack:
|
||||
- During base lane: `min(walApplied, syncedLSN-at-ack-time)`.
|
||||
- After `MarkBaseComplete`: substrate `Sync()` → use returned frontier.
|
||||
- Final ack at `TryComplete`: same as barrier — receiver's syncedLSN after final Sync.
|
||||
|
||||
---
|
||||
|
||||
## 4. `SetPinFloor` semantics
|
||||
|
||||
Coordinator-side rule (already in code, just unused):
|
||||
|
||||
```
|
||||
SetPinFloor(replicaID, lsn):
|
||||
if no active session for replicaID → error (Idle peer)
|
||||
if lsn ≤ current pinFloor → silently ignored (monotonic)
|
||||
else → pinFloor = lsn
|
||||
```
|
||||
|
||||
What `pinFloor = X` means in the spec:
|
||||
|
||||
> Primary commits: replica has durably installed everything with LSN ≤ X. Primary MAY safely recycle WAL up to X for THIS replica's account.
|
||||
|
||||
What it does NOT mean:
|
||||
- Does NOT mean primary's WAL has actually been recycled (the recycle path consults `MinPinAcrossActiveSessions()` plus retention policy independently).
|
||||
- Does NOT mean replica claims InSync — that requires barrier-ack, not incremental BaseBatchAck.
|
||||
|
||||
---
|
||||
|
||||
## 5. Retention inequality (closes `INV-PIN-COMPATIBLE-WITH-RETENTION`)
|
||||
|
||||
At any moment during an active session for replica P:
|
||||
|
||||
```
|
||||
pin_floor(P) ≥ S_primary // (1)
|
||||
pin_floor(P) ≤ walApplied(P) ≤ H_primary // (2)
|
||||
```
|
||||
|
||||
Where:
|
||||
- `S_primary` = primary's WAL retain start (`storage.LogicalStorage.Boundaries()` returns S).
|
||||
- `H_primary` = primary's WAL head.
|
||||
- `walApplied(P)` = receiver's highest applied WAL LSN.
|
||||
|
||||
**Violation handling**:
|
||||
|
||||
- **(1) violated** (`pin_floor < S_primary`): primary has already recycled past where this session committed. This is catastrophic: the session contract is unrecoverable on this primary. Action: invalidate session → `Failure(SingleFlight, ?)` or new typed kind `FailurePinUnderRetention` (see §7 below) → engine starts new lineage with fresher fromLSN.
|
||||
- **(2) violated** (`pin_floor > walApplied`): receiver lied about its frontier OR coord computed wrongly. Treat as `Failure(Contract, …)`.
|
||||
|
||||
The check happens at `coord.SetPinFloor`:
|
||||
|
||||
```go
|
||||
func (c *PeerShipCoordinator) SetPinFloor(id ReplicaID, floor uint64) error {
|
||||
// existing monotonic guard
|
||||
if floor <= existing { return nil }
|
||||
// NEW: retention compatibility — needs primary's S boundary as input
|
||||
if floor < primaryRetainStart {
|
||||
return &FailureSingleFlight{...} // or a new kind, see §7
|
||||
}
|
||||
// existing update
|
||||
}
|
||||
```
|
||||
|
||||
Open question for review: should `SetPinFloor` take `primaryRetainStart` as a parameter, or should the coordinator hold a callback that fetches it from the substrate? Latter is cleaner but introduces a dependency direction. **Recommend**: parameter form, caller (sender) fetches `primary.Boundaries()` before calling `SetPinFloor`. Substrate call is cheap; coordinator stays substrate-free.
|
||||
|
||||
---
|
||||
|
||||
## 6. Failure surface — extends `core/recovery/failure.go`
|
||||
|
||||
### Reuse of existing kinds
|
||||
|
||||
| Wire / coord event | `FailureKind` | Phase | Retryable |
|
||||
|---|---|---|---|
|
||||
| Decode error on `frameBaseBatchAck` payload | `FailureProtocol` | `recv-dispatch` | no |
|
||||
| `SessionID` in ack ≠ active session | `FailureProtocol` | `recv-dispatch` | no |
|
||||
| `SetPinFloor` error: `floor > walApplied` (impossible without bug) | `FailureContract` | `pin-update` (new Phase) | yes (re-probe) |
|
||||
| `SetPinFloor` error: `floor < S_primary` (recycle past commitment) | new kind `FailurePinUnderRetention` (§7) | `pin-update` | no — escalate to new lineage |
|
||||
| Receiver wire write error sending ack | `FailureWire` | `recv-ack-write` (new Phase) | yes |
|
||||
|
||||
### New `FailureKind`?
|
||||
|
||||
`FailurePinUnderRetention` is semantically distinct from `FailureWALRecycled`:
|
||||
- `WALRecycled` = sender's `ScanLBAs(fromLSN)` returned recycled error → couldn't even start streaming.
|
||||
- `PinUnderRetention` = mid-session, primary's S advanced past replica's pin floor → session must invalidate even though it was streaming fine.
|
||||
|
||||
**Recommend**: add the new kind. Mapping at engine boundary still feeds `RebuildPinned` for both (rebuild from a fresher anchor).
|
||||
|
||||
---
|
||||
|
||||
## 7. Code surface (sender / receiver / coordinator changes)
|
||||
|
||||
Only sketched; no implementation in this doc.
|
||||
|
||||
```
|
||||
core/recovery/wire.go
|
||||
+ frameBaseBatchAck = 0x07
|
||||
+ encodeBaseBatchAck / decodeBaseBatchAck
|
||||
|
||||
core/recovery/receiver.go
|
||||
+ cadence config (K blocks, T duration; defaults 256/100ms)
|
||||
+ ack goroutine OR inline ack-send after each Apply* if cadence reached
|
||||
+ final ack on MarkBaseComplete + barrier path
|
||||
|
||||
core/recovery/sender.go
|
||||
+ new goroutine: read frames from conn, multiplex BarrierResp + BaseBatchAck
|
||||
(today sender only reads BarrierResp at end — needs a frame demux loop)
|
||||
+ on BaseBatchAck: validate sessionID, fetch primary.Boundaries().S, call coord.SetPinFloor
|
||||
+ new Phase tag: PhasePinUpdate
|
||||
|
||||
core/recovery/peer_ship_coordinator.go
|
||||
+ SetPinFloor(id, floor uint64, primarySBoundary uint64) error
|
||||
+ new return: FailurePinUnderRetention (or whatever name lands)
|
||||
|
||||
core/recovery/failure.go
|
||||
+ FailurePinUnderRetention (if new kind chosen)
|
||||
+ PhasePinUpdate, PhaseRecvAckWrite
|
||||
```
|
||||
|
||||
The frame demux loop on the sender side is the largest delta — today the sender only reads ONE inbound frame (BarrierResp at end). Switching to a demux pattern with a goroutine + channel is straightforward but worth flagging.
|
||||
|
||||
---
|
||||
|
||||
## 8. Test plan
|
||||
|
||||
In `core/recovery/`:
|
||||
|
||||
| Test | Pins |
|
||||
|---|---|
|
||||
| `TestWire_BaseBatchAck_RoundTrip` | encode/decode wire format |
|
||||
| `TestCoordinator_SetPinFloor_RejectsBelowRetention` | INV-PIN-COMPATIBLE-WITH-RETENTION (new) |
|
||||
| `TestCoordinator_SetPinFloor_RejectsAboveWalApplied` | inequality (2) — Contract failure |
|
||||
| `TestE2E_PinFloorAdvancesIncrementally` | INV-PIN-ADVANCES-ONLY-ON-REPLICA-ACK — drive 1000 LBAs, observe pinFloor advance in a series of steps via Status snapshots |
|
||||
| `TestE2E_AckCadence_K_Triggered` | every K blocks → one ack |
|
||||
| `TestE2E_AckCadence_T_Triggered` | bursty workload + idle → time-based ack |
|
||||
| `TestE2E_NoAckUntilEnd_StillCorrect` | receiver sends only the mandatory final ack; pinFloor advances exactly once at session end (legacy/fallback path) |
|
||||
| `TestIntegrationStub_FailurePinUnderRetention` | typed `*Failure` surface for the new kind |
|
||||
|
||||
Test count expected: ~8 new, all in `core/recovery/`. No new substrate work; `MemoryWAL` already exposes `Boundaries().S` in V2-faithful form.
|
||||
|
||||
---
|
||||
|
||||
## 9. Cross-references
|
||||
|
||||
After this lands, update:
|
||||
|
||||
- `core/recovery/doc.go` — pin INV section: replace `_Pending #3_` markers with `see docs/recovery-pin-floor-wire.md §N`.
|
||||
- `docs/recovery-inv-test-map.md` — Layer-2 forward rows for the two pin INVs: move from "forward" to "pinned" with the new test cites.
|
||||
- `docs/recovery-inv-test-map.md` — Layer-3 taxonomy section: add row for `FailurePinUnderRetention` if that kind lands.
|
||||
|
||||
---
|
||||
|
||||
## 10. Out of scope for this milestone
|
||||
|
||||
- **§3.2 #3 single-queue real-time interleave** (architect priority #2). Pin advancement does NOT depend on it.
|
||||
- **Wiring into `core/transport`**. Pin advancement lives entirely in `core/recovery/`'s self-contained POC; the wiring PR consumes it later.
|
||||
- **Multi-replica fanout in primary**. `MinPinAcrossActiveSessions` is already implemented and tested; no new code there for this milestone.
|
||||
- **Retention policy at WAL recycle**. The recycle path in `core/storage/walstore.go` is unchanged. A separate doc / PR will wire `MinPinAcrossActiveSessions()` into the recycle decision.
|
||||
|
||||
---
|
||||
|
||||
## 11. Open questions for architect — Resolved (architect ACK 2026-04-29)
|
||||
|
||||
1. **`FailurePinUnderRetention` as a new kind** vs reusing `FailureWALRecycled`. **RESOLVED: new kind.** Rationale: `WALRecycled` is a cold-start scan failure (typical fix: bump pin / new lineage); `PinUnderRetention` is a mid-session contract violation (typical fix: invalidate session, log Invariant breach). Different `Retryable()` defaults, different operator response. Implementation MUST update `failure.go` matrix + `doc.go` INV ledger + `recovery-inv-test-map.md` row in lockstep — no verbal-only distinction.
|
||||
2. **`SetPinFloor` signature**: parameter vs callback. **RESOLVED: explicit parameter.** Caller computes floor from `(S, H, AckLSN)` and calls `SetPinFloor(floor)`. Coordinator stays substrate-free. If a unified entry is needed later, it should be a value type (`PinFloorInput struct`), NOT a `func() uint64` callback.
|
||||
3. **Wire compat**: independent frame `0x07` vs piggyback on `MsgShipEntry`. **RESOLVED: keep independent frame for this milestone.** Ack / data split → packet-capture, log, review all simpler; control-plane (receiver→primary ack) decoupled from data-plane (rate, retry). Piggyback / merge is a later bandwidth optimization — does not gate #3 correctness.
|
||||
@@ -1,184 +0,0 @@
|
||||
# Recovery wiring plan — `core/recovery` into `core/transport` + cmd
|
||||
|
||||
**Status**: design draft, not yet implemented. Targets architect priority **wiring + 2.5** (the natural next milestone after `g7-redo/pin-floor`).
|
||||
**Branch target**: `g7-redo/wiring`, stacked on `g7-redo/pin-floor`.
|
||||
**Depends on**: `g7-redo/dual-lane-recovery-poc` + `g7-redo/pin-floor` merged or reviewed first; this PR is meaningless without them.
|
||||
|
||||
This doc fixes the strategy for moving the dual-lane recovery package from a self-contained POC into the production daemon path, alongside (NOT replacing) the existing single-lane `core/transport` path. Architect ruling: "parallel + flag, don't replace existing path until one happy path runs green alongside".
|
||||
|
||||
---
|
||||
|
||||
## 1. Why parallel-flag, not in-place replacement
|
||||
|
||||
The existing single-lane path (`core/transport/rebuild_sender.go::doRebuild` + `replica.go::handleConn` MsgRebuildBlock/MsgRebuildDone handlers) is what hardware integration tests (G6 §close, prior G5-5* milestones) currently exercise. A direct in-place replacement of `doRebuild` carries the risk of breaking those without giving QA a deterministic A/B comparison.
|
||||
|
||||
Plan: introduce a flag (config + cmd-line + env) that selects between:
|
||||
|
||||
- `--recovery-mode=legacy` (default) — existing single-lane path, no new code on hot path.
|
||||
- `--recovery-mode=dual-lane` — the new `core/recovery` package drives rebuild sessions.
|
||||
|
||||
Both paths share the same `BlockExecutor` outer surface (`StartRebuild` / `StartRecoverySession` callers do not care which is used). Wire-format compatibility is NOT required between paths — the dual-lane mode opens its own conn / port (TBD; see §4 below), the legacy mode keeps its existing one.
|
||||
|
||||
Until a green hardware run on `--recovery-mode=dual-lane` is observed, the default stays `legacy`. Removal of the legacy path is a separate PR after at least one milestone of dual-lane GREEN observability.
|
||||
|
||||
---
|
||||
|
||||
## 2. Surface inventory — files that need changes
|
||||
|
||||
### Sender side (primary)
|
||||
|
||||
| File | Change | Notes |
|
||||
|---|---|---|
|
||||
| `core/transport/rebuild_sender.go::StartRebuild` | Branch on mode flag. Legacy path unchanged. Dual-lane path delegates to `recovery.PrimaryBridge.StartRebuildSession`. | Outer signature unchanged so all upstream callers (`core/host/volume/peer_command_executor.go`, `core/transport/recovery_session.go::StartRecoverySession`'s `full_extent` branch, etc.) continue working. |
|
||||
| `core/transport/recovery_session.go::StartRecoverySession` | The `full_extent` branch (line 117 today) calls `StartRebuild`. No change needed if `StartRebuild` itself branches; the dispatch already lives one level up. | Lowest-touch option. |
|
||||
| `core/transport/executor.go::BlockExecutor` struct | Add optional fields: `dualLaneCoordinator *recovery.PeerShipCoordinator`, `dualLaneBridge *recovery.PrimaryBridge`. Nil ⇒ legacy mode. | Constructor variant `NewBlockExecutorWithDualLane(...)` initializes these. Existing `NewBlockExecutor` stays legacy. |
|
||||
|
||||
### Receiver side (replica)
|
||||
|
||||
| File | Change | Notes |
|
||||
|---|---|---|
|
||||
| `core/transport/replica.go::ReplicaListener` | Two listener configurations: legacy listens on existing port for old MsgRebuildBlock dispatch; dual-lane listens on a separate port (or same port + frame-type discriminator). Decision in §4. | Most invasive surface. |
|
||||
| `core/transport/replica.go::handleConn` | Branch on first frame: if it's `recovery.frameSessionStart` (0x01), hand off to a `recovery.Receiver` for the rest of the conn lifetime. Otherwise use existing dispatch. | Type byte 0x01 in the new wire vs 0x01 (`MsgShipEntry`) in the old wire — collision; see §4. |
|
||||
| `core/transport/replica.go::liveShipTargetLSNSentinel` + the lane-shim block | Document as deprecated when dual-lane is active (rebuild lineage no longer rejects live ship — that's the whole point of dual-lane). For legacy mode, keep working. | Removal in a later PR after dual-lane is default. |
|
||||
|
||||
### cmd / daemon
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `cmd/blockvolume/main.go` (or wherever the executor is constructed) | Add `--recovery-mode` flag. Legacy: build `NewBlockExecutor(...)`. Dual-lane: build coordinator + bridge + `NewBlockExecutorWithDualLane(...)`. |
|
||||
| `cmd/blockvolume/main.go` | Add `--recovery-pin-floor-recycle` flag (default off) gating priority 2.5 hookup (see §6). |
|
||||
|
||||
### Replication wiring
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `core/replication/component/cluster.go` | If integration tests construct executors directly, propagate the mode flag through the test fixture. Otherwise unchanged. |
|
||||
| `core/host/volume/peer_command_executor.go` | No change — wraps `BlockExecutor`'s `StartRebuild` which itself branches. |
|
||||
|
||||
---
|
||||
|
||||
## 3. Lifecycle alignment (architect's "不能做第二套相位机")
|
||||
|
||||
**Rule**: there must be exactly one source of truth for "is replica P in a rebuild session right now" — the `recovery.PeerShipCoordinator`. The legacy `BlockExecutor.activeSession` map is internal to the legacy path; the dual-lane path consults `coordinator.Phase()`. Mode is exclusive — at any moment only one tracker is authoritative for a given replica.
|
||||
|
||||
**StartSession ↔ EndSession**:
|
||||
|
||||
- Legacy mode: `BlockExecutor.registerSession` / `finishSession` pair (existing).
|
||||
- Dual-lane mode: `coord.StartSession` / `coord.EndSession` pair (already implemented in `core/recovery`). The `PrimaryBridge.StartRebuildSession` calls `StartSession` synchronously before returning to its caller; the goroutine spawned underneath handles `EndSession` via `Sender.Run`'s defer.
|
||||
|
||||
**OnSessionStart / OnSessionClose callbacks** (`adapter.CommandExecutor` surface):
|
||||
|
||||
- Legacy: `BlockExecutor.SetOnSessionStart / SetOnSessionClose` already wired.
|
||||
- Dual-lane: `PrimaryBridge` accepts the same callback shape; `BlockExecutor` constructor in dual-lane mode forwards its `onStart / onClose` down to `PrimaryBridge`. Caller (`HealthyPathExecutor` etc.) cannot tell which path fired the callback — by design.
|
||||
|
||||
---
|
||||
|
||||
## 4. Wire-format collision
|
||||
|
||||
**Problem**: legacy `MsgShipEntry = 0x01`, dual-lane `frameSessionStart = 0x01`. If both paths share a port, the receiver cannot dispatch on first byte alone.
|
||||
|
||||
**Three resolution options**:
|
||||
|
||||
### Option A — separate port per mode
|
||||
|
||||
`--rebuild-listen=:9221` (legacy) and `--recovery-listen=:9222` (dual-lane). Daemon binds whichever the mode flag selects. **Pro**: zero protocol coupling; **con**: cmd flag surface grows; integration tests need to know which port.
|
||||
|
||||
### Option B — wire-version handshake on connect
|
||||
|
||||
First byte after dial is a wire-version byte (0x00 = legacy, 0x01 = dual-lane). Subsequent bytes follow the corresponding protocol. **Pro**: single port, cleanly versioned; **con**: existing legacy hardware tests don't send a version byte — backward-compat shim required.
|
||||
|
||||
### Option C — re-number dual-lane frames to avoid 0x01
|
||||
|
||||
Move `frameSessionStart` to e.g. `0x10`, leaving `0x01..0x07` for legacy. **Pro**: same port, no handshake, cheap; **con**: special-cases the frame-type table; collision-free zone shrinks for future frames.
|
||||
|
||||
**Recommend Option A** for this milestone. Cleanest separation, least risk to the legacy hardware path. Reverts to single-port multiplexing later if/when legacy is removed.
|
||||
|
||||
---
|
||||
|
||||
## 5. Coordinator instance scope
|
||||
|
||||
One `PeerShipCoordinator` per **volume**, NOT per **executor or per replica**. The coordinator's `MinPinAcrossActiveSessions` is meaningful only when it sees ALL replicas of a single volume. Per-replica coordinators would each report their own pin floor with no minimum.
|
||||
|
||||
**Wiring**: cmd constructs a coordinator at volume open; passes it to all per-replica `BlockExecutor` constructors for that volume. The daemon owns the coordinator lifecycle.
|
||||
|
||||
This is also why the WAL recycle hookup (§6 below) lives at the volume level, not the executor level.
|
||||
|
||||
---
|
||||
|
||||
## 6. Priority 2.5 — WAL recycle path consumes `MinPinAcrossActiveSessions()`
|
||||
|
||||
**Problem**: today `core/storage/walstore.go`'s flusher / recycle path advances `walTail` based on its own retention policy + checkpoint. It does NOT consult any per-peer pin floor. Until the recycle path knows about active sessions' commitments, `pin_floor` advancement is a paper exercise.
|
||||
|
||||
**Hookup point**: `walstore.go::flusher.advanceTail` (or wherever the flusher decides what to recycle). New gate:
|
||||
|
||||
```go
|
||||
recycleFloor := computeRetentionFloor() // existing logic
|
||||
if pinSrc != nil {
|
||||
if pinned, anyActive := pinSrc.MinPinAcrossActiveSessions(); anyActive {
|
||||
if pinned < recycleFloor {
|
||||
recycleFloor = pinned // pin holds back recycle
|
||||
}
|
||||
}
|
||||
}
|
||||
// trim WAL to recycleFloor
|
||||
```
|
||||
|
||||
**Interface seam**: `walstore.WALStore` does not know about `core/recovery` (and shouldn't — substrate stays orthogonal to engine). Solution: a small interface in `core/storage`:
|
||||
|
||||
```go
|
||||
type RecycleFloorSource interface {
|
||||
MinPinAcrossActiveSessions() (floor uint64, anyActive bool)
|
||||
}
|
||||
|
||||
func (s *WALStore) SetRecycleFloorSource(src RecycleFloorSource)
|
||||
```
|
||||
|
||||
`recovery.PeerShipCoordinator` already implements this signature exactly. cmd wires the coordinator into the volume's WAL store after both are constructed. Default: nil source (legacy behavior).
|
||||
|
||||
**Test**: a new `walstore_recycle_pin_test.go` confirms recycle floor is gated by min pin when source is set; falls back to existing logic when nil. No e2e change required — the unit test is sufficient because the coordinator's contract is already covered.
|
||||
|
||||
**Architect priority 2.5 closes when this hookup lands** AND a brief test confirms the integration works end-to-end (set pin floor on coord, observe recycle path respect it).
|
||||
|
||||
---
|
||||
|
||||
## 7. Test plan
|
||||
|
||||
Existing tests must continue to pass on `--recovery-mode=legacy` (default). The wiring PR adds:
|
||||
|
||||
| Test | Scope |
|
||||
|---|---|
|
||||
| `core/transport/rebuild_sender_dual_lane_test.go` | Dual-lane mode end-to-end with the existing `BlockExecutor` shape: same OnSessionStart/Close callbacks fire, achievedLSN equals primary H. |
|
||||
| `core/transport/replica_dual_lane_test.go` | Receiver-side dispatch for `frameSessionStart` correctly hands off to a `recovery.Receiver`. |
|
||||
| `core/storage/walstore_recycle_pin_test.go` | §6 — recycle path consults `MinPinAcrossActiveSessions`. |
|
||||
| Existing `TestE2E_*` in `core/recovery/` | UNCHANGED — they use `core/recovery` directly, not `core/transport`. Wiring PR doesn't touch them. |
|
||||
|
||||
Hardware acceptance (G7 §2 #2 / #5 / #6): NOT a gate for this PR. Architect ruling: "validate happy-path one round green alongside legacy first, then enable as default in a separate PR".
|
||||
|
||||
---
|
||||
|
||||
## 8. Rollback / removal plan
|
||||
|
||||
If something is critically wrong with the dual-lane path post-merge:
|
||||
|
||||
- **Default flip back**: change `--recovery-mode` default in cmd from `legacy` to `dual-lane` (or vice versa) is a single-line revert.
|
||||
- **Code removal**: requires reverting the wiring PR. Because `core/recovery` is independent of `core/transport`, the package itself can stay even if the integration is rolled back.
|
||||
- **legacy removal**: a future PR removes `core/transport/rebuild_sender.go::doRebuild` + the old wire frames. Should NOT be in this PR. Track as `g7-redo/legacy-removal`.
|
||||
|
||||
---
|
||||
|
||||
## 9. Open questions for architect — Resolved (architect ACK 2026-04-29)
|
||||
|
||||
1. **Wire collision** (§4): **RESOLVED — Option A (separate ports)**. Daemon binds a second listen address; `--recovery-mode` flag pairs with it. Firewall / Helm registration must follow. Fallback to Option B (version handshake) is permitted only if a platform constraint requires single-port. Option C (re-number frames) is rejected as a long-term solution.
|
||||
2. **2.5 split**: **RESOLVED — split into `g7-redo/recycle-pin-hookup`**. Wiring PR stays focused on transport + cmd + lifecycle. Recycle hookup lands immediately after wiring merges, NOT held for a long gap (otherwise pin advances in the air while flusher recycles by old policy).
|
||||
3. **Default mode flip timing**: **RESOLVED — stays `legacy`** until CI + hardware-targeted dual-lane scenarios run GREEN, then a separate single-line PR flips the default. Default flip is a release / ops event, not a wiring implementation detail.
|
||||
4. **Legacy removal timing**: **RESOLVED — after default flip + at least one release cycle (canary / N weeks)**, NOT just calendar time. Pre-removal checklist: no-flag run green, monitoring / rollback documented. Tracked as `g7-redo/legacy-removal`.
|
||||
|
||||
---
|
||||
|
||||
## 10. Out of scope (explicit)
|
||||
|
||||
- `§3.2 #3 single-queue real-time interleave` (architect priority #2). Wiring PR ships sequential phases, same as POC.
|
||||
- `INV-REPL-OVERLAP-HISTORY-NO-REGRESS` bitmap-as-WAL-claim refinement. Separate PR after apply-gate redesign.
|
||||
- Sparse base + substrate basement-clearing.
|
||||
- Layer 3 retry budget at engine level (architect priority #3 [retry]). Architect: "可与 wiring 并行 ... 不同目录"; tracked as a separate concurrent PR.
|
||||
- Removing `core/transport/replica.go::liveShipTargetLSNSentinel` and the lane-shim. Lives until legacy is removed.
|
||||
Reference in new issue
Block a user