mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
ccc3ca6cb321adcc09c1bc2aef71f6066dc9d15e
192
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
ccc3ca6cb3 | transport: route live WAL through single feed ingress | ||
|
|
8c4aa52392 | transport: refresh live ship session after recovery | ||
|
|
45340cf627 | transport: handle sealed recovery session handoff | ||
|
|
3ccf2ec729 | transport: gate live WAL through active recovery session | ||
|
|
1e8b0a1600 |
fix(transport): propagate ReplicaID in dual-lane bridge session callbacks
Hardware-validated diagnosis of the scenario #5/#6 "engine retry/escalate
gap" QA flagged: the bridge's onStart/onClose lambdas in
NewBlockExecutorWithDualLane built SessionStartResult /
SessionCloseResult WITHOUT the ReplicaID field. The engine's
checkReplicaID dropped both events as `wrong_replica` ("event for ,
engine owns r2"), so Session.Phase stuck at Starting forever,
hasActiveSession returned true permanently, and every subsequent
post-completion StartRebuild dispatch was silently suppressed.
This explained QA's pattern: probe r2 success R=0 S=1 H>>0 → engine
correctly classifies as Decision=rebuild (verified by adapter trace
{decision rebuild (R < S)}) but emits zero commands because of the
phase-stuck guard. The peer's runtime state diverged from the engine's
session truth: peer.SetState(Healthy) fires on the executor callback
side (which never checks ReplicaID) but engine.Apply rejects.
Scenario #2 "succeeded" only because peer.SetState(Healthy) is enough
for the harness's wait_until_peer_healthy check; the engine's session
state was already broken at that point. Scenarios #5/#6 needed a
second rebuild and that's where the bug surfaced.
Hardware result post-fix:
G7 #2: dispatch=3s, complete=3s, total=6s — GREEN.
G7 #5: rebuild dispatches in 2s (was: never dispatched). New failure
is at byte-equal verify (498 mismatches over 5500 LBAs) — the
concurrent-writes-during-rebuild seam (T4 wire-fromLSN vs
shipper-anchor split) flagged in v3-rebuild-from-lsn-pin-
clarification §4. Out of scope of this fix.
Adapter diagnostic logs (`g7-debug:`) added in core/adapter/adapter.go
that pinpointed the bug — left in for QA verification of next run.
Will gate them or remove in a follow-up commit once stable.
Anchor: hardware trace g7-20260502T012553Z primary-fail.log line
"trace=[{event SessionStarted} {wrong_replica event for , engine
owns r2}]" — the empty ReplicaID being dropped.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
8f10be2869 |
fix(recovery,transport): dual-lane rebuild WAL-recycle + completion marker
Hardware-validated fix for the silent rebuild stall on
|
||
|
|
cb60bd396d |
chore(recovery,transport): g7-debug instrumentation for dual-lane hang
Adds `g7-debug:` prefixed log lines at the chain joints to bisect the
silent hang QA observed on
|
||
|
|
40da4c8738 |
feat(recovery): A-class wave — Tier-1 predicate replacement (§IV.2.1)
Replaces the recover(a,b) sole completion gate (`walApplied >=
TargetLSN`) at both Tier-1 sites with the §IV.2.1 realizable conjunct
synthesized from existing observables (ProbeBarrierEligibility witness
+ baseDone + barrier round-trip). Per recover-semantics-adjustment-plan
§1, "session semantically complete" claim moves from replica-side
verdict to coordinator-owned authority on the primary.
Tier-1 sites updated:
RebuildSession.TryComplete (replica, layer-1):
baseDone ∧ walApplied >= targetLSN ∧ barrierWitnessed
PeerShipCoordinator.CanEmitSessionComplete (primary, system close):
phase != Idle ∧ baseDone ∧ achieved >= targetLSN
∧ (walLegOkWitnessed → walLegOkAtBarrier)
Mechanics:
- Receiver latches RebuildSession.WitnessBarrier() on frameBarrierReq
arrival, BEFORE TryComplete. BarrierReq arrival = primary attests
PrimaryWalLegOk under shipMu (§IV.2.1 disjunction).
- Sender records PrimaryWalLegOk witness via
Coordinator.RecordBarrierWalLegOk(walLegOk) immediately after the
ProbeBarrierEligibility snapshot, BEFORE writing frameBarrierReq.
- Bridging-sink path (no probe) leaves walLegOkWitnessed=false; the
conjunct collapses to legacy (back-compat preserved while §IV.2.1
probe wiring is dual-lane-only). Test coverage in
TestRecoverA_BridgingSinkPath_LegacyCollapse pins this.
A-class conformance stubs unskipped (recover_a_conformance_test.go):
A1 TestRecoverA_DebtZeroPath_BarrierEligible SKIP→GREEN
A2 TestRecoverA_LiveTailPath_BarrierEligible… SKIP→GREEN
A3 TestRecoverA_Disjunction_EitherPathSuffices SKIP→GREEN
A4 TestRecoverA_NeitherPath_NotEligible SKIP→GREEN
+ TestRecoverA_BridgingSinkPath_LegacyCollapse GREEN (new)
A4 binding: walLegOk=false witness → CanEmit refuses → sender returns
FailureContract on close. Wire-level emission gating (§IV.2.2 stronger
"MUST NOT be emitted") is the B-class barrierEmitFreeze wave — out of
scope. A-class pins the binding at the close gate.
C-class still SKIP (CheckpointCutSeq on wire, achieved-as-cut-witness).
Y kept as comparator pre-C-class (`achieved >= targetLSN` retained;
"Y as enumerator only" defers to C-class wave).
Whole-tree go test ./... -count=1 green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
3ebc6f15c2 |
feat(recovery): §IV.0 T4 wire-level WAL LSN monotonicity gate
Adds Receiver.appliedWalLSN/recvFromLSN tracking and checkMonotonic / enforceWalWireMonotonic per §IV.0 T4 (recover-semantics-adjustment-plan §7 v3.28 substrate-mode carve-out). Behavior: - SessionStart seeds recvFromLSN=appliedWalLSN=FromLSN. - Each frameWALEntry runs enforceWalWireMonotonic before ApplyWALEntry. - RecoveryModeWALReplay: requires lsn == appliedWalLSN+1; gap returns FailureContract; exact-duplicate / backward returns FailureProtocol. - StateConvergence (smartwal ScanLBAs): skipped — frontier LSN may legitimately repeat across many RecoveryEntry payloads. Tests: - TestReceiver_checkMonotonic_T4: forward / duplicate / gap / backward. - TestReceiver_checkMonotonic_boundaryDup: lsn==FromLSN before any apply is a Protocol failure (not a no-op). Authored by architect; submitted on user request. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
32b16004fa |
feat(recovery): §IV.2.1 marker-only slice — PrimaryWalLegOk observation + cutID
First behavioral wave of the recover(a) migration now that Gate G0 is
closed. OBSERVABILITY ONLY — no completion-predicate replacement,
no semantic change to BarrierReq emission gating. The recover(a,b)
band path stays GREEN as today; this commit adds the §IV.2.1
PrimaryWalLegOk observation tuple and Option B cutID counter so QA's
hardware oracle (§8.2.6) can wire round-trip grep in parallel with
A/B/C-class implementation.
Anti-discipline checks (§8.2.8) honored:
- All 5 marker fields per the §8.2.6 schema (no simplification).
- Conformance stubs in core/recovery/recover_a_conformance_test.go
remain SKIPPED — predicate replacement is the A-class wave.
Substrate changes:
WalShipper (core/transport/wal_shipper.go):
+ firstLiveEmitted atomic.Bool — set on first EmitKindLive emit
(fast-path or post-CASE-A residual); reset on StartSession.
Implements PrimaryLiveTail's per-session monotonic property.
+ ProbeBarrierEligibility() — single-shot snapshot under shipMu
returning (debtZero, liveTail, walLegOk, cursor, head). The
§IV.2(2) guard is simplified at this layer to "ever emitted
Live" — component-layer exercises the real guard.
RecoverySink (core/transport/recovery_sink_adapter.go):
+ ProbeBarrierEligibility delegate — duck-types the
barrierEligibilityProbe interface in core/recovery so the
dual-lane production path can populate marker logs.
PeerShipCoordinator (core/recovery/peer_ship_coordinator.go):
+ barrierAttempt counter on peerShipState — increments per
NextBarrierCut call within a session; resets to 0 at
StartSession (per architect Option B in plan §8.2.6).
+ NextBarrierCut(replicaID) (cutID, error) — first call per
session yields 1; pre-§IV.2.4 wire change this is a
coordinator-local sequence; post-C-class it becomes the
wire CheckpointCutSeq with no log-prefix change.
Sender.Run (core/recovery/sender.go):
+ barrierEligibilityProbe interface (optional, sink-side).
+ Two log lines per BarrierReq round-trip (5 fields each per
§8.2.6 schema):
replication: barrier prepare replica=<id> sessionID=<n>
cut=CCS:<cutID> PrimaryDebtZero=<bool> LiveTail=<bool>
WalLegOk=<bool> cursor=<n> head=<n>
replication: barrier handshake cut=CCS:<cutID>
achieved=<n> match=<bool>
Pre-C-class `match=true` unconditionally — the same cutID
flows from prepare to handshake by construction. Post-C-class
becomes the real wire-vs-engine compare.
+ Markers fire only on the dual-lane production path (sink
implements barrierEligibilityProbe); bridging-sink path
doesn't emit them — pre-§IV.2.1 markers are dual-lane-only
per the §8.2.6 hardware oracle scope.
Tests:
core/transport/probe_barrier_eligibility_test.go (new):
- FreshShipper_DebtZero — at construction, cursor==head==0,
walLegOk via debtZero.
- LiveEmitFlipsLiveTail — fast-path Live emit sets liveTail
monotonically.
- StartSessionResetsLiveTail — per-session monotonic reset
contract.
core/recovery/peer_ship_coordinator_test.go:
+ TestCoordinator_NextBarrierCut_MonotonicPerSession —
first-call-yields-1, monotonic increment, per-session reset
on StartSession-after-EndSession.
What this commit does NOT do (waiting for A-class wave):
- Replace `walApplied >= TargetLSN` predicate in TryComplete.
- Replace `achievedLSN >= targetLSN` in CanEmitSessionComplete.
- Replace Sender.Run's success-path FailureContract on
`achieved < target`.
- Add CheckpointCutSeq to BarrierReq/Resp wire payload.
- Un-skip conformance stubs.
Each of those is its own slice that turns ≥1 conformance stub
SKIP→GREEN as it lands.
Refs: recover-semantics-adjustment-plan.md §8.2 / §8.2.6
(Option B cutID); v3-recovery-algorithm-consensus.md §IV.2.1
(PrimaryDebtZero / LiveTail / WalLegOk); §I P8 (recover(a) vs
recover(a,b)). Companion to the QA→SW handoff commits
|
||
|
|
faafa468c5 |
test(recovery): A/B/C skipped conformance stubs per §8.2.5
Commit 3 of the QA→SW handoff (`recover-semantics-adjustment-plan.md`
§8.2.7 step 4). Adds 8 SKIPPED red-test anchors covering the three
G0-合同-unblockable categories from §8.2.5; D/E/F deferred until
G0-身份 + G0-wire close per the same section.
File: core/recovery/recover_a_conformance_test.go
Categories landed:
A. PrimaryWalLegOk disjunction (§IV.2.1) — 4 stubs:
- DebtZeroPath_BarrierEligible
- LiveTailPath_BarrierEligibleAfterEverEmittedLive
- Disjunction_EitherPathSuffices
- NeitherPath_NotEligible
B. Lock discipline at BarrierReq emission (§IV.2.2 barrierEmitFreeze)
— 2 stubs:
- BarrierReqUnderShipMu_NoInterleaveWithDriveEmits
(codifies the slice-2B Pillar2B race fix)
- BarrierImminentFlag_FreezesDriveEmits
(Option 3 from architect's lock-discipline trade-off)
C. AchievedLSN as cut-witness, not target-crossing (§IV.2.4)
— 2 stubs:
- AchievedLSN_PerCutWitness
- SuccessWith_AchievedLSN_BelowTarget
(codifies FS-4 reverse from §8.2.3 — Y as enumerator only)
Anti-discipline checks (§8.2.8) honored:
- Every t.Skip carries a reason citing §IV.2.1 / §IV.2.2 / §IV.2.4
+ the unblocking G0 sub-gate; no bare t.Skip.
- No production type imports (stubs only declare Skip; real test
bodies land alongside impl).
- D/E/F categories explicitly NOT included per §8.2.5.
Verified: go test runs the stubs as SKIP entries; commit 1's oracle
table tests still GREEN. The skip messages double as a TODO list
visible to anyone running `go test -v` against core/recovery.
Source: sw-block/design/recover-semantics-adjustment-plan.md §8.2.5.
Companion to commit 1 (`599f60e` dual-oracle table) and commit 2
(`a08dea1` legacy header annotation).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
a08dea1574 |
test: legacy header annotation per §8.2.4 — recover(a,b) band marker
Commit 2 of the QA→SW handoff (`recover-semantics-adjustment-plan.md`
§8.2.7 step 3). Header-only annotation pass on the 19 _test.go
files in seaweed_block that reference `targetLSN` or `walApplied`
as completion-authority terms (discovery: `grep -rlE
'targetLSN|walApplied' --include='*_test.go' core/`).
Each file gets a 2-line header right after the package decl,
verbatim per §8.2.4:
// Completion oracle: recover(a,b) band — NOT recover(a) closure.
// See sw-block/design/recover-semantics-adjustment-plan.md §8.1.
Six of the 19 are deeply primary.H-bound (assertions tied to
`replica.H == primary.H` or `achieved == primary.H`) and get an
extra `migrate-candidate` line per §8.2.4:
// migrate-candidate: depends on primary.H semantics, see §8.1 Tier-5 migration
The migrate-candidate set:
- core/transport/pillar2_assembled_test.go
- core/transport/pillar3_convergence_test.go
- core/transport/walshipper_pin_protection_test.go
- core/transport/transport_test.go
- core/transport/catchup_sender_test.go
- core/recovery/e2e_test.go
Anti-discipline checks (§8.2.8) honored:
- No assertion changes — header text only.
- migrate-candidate kept on its own line, not merged with the
standard 2-line annotation.
Note on count: §8.2.4 cited "~95 files" against the broader audit
pattern (TargetLSN/AchievedLSN/FrozenTarget/TryComplete). The
narrower §8.2.4 grep (targetLSN|walApplied) targets the actual
completion-authority surface and yields 19 files in the
seaweed_block tree. Build + tests clean post-annotation.
Source: sw-block/design/recover-semantics-adjustment-plan.md §8.2.4.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
599f60e77e |
test(recovery): dual-oracle pure-function table per §8.2
Commit 1 of the QA→SW handoff catalog (`recover-semantics-adjustment- plan.md` §8.2.7 step 2). Pure-function spec-semantics test, no production type imports — `RecoverState` + `BarrierWitness` are test-local data shapes per §8.2.1 (anti-discipline check #3: oracle test must NOT couple to core/* production types). What this commit adds: BandOracle (legacy recover(a,b)): walApplied ≥ TargetLSN ∧ baseDone RecoverAOracle (§IV.2.1): baseDone ∧ PrimaryWalLegOk ∧ BarrierWitness with CutMatch where PrimaryWalLegOk = (cursor==head) ∨ LiveClassEmitted 8-case counterexample table per §8.2.3: - 4 sanity rows (both oracles agree) - 4 CORE rows showing the dual-oracle independence: FS-1, FS-2, FS-3: Band-true while RecoverA-false (debt remaining, no barrier, cut mismatch) FS-4 (reverse): Band-false while RecoverA-true (Y as enumerator only — walApplied<Y but LiveTail+barrier hold) TestRecoverA_DualOracle_MutualIndependence: Explicit pin that neither oracle implies the other. This is the minimal expression of the dual-oracle motivation (plan §8.1): keeping both green-by-each-side without forcing either's completion authority on the other. Test status: GREEN — table-driven, no production deps, no I/O. Becomes the green-1 anchor of the §8.1 four-tier red-green ladder that sw + QA will extend (commit 3 stubs are A/B/C skipped pending G0 sub-gates). Source: sw-block/design/recover-semantics-adjustment-plan.md §8.2 (QA-canonical handoff). The 8-case state vectors + oracle function bodies are copied verbatim from §8.2.1 / §8.2.2 / §8.2.3 — sw-side adjustments are gofmt + file-header convention only. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
39cfe1ce84 |
docs(recovery): mirror Tier-1 §IV.2.1 / FS-1 / Gate G0 anchors
Annotation-only pass on the three Tier-1 completion-authority sites
in core/recovery, mirroring the architect's pass on the seaweedfs
weed/storage/blockvol + weed/server side. No logic change — every
predicate remains exactly as before; only doc comments added that
point future migrators at:
sw-block/design/recover-semantics-adjustment-plan.md §1 (the migration plan)
sw-block/design/learn/2026-05-01-recover-target-audit.md Tier 1 (the audit)
v3-recovery-algorithm-consensus.md §IV.2.1 (the new PrimaryWalLegOk contract)
consensus §I P8 (recover(a) vs recover(a,b) distinction)
Sites annotated:
core/recovery/rebuild_session.go:192
TryComplete predicate `walApplied < targetLSN` — historic
recover(a,b) gate; migration target = baseDone ∧
ReplicaWalWitness ∧ coordinator-explicit PrimaryWalLegOk OR
barrier state machine phase.
core/recovery/peer_ship_coordinator.go:273
CanEmitSessionComplete `achievedLSN >= targetLSN` — historic
recover(a,b) gate; migration target = PrimaryWalLegOk(P) under
serializer lock + ReplicaWalWitness reporting at the
BarrierHandshake cut.
core/recovery/sender.go:480-484
Run's CanEmitSessionComplete check + FailureContract on
achieved<target — historic recover(a,b) Run-success predicate;
migration target = baseDone (replica) ∧ PrimaryWalLegOk(P)
(primary WalShipper) ∧ BarrierHandshake; FailureContract
rebound to "lifecycle contract violation" rather than "did
not reach Y".
Build + tests clean (recovery + transport). Tier-1 behavior edits
remain blocked on Gate G0 (T2 predicate name + witness channel
pinning) per recover-semantics-adjustment-plan.md §0.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
25a1be2872 |
test(transport,replication): §6.3 slice-2B Path B test rewrites
Per architect's Path B ruling (2026-04-30), the four §13-era tests
that were skipped during slice-1 are re-authored to §6.3 contracts.
Three pass cleanly; one stays skipped pending deeper integration work.
TestWalShipper_R2_SaturationUnderSustainedLoad
(renamed from TestWalShipper_BacklogStaysBacklog_UnderLoad)
§13-era claim: "mode stays Backlog under saturation". Retired —
§6.3 single drive() collapse removes mode-as-dispatch. Re-authored
to the §6.3 saturation observability contract:
- Slow EmitFunc + pre-seeded substrate (lag ≥ threshold)
- Background writer extends head during scan
- OnSaturation fires single-shot per session
- cursor advances monotonically (INV-MONOTONIC-CURSOR)
- Eventually catches up after writer stops
10× stability locally clean (~5s per run with slow-emit).
TestDualLane_LiveWritesDuringSession_AtomicSeal
Pre-§6.3: per-pusher acceptedSet vs replica.Read; failed ~1/10
runs under §6.3 (concurrent CASE A scans race with producer).
Architect Path B: drop per-pusher cache; assert post-barrier
convergence on backlog + accepted-push LBA range. Cache-data
mismatch can no longer surface; the canonical truth at each
accepted LBA is primary.Read post-barrier.
15× stability locally clean.
TestPillar2B_LiveWrites_HighPressure_BarrierIntegrity
Architect's "DisableTimerDrain + 串行 push" path B variant.
The race surfaced under §6.3 isn't frame-tear; it's a session-
bracket vs in-flight-emit race: drive() emits hold writeMu
briefly per frame, sender's BarrierReq writeMu acquire can
interleave between emits, and receiver may then read the
barrier and return before in-flight push frames arrive. This
is a real §6.3 semantic gap with concurrent push during a
session, NOT a §6.3 correctness bug — the §6.3 model doesn't
bracket per-push barriers (architect's "另开 ADR for per-push
barrier semantics"). Path B explicitly listed serialized
pushes as an acceptable shape: 128 sequential pushes preserve
high-pressure intent without the race.
15× stability locally clean.
TestT4a6_BestEffort_DisconnectThenReassign
STAYS SKIPPED with a more honest §6.3 + walstore-recycle note.
§6.3 auto-fill via substrate (Path B) requires substrate to
retain the entries the new shipper backfills. In this L2
integration test, the second batch's LSNs may be past the
walstore recycle floor by the time the post-reassign shipper
opens with cursor=0; ScanLBAs returns ErrWALRecycled, drive()
treats as transient (cursor stays 0), and CASE B fires with
lsn=61 cursor=0 → tail-gap error. The proper §6.3 contract
here is engine-driven rebuild on WAL-recycled signal, but
that path isn't wired through this test's UpdateReplicaSet
flow. Re-author requires either tuning walstore retention OR
wiring the rebuild-on-recycled escalation; both out of slice-2B
scope. Tracked in §11.9 follow-ups.
5× cross-package sweep (transport / recovery / replication /
replication/component / storage / storage/memorywal /
storage/smartwal) all green post-slice-2B.
Refs: architect Path B ruling 2026-04-30; v3-recovery-algorithm-
consensus.md §6.3 + §6.9 + §11.9. Companion to slice-1
|
||
|
|
8672e63562 |
transport: §6.3 slice-2A — flip LegacyOutOfOrderEmit default to false
Architect ruling 2026-04-30: §6.3 normative tail-gap fail-closed
becomes the default. LegacyOutOfOrderEmit defaults to false in
DefaultWalShipperConfig; new code MUST NOT rely on log+drop-gap
behavior. The shipper does NOT silently emit input bytes for a
missing-LSN case; engine MUST escalate to rebuild.
Test migration to §6.3 fail-closed default (sequential cursor+1
LSNs, production-mirror pattern):
- dual_lane_p2d_profile_test: P2d wire-format dispatch tests
used arbitrary lsn=50/200 for distinctness. Changed to lsn=1
(cursor+1 fast-path); wire-format claims (SWRP preamble vs
frameWALEntry, kind tag) unchanged.
- recovery_sink_adapter_test: post-EndSession context-restore
tests used arbitrary lsn=100/9999. Changed to use
shipper.Cursor()+1 dynamic so fast-path fires; rule-2 context-
restore claim is independent of LSN value.
- walshipper_resident_test (3 phase tests): cross-session
NotifyAppends with lsn={1,2,3} mismatched cursor (StartSession
rewinds cursor to fromLSN=0). Changed to dynamic shipper.Cursor()
+1 per phase.
- ship_sender_test (StaleEpoch_SilentDrop): fresh-epoch sanity
Ship with lsn=2 → cursor=0 mismatch under §6.3. Changed to
lsn=1.
- wal_shipper_executor_test (AdvancesCursor): ships at lsn={10,
20, 15} testing cursor-advances claim. Re-authored to lsn={1, 2,
1 idempotent} — production-mirror dense sequence.
- wal_shipper_executor_test (RegistryStableConcurrent): pre-§6.3
used 8×25 concurrent Ships with random LSNs (header itself
flagged "concurrent Ship is NOT production"). Re-authored per
architect Path B ruling: sequential Ship from one goroutine
(with lossless cursor==maxLSN assertion as the §6.3 contract
permits) + concurrent WalShipperFor lookups (the registry-
stability claim). Concurrency stress preserved on the part that
survives §6.3.
5× consecutive cross-package sweep (transport / recovery /
replication / replication/component / storage / storage/memorywal /
storage/smartwal) all green. No flakes.
Production audit (cmd/blockvolume + cluster.go): both use
NewWalShipper → DefaultWalShipperConfig, now Legacy=false. Production
flow inserts NotifyAppend(lsn==cursor+1) per primary's WAL append
chain — fast-path fires, no tail-gap reachable. If a tail gap ever
surfaces under load (network drop / shipper bug), the engine sees
the error and escalates to rebuild — the explicit §6.3 contract.
Refs: architect ruling 2026-04-30 (Path B + Legacy=false default);
v3-recovery-algorithm-consensus.md §6.3 + §6.9 NEGATIVE-EQUITY.
Companion to slice-1
|
||
|
|
b3826b210d |
transport: §6.3 single drive() collapse — slice 1 (structural)
Refactors WalShipper's dispatch from mode-dispatched (NotifyAppend +
drainOpportunity as separate entry points with mode-keyed bodies) to
the consensus §6.3 single drive(input) function. NotifyAppend +
drainOpportunity become thin wrappers that offer input{has:true,...}
or input{has:false} respectively.
Dispatch (drive holds shipMu for the whole call — single serializer
per peer):
Idle (mode == ModeIdle): drop everything.
Fast-path (in.has + in.lsn == cursor+1 + head <= in.lsn):
Tail-emit input bytes as EmitKindLive. Preserves Realtime hot
path observability — cursor monotonic + no debt + input is the
next LSN means input bytes are canonical-equivalent to substrate;
no scan needed.
CASE A (cursor < head, debt-first per §6.3):
Substrate is canonical. Scan from cursor, emit each entry as
EmitKindBacklog, advance cursor; loop until cursor == head OR
scan exits. Per consensus §13 alignment, this is BACKLOG-DRAIN
semantics even when invoked from a NotifyAppend caller —
"Realtime is reading substrate?" is a misread; the wire kind tag
is Backlog, the dispatch is debt-first. R1 transition runs at the
tail of CASE A under shipMu.
Idempotent skip (in.lsn <= cursor after CASE A): drop.
CASE B (caught up + fresh tail, in.lsn == cursor+1):
Tail-emit input as EmitKindLive.
Tail-gap (in.has + in.lsn > cursor+1 + cursor == head):
Per §6.3 / §6.9 NEGATIVE-EQUITY ban — input MUST NOT replace a
missing LSN. Default fail-closed; engine MUST escalate to
rebuild. LegacyOutOfOrderEmit=true (transitional, see below)
restores pre-§6.3 log+emit.
Config delta:
+ LegacyOutOfOrderEmit (DEPRECATED, transitional):
True restores pre-§6.3 "log + emit input on tail gap"
behavior. Slice-1 default = true (transitional bridge — zero
behavior change for existing callers); slice-2 will flip to
false (§6.3 normative). Documented in field doc + DefaultWal
ShipperConfig comment.
StrictRealtimeOrdering (existing): semantically subsumed by
§6.3 tail-gap fail-closed. Both strict and non-strict (with
Legacy=false) now fail-closed at tail-gap. Kept for production
wiring expressivity; field doc updated.
CONVENTION block at file top: this implementation tracks `cursor` as
LAST-EMITTED LSN; spec §6.3 uses `cursor` as NEXT-TO-EMIT. Translation
in code: spec.cursor == internal.cursor + 1; the check `lsn ==
cursor+1` is identical to spec's `lsn == cursor`. Documented inline
on drive() so reviewers don't flip the bit.
Test migration (3 tests skipped with §6.3-migration notes; will be
re-authored against the new model in a separate slice or removed if
their pre-§6.3 contract is fully retired):
- TestT4a6_BestEffort_DisconnectThenReassign: asserted that a
degraded peer + reassign does NOT silently catch up the
suppressed batch. §6.3 default is automatic substrate-fill on
reattach — pre-§6.3 "best-effort = no auto catch-up" contract is
superseded. Skipped.
- TestWalShipper_BacklogStaysBacklog_UnderLoad: asserted that
Backlog mode persists while writer outpaces drain. §6.3 single
drive() runs CASE A scan to completion under one shipMu acquire;
R1 fires when caught up; Backlog mode is no longer load-bearing
in dispatch. Skipped.
- TestDualLane_LiveWritesDuringSession_AtomicSeal +
TestPillar2B_LiveWrites_HighPressure_BarrierIntegrity: concurrent
pushers race against each other's CASE A substrate scans; the
end replica state is byte-equal-primary post-barrier in the
common case, but the per-pusher acceptedSet vs replica-Read
direct comparison surfaces stragglar LBAs in ~1/10 runs. The
atomic-seal contract holds; the test shape needs re-authoring
to assert replica == primary (which is the same claim AtomicSeal
intended without per-pusher tracking). Skipped.
Updated test (re-authored against §6.3, kept passing):
- TestWalShipper_R2_LagSignalFires: pre-§6.3 the test could pump
1000 NotifyAppends in Backlog mode (lag-only) and observe lag
accumulate. Post-§6.3, NotifyAppend with lsn==cursor+1 takes
fast-path tail emit; cursor advances; lag stays at 0. The new
R2 test pre-seeds substrate (head advances without triggering
drive), then a single trigger NotifyAppend invokes drive() →
CASE A scan whose first emit's updateLag observes lag ≈ 1000 ≥
threshold 500 → OnSaturation fires single-shot. Same INV pinned;
different reach.
5× full cross-package sweep (transport / recovery / replication /
storage) all green — no flakes observed.
Out of scope (slice 2):
- Flip LegacyOutOfOrderEmit default to false (§6.3 normative).
- Migrate skipped tests to §6.3 contracts (or retire them).
- Address the concurrent-pusher race semantics surfaced in
AtomicSeal/Pillar2B at the design level — likely a per-LBA
write barrier on the dual-lane path is the right answer; needs
architect call.
- OpenWALScan stateful iterator (§12.4 #8).
Refs: v3-recovery-algorithm-consensus.md §6.3 send(input,debt) +
§6.9 HOPE-SHIPPER-MONOTONIC + §13 ModeRealtime alignment + §6.10
INV-RECV-* (receiver-side, already landed in
|
||
|
|
df35d07e98 |
test(smartwal): WriteExtentDirect contract pin
smartwal isn't in core/storage/contract_test.go's implementation
matrix (intentional — the experimental subpackage stays
self-contained per its own test header), so the §6.10 BASE bypass
contract was unverified at the smartwal-named level after
|
||
|
|
aa05cff2df |
test(transport): pillar 2 C — deterministic faulty-store failure (was wire-abort race)
§6.10 BASE bypass (commit
|
||
|
|
055fd468a0 |
storage+recovery: §6.10 BASE bypass — WriteExtentDirect + RebuildSession switch
Implements consensus §6.10 (INV-RECV-BITMAP-CORE / INV-RECV-WAL-NAIVE):
BASE lane writes go directly to extent, bypassing the LSN-tracked WAL
apply path entirely. The receiver's per-session bitmap is the sole
arbiter of BASE-vs-WAL conflict at this LBA; substrate stale-skip is
irrelevant for BASE because BASE never enters the WAL.
Substrate contract delta (LogicalStorage):
+ WriteExtentDirect(lba uint32, data []byte) error
Writes one block's bytes to the substrate's extent. No LSN. No
frontier (R/S/H) advancement. Substrate stale-skip / WAL apply
machinery NOT invoked. Receiver pairs with AdvanceFrontier in
MarkBaseComplete to keep post-rebuild frontier reporting honest.
Implementations:
- BlockStore — write to in-memory blocks map; nextLSN/walHead
untouched.
- memorywal — append a record with LSN=0 sentinel; no
retention/nextLSN advance. Receiver bitmap
discipline keeps semantics correct (BASE only
reaches substrate when WAL hasn't touched LBA).
- WALStore — wraps existing private writeExtent; pwrites to
extent file, no WAL append, no dirty-map entry.
- smartwal.Store — pwrites directly to extent at lba's offset; ring
NOT touched, no LSN/frontier advance.
RebuildSession changes:
- ApplyBaseBlock now calls store.WriteExtentDirect(lba, data) instead
of store.ApplyEntry(lba, data, targetLSN). The targetLSN-as-base-LSN
POC compromise (which silently rode substrate stale-skip) is gone.
- MarkBaseComplete now calls store.AdvanceFrontier(targetLSN) — the
explicit frontier-advance that ApplyEntry's side effect previously
provided implicitly. Pre-§6.10, BASE applies bumped walHead per
LBA; now we make the bump explicit at base-done.
Contract test (TestContract_WriteExtentDirect): pins
- WriteExtentDirect succeeds and Read returns the bytes
- Frontier (H) and nextLSN MUST NOT advance (BASE has no LSN)
- Subsequent ApplyEntry at LSN > 0 shadows the BASE bytes
runs against BlockStore-mem / WALStore / MemoryWAL.
Refs: v3-recovery-algorithm-consensus.md §6.10 (INV-RECV-BITMAP-CORE,
INV-RECV-WAL-NAIVE); §6.3 cursor-monotonic sender invariant; mini-plan
§12 design-candidate doc-track.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
c0c84036be |
test(component): pillar 3 slice-2 — same-LBA arbitration on engine-driven path
Mirrors slice-1 (transport-stack only, |
||
|
|
39d57f215a |
test(transport): pillar 3 slice-1 polish per architect review
Non-blocking improvements landed before slice-2:
1. AchievedLSN assertion. Was log-only; now asserts
res.AchievedLSN == post-session primary.H, which is
frozenTarget + len(overwrites) by construction. Tighter than
"achieved >= target" — catches a SessionLive frame that
silently didn't apply (achieved would lag) or barrier ack
drifting past the actually-shipped tail.
2. Convergence assertion now compares replica.Read(lba) against
primary.Read(lba) directly (replica == primary), not just
against the cached bRefs payload. Defence-in-depth: if a
future receiver bug diverges from primary in a way that
"happens to" still match the cache, the primary-direct
comparison catches it. bRefs check retained as test-internal
sanity that the live-write payload itself wasn't dropped.
3. Comment fix: "5× locally" → "10 consecutive runs" to match
what the stability check actually did.
4. Companion-SHA list in the file header now lists
|
||
|
|
cf232f2866 |
test(transport): pillar 3 slice-1 — same-LBA arbitration on transport stack
Mini-plan §11.7 pillar 3 (receiver-side convergence): when the same
LBA is touched by both the backlog (WAL ≤ targetLSN) AND a live
write during the session (WAL > targetLSN flushed at seal), the
replica's final state matches the higher-LSN write. AtomicSeal and
Pillar 2 B both use disjoint LBA ranges (push window > base window),
so neither asserts the arbitration claim.
Single subtest in core/transport/pillar3_convergence_test.go:
TestPillar3Slice1_ReceiverConvergence_LiveOverwritesBacklog_SameLBAs
- Seed primary with 12 LBAs (LBA 0..11, pattern A_i). Sync,
primaryH=12.
- StartRebuild with frozenTarget=12.
- After OnSessionStart: live-overwrite LBA {3, 5, 7} with pattern
B_i (LSN 13/14/15 > frozenTarget → SessionLive path).
- After barrier: untouched LBAs (0,1,2,4,6,8,9,10,11) → seed A;
overwritten LBAs (3,5,7) → live B.
The discriminating assertion is on the overwritten LBAs: a receiver
without proper wire-ordering or apply-order arbitration could leave
those LBAs at A. Convergence to B for all three captures the
INV-PILLAR3-SAMELBA-CONVERGENCE invariant. Verified deterministic
across 10 consecutive runs.
In-scope (slice-1):
- Transport stack only (NewBlockExecutorWithDualLane + real
RecoverySink + runDualLaneListener + real receiver).
- Single arbitration assertion across multi-LBA seed + overwrites.
Out of scope (deferred):
- Full engine/cluster path (component.Cluster.DriveAssignment +
DriveProbeResult) — slice-2 territory.
- §IV T2 (architect-open at consensus §IV) — this slice asserts
barrier semantics under a frozen target only.
- RF > 1, long-duration soak.
- Wire-level frame tap with explicit LSN-monotonicity proof —
convergence here is asserted via post-barrier replica reads;
frame integrity remains transitive (any torn frame → receiver
decode fail → session.Success = false).
Refs: v3-recovery-wal-shipper-mini-plan.md §11.7 pillar 3 (receiver
convergence). Companion to
|
||
|
|
ceac3bfc84 |
test(transport): pillar 2 — fault-injection on the assembled stack (A+B+C)
Mini-plan §11.7 pillar 2: same fault dimensions as C3 fault-injection,
but on the manager-assembled stack (BlockExecutor + PrimaryBridge +
real RecoverySink + recovery.Sender + resident WalShipper +
PeerShipCoordinator under unified replicaID). C3 used a spy
WalShipperSink and net.Pipe; this slice exercises the same robustness
through TCP + real receiver.
Three sibling tests in core/transport/pillar2_assembled_test.go:
A — TestPillar2A_BaseError_AssembledStack_FailReason
faultyReadStorePillar2 wraps the primary; Read fails after 4
successful base-block reads. Asserts: OnSessionClose Success=false
with FailReason wrapping the synthetic error; coord.Phase back to
Idle (EndSession defer ran); replica.R < primary.H (recovered
frontier never reached the target — barrier never fired).
B — TestPillar2B_LiveWrites_HighPressure_BarrierIntegrity
Sibling to TestDualLane_LiveWritesDuringSession_AtomicSeal with
different focus: larger backlog (300 entries) + more pushers
(16 × 8 = 128 attempts) for genuine writeMu contention; stricter
convergence (replica.H == primary.H exactly post-barrier — not
asserted by AtomicSeal). Frame integrity is asserted transitively
through Success=true: any torn frame would fail receiver decode.
Documents wire-tap as a future test-infra follow-up.
C — TestPillar2C_WireAbortMidSession_AssembledStack_RestoresEmitContext
Production-equivalent abort: peer drops connection mid-session
(network failure / replica crash) — startRebuildDualLane uses
context.Background, so wire close is the closest analog to C3's
ctx-cancel test. Snapshots the resident WalShipper's pre-session
emit context, aborts mid-session, asserts post-session snapshot
equals pre (rule-2 restore). Plus: OnSessionClose with FailReason,
coord.Phase=Idle.
What's intentionally out of scope:
- Wire-level frame tap with explicit decode + LSN-monotonicity
(current tests prove integrity transitively).
- Pillar 3 (receiver convergence with live writes during session,
bitmap/barrier interaction, T2 hardware soak).
- streamBase ctx-awareness (C3 #2B variant — separate follow-up).
Refs: v3-recovery-wal-shipper-mini-plan.md §11.7 pillar 2; architect
sign-off "A+B+C 一个 commit"; Phase 0 unified replicaID (
|
||
|
|
cc457c06c4 |
test(recovery): C3 fault-injection — BASE/WAL goroutine pair termination
Three table-shaped subtests covering the failure paths of Sender.Run's BASE ∥ WAL goroutine pair (§6.8 #6 / P6 / G3). Companion to the existing TestC3_BaseWalParallel_FramesInterleave (happy path / overlap claim). #1 BASE error → WAL exits via groupCtx.Done Faulty store fails primaryStore.Read after N reads; streamBase returns a Substrate failure; groupCancel from BASE goroutine unblocks DrainBacklog parked on ctx; spy sink confirms drainCtxErrSeen != nil; lifecycle counters StartSession=1, EndSession=1; Run returns within 2s. #3 Outer ctx cancel → both lanes wind down Caller cancels parent ctx mid-session after WAL goroutine has entered DrainBacklog. Run returns within 2s; coord.EndSession defer fires (Phase back to Idle); sink.EndSession defer fires exactly once; DrainBacklog observed ctx cancellation. #2A WAL error → Run terminates (variant A — narrow) Spy sink returns synthetic error from DrainBacklog. BASE goroutine runs to completion (small store; streamBase is not ctx-aware). Run returns the WAL failure with PhaseBacklog; errors.Is unwraps to the synthetic; lifecycle counters correct. NOT asserted: prompt BASE stop on WAL failure. streamBase has no ctx-check today; variant B (future follow-up) would pair a periodic groupCtx.Err() check inside streamBase's loop with a strict prompt-stop assertion. Test header documents this. Spy WalShipperSink: structural-typing match (no exported types added); records StartSession / DrainBacklog / EndSession call counts; per-test drainBehavior selects immediate / block-until-ctx / synthetic-error. Refs: v3-recovery-wal-shipper-mini-plan.md §11.7 pillar 2 (dual-line execution); architect-recommended scope #1 + #3 + #2A. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
eb4071ed05 |
fix(test): align component cluster harness to replica-%d (Phase 0 prerequisite)
The component harness (cluster.go) constructed dual-lane executors with rid="r-%d" while the engine driver in dual_lane_engine_test.go sent AssignmentInfo / ProbeResult under "replica-%d". Pre-Phase-0- Fix-#1 this silently diverged: bridge keyed coord.PinFloor under "r-N", sink keyed WalShipper writeMu + post-emit RecordShipped under "replica-N". The rebuild barrier completed despite the keying mismatch (replica-driven BarrierResp), so the bug stayed invisible. Now that startRebuildDualLane fail-closes on a mismatched non-empty construction RID (commit |
||
|
|
11392baf41 |
fix(transport): unify replicaID in startRebuildDualLane (Phase 0 Fix #1)
INV-RID-UNIFIED-PER-SESSION: the engine arg replicaID is the single
source of truth for keying coord / WalShipper / sink / bridge for a
recovery session. Pre-fix, startRebuildDualLane built the RecoverySink
with the engine arg but called bridge.StartRebuildSessionWithSink with
the construction-time dl.ReplicaID. If the two diverged, the post-emit
hook keyed coord.RecordShipped under arg while the bridge keyed
coord.PinFloor under dl.ReplicaID — the keys never reconciled, no
error fired, watchdog timed out long after.
Fix:
(a) Fail-closed assert at session entry: non-empty dl.ReplicaID must
equal recovery.ReplicaID(arg). Empty stays permissive (legacy /
test omission; arg flows through unchanged).
(b) Thread argRID through to bridge.StartRebuildSessionWithSink so
coord and sink key uniformly under arg from this point on.
Tests (core/transport/replicaid_unified_test.go):
- TestPhase0Fix1_DriftRejected_FailsClosedAtEntry: non-empty drift
returns error before any wire activity; coord.Phase Idle under
both IDs; OnSessionStart/Close never fire.
- TestPhase0Fix1_HappyPath_ArgEqualsConstructionID: aligned IDs,
full rebuild, frontier converges, coord returns to Idle.
- TestPhase0Fix1_EmptyConstructionRID_ArgFlowsThrough: empty
construction RID bypasses guard; arg keys both bridge and sink;
coord lifecycle observed under arg, never under empty key.
Refs: v3-recovery-execution-institution.md "Entity layering &
assembly contract" Phase 0; v3-recovery-wal-shipper-mini-plan §11.6.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
4f6d5c22e4 |
docs: drainOpportunity comment matches §13 dual-mode contract
Architect code-review caught comment/code mismatch: docstring above drainOpportunity still said "Realtime mode: if cursor < head, scan to fill the gap" — but the implementation correctly returns early when mode != ModeBacklog (matches consensus §13 E-WALSHIPPER-DUAL- MODE / mini-plan §11.2a / T4a no-replay carve-out). Risk this doc-debt prevented: future contributor reads the stale comment, "fixes" the function to scan in Realtime, re-introduces the silent-divergence bug C2 closed (Realtime substrate scan would replay dead-window writes when peer comes back online). Comment now states the dual-mode contract explicitly with a DO-NOT-ADD-A-REALTIME-BRANCH warning citing §13 / T4a / CHK- WALSHIPPER-TIMER-DRAIN's ModeBacklog scope. No code logic change. go test all four packages — PASS. |
||
|
|
843188bd6d |
review-fix: T4a Realtime sequence guard + drainOpportunity TOCTOU
Architect review (offline against §6.8 / §IV / §V) flagged two correctness gaps in C1+C2+C3: 1. NotifyAppend Realtime missing the §6.8 #9 sequence invariant (lsn == cursor + 1). Without it, a caller that drops a notification or races would silently emit out-of-order LSNs leaving permanent gaps on replica (T4a no-replay carve-out means no self-healing in Realtime). 2. drainOpportunity TOCTOU: mode/cursor read under shipMu, then shipMu released before head.Head(). A concurrent NotifyAppend (Backlog lag-only) could shift state between the unlock and the head read. Also two architect-derived doc tightenings: 3. DisableTimerDrain inline doc now states production MUST leave false (§6.8 #4 forbids primary-idle starvation); test-only invariant: shipper MUST NOT linger in cursor < head without alternative drain source. 4. walShipperEntry.writeMu lock hierarchy doc: shipMu → writeMu, never reverse. Fixes: - WalShipperConfig.StrictRealtimeOrdering (default false): tier selector per architect's "production fail-close vs minimum log + monitor" guidance. Default mode logs WALSHIPPER-OUT-OF-ORDER warning + emits anyway (preserves pre-guard test compatibility); strict mode returns explicit error (production opt-in once engine drives rebuild-on-gap). - drainOpportunity now reads mode + cursor + head under one shipMu hold (consistent snapshot), then releases for the heavy ScanLBAs call. Eliminates the TOCTOU window. Tests: + TestC1_Realtime_OutOfOrder_StrictFailsClosed — strict mode rejects lsn != cursor+1 with explicit error. Banned regression anchor: the old `if lsn > cursor + 1 ... drain` check (the dense-edge counterexample architect flagged). - Existing tests preserved by non-strict default mode. Engine- driven dual-lane PushLiveWrite test + T4a6 reassign test now log warning during the brief race window but emit + pass. Existing test renamed: - TestC1_WriteMu_NoInterleave → TestC1_WriteMu_FramesWellFormed (concurrent-NotifyAppend was unrealistic; production callers serialize per-replica via volume.mu; real concurrent-writer coverage lives in TestDualLane_LiveWritesDuringSession_AtomicSeal). go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} — all PASS. Production migration path (separate work): - Engine wires StrictRealtimeOrdering=true once peer churn / UpdateReplicaSet drives rebuild-on-gap (re-anchors WalShipper cursor for the new endpoint). - Fix replicaID consistency in startRebuildDualLane (engine replicaID vs dl.ReplicaID — currently sink uses one, bridge coord uses the other). |
||
|
|
14a0d32d40 |
docs: §6.8 review-derived invariants — DisableTimerDrain + lock order
Architect review of C1+C2+C3 (offline against §6.8 / §IV / §V) flagged two doc gaps that should be inline in the code, not just PR descriptions: 1. DisableTimerDrain (wal_shipper.go WalShipperConfig): - PRODUCTION MUST leave false. §6.8 #4 is MUST: "primary-idle starvation forbidden". Setting true in production violates architect contract. - Test-only invariant: shipper MUST NOT linger in cursor < head without alternative drain source. Today's only users are R2 saturation tests (scope-bounded). 2. Lock hierarchy (executor.go walShipperEntry.writeMu): - shipMu → writeMu (always; reversal risks deadlock). - WalShipper holds shipMu; calls EmitFunc under it; EmitFunc acquires writeMu. - recovery.Sender.writeFrame acquires only writeMu (does not hold shipMu). Order is consistent: shipMu outermost when both in play. No code logic change; documentation tightening so future readers can verify §6.8 mechanical SINGLE-SERIALIZER without re-deriving from grep. go test all four packages — PASS. |
||
|
|
dd370a5367 |
C3: BASE ∥ WAL parallel in Sender.Run (§6.8 #6 / P6 / G3)
Architect §6.8 #6 BASE ∥ WAL WALL-CLOCK OVERLAP: extent/base bulk SHOULD overlap WAL drain where product permits (reduces wall-clock pin exposure). Pre-C3 Sender.Run ran streamBase fully before sink.DrainBacklog — strictly serial. Sender.Run now spawns two goroutines: Base goroutine: streamBase → frameBaseDone → coord.MarkBaseDone WAL goroutine: sink.StartSession → sink.DrainBacklog Both share writeMu via C1 (sink's WriteMu() duck-typing). Frame integrity preserved by mutex-bounded interleaving on the wire — two writers never interleave bytes within a single frame. Wall- clock benefit comes from CPU/IO overlap (substrate scans, encoding, small base-block writes). Coordination: - groupCtx with cancel; first failing goroutine cancels to unblock the other (in particular DrainBacklog observes ctx). - Both error channels collected; first non-nil error returned. - Barrier writes after both goroutines complete (errgroup-Wait pattern via two channels). Note on physical reality: shared writeMu means base waits on slow WAL writes (and vice versa). This is correct serialization. Hard SLO on base under bursty WAL would need a separate credit channel (out of scope §6.8 #6 strict reading; see consensus §6.8 note). Test: + TestC3_BaseWalParallel_FramesInterleave — receiver-side capture parses sender's wire stream into a frame sequence; asserts at least one frameWALEntry appears BEFORE the last frameBaseBlock in that sequence (interleaved progress, not strictly base- then-WAL). Verified: firstWAL index << lastBase index. go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} — all PASS. C1+C2+C3 close §6.8 nine MUSTs: ✓ #1 SINGLE-SERIALIZER (C1: shared writeMu) ✓ #2 ONE TAPE (single shipMu + cursor; substrate is canonical) ✓ #3 PRIORITY (C2: drain in cursor order during Backlog) ✓ #4 TIMER (C2: self-driving Backlog drain) ✓ #5 FRAMING ≠ SECOND TAPE (P2d: profile selects encoder, not tape) ✓ #6 BASE ∥ WAL (C3: errgroup goroutines) ✓ #7 R1 (existing: assertCaughtUpAndEnableTailShipLocked) ✓ #8 R2 (existing: OnSaturation single-shot per session) ✓ #9 send(·,·) consistency (C2: NotifyAppend + drain dispatch) |
||
|
|
78169075c2 |
C2: WalShipper self-driving Backlog drain + DisableTimerDrain config
§6.8 #4 / consensus v3.8 §V CHK-WALSHIPPER-TIMER-DRAIN: Backlog mode must self-drive via periodic timer (or shipper-internal loop) so backlog cannot depend solely on new appends — primary-idle starvation forbidden. Scope (architect framing): - §6.8 #4 TIMER drain applies to BACKLOG mode (recovery session backlog phase). Realtime mode is driven by NotifyAppend (T4a best-effort steady ship). - Realtime NotifyAppend keeps direct-emit semantics (cursor advances 1:1 with caller's lsn). The strict "cursor < head → drain" path in Realtime broke T4a's no-replay invariant (dead-window writes surfaced on a fresh peer post-rebuild — that's T4c territory). WalShipper additions: + EmitKind enum + EmitFunc signature gain `kind` param (delivered in C1's predecessor commit; carried here for completeness). + nudgeCh / stopCh / timerDone goroutine plumbing. + timerLoop runs for shipper's lifetime; stops via Stop() (also called from Stop chan close). + drainOpportunity: scans substrate from cursor, emits in scan order, advances cursor; post-scan R1 transition opportunity (Backlog → Realtime when caught up). + nudgeDrainLocked for sub-IdleSleep wake (collapses multiple nudges into one wake). WalShipperConfig: + DisableTimerDrain (default false) — suppresses the goroutine for tests that need manual DrainBacklog control (R2 saturation tests drive lag without auto-drain interfering). NotifyAppend behavior: - Backlog mode: lag-only (no emit). Drain is the emit path. - Realtime mode: direct emit using caller's data. - Idle mode: silent no-op. Substrate ScanLBAs semantics: - fromLSN passed as cursor directly. memorywal exclusive lower; smartwal inclusive lower; callback's `e.LSN <= s.cursor` filter aligns both. ErrWALRecycled treated as transient (engine layer re-anchors session). Tests: + TestC2_TimerDrainsIdle (CHK-WALSHIPPER-TIMER-DRAIN) — substrate seeded; StartSession(0); timer alone catches up cursor + R1 transitions Backlog → Realtime. NO NotifyAppend or DrainBacklog calls. + TestC2_PriorityOldFirst — drain emits LSN-ascending (oldest first); all kind=EmitKindBacklog (Backlog scan). + TestC2_NoGapDenseLSNEdge — substrate seeded + drained; then a Realtime NotifyAppend for one new entry direct-emits (the dense single-LSN case the user flagged). + TestC2_TimerNudge_FromNotifyAppend — skipped placeholder for future Backlog-mode nudge from external trigger. Existing tests: - TestWalShipper_R2_LagSignalFires / NoSpuriousSignal — added DisableTimerDrain: true so test drives lag manually (auto-drain would catch up and saturation never fires). go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} — all PASS. |
||
|
|
c314b608df |
C1: shared writeMu + post-emit RecordShipped hook (§6.8 #1)
Architect review of |
||
|
|
ad7bc74d3a |
P2d: WalShipper-routed dual-lane rebuild + per-connection wire format
Architect ratification (2026-04-30 §10): dual-lane port emits recovery
frameWALEntry; legacy port keeps MsgShipEntry. Single resident
WalShipper per (volume, replicaID); per-connection format selected by
emit profile on walShipperEntry, switched by recovery session brackets.
Changes:
recovery: export WriteWALEntryFrame(w, kind, lba, lsn, data) — public
helper for transport-side EmitFunc to write the dual-lane WAL frame
format. Wraps internal writeFrame + encodeWALEntry.
transport.WalShipper: EmitFunc signature gains EmitKind parameter.
NotifyAppend Realtime path passes EmitKindLive; DrainBacklog scan
passes EmitKindBacklog. Allows EmitFunc to choose WALKindBacklog
vs WALKindSessionLive on the dual-lane wire.
transport.BlockExecutor:
+ EmitProfile { SteadyMsgShip, DualLaneWALFrame }
+ walShipperEntry.emitProfile field (atomic with conn + lineage)
+ EmitFunc dispatches on profile + kind:
SteadyMsgShip + any kind → MsgShipEntry (SWRP envelope +
EncodeShipEntry)
DualLaneWALFrame + Live → frameWALEntry(WALKindSessionLive)
DualLaneWALFrame + Backlog → frameWALEntry(WALKindBacklog)
+ EmitFunc treats nil conn as silent drop (matches Idle-mode
semantics; avoids racing against session-bracket installation
when callers inject live writes via PushLiveWrite during the
WalShipperFor → sink.StartSession window)
- updateWalShipperEmitContext takes profile param
- SnapshotEmitContext returns profile too
- Ship() passes EmitProfileSteadyMsgShip to preserve legacy wire
transport.RecoverySink:
+ NewRecoverySinkWithProfiles for explicit profile control
+ sessionProfile / steadyProfile fields
+ StartSession installs session profile (default: DualLaneWALFrame)
+ EndSession seals the sink (sealed=true under sealMu) FIRST, then
restores steady context. Matches senderBacklogSink.flushAndSeal
contract — post-EndSession NotifyAppend returns ErrSinkSealed
(clean "session is closing" signal during the window between
session-end and bridge-map-removal).
transport.startRebuildDualLane (production hot path):
- Snapshots steady (conn, lineage, profile) before constructing sink
- Builds RecoverySink with session profile=DualLaneWALFrame
- Calls bridge.StartRebuildSessionWithSink (replaces
StartRebuildSession with bridging sink)
Result: WalShipper handles both backlog drain (DrainBacklog) and
live writes (NotifyAppend) during the session, on the dual-lane
port, in recovery wire format. EndSession restores steady context
(legacy port + MsgShipEntry).
Tests:
+ TestP2d_EmitDispatch_SteadyMsgShipProfile — wire bytes start with
SWRP magic + msgType=MsgShipEntry.
+ TestP2d_EmitDispatch_DualLaneWALFrameProfile_LiveKind — wire
bytes are recovery frame format with WALKindSessionLive tag.
+ TestP2d_EmitDispatch_DualLaneWALFrameProfile_BacklogKind —
DrainBacklog scan emits with WALKindBacklog tag.
+ TestRecoverySink_NotifyAppendAfterEndSession_Sealed — post-
EndSession NotifyAppend returns ErrSinkSealed.
Existing E2E coverage (now routed through WalShipper):
- TestDualLane_BlockExecutor_StartRebuild — byte-equal post-rebuild
(profile dispatch correct → receiver decodes → bytes land).
- TestDualLane_LiveWritesDuringSession_AtomicSeal — 40 concurrent
pushes, all byte-equal on replica.
- TestDualLane_EngineDrivenRebuild_HappyPath +
TestDualLane_EngineDrivenRebuild_WithPushLiveDuringSession
(component-level engine→adapter→executor→bridge full chain).
Cluster gains BlockExecutor(replicaIdx) accessor for component tests
that exercise dual-lane bridge surfaces.
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS, no regressions.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
a96373dda9 |
transport: pin protection + ack-feedback advance + release tests
Pins the user-stated architectural invariant:
Steady: WalShipper handles NotifyAppend (recv) + emit (peer).
Recovery session: pin floor PROTECTED at fromLSN so substrate WAL
retention can't recycle entries the session still needs.
Pin advances via FEEDBACK: replica BaseBatchAck → recovery.Sender
readerLoop → coord.SetPinFloor → pin advances; substrate may
now recycle below the new floor.
Session end: pin released.
Tests:
+ TestPin_ProtectedDuringSession_AdvancesViaFeedback_ReleasedOnEnd —
full single-replica lifecycle:
1. coord.StartSession → pin = fromLSN
2. RecoverySink.StartSession → WalShipper Backlog;
pin still = fromLSN (shipper mode change must NOT move pin)
3. coord.SetPinFloor(replica, ackLSN, S) — simulates
readerLoop's BaseBatchAck translation; pin advances
4. Out-of-order lower-LSN ack: pin must NOT regress
5. RecoverySink.EndSession → shipper Realtime;
pin survives (sink.EndSession is shipper-side, doesn't
release coord pin)
6. coord.EndSession → pin released to 0
+ TestPin_MultiSession_MinPinAcrossActiveSessions — cluster-wide
invariant: WAL retention gated by min pin across all active
sessions. Slow replica's pin floors the whole cluster; fast
replicas advancing past it don't unlock recycling. After all
sessions end, anyActive=false and no floor is enforced.
Together these confirm the user's architecture: WalShipper-side
mode transitions and coord-side pin lifecycle are orthogonal —
sink.EndSession ≠ session-pin-release; only coord.EndSession
releases. Production callers (recovery.Sender.Run defer) call BOTH
on every exit path, which is what the existing wiring already does.
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (no regressions; 2 new tests).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
822d8414f1 |
transport: WalShipper-as-resident integration tests
Pins the algorithmic invariant the user named in §10 framing:
WalShipper 常驻; recovery 时是 Backlog; 追平后仍在同一实例上变成
Realtime, 再接 steady 的 NotifyAppend.
One resident WalShipper per (volume, replicaID); steady ship and
recovery sessions share the SAME instance; mode transitions are
internal to the shipper; the recovery session is just a bracket
(StartSession / EndSession) around it.
Tests:
+ TestWalShipper_Resident_SameInstanceAcrossSessions —
INV-SINGLE: WalShipperFor returns the same instance during
and after multiple consecutive RecoverySink-bracketed sessions
on the same replica.
+ TestWalShipper_Resident_ModeTransitionsAcrossSessions —
pins the cycle: Realtime → (StartSession) → Backlog →
(DrainBacklog R1) → Realtime → (EndSession) → Realtime,
repeatable across consecutive sessions.
+ TestWalShipper_Resident_SteadyShipBetweenSessions — full
timeline: steady NotifyAppend → recovery session 1 → steady
NotifyAppend → recovery session 2 → steady NotifyAppend.
Recording EmitFunc captures all emits; verifies the three
steady-phase emits use steady lineage (rule 2 holds across
multiple bracket cycles).
+ TestWalShipper_Resident_NotifyAppendDuringSession_BacklogMode —
while a session holds the shipper in Backlog mode, concurrent
steady NotifyAppend calls are lag-only (no emit). After
EndSession, post-session NotifyAppend emits normally under
restored steady context. Pins the mode-decision boundary.
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (no regressions; 4 new tests).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
946dee3031 |
transport: dual-lane E2E failure-path coverage
Three failure-mode tests pinning clean teardown across the full
StartRebuild → bridge → Sender → wire stack:
+ TestDualLane_ReplicaListenerStopped_BeforeRebuild — listener
closed before dial; StartRebuild surfaces the dial error
synchronously; coordinator never advances past Idle (session
never registered).
+ TestDualLane_ReplicaListenerStopped_MidSession — listener
accepts and immediately closes the conn (no Receiver behind it);
Sender's first writeFrame fails with Wire failure; OnSessionClose
fires Success=false; coordinator returns to Idle via Sender.Run's
deferred coord.EndSession; PrimaryBridge's senders entry torn
down (subsequent PushLiveWrite returns "no active session").
+ TestDualLane_SubsequentRebuild_AfterFailure_Succeeds — regression:
after a failed rebuild teardown, a fresh rebuild on the same
replica with a healthy listener succeeds end-to-end. Verifies
registry / coordinator state is genuinely cleaned, not just
dead-but-still-occupying-slots.
This pins the deferred-EndSession contract at the integration level:
no matter how Sender.Run exits (success, wire error, ctx cancel),
both sink.EndSession and coord.EndSession fire — observable as
PrimaryBridge sender-map cleanup + coordinator Idle.
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (no regressions; 3 new tests).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
e2cde75d43 |
transport: dual-lane E2E with concurrent live writes during session
Closes the test gap the recovery package's e2e_test.go disclaimed at
the dual-lane (cross-process-shape) level: live writes pushed via
PrimaryBridge.PushLiveWrite during an active dual-lane rebuild
session, exercising senderBacklogSink.flushAndSeal's atomic-seal
boundary on the real TCP wire.
Tests:
+ TestDualLane_LiveWritesDuringSession_AtomicSeal — full chain:
StartRebuild → engine→adapter→executor (dual-lane) → bridge →
Sender.Run → streamBacklog (100 backlog LBAs) + flushAndSeal +
barrier; concurrently 8 workers × 5 = 40 pushers via
bridge.PushLiveWrite. Asserts the atomic-seal contract:
every push that returned nil MUST be byte-equal on replica.
Verified: 40/40 pushes accepted, all on replica.
+ TestDualLane_LiveWritesDuringSession_AchievedLSN — sanity
lower bound: achievedLSN >= frozenTarget after backlog drain.
+ TestDualLane_PushLiveWrite_NoSession_Errors — bridge guard:
PushLiveWrite without an active session returns an explicit
"no active session for replica" error.
Substrate: memorywal on primary so live writes get LSN > frozenTarget
and streamBacklog filters them for flushAndSeal to ship as
WALKindSessionLive (BlockStore's walHead-synthesized LSN would have
collapsed all backlog entries past targetLSN under concurrent
primary.Write). Replica stays BlockStore.
This is G7 §2 #4 (concurrent writes during rebuild) in scope as the
architect ratified — the dual-lane bridging path now has end-to-end
coverage of that scenario, independent of P2d.
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (no regressions; 3 new tests).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
de2dceaf32 |
recovery+transport: pre-decision integration helpers (P2d-parallel)
Two parallel-safe wiring helpers that don't lock in the dual-lane
wire-body format (P2d still architect-gated) but unblock the
production wiring sequence so the format swap, when it lands, is
mechanical.
transport.BlockExecutor.SnapshotEmitContext(replicaID):
- Accessor that returns the per-replica WalShipper's current
(emitConn, emitLineage) under emitCtxMu — same lock discipline
as production EmitFunc.
- Honest signal when no entry exists: returns (nil, zero) so
callers can pass through to NewRecoverySink as the steady-
restore values without a special case.
- Canonical caller pattern (P2d-post): snapshot BEFORE
constructing RecoverySink → pass to NewRecoverySink as the
steady context → EndSession's rule-2 restore lands the right
values.
recovery.PrimaryBridge.StartRebuildSessionWithSink(...):
- New entry point that accepts an external WalShipperSink (e.g.,
transport.RecoverySink wrapping the per-replica WalShipper).
- Existing StartRebuildSession unchanged — continues to use the
bridging senderBacklogSink path (legacy compatible).
- Internal startRebuildSessionLocked is shared between the two
public methods; switches between NewSenderWithBacklogRelay and
NewSenderWithSink based on whether sink is nil.
- Fail-closed: nil sink → explicit error (callers that want the
bridging path call StartRebuildSession explicitly).
Tests:
+ TestSnapshotEmitContext_NoEntry_ReturnsZero
+ TestSnapshotEmitContext_AfterUpdate_ReturnsCurrent
+ TestSnapshotEmitContext_ThenRecoverySink_RestoresCaptured —
end-to-end of the canonical wiring pattern: snapshot → build
sink with snapshotted steady → run session → assert restored
context matches snapshot.
+ TestPrimaryBridge_StartRebuildSessionWithSink_NilRejected
+ TestPrimaryBridge_StartRebuildSessionWithSink_InvokesSinkLifecycle —
sink receives StartSession + DrainBacklog + EndSession in order
when invoked through the bridge's public surface.
+ TestPrimaryBridge_StartRebuildSession_StillUsesBridgingSink —
regression: legacy entry point still installs senderBacklogSink.
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (incl. existing test suite, no regressions).
Production enable still requires P2d (wire body format / applier
owner / replay source). These helpers are "ready but not switched
on" — calling StartRebuildSessionWithSink today would produce a
wire-format mismatch on the dual-lane port (executor's EmitFunc
encodes MsgShipEntry; recovery.Receiver decodes frameWALEntry).
The §10 decision request on seaweedfs/feature/sw-block resolves
that.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
bb36a601b8 |
transport: RecoverySink — review-feedback doc tightening
Three doc-only follow-ups from architect code review of
|
||
|
|
845c81071d |
transport: RecoverySink adapter scaffolding + rules-1+2 tests
Pre-decision parallel work for P2d (per architect ratification): the
transport-side adapter that satisfies recovery.WalShipperSink by
duck typing, plus integration tests that pin architect P1 review
rules 1+2. No wire-format branching — the adapter inherits whatever
EmitFunc executor.WalShipperFor wired in. P2d resolves MsgShipEntry
vs frameWALEntry; this adapter survives that decision either
unchanged (if "unify on MsgShipEntry") or via swap of the underlying
shipper construction (if "use frameWALEntry on dual-lane port" or
envelope tag).
RecoverySink:
- NewRecoverySink(executor, replicaID, sessionConn/Lineage,
steadyConn/Lineage)
- StartSession: updateWalShipperEmitContext(session) BEFORE
WalShipper.StartSession (rule 1)
- DrainBacklog / NotifyAppend: thin delegate
- EndSession: WalShipper.EndSession FIRST, then
updateWalShipperEmitContext(steady) (rule 2)
Tests (lifecycle ordering only — no wire decode):
+ TestRecoverySink_StartSession_InstallsSessionContext —
direct post-condition, white-box check on entry.emitConn /
emitLineage after StartSession returns.
+ TestRecoverySink_DrainBacklogEmits_UseSessionContext —
rule 1 indirect: install recording EmitFunc; assert every
backlog drain emit captures session context. Stale context
would surface immediately on the first drain emit.
+ TestRecoverySink_EndSession_RestoresSteadyContext —
rule 2 direct: post-EndSession entry context == steady.
+ TestRecoverySink_NotifyAppendAfterEndSession_UsesSteadyContext —
rule 2 indirect: post-EndSession Realtime emit captures
steady context at emit time.
+ TestRecoverySink_FullLifecycle — combined ordering across
StartSession → DrainBacklog → EndSession → post-session
NotifyAppend; each phase's emits use the expected context.
+ TestRecoverySink_SatisfiesWalShipperSink — compile-time
duck-type check via locally re-declared interface (no
recovery import to keep cycle-free option open).
Recording EmitFunc strategy: replace per-replica WalShipperEntry's
shipper with a fresh one whose EmitFunc reads emitConn/emitLineage
under emitCtxMu (same lock discipline as production) and records
into a slice. This captures the at-emit-time context — the only
honest evidence of rule-1 / rule-2 ordering without coupling to
wire format.
go test ./core/transport/ ./core/recovery/ ./core/replication/{,component} —
all PASS (incl. existing test suite, no regressions).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
8f51ec6f29 |
recovery: P2c-B-2 — delete Close/closeCh/liveQueue/drainAndSeal
Buffer state moves into senderBacklogSink (sinkMu / queue / sealed
fields, flushAndSeal method); Sender no longer owns any live-write
scaffolding. Sender.Run flow becomes:
StartSession → BaseLane → BaseDone → sink.StartSession →
sink.DrainBacklog → barrier → return
DrainBacklog (in the bridging sink) does scan + flushAndSeal +
seal atomically — sender.Run barriers as soon as it returns.
There is no engine "go barrier" signal anymore; the previous
sender.Close / closeCh / FinishLiveWrites pattern is gone.
Atomic-seal contract migrates from sender.drainAndSeal (queueMu)
to senderBacklogSink.flushAndSeal (sinkMu): NotifyAppend that lands
before the seal lock is captured + shipped; pushes after see
"sink sealed" error. EndSession is the defer-safety net (idempotent
seal so post-Run NotifyAppend still gets explicit error).
Deleted from Sender:
- Close(), closeCh, closeOnce
- queueMu, liveQueue, sealed, walItem
- drainAndSeal, bufferLiveWriteLocked
- PhaseAwaitClose
Deleted from PrimaryBridge:
- FinishLiveWrites (engine→sender "go barrier" signal no longer
needed — barrier auto-fires after DrainBacklog)
Updated:
- transport/rebuild_sender.go: drop FinishLiveWrites call
- sender.Run defer: just sink.EndSession + coord.EndSession
- failure.go: remove PhaseAwaitClose
Tests rewritten per architect rule 3 (delete scaffolding once e2e
cases that inject mid-session writes pass barrier convergence
through the new path):
e2e_test.go:
- 5 sender.Close() calls removed
- TestE2E_RebuildWithLiveWritesDuringSession: push live writes
BEFORE sender.Run starts — sink buffers under sinkMu until
flushAndSeal ships them
- TestE2E_KindCountsPinsBacklogVsLive: substrate switched to
memorywal (preserves write-time LSN) so push-before-Run
preserves LSN > frozenTarget filter discipline; BlockStore's
walHead-synthesized LSN would have shifted under push-before
- TestE2E_PushLiveWriteAtomicSeal: race window is now between
pushers and sink's flushAndSeal seal point; contract holds
integration_stub_test.go:
- TestIntegrationStub_LifecycleCallbacks: drop FinishLiveWrites
- TestIntegrationStub_CtxCancelUnblocksSender: skipped — no
idle wait window to cancel into post-B-2
- TestIntegrationStub_FailureTypedOnCancellation: skipped —
same reason
sender_walshipper_sink_test.go:
- TestSenderBacklogSink_NotifyAppend_BuffersForFlushAndSeal:
white-box accessor now reads sink's queue (was sender's)
- var _ WalShipperSink = &senderBacklogSink{} (pointer receiver)
- TestSender_WithSink_DelegationOrder: drop sender.Close;
Run barriers autonomously after DrainBacklog returns
Verified: all recovery (incl. 5 e2e) + transport + replication +
replication/component tests PASS. Net deletion: -175 lines.
Note: dual-lane frameWALEntry vs MsgShipEntry alignment remains
P2d. The bridging senderBacklogSink stays as the in-package sink
until then; once a real transport.WalShipper sink replaces it,
the buffer + flushAndSeal scaffolding here goes too.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
bf84ed4ab1 |
recovery: P2c-B-1 — single live path via sink.NotifyAppend (TDD)
Add NotifyAppend(lba, lsn, data) error to WalShipperSink interface.
Sender.PushLiveWrite now routes through s.sink.NotifyAppend instead
of touching liveQueue directly — the sink owns buffering / ordering
discipline.
Bridging path (senderBacklogSink) implements NotifyAppend by
buffering into the sender's liveQueue under queueMu — production
discipline (architect rule 2). streamBacklog is one-shot ScanLBAs;
direct wire emit during the scan would interleave LSNs and break
the receiver's monotonic-LSN check, so the buffer + ordered
drainAndSeal flush stays as the safety net until P2d aligns the
dual-lane wire format.
When P2d swaps in a real transport.WalShipper sink, NotifyAppend
will route to WalShipper.NotifyAppend (Backlog mode lag-tracking;
Realtime direct ship under shipMu) — at that point the queueMu /
liveQueue / drainAndSeal scaffolding can be deleted (slice B-2).
Tests:
+ TestSender_PushLiveWrite_RoutesViaSinkNotifyAppend — RED→GREEN,
pins the routing contract (incl. error propagation from sink).
+ TestSenderBacklogSink_NotifyAppend_BuffersForDrainAndSeal — pins
the bridging-path buffer discipline.
recordingSink in tests gains NotifyAppend + snapshotNotifyAppend.
Verified:
- go test ./core/recovery/ — all PASS, including 5 e2e tests
(PushLiveWriteAtomicSeal exercises mid-session writes and
barrier convergence end-to-end).
- go test ./core/transport/ ./core/replication/{,component} — all PASS.
Note: dual-lane frameWALEntry vs MsgShipEntry alignment remains P2d;
backlog relay continues as the bridging sink until then.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
616583fc38 |
recovery: P2c-A — sink mandatory; remove legacy Run() else branch
Slice A (mechanical, dead-code removal):
- NewSenderWithSink panics on nil sink (was: silent promote to legacy)
- NewSender → private newSender (only used by sink-installing
constructors as builder)
- Run() drops the `if s.sink != nil { ... } else { legacy }` split;
sink path is unconditional. INV-NO-DOUBLE-LIVE at recovery layer
is now a structural guarantee (one emit path, not a runtime check)
- TryAdvanceToSteadyLive call site removed (kickoff Q3 collapsed
Phase enum to {Idle, Active}; barrier-ack is the completion
signal)
Kept for slice B per architect framing:
- Close, drainAndSeal, liveQueue, sealed, closeCh, queueMu, walItem
- PushLiveWrite (still feeds session-lane tails until live writes
route through WalShipper.NotifyAppend)
- streamBacklog (called by senderBacklogSink.DrainBacklog)
Tests:
+ TestNewSenderWithSink_NilSinkPanics — locks sink-mandatory contract
- TestSender_NoSink_FallsBackToLegacyBehavior — replaced by panic test
go test ./core/recovery/ ./core/transport/ — all PASS.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
ee60eb0ced |
recovery: P2b — backlog relay sink + e2e migration
Sender's WAL pump now flows through a sink in P2b too — but via a
backlog-relay adapter that keeps the same frameWALEntry wire
behavior as legacy streamBacklog. This keeps the receiver path
(decoder + RebuildSession.ApplyWALEntry on dual-lane port) untouched.
Real rewind / transport.WalShipper integration is P2d (which also
wires the dual-lane / receiver decoding alignment).
Why a relay-not-real-WalShipper for P2b:
Recovery's receiver consumes frameWALEntry on the dual-lane port.
transport.WalShipper writes MsgShipEntry on the executor's legacy
port. Plugging transport.WalShipper directly into recovery.Sender
in P2b would mean wire-format mismatch + receiver dispatch break.
The intentional shim is `senderBacklogSink` (DrainBacklog →
streamBacklog) — sink-shape API, same wire bytes.
Changes:
sender.go:
+ senderBacklogSink — adapts streamBacklog() to WalShipperSink:
StartSession / EndSession are no-ops (real rewind stays in
transport.WalShipper for P2d); DrainBacklog calls the existing
streamBacklog() in-place.
+ NewSenderWithBacklogRelay(primary, coord, conn, replicaID) —
constructs sender with senderBacklogSink{s: s}. Used by all
existing e2e + integration callers in P2b.
Sink-mode Run() flow: after sink.DrainBacklog returns nil, the
legacy `<-closeCh` wait + drainAndSeal still run so
PushLiveWrite session-lane entries (the existing test
scenario that injects post-target writes) keep converging.
P2c can move session-live into NotifyAppend once transport
WalShipper is wired.
NewSenderWithSink doc updated to reflect the closeCh + drainAndSeal
retention until P2c.
e2e_test.go:
All NewSender(...) → NewSenderWithBacklogRelay(...). No assertion
changes; same e2e shape, sink-mode path now exercised end-to-end.
integration_stub.go:
PrimaryBridge uses NewSenderWithBacklogRelay so the
bridge-shaped lifecycle (StartRebuildSession + PushLiveWrite +
FinishLiveWrites) still works through the sink branch.
sender_walshipper_sink_test.go:
+ TestSender_WithSink_DelegationOrder: spawns a goroutine that
`sender.Close()` after `<-sink.drainCalledCh` so sink-mode
Run unblocks past the closeCh wait and reaches sink.EndSession +
barrier path (otherwise drainCalledCh never fires).
+ TestNewSenderWithBacklogRelay_installsRelaySink: smoke test
that the new constructor installs senderBacklogSink and the
type satisfies WalShipperSink (compile-time check).
Lint fix: remove sync/atomic copy from earlier scaffolding.
Header comments clarified for P2 stage progression.
Test sweep:
go test ./core/recovery/... → all PASS (legacy path + sink path
both exercised; e2e tests now run via the relay sink).
go test ./core/transport/... → all PASS (no transport changes
in P2b).
go test ./core/replication/... ./core/replication/component/...
→ all PASS.
Roadmap note (architect-aware):
P2c — make sink required; delete legacy NewSender pump (streamBacklog
+ closeCh + drainAndSeal + PushLiveWrite + liveQueue + sealed
+ queueMu + walItem + Close). Sink-mode Run is already the
future shape; legacy path is deletable when no caller relies
on Close + drainAndSeal.
P2d — wire transport.WalShipper into recovery.Sender by aligning
wire format (dual-lane vs legacy port) at receiver decoding.
Then NewSenderWithBacklogRelay can be retired in favor of
NewSenderWithSink(real walShipperAdapter). Transport-layer
integration tests for architect rules 1+2 (updateContext
before StartSession; restore after EndSession) land here.
|
||
|
|
04b0bb2fc4 |
recovery: P2a — WalShipperSink interface + Sender delegate (TDD)
Per v3-recovery-wal-shipper-mini-plan.md §3 P2 — "Drain API wired
from recovery.Sender; delete/disable recovery/sender duplicate
pump". P2a is the smallest green-on-merge step: introduce the
sink, make Sender accept it as OPTIONAL, branch Run() based on
presence. P2b/c migrate existing tests + delete legacy pump.
Architect 2026-04-29 P1 review ratification: "Proceed with P2 TDD
as you outlined, and keep these two integration rules explicit
in tests:
1. updateWalShipperEmitContext(replicaID, sessionConn,
sessionLineage) before StartSession.
2. After EndSession, restore whatever lineage conn Ship will
use, or the next steady emit will use stale recovery
lineage on the wire."
Rules 1 + 2 are caller obligations and live in transport (P2d).
P2a establishes the SINK interface contract that those rules
plug into.
WalShipperSink interface (core/recovery/sender.go):
type WalShipperSink interface {
StartSession(fromLSN uint64) error
DrainBacklog(ctx context.Context) error
EndSession()
}
Lives in core/recovery to avoid import cycle (transport
imports recovery for ReplicaID etc.). transport.WalShipper
satisfies it via duck typing.
Boundary docstring spells out architect rules 1+2 as caller
obligations; Sender does not enforce them.
Sender constructor:
NewSender(...) — legacy path (sink == nil; Run uses
streamBacklog/closeCh/drainAndSeal).
P2c removes this path.
NewSenderWithSink(..., sink) — sink-mode path (Run delegates).
Defensive: nil sink promotes to
NewSender so behavior is predictable.
Run() branching:
if s.sink != nil:
defer s.sink.EndSession() // always-cleanup defer FIRST so
// it fires on every exit path
// (success, StartSession err,
// DrainBacklog err, barrier err).
s.sink.StartSession(fromLSN)
s.sink.DrainBacklog(ctx)
// skip TryAdvanceToSteadyLive (kickoff Q3 collapse:
// {Idle, Active}; barrier-ack is the only completion signal)
else:
// LEGACY: streamBacklog → closeCh wait → drainAndSeal →
// TryAdvanceToSteadyLive (P2c removes)
Failure mapping for sink errors:
sink.StartSession err → FailureContract @ PhaseBacklog
sink.DrainBacklog err (ctx) → FailureCancelled @ PhaseBacklog
sink.DrainBacklog err (other) → FailureSubstrate @ PhaseBacklog
Test (TDD, sender_walshipper_sink_test.go):
TestSender_WithSink_DelegationOrder
- recordingSink mock captures call order
- Run sender (with deliberately non-converging setup so test
doesn't depend on barrier success)
- Assert: sink.callOrder = [StartSession, DrainBacklog, EndSession]
- Assert: startCalls/drainCalls/endCalls all 1 (always-cleanup)
- Assert: fromLSN argument forwarded to sink.StartSession
Other sink-test scaffolds (NoSink_FallsBackToLegacy,
WithSink_DelegatesStartSession, WithSink_EndSessionAlwaysCalled,
WithSink_StartSessionFailureAborts, WithSink_NoStreamBacklog
Reachable) marked t.Skip — they will be filled in as P2b/c
delete the legacy path and provide the e2e harness for sink-
driven WAL pump.
Test infrastructure:
recordingSink — mock with mutex-guarded call log; also has
shipDuringDrain hook + drainBlocksUntil channel
for P2b's e2e tests where the sink does pump
WAL via the test wire.
Test deadlock fix (caught during impl):
receiver returning error didn't close replicaConn → sender's
readerLoop blocks forever reading. Fixed by closing replicaConn
immediately after receiver.Run returns in the test goroutine.
Documented in test comments.
Test sweep:
go test ./core/recovery/ -run "TestSender_WithSink_DelegationOrder"
→ PASS (0.00s).
go test ./core/recovery/ ./core/transport/ -count=1
→ all PASS (no regression on legacy path, including existing
e2e tests that still use NewSender / sender.Close /
PushLiveWrite — those keep working in P2a).
Next:
P2b — migrate existing e2e tests (TestE2E_RebuildHappyPath etc.)
to NewSenderWithSink + a real walShipper / passthrough
sink. Required before P2c.
P2c — make sink required; delete streamBacklog, drainAndSeal,
PushLiveWrite, liveQueue, sealed, closeCh, queueMu,
walItem, Close.
P2d — transport-layer integration tests for architect rules
1 (updateContext before StartSession) and 2 (restore
after EndSession). Wire BlockExecutor.startRebuildDualLane
to call updateWalShipperEmitContext + walShipper.StartSession.
|
||
|
|
f905ef40fa |
transport: P1 architect review fixes — encoding seam + test scope
Architect P1 review (2026-04-29 of commit
|
||
|
|
0d3e3795d2 |
transport: P1 — BlockExecutor WalShipper registry + Ship delegate
Per v3-recovery-wal-shipper-mini-plan.md §3 P1, with TDD discipline
(tests first, impl drives by failing tests):
Tests written first (wal_shipper_executor_test.go, RED phase):
TestBlockExecutor_WalShipperRegistry_GetOrCreate
spec §3 INV-SINGLE — WalShipperFor idempotent get-or-create;
different replicaIDs get distinct instances; concurrent calls
for same replicaID linearize through walShipperMu.
TestBlockExecutor_Ship_AdvancesWalShipperCursor
Ship() delegates to per-replica WalShipper. Observable via
cursor advancing per Ship call. Idempotent Ship with lsn ≤
cursor (NotifyAppend's idempotent-skip path) does NOT regress
cursor.
TestBlockExecutor_WalShipperFor_StableUnderConcurrent_Ship
Strong INV-SINGLE under load — 8 writer goroutines × 25 Ships
each (200 distinct LSNs) all funnel through the same shipper
instance; cursor reaches max LSN.
3a coverage (architect 2026-04-29 ratification): "仅 Ship 只走
WalShipper (mock transport)". Mock here is net.Pipe with
io.Copy(io.Discard, replicaConn) — Ship's wire writes succeed,
test asserts on cursor advancement (the delegation observable).
3b deferred per architect to nightly: "Sender + Ship integration
冒烟" (cross-component INV-NO-DOUBLE-LIVE). Will be added when
P2 wires recovery.Sender to call walShipper.StartSession /
DrainBacklog (replacing its own streamUntilHead).
Implementation (driven by failing tests):
core/transport/executor.go:
+ walShipperMu sync.Mutex
+ walShippers map[string]*walShipperEntry
+ walShipperEntry struct { shipper *WalShipper; emit conn ctx }
+ WalShipperFor(replicaID) *WalShipper — get-or-create; on
create, the EmitFunc closes over entry.emitConn (mu-guarded
pointer that Ship updates per-call)
+ updateWalShipperConn(replicaID, conn) — Ship's per-call
hook to set the conn the EmitFunc will use
core/transport/ship_sender.go:
Modified Ship():
- Lineage validation + epoch fence + lazy dial: UNCHANGED.
- After conn resolved + payload encoded: delegate to
WalShipperFor + updateWalShipperConn + NotifyAppend.
- The walShipper's EmitFunc does the WriteMsg under shipMu
(INV-NO-DOUBLE-LIVE at the wire path).
No behavior change for callers: Ship's signature, return
semantics (silent-drop on stale epoch, error on dial/write
failure, nil on success) all preserved.
Architectural notes:
- WalShipper.Activate(0) at first WalShipperFor — Realtime mode
immediate. First Ship's lsn > 0 emits cleanly.
- emitConn is mutable per-Ship: caller's session conn may change
over time (lazy dial, session re-attach). EmitFunc reads under
entry.emitCtxMu so mutations are visible.
- Idempotent NotifyAppend (lsn <= cursor) returns nil silently;
Ship caller can't distinguish from successful emit. Acceptable
for fire-and-forget contract.
Test sweep (TDD GREEN):
go test ./core/transport/ -run "TestBlockExecutor_(WalShipper|Ship_)"
→ 3 PASS, 0 FAIL.
Wider sweep:
go test ./core/transport/ ./core/recovery/ ./core/storage/...
./core/replication/component/ ./core/replication/
→ all PASS — no regression in existing executor / recovery /
storage / replication tests.
LOC delta:
+ executor.go ~70 LOC (registry struct + WalShipperFor +
updateWalShipperConn)
~ ship_sender.go ~10 LOC change (delegate via NotifyAppend)
+ wal_shipper_executor_test.go ~250 LOC (3 tests)
Next: P2 — recovery.Sender drops streamUntilHead/PushLiveWrite/
drainAndSeal; calls walShipper.StartSession + DrainBacklog
instead. TDD again, write tests first against the new
"recovery.Sender does NOT own WAL pump" contract.
|
||
|
|
c3d8907725 |
transport: WalShipper P0 cleanup per architect signoff
Architect 2026-04-29 P0 review: signed off, two doc-vs-impl mismatches
to fix + one dead-code cleanup. All comment / dead-field changes; zero
behavior change.
(1) EmitFunc docstring (line ~46-48):
Was: "Returning an error transitions WalShipper to Backlog (or
stays Backlog if already there) and aborts the current emit"
Reality: NotifyAppend in Realtime returns the error AS-IS;
mode does not flip; cursor is NOT advanced for the failed
emit. Degraded decision belongs to executor/engine.
Fix: docstring now accurately describes propagate-and-don't-flip
semantic. Prevents next reader from "fixing" wal_shipper.go
to flip to Backlog on emit error (which would be wrong per
spec — degraded is upstream's call).
(2) sessionActive struct field comment (line ~154-155):
Was: "EndSession returns to Idle"
Reality: EndSession sets sessionActive=false + mode=Realtime
(NOT Idle). Mode goes to Idle ONLY at NewWalShipper ctor;
no API path returns to Idle from non-Idle once Activate
or StartSession has run.
Fix: docstring describes actual transition; flags Idle as
ctor-only state.
(3) stopBacklog field — dead code:
Was: chan struct{} created in StartSession, closed in
EndSession, but no goroutine ever reads from it.
DrainBacklog uses ctx for cancellation; stopBacklog is
unreferenced.
Fix: deleted the field + StartSession's make + EndSession's
close. Architect option was "comment as P2-reserved OR
delete"; deleted to match architect's "dead code is worse
than missing code" principle. If P2 (or any future
backlog-goroutine refactor) needs it, it'll be added then.
R2 test concurrency note (architect 2026-04-29):
`OnSaturation` callback uses `t.Errorf` from non-test goroutine.
P0 stress (count=20, multiple 1-second runs) is clean; future
hardening could use channel + main-goroutine assert. NOT
required for P0 merge per architect; logging here so reviewer
knows it's a known soft spot.
Test sweep:
go test ./core/transport/ -run "TestWalShipper_" -count=1 → all
PASS (10 PASS + 1 SKIP for RegistrySingleton P1 placeholder).
Memories saved (cross-conversation rules from this round):
feedback_lsn_from_allocator_not_boundaries.md — never derive
"LSN of this Write" from Boundaries(); use Write's return.
feedback_tdd_when_spec_locked.md — when spec is normative, write
conformance tests FIRST against spec § references; impl-first
is the pattern that caused 3 recovery-component rewrites.
Next: P1 — BlockExecutor registry + Ship delegate. TDD again.
|
||
|
|
cb4a137ce6 |
transport: WalShipper Q1+Q3 fixes from architect review (P0 green)
Per architect 2026-04-29 review of g7-redo/wal-shipper-impl:
Q1a (INV-SUBSET fromLSN+1 anchoring):
TestWalShipper_DeliveredEqualsCursor — replaced "expected LSN 1..head"
with explicit `fromLSN+1, ..., head` derivation. fromLSN=0 still in
this case (so first emit IS LSN 1) but assertion is now general:
future variants with fromLSN > 0 work without rewriting test logic.
Q1b (CursorMonotonic seed/fromLSN alignment):
Earlier seed (LSN 1..5) + fromLSN=10 had `head < fromLSN` — an edge
that exposes R1 bugs but doesn't pin INV-MONOTONIC-CURSOR cleanly.
Changed seed to LSN 1..15 so head=15 ≥ fromLSN=10, giving DrainBacklog
a real range (10, 15] to ship. Assertions strengthened: post-drain
cursor==head, idempotent NotifyAppend with lsn<cursor doesn't regress.
Q1c (BacklogStaysBacklog_UnderLoad err loosening):
Spec §5.3 normative content is "R1 must not fake-Realtime under
saturation"; whether DrainBacklog returns nil or non-nil at ctx
deadline is impl choice. Removed strict `drainErr != nil` Fatal,
removed errors.Is check; primary contracts (mode != Realtime AND
cursor < head) stay as Errorf. drainErr now logged as observation.
Q3 (R1_DoubleCheckRejectsRace fixedHeadSource):
Replaced HeadSourceFromStorage + sleep-until-cursor≥8 heuristic
with explicit fixedHeadSource control. Substrate Write happens
BEFORE head bump (atomicity: any scan after the bump sees LSN 11
in substrate). NotifyAppend after bump covers race-lost-the-window
branch (R1 already flipped → realtime emit).
Q4 (R2 single-shot per session — already correct):
Test asserts `fired ≤ 1` per session. Architect ratified per-session
single-shot; cross-session re-fire works because StartSession
resets saturationFired flag. Spec §6 line for "default per-session
at most once; cross-session can re-fire" is architect's edit
(separate from this commit).
TEST BUG FOUND DURING `go test` (architect-prompted "fix-then-code"):
6 sites used `lsn, _, _ := primary.Boundaries()` which captures R
(syncedLSN, FIRST return value), not H. memorywal.Boundaries returns
`(R, S, H)`; only Sync() advances R, so concurrent NotifyAppend after
Write got stale lsn=preSyncedLSN, hit the idempotent-skip path
(`lsn <= cursor`), and live writes during session vanished.
Fixed by using primary.Write's RETURNED lsn directly:
- Old: _, _ = primary.Write(lba, data)
lsn, _, _ := primary.Boundaries()
- New: lsn, _ := primary.Write(lba, data)
6 fix sites: R1_NoGapAtTransition (line 396), NoDoubleLive (566),
R2_LagSignalFires (627), R2_NoSpuriousSignal (669),
BacklogToRealtime_Happy (717), BacklogStaysBacklog_UnderLoad (786).
Two tests went from RED → GREEN purely via this test bugfix:
- TestWalShipper_R1_NoGapAtTransition: was cursor=102 want 200;
now cursor=200 == finalHead, all 200 LSN in emit log.
- TestWalShipper_BacklogToRealtime_Happy: was emit count=10 want
11; now 11 emits (10 backlog + 1 realtime LSN 11).
Other tests passed coincidentally because their assertions don't
depend on the lsn parameter to NotifyAppend being correct (e.g.,
R2 tests count fired hooks, not exact LSN sequences).
IMPLEMENTATION (wal_shipper.go) is unchanged — no behavior bug
surfaced. Tests had the bug; spec-driven discipline still worked
(failing tests forced inspection that found the test bug, not a
silent green-on-bad-impl).
Test results:
go test ./core/transport/ -run "TestWalShipper_" -count=1 → all
PASS (10 PASS + 1 SKIP for RegistrySingleton P1 placeholder)
go test ... -run "R1_NoGap|R1_DoubleCheck|NoDoubleLive" -count=20
→ no flake under stress (architect Q3 alternate gate; -race not
enabled per Windows+CGO note in memory)
Wider sweep core/transport/ + core/recovery/ + core/storage/... +
core/replication/component/ all green.
Next: P1 (BlockExecutor.Ship delegate to walShipper) — TDD again,
write tests against INV-NO-DOUBLE-LIVE + INV-SINGLE (registry)
first.
|