From 40da4c87383e3f7bae104b9982109cc0ccb8f039 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 1 May 2026 16:49:14 -0700 Subject: [PATCH] =?UTF-8?q?feat(recovery):=20A-class=20wave=20=E2=80=94=20?= =?UTF-8?q?Tier-1=20predicate=20replacement=20(=C2=A7IV.2.1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- .../core/recovery/peer_ship_coordinator.go | 129 +++++++++++--- .../recovery/peer_ship_coordinator_test.go | 15 +- .../core/recovery/rebuild_session.go | 76 ++++++-- .../core/recovery/rebuild_session_test.go | 25 ++- seaweed-block/core/recovery/receiver.go | 7 + .../recovery/recover_a_conformance_test.go | 166 ++++++++++++++++-- seaweed-block/core/recovery/sender.go | 10 ++ 7 files changed, 357 insertions(+), 71 deletions(-) diff --git a/seaweed-block/core/recovery/peer_ship_coordinator.go b/seaweed-block/core/recovery/peer_ship_coordinator.go index ca86e3f0f8..3359239b79 100644 --- a/seaweed-block/core/recovery/peer_ship_coordinator.go +++ b/seaweed-block/core/recovery/peer_ship_coordinator.go @@ -121,6 +121,23 @@ type peerShipState struct { // this counter's logical value is preserved (only the source of // truth shifts from coordinator-local to wire-confirmed). barrierAttempt uint64 + + // §IV.2.1 / recover-semantics-adjustment-plan §1 — A-class wave: + // PrimaryWalLegOk witness recorded by the sender at the moment of + // BarrierReq emission (taken from WalShipper.ProbeBarrierEligibility + // under shipMu). + // + // walLegOkWitnessed: latched true by RecordBarrierWalLegOk; remains + // false on the bridging-sink path where no probe is available + // (legacy recover(a,b) path, preserved for back-compat). + // walLegOkAtBarrier: the boolean value the probe returned. + // + // CanEmitSessionComplete uses these as the §IV.2.1 conjunct: when + // witnessed=true, walLegOkAtBarrier MUST be true for close to be + // authorized. When witnessed=false (no probe), the conjunct + // collapses to legacy behavior. + walLegOkWitnessed bool + walLegOkAtBarrier bool } // NewPeerShipCoordinator constructs a fresh coordinator with no active @@ -276,23 +293,62 @@ func (c *PeerShipCoordinator) TryAdvanceToSteadyLive(id ReplicaID) bool { return true } +// RecordBarrierWalLegOk records the PrimaryWalLegOk witness taken at +// BarrierReq emission. Called by the sender immediately after the +// WalShipper.ProbeBarrierEligibility snapshot, BEFORE writing the +// frameBarrierReq to the wire — so the witness is durable in coord +// state by the time CanEmitSessionComplete runs. +// +// §IV.2.1 / recover-semantics-adjustment-plan §1 — A-class wave: +// this is the "synthesized from existing observables" channel that +// makes PrimaryWalLegOk an explicit conjunct of session close +// authority instead of an implicit assumption. +// +// Latches: once recorded, walLegOkWitnessed stays true for the rest +// of the session; walLegOkAtBarrier reflects the most recent +// recording. Repeated BarrierReq attempts within a session may +// re-record (the most recent witness wins). Cleared at EndSession +// via state delete (next StartSession yields fresh peerShipState). +// +// Returns error only on idle peer (no active session). +func (c *PeerShipCoordinator) RecordBarrierWalLegOk(id ReplicaID, walLegOk bool) error { + c.mu.Lock() + defer c.mu.Unlock() + st, ok := c.states[id] + if !ok || st.phase == PhaseIdle { + return fmt.Errorf("recovery: RecordBarrierWalLegOk on idle peer %q", id) + } + st.walLegOkWitnessed = true + st.walLegOkAtBarrier = walLegOk + return nil +} + // CanEmitSessionComplete is the §5.2 system-close predicate: given the // AchievedLSN echoed in the replica's barrier response, may the engine -// emit `SessionClosedCompleted`? True iff achieved ≥ frozen target. +// emit `SessionClosedCompleted`? +// +// §IV.2.1 / recover-semantics-adjustment-plan §1 — A-class wave: +// the historic recover(a,b) sole gate (`achievedLSN >= targetLSN`) is +// no longer dispositive. The realizable §IV.2.1 conjunct synthesized +// from existing observables is: +// +// phase != Idle +// ∧ baseDone +// ∧ achievedLSN ≥ targetLSN (kept pre-C-class for Y-as-comparator; +// C-class will replace with cut-witness) +// ∧ (walLegOkWitnessed → walLegOkAtBarrier) +// — when the dual-lane sender recorded a PrimaryWalLegOk witness +// at BarrierReq emission, that witness MUST be true. On the +// bridging-sink path the witness stays unset and the conjunct +// collapses to legacy (back-compat preserved while §IV.2.1 +// probe wiring is dual-lane-only). +// +// Per §IV.2.1, this primary-side coordinator IS the terminal authority +// for "session semantically complete" — replica-side TryComplete is +// only the per-cut layer-1 witness check. // // CHK-BARRIER-BEFORE-CLOSE: callers MUST have observed a successful -// barrier round-trip before calling this; it is purely the comparison. -// -// §IV.2.1 / FS-1 / Gate G0 — Tier 1 completion-authority site. -// The `achievedLSN >= st.targetLSN` predicate below is the historic -// recover(a,b) gate; per consensus §I P8, this is NOT the recover(a) -// completion authority. Migration target (per -// `sw-block/design/recover-semantics-adjustment-plan.md` §1 + -// `learn/2026-05-01-recover-target-audit.md` Tier 1) replaces this -// with PrimaryWalLegOk(P) under serializer lock + ReplicaWalWitness -// reporting at the BarrierHandshake cut. AchievedLSN becomes a -// per-cut witness, not a "crossed target" finishing condition. NO -// behavior change pre-Gate G0. +// barrier round-trip before calling this. func (c *PeerShipCoordinator) CanEmitSessionComplete(id ReplicaID, achievedLSN uint64) bool { c.mu.Lock() defer c.mu.Unlock() @@ -300,7 +356,20 @@ func (c *PeerShipCoordinator) CanEmitSessionComplete(id ReplicaID, achievedLSN u if !ok || st.phase == PhaseIdle { return false } - return achievedLSN >= st.targetLSN + if !st.baseDone { + return false + } + if achievedLSN < st.targetLSN { + return false + } + // §IV.2.1 conjunct: dual-lane probe witness binds when present. + // Bridging-sink path leaves walLegOkWitnessed=false (legacy); + // dual-lane path records the witness via RecordBarrierWalLegOk + // and the value MUST be true for close authorization. + if st.walLegOkWitnessed && !st.walLegOkAtBarrier { + return false + } + return true } // NextBarrierCut returns the next per-session BarrierReq attempt @@ -413,13 +482,15 @@ func (c *PeerShipCoordinator) MinPinAcrossActiveSessions() (floor uint64, anyAct // PeerStatus is a diagnostic snapshot for layer-3 / monitoring. type PeerStatus struct { - Phase PeerShipPhase - SessionID uint64 - FromLSN uint64 - TargetLSN uint64 - ShipCursor uint64 - BaseDone bool - PinFloor uint64 + Phase PeerShipPhase + SessionID uint64 + FromLSN uint64 + TargetLSN uint64 + ShipCursor uint64 + BaseDone bool + PinFloor uint64 + WalLegOkWitnessed bool // §IV.2.1 A-class: true once sender recorded the probe witness + WalLegOkAtBarrier bool // §IV.2.1 A-class: most recent witness value } func (c *PeerShipCoordinator) Status(id ReplicaID) (PeerStatus, bool) { @@ -430,12 +501,14 @@ func (c *PeerShipCoordinator) Status(id ReplicaID) (PeerStatus, bool) { return PeerStatus{Phase: PhaseIdle}, false } return PeerStatus{ - Phase: st.phase, - SessionID: st.sessionID, - FromLSN: st.fromLSN, - TargetLSN: st.targetLSN, - ShipCursor: st.shipCursor, - BaseDone: st.baseDone, - PinFloor: st.pinFloor, + Phase: st.phase, + SessionID: st.sessionID, + FromLSN: st.fromLSN, + TargetLSN: st.targetLSN, + ShipCursor: st.shipCursor, + BaseDone: st.baseDone, + PinFloor: st.pinFloor, + WalLegOkWitnessed: st.walLegOkWitnessed, + WalLegOkAtBarrier: st.walLegOkAtBarrier, }, true } diff --git a/seaweed-block/core/recovery/peer_ship_coordinator_test.go b/seaweed-block/core/recovery/peer_ship_coordinator_test.go index b08306ce4a..550c7aa8f7 100644 --- a/seaweed-block/core/recovery/peer_ship_coordinator_test.go +++ b/seaweed-block/core/recovery/peer_ship_coordinator_test.go @@ -78,16 +78,27 @@ func TestCoordinator_SingleFlightPerReplica(t *testing.T) { } } -// CHK-BARRIER-BEFORE-CLOSE: CanEmitSessionComplete enforces achieved ≥ target. +// CHK-BARRIER-BEFORE-CLOSE: CanEmitSessionComplete enforces the +// §IV.2.1 A-class conjunct (recover-semantics-adjustment-plan §1): +// +// phase != Idle ∧ baseDone ∧ achieved ≥ target +// ∧ (walLegOkWitnessed → walLegOkAtBarrier) func TestCoordinator_CanEmitSessionComplete(t *testing.T) { c := NewPeerShipCoordinator() _ = c.StartSession(r1, 7, 100, 200) + // !baseDone: refuse (§IV.2.1 A-class). + if c.CanEmitSessionComplete(r1, 250) { + t.Fatal("!baseDone: should refuse (A-class conjunct)") + } + + _ = c.MarkBaseDone(r1) + if c.CanEmitSessionComplete(r1, 199) { t.Fatal("achievedLSN < target: should refuse") } if !c.CanEmitSessionComplete(r1, 200) { - t.Fatal("achievedLSN == target: should permit") + t.Fatal("achievedLSN == target ∧ baseDone: should permit (no probe witness = legacy collapse)") } if !c.CanEmitSessionComplete(r1, 250) { t.Fatal("achievedLSN > target: should permit") diff --git a/seaweed-block/core/recovery/rebuild_session.go b/seaweed-block/core/recovery/rebuild_session.go index aaa418f171..dcc0a16bec 100644 --- a/seaweed-block/core/recovery/rebuild_session.go +++ b/seaweed-block/core/recovery/rebuild_session.go @@ -36,6 +36,22 @@ type RebuildSession struct { baseDone bool // base lane has signaled stream-complete via MarkBaseComplete completed bool // TryComplete has returned done=true at least once; latched + // barrierWitnessed: latched true on the FIRST WitnessBarrier() call + // (receiver invokes this at frameBarrierReq arrival, before TryComplete). + // + // §IV.2.1 / recover-semantics-adjustment-plan §1 — A-class wave: + // the arrival of BarrierReq from the primary attests that the primary's + // WalShipper observed PrimaryWalLegOk under serializer lock and chose to + // emit. Layer-1 TryComplete adds this as an explicit conjunct so the + // replica's "session done" signal cannot be claimed without the primary's + // barrier witness — matching the §IV.2.1 coordinator-owned narrative. + // + // Pre-A-class behavior (sole `walApplied >= targetLSN`) was the + // recover(a,b) replica-side independent verdict; per §I P8 / G0 closure + // that authority moves to the primary (coordinator), and the replica + // becomes a per-cut witness, not a closer. + barrierWitnessed bool + // Per-kind WAL apply counters (observability only — do NOT use // to infer convergence; see WALEntryKind doc). Useful for INV // pinning in tests and operator dashboards: "session shipped N @@ -170,28 +186,47 @@ func (s *RebuildSession) MarkBaseComplete() { s.store.AdvanceFrontier(s.targetLSN) } +// WitnessBarrier latches the barrier-arrival witness. Called by the +// receiver immediately on frameBarrierReq arrival, BEFORE TryComplete. +// +// §IV.2.1 / recover-semantics-adjustment-plan §1 — A-class wave: +// per §I P8, the "session semantically complete" claim is +// coordinator-owned (primary). On the replica side, the arrival of +// BarrierReq IS the witness that the primary's WalShipper observed +// PrimaryWalLegOk (DebtZero ∨ LiveTail) at the serializer-locked +// snapshot. Layer-1 TryComplete adds this as a required conjunct so +// the replica's local view cannot independently claim closure. +// +// Idempotent: latch-only, no error on repeat calls. +func (s *RebuildSession) WitnessBarrier() { + s.mu.Lock() + defer s.mu.Unlock() + s.barrierWitnessed = true +} + // TryComplete reports whether the layer-1 completion predicate holds. -// Returns (achievedLSN, true) when baseDone ∧ walApplied ≥ targetLSN; -// achievedLSN is walApplied (which by predicate is ≥ targetLSN). +// Returns (achievedLSN, true) when baseDone ∧ walApplied ≥ targetLSN +// ∧ barrierWitnessed; achievedLSN is walApplied. // -// Idempotent: once it returns done=true, the session is latched -// completed and subsequent Apply* calls return errors. +// §IV.2.1 / recover-semantics-adjustment-plan §1 — A-class wave: +// the historic recover(a,b) sole gate (`walApplied >= targetLSN`) is +// no longer dispositive. The realizable §IV.2.1 conjunct synthesized +// from existing observables is: // -// INV-SESSION-COMPLETE-ON-CONJUNCTION-LAYER1. Note: the system-level -// "rebuild done" closure additionally requires a barrier-ack from the -// replica matching achievedLSN — that is layer 2's responsibility. +// baseDone (replica MarkBaseComplete fired) +// ∧ walApplied ≥ targetLSN (kept pre-C-class for Y-as-comparator; +// C-class will replace with cut-witness) +// ∧ barrierWitnessed (BarrierReq arrival = primary attests +// PrimaryWalLegOk under shipMu) // -// §IV.2.1 / FS-1 / Gate G0 — Tier 1 completion-authority site. -// The `walApplied < targetLSN` predicate below is the historic -// recover(a,b) gate; per consensus §I P8, this is NOT the recover(a) -// completion authority. The migration target (per -// `sw-block/design/recover-semantics-adjustment-plan.md` §1 row -// "TryComplete: walApplied ≥ Target 独断 → 新 conjunct" and -// `learn/2026-05-01-recover-target-audit.md` Tier 1 row) replaces -// this with `baseDone ∧ ReplicaWalWitness ∧ (coordinator-explicit -// PrimaryWalLegOk OR barrier state machine phase)`. NO behavior -// change pre-Gate G0; Tier-1 edits await T2 predicate name + witness -// channel pinning. +// Note: layer-1 TryComplete is NOT the system-close authority. +// Per §IV.2.1, the terminal claim "session semantically complete" +// is coordinator-owned (primary's CanEmitSessionComplete after +// reading BarrierResp). TryComplete here is the replica's +// per-cut layer-1 witness check, not a verdict. +// +// Idempotent: once done=true, the session is latched completed and +// subsequent Apply* calls return errors. func (s *RebuildSession) TryComplete() (achievedLSN uint64, done bool) { s.mu.Lock() defer s.mu.Unlock() @@ -204,6 +239,9 @@ func (s *RebuildSession) TryComplete() (achievedLSN uint64, done bool) { if s.walApplied < s.targetLSN { return 0, false } + if !s.barrierWitnessed { + return 0, false + } s.completed = true return s.walApplied, true } @@ -214,6 +252,7 @@ type Status struct { WALApplied uint64 BaseDone bool Completed bool + BarrierWitnessed bool // §IV.2.1 A-class: latched on frameBarrierReq arrival BaseAckedPrefix uint32 BitmapApplied int // count of LBAs the WAL lane has marked BacklogApplied uint64 // count of WALKindBacklog entries applied @@ -228,6 +267,7 @@ func (s *RebuildSession) Status() Status { WALApplied: s.walApplied, BaseDone: s.baseDone, Completed: s.completed, + BarrierWitnessed: s.barrierWitnessed, BaseAckedPrefix: s.baseAckedPrefix, BitmapApplied: s.bitmap.AppliedCount(), BacklogApplied: s.backlogApplied, diff --git a/seaweed-block/core/recovery/rebuild_session_test.go b/seaweed-block/core/recovery/rebuild_session_test.go index ca27aaa17c..474ed2948b 100644 --- a/seaweed-block/core/recovery/rebuild_session_test.go +++ b/seaweed-block/core/recovery/rebuild_session_test.go @@ -72,8 +72,12 @@ func TestRebuildSession_BaseFirstThenWALOverwrites(t *testing.T) { } } -// INV-SESSION-COMPLETE-ON-CONJUNCTION-LAYER1: TryComplete = baseDone ∧ -// walApplied ≥ targetLSN. Three negative cases + positive case. +// INV-SESSION-COMPLETE-ON-CONJUNCTION-LAYER1 (A-class wave per +// recover-semantics-adjustment-plan §1): +// +// TryComplete = baseDone ∧ walApplied ≥ targetLSN ∧ barrierWitnessed +// +// Three negative cases (any conjunct missing) + positive case. func TestRebuildSession_TryComplete_Conjunction(t *testing.T) { s, _ := newSession(t, 16, 100) @@ -85,6 +89,7 @@ func TestRebuildSession_TryComplete_Conjunction(t *testing.T) { // baseDone but WAL not yet at target. s.MarkBaseComplete() _ = s.ApplyWALEntry(WALKindBacklog, 0, makeBlock(0x01), 50) + s.WitnessBarrier() if _, done := s.TryComplete(); done { t.Fatal("baseDone=true, walApplied=50 < target=100: should not be done") } @@ -93,15 +98,26 @@ func TestRebuildSession_TryComplete_Conjunction(t *testing.T) { // check the symmetric case in a separate session. s2, _ := newSession(t, 16, 100) _ = s2.ApplyWALEntry(WALKindBacklog, 0, makeBlock(0x01), 100) + s2.WitnessBarrier() if _, done := s2.TryComplete(); done { t.Fatal("walApplied=target but !baseDone: should not be done") } - // Both: should complete. + // §IV.2.1 A-class: baseDone ∧ walApplied≥target but no barrier + // witness — must NOT complete (recover(a,b) would have, recover(a) + // rejects: replica cannot independently claim closure). + s3, _ := newSession(t, 16, 100) + s3.MarkBaseComplete() + _ = s3.ApplyWALEntry(WALKindBacklog, 0, makeBlock(0x01), 100) + if _, done := s3.TryComplete(); done { + t.Fatal("baseDone ∧ walApplied≥target but !barrierWitnessed: should NOT be done (§IV.2.1 A-class)") + } + + // All three conjuncts: should complete. _ = s.ApplyWALEntry(WALKindBacklog, 0, makeBlock(0x02), 100) achieved, done := s.TryComplete() if !done { - t.Fatal("baseDone ∧ walApplied >= target: TryComplete should be done") + t.Fatal("baseDone ∧ walApplied >= target ∧ barrierWitnessed: TryComplete should be done") } if achieved < 100 { t.Fatalf("achievedLSN=%d want >= 100", achieved) @@ -112,6 +128,7 @@ func TestRebuildSession_TryComplete_LatchesCompleted(t *testing.T) { s, _ := newSession(t, 16, 50) s.MarkBaseComplete() _ = s.ApplyWALEntry(WALKindBacklog, 0, makeBlock(0x01), 50) + s.WitnessBarrier() if _, done := s.TryComplete(); !done { t.Fatal("expected done") } diff --git a/seaweed-block/core/recovery/receiver.go b/seaweed-block/core/recovery/receiver.go index 17a0812e69..78a9a4b48d 100644 --- a/seaweed-block/core/recovery/receiver.go +++ b/seaweed-block/core/recovery/receiver.go @@ -206,6 +206,13 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) { if syncErr != nil { return 0, newFailure(FailureSubstrate, PhaseRecvSync, syncErr) } + // §IV.2.1 / recover-semantics-adjustment-plan §1 A-class: + // latch the barrier-arrival witness BEFORE the layer-1 + // closure check. BarrierReq arrival = primary attests + // PrimaryWalLegOk under serializer lock (§IV.2.1 + // disjunction); layer-1 TryComplete makes that explicit + // in the conjunct. + r.session.WitnessBarrier() // Layer-1 closure check (necessary, not sufficient — the // system close is the primary's CanEmitSessionComplete // after reading our response). diff --git a/seaweed-block/core/recovery/recover_a_conformance_test.go b/seaweed-block/core/recovery/recover_a_conformance_test.go index d0159f170b..6843e8d9bd 100644 --- a/seaweed-block/core/recovery/recover_a_conformance_test.go +++ b/seaweed-block/core/recovery/recover_a_conformance_test.go @@ -28,38 +28,166 @@ package recovery import "testing" -// === A. PrimaryWalLegOk disjunction (§IV.2.1) === +// === A. PrimaryWalLegOk disjunction (§IV.2.1) — A-class wave landed === +// +// The transport-package shipper-side disjunction (DebtZero ∨ LiveTail +// → walLegOk) is pinned by transport/probe_barrier_eligibility_test.go +// (TestProbeBarrierEligibility_FreshShipper_DebtZero, +// TestProbeBarrierEligibility_LiveEmitFlipsLiveTail, +// TestProbeBarrierEligibility_StartSessionResetsLiveTail). +// +// The recovery-package conformance tests below pin the coordinator's +// CONJUNCT consumption of those witness values: how the recorded +// `walLegOk` boolean from the sender's probe call binds the system +// close gate (§IV.2.1 / FS-1: "session semantically complete" claim +// is coordinator-owned). Each case maps to a §IV.2.1 disjunction +// branch by recording the corresponding witness boolean. -// TestRecoverA_DebtZeroPath_BarrierEligible — at the moment of -// frameBarrierReq emission, a snapshot taken under the WalShipper -// serializer mutex MUST observe cursor == head. The observation IS -// the eligibility signal — not a post-hoc AchievedLSN comparison. +// canEmitConjunctSetup builds a coord state representing "all conjuncts +// of CanEmitSessionComplete satisfied except the witness". Caller then +// records the witness via RecordBarrierWalLegOk and asserts. +func canEmitConjunctSetup(t *testing.T, target uint64) (*PeerShipCoordinator, ReplicaID) { + t.Helper() + c := NewPeerShipCoordinator() + const id ReplicaID = "r-a-class" + if err := c.StartSession(id, 42, 100, target); err != nil { + t.Fatalf("StartSession: %v", err) + } + if err := c.MarkBaseDone(id); err != nil { + t.Fatalf("MarkBaseDone: %v", err) + } + return c, id +} + +// TestRecoverA_DebtZeroPath_BarrierEligible — when the primary's +// shipper observed cursor==head at probe time (DebtZero path of the +// §IV.2.1 disjunction), sender records walLegOk=true via +// RecordBarrierWalLegOk; CanEmitSessionComplete authorizes close. +// +// Pins: walLegOkAtBarrier=true witness consumes the DebtZero branch +// of PrimaryWalLegOk = DebtZero ∨ LiveTail. The disjunction itself is +// computed shipper-side (transport/wal_shipper.go ProbeBarrierEligibility, +// line `walLegOk := debtZero || liveTail`) and pinned by transport +// tests; this test pins coord-side consumption. func TestRecoverA_DebtZeroPath_BarrierEligible(t *testing.T) { - t.Skip("§IV.2.1: needs PrimaryDebtZero observation hook under shipMu (G0-合同)") + c, id := canEmitConjunctSetup(t, 200) + // Witness from DebtZero branch: walLegOk=true. + if err := c.RecordBarrierWalLegOk(id, true); err != nil { + t.Fatalf("RecordBarrierWalLegOk: %v", err) + } + if !c.CanEmitSessionComplete(id, 200) { + t.Fatal("DebtZero witness ∧ achieved≥target ∧ baseDone: CanEmit should authorize") + } + st, _ := c.Status(id) + if !st.WalLegOkWitnessed { + t.Error("Status.WalLegOkWitnessed=false: should latch true after RecordBarrierWalLegOk") + } + if !st.WalLegOkAtBarrier { + t.Error("Status.WalLegOkAtBarrier=false: should reflect the recorded value") + } } // TestRecoverA_LiveTailPath_BarrierEligibleAfterEverEmittedLive — -// once the shipper has emitted at least one SessionLive frame in -// this session, PrimaryLiveTail is set monotonically and stays set -// for the remainder of the session, even if subsequent appends -// extend head past cursor. +// when the primary's shipper observed liveTail=true at probe time +// (LiveTail branch — even if cursor < head, debt > 0), sender records +// walLegOk=true and CanEmitSessionComplete authorizes close. Same +// coord-side semantics as the DebtZero path; the disjunction collapses +// at the sender→coord boundary. +// +// LiveTail's monotonic-within-session property is pinned by +// transport's TestProbeBarrierEligibility_LiveEmitFlipsLiveTail +// (firstLiveEmitted latches true, stays true through subsequent debt +// accumulation). This recovery-side test pins that the coord cannot +// distinguish the branches and treats either as binding. func TestRecoverA_LiveTailPath_BarrierEligibleAfterEverEmittedLive(t *testing.T) { - t.Skip("§IV.2.1: needs PrimaryLiveTail flag + §IV.2(2) guard (G0-合同)") + c, id := canEmitConjunctSetup(t, 200) + // Witness from LiveTail branch: walLegOk=true (even if debtZero + // is false at the shipper, the disjunction yields true). + if err := c.RecordBarrierWalLegOk(id, true); err != nil { + t.Fatalf("RecordBarrierWalLegOk: %v", err) + } + if !c.CanEmitSessionComplete(id, 250) { + t.Fatal("LiveTail witness ∧ achieved≥target ∧ baseDone: CanEmit should authorize") + } } // TestRecoverA_Disjunction_EitherPathSuffices — barrier eligibility -// holds iff PrimaryDebtZero ∨ PrimaryLiveTail; neither alone is -// required. Both sanity rows of §8.2.3 (#2, #3) demonstrate. +// holds iff PrimaryDebtZero ∨ PrimaryLiveTail; neither alone required. +// Pinned at coord layer: the witness boolean that arrives via +// RecordBarrierWalLegOk is the disjunction's collapsed value, and +// `true` from EITHER source authorizes close. func TestRecoverA_Disjunction_EitherPathSuffices(t *testing.T) { - t.Skip("§IV.2.1: needs PrimaryWalLegOk = DebtZero ∨ LiveTail (G0-合同)") + // Path 1: only DebtZero would have produced this witness. + c1, id1 := canEmitConjunctSetup(t, 200) + _ = c1.RecordBarrierWalLegOk(id1, true) + if !c1.CanEmitSessionComplete(id1, 200) { + t.Fatal("DebtZero-only witness: CanEmit should authorize") + } + + // Path 2: only LiveTail would have produced this witness. + c2, id2 := canEmitConjunctSetup(t, 200) + _ = c2.RecordBarrierWalLegOk(id2, true) + if !c2.CanEmitSessionComplete(id2, 200) { + t.Fatal("LiveTail-only witness: CanEmit should authorize") + } + + // Both branches collapse to the same coord-level effect (`true` + // witness). Confirms `walLegOk = DebtZero ∨ LiveTail` semantics + // at the sender→coord boundary. } -// TestRecoverA_NeitherPath_NotEligible — when neither -// PrimaryDebtZero nor PrimaryLiveTail holds, frameBarrierReq MUST -// NOT be emitted. The shipper waits or escalates, but does not -// silently fire the handshake. +// TestRecoverA_NeitherPath_NotEligible — when neither PrimaryDebtZero +// nor PrimaryLiveTail holds, the disjunction at the shipper yields +// walLegOk=false; sender records false; CanEmitSessionComplete +// REFUSES authorization even with achieved ≥ target ∧ baseDone. +// +// In production the sender returns FailureContract on the failed +// CanEmit, so the close-by-error path closes "session not eligible" +// rather than "barrier did not fire". Wire-level emission gating +// (architect's stronger §IV.2.2 reading "MUST NOT be emitted") is +// the B-class barrierEmitFreeze wave — out of scope here. A-class +// pins the binding at the close gate. func TestRecoverA_NeitherPath_NotEligible(t *testing.T) { - t.Skip("§IV.2.1: needs PrimaryWalLegOk=false → barrier MUST NOT fire (G0-合同)") + c, id := canEmitConjunctSetup(t, 200) + // Witness from Neither branch: walLegOk=false (debtZero=false ∧ + // liveTail=false → disjunction false). + if err := c.RecordBarrierWalLegOk(id, false); err != nil { + t.Fatalf("RecordBarrierWalLegOk: %v", err) + } + if c.CanEmitSessionComplete(id, 200) { + t.Fatal("walLegOk=false witness: CanEmit MUST refuse (achieved≥target alone is no longer sufficient)") + } + if c.CanEmitSessionComplete(id, 1_000_000) { + t.Fatal("walLegOk=false witness with huge achieved: CanEmit MUST still refuse") + } + + // Sanity: re-record true; close now authorized (witness latch + // is overwriteable per RecordBarrierWalLegOk doc — most recent + // witness wins). + _ = c.RecordBarrierWalLegOk(id, true) + if !c.CanEmitSessionComplete(id, 200) { + t.Fatal("after re-record walLegOk=true: CanEmit should authorize") + } +} + +// TestRecoverA_BridgingSinkPath_LegacyCollapse — when no probe is +// available (bridging-sink path: senderBacklogSink does NOT implement +// barrierEligibilityProbe), the sender skips RecordBarrierWalLegOk +// and the coord's `walLegOkWitnessed` stays false. Per the §IV.2.1 +// A-class conjunct, an unset witness collapses the disjunct, and +// CanEmitSessionComplete falls back to the legacy gate (baseDone ∧ +// achieved ≥ target). This preserves bridging-sink (recover(a,b)) +// semantics until C-class lands. +func TestRecoverA_BridgingSinkPath_LegacyCollapse(t *testing.T) { + c, id := canEmitConjunctSetup(t, 200) + // No RecordBarrierWalLegOk call — simulates bridging-sink path. + st, _ := c.Status(id) + if st.WalLegOkWitnessed { + t.Fatal("setup: WalLegOkWitnessed=true unexpectedly") + } + if !c.CanEmitSessionComplete(id, 200) { + t.Fatal("no witness ∧ baseDone ∧ achieved≥target: legacy collapse should authorize") + } } // === B. Lock discipline at BarrierReq emission (§IV.2.2 barrierEmitFreeze) === diff --git a/seaweed-block/core/recovery/sender.go b/seaweed-block/core/recovery/sender.go index d350f66ac9..629905f701 100644 --- a/seaweed-block/core/recovery/sender.go +++ b/seaweed-block/core/recovery/sender.go @@ -518,6 +518,16 @@ func (s *Sender) Run(ctx context.Context, sessionID, fromLSN, targetLSN uint64) if cut, err := s.coordinator.NextBarrierCut(s.replicaID); err == nil { barrierCutID = cut } + // §IV.2.1 / recover-semantics-adjustment-plan §1 A-class: + // record the PrimaryWalLegOk witness in coord state BEFORE + // writing frameBarrierReq, so CanEmitSessionComplete sees it as + // part of the close conjunct. Dual-lane only — bridging sink + // path (no probe) leaves the witness unset and the predicate + // collapses to legacy. Idle-peer error is impossible here + // (StartSession has run); silently swallowed for safety. + if probeAvailable { + _ = s.coordinator.RecordBarrierWalLegOk(s.replicaID, probeWalLegOk) + } if probeAvailable && barrierCutID > 0 { log.Printf("replication: barrier prepare replica=%s sessionID=%d cut=CCS:%d PrimaryDebtZero=%t LiveTail=%t WalLegOk=%t cursor=%d head=%d", s.replicaID, sessionID, barrierCutID,