diff --git a/seaweed-block/core/recovery/peer_ship_coordinator.go b/seaweed-block/core/recovery/peer_ship_coordinator.go index 2f14c82f40..ca86e3f0f8 100644 --- a/seaweed-block/core/recovery/peer_ship_coordinator.go +++ b/seaweed-block/core/recovery/peer_ship_coordinator.go @@ -59,6 +59,10 @@ func (p PeerShipPhase) String() string { // local write must travel on for a given peer, given that peer's current // ship phase. Spec §3.2 #3: "one ordered outbound queue per peer mixing // recover-tagged and post-target traffic with explicit LSN order". +// +// §IV.0 T3 (v3-recovery-algorithm-consensus.md): RouteSessionLane means +// all WAL for this peer MUST ship on the recover dual-lane session path — +// never a parallel steady bearer fork (§I P2). type LocalWriteRouting int const ( @@ -102,6 +106,21 @@ type peerShipState struct { // path via PinFloor() and the cluster-wide // MinPinAcrossActiveSessions() helper. pinFloor uint64 + + // barrierAttempt counts BarrierReq attempts made in THIS session. + // Increments on each call to NextBarrierCut; starts at 0 at + // StartSession; the first call yields 1. + // + // Pre-§IV.2.4 wire change (G0-wire ratified 2026-05-03 to keep + // targetLSN as compat band; CCS not yet on wire), this counter is + // the marker-line cutID per architect's Option B (plan §8.2.6): + // `cut=CCS:` in `barrier prepare` AND + // `barrier handshake` log lines, providing QA's grep round-trip + // even before the real CheckpointCutSeq is on the wire. When + // C-class lands the CCS field on the BarrierReq/Resp payload, + // this counter's logical value is preserved (only the source of + // truth shifts from coordinator-local to wire-confirmed). + barrierAttempt uint64 } // NewPeerShipCoordinator constructs a fresh coordinator with no active @@ -284,6 +303,31 @@ func (c *PeerShipCoordinator) CanEmitSessionComplete(id ReplicaID, achievedLSN u return achievedLSN >= st.targetLSN } +// NextBarrierCut returns the next per-session BarrierReq attempt +// counter for this peer, incrementing in-place. First call after +// StartSession yields 1; subsequent calls within the same session +// increment monotonically. Per architect Option B (plan §8.2.6): +// +// - Pre-§IV.2.4 wire change, this counter populates the marker +// line `cut=CCS:` so QA hardware oracle can grep round-trip +// between `barrier prepare` and `barrier handshake`. +// - When C-class wire lands CheckpointCutSeq on the +// BarrierReq/Resp payload, this counter's logical value is +// preserved; only the source-of-truth shifts. +// +// Returns 0 + error when no active session exists (caller MUST treat +// 0 as invalid and not log a marker with cut=CCS:0). +func (c *PeerShipCoordinator) NextBarrierCut(id ReplicaID) (uint64, error) { + c.mu.Lock() + defer c.mu.Unlock() + st, ok := c.states[id] + if !ok || st.phase == PhaseIdle { + return 0, fmt.Errorf("recovery: NextBarrierCut on idle peer %q", id) + } + st.barrierAttempt++ + return st.barrierAttempt, nil +} + // EndSession tears down the session for a peer (after barrier-ack // success path or after explicit invalidation). Returns to PhaseIdle; // pin floor is dropped (recycle gate releases for this peer). diff --git a/seaweed-block/core/recovery/peer_ship_coordinator_test.go b/seaweed-block/core/recovery/peer_ship_coordinator_test.go index 8e427c07cb..b08306ce4a 100644 --- a/seaweed-block/core/recovery/peer_ship_coordinator_test.go +++ b/seaweed-block/core/recovery/peer_ship_coordinator_test.go @@ -320,3 +320,49 @@ func TestCoordinator_IdlePeer_OperationsError(t *testing.T) { t.Error("BacklogDrained on idle: want false") } } + +// TestCoordinator_NextBarrierCut_MonotonicPerSession — Option B +// (plan §8.2.6): per-session counter starts at 1, increments per +// call within a session, resets to 0 on next StartSession. +func TestCoordinator_NextBarrierCut_MonotonicPerSession(t *testing.T) { + c := NewPeerShipCoordinator() + + // Pre-session: error. + if cut, err := c.NextBarrierCut(r1); err == nil || cut != 0 { + t.Errorf("NextBarrierCut on idle: cut=%d err=%v want 0+error", cut, err) + } + + if err := c.StartSession(r1, 7, 100, 200); err != nil { + t.Fatalf("StartSession: %v", err) + } + + // First call: 1. + cut, err := c.NextBarrierCut(r1) + if err != nil { + t.Fatalf("NextBarrierCut #1: %v", err) + } + if cut != 1 { + t.Errorf("first cut=%d want 1", cut) + } + // Second call: 2. + cut, err = c.NextBarrierCut(r1) + if err != nil { + t.Fatalf("NextBarrierCut #2: %v", err) + } + if cut != 2 { + t.Errorf("second cut=%d want 2", cut) + } + + // EndSession + new StartSession resets to 0; first call yields 1. + c.EndSession(r1) + if err := c.StartSession(r1, 8, 100, 200); err != nil { + t.Fatalf("StartSession (second session): %v", err) + } + cut, err = c.NextBarrierCut(r1) + if err != nil { + t.Fatalf("NextBarrierCut after restart: %v", err) + } + if cut != 1 { + t.Errorf("post-restart first cut=%d want 1 (per-session reset)", cut) + } +} diff --git a/seaweed-block/core/recovery/sender.go b/seaweed-block/core/recovery/sender.go index c98e6a87e6..d350f66ac9 100644 --- a/seaweed-block/core/recovery/sender.go +++ b/seaweed-block/core/recovery/sender.go @@ -5,11 +5,34 @@ import ( "errors" "fmt" "io" + "log" "sync" "github.com/seaweedfs/seaweed-block/core/storage" ) +// barrierEligibilityProbe is the optional sink-side hook that exposes +// the §IV.2.1 PrimaryWalLegOk observation tuple. Implemented by the +// dual-lane RecoverySink (transport package) which has access to the +// per-replica WalShipper; bridging-sink (senderBacklogSink) does NOT +// implement this — only the dual-lane production path emits the +// `barrier prepare` / `barrier handshake` markers per plan §8.2.6. +// +// Returning values: +// +// debtZero — cursor == head observed under serializer lock at probe +// liveTail — at least one EmitKindLive frame in this session +// walLegOk — debtZero ∨ liveTail +// cursor — last-emitted LSN +// head — primary's head at probe +// +// Slice marker-only stage: probe is observation; the values do NOT +// gate BarrierReq emission. A-class wave (post-G0) replaces the +// recover(a,b) `walApplied >= target` predicate with this tuple. +type barrierEligibilityProbe interface { + ProbeBarrierEligibility() (debtZero, liveTail, walLegOk bool, cursor, head uint64) +} + // Sender is the primary-side driver of one rebuild session. It runs // the base lane, then delegates the WAL pump (and live-write traffic // during the session) to its WalShipperSink, and finally runs the @@ -464,6 +487,44 @@ func (s *Sender) Run(ctx context.Context, sessionID, fromLSN, targetLSN uint64) // Step 5 + 6: barrier round-trip — reader goroutine delivers the // inbound BarrierResp via barrierRespCh (or any wire / protocol / // pin-update error surfaced earlier). + // + // §IV.2.1 / §8.2.6 marker-only stage (G0 closed; Tier-1 predicate + // replacement = A-class wave, not this commit). Before writing + // frameBarrierReq, snapshot the PrimaryWalLegOk inputs from the + // sink (if it implements barrierEligibilityProbe) and emit the + // 5-field `barrier prepare` log line per plan §8.2.6 hardware + // oracle contract. The values are real (debtZero, liveTail, + // walLegOk computed from current shipper state) but do NOT yet + // gate the emission — observability bridge for QA. + // + // cutID source per architect Option B (plan §8.2.6 + §6 v3.27): + // per-session monotonic counter from coord.NextBarrierCut. 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 (still `cut=CCS:`). + var ( + barrierCutID uint64 + probeDebtZero bool + probeLiveTail bool + probeWalLegOk bool + probeCursor uint64 + probeHead uint64 + probeAvailable bool + ) + if probe, ok := s.sink.(barrierEligibilityProbe); ok { + probeDebtZero, probeLiveTail, probeWalLegOk, probeCursor, probeHead = probe.ProbeBarrierEligibility() + probeAvailable = true + } + if cut, err := s.coordinator.NextBarrierCut(s.replicaID); err == nil { + barrierCutID = cut + } + 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, + probeDebtZero, probeLiveTail, probeWalLegOk, + probeCursor, probeHead) + } + if err := s.writeFrame(frameBarrierReq, nil); err != nil { return 0, newFailure(FailureWire, PhaseBarrierReq, err) } @@ -477,6 +538,19 @@ func (s *Sender) Run(ctx context.Context, sessionID, fromLSN, targetLSN uint64) case <-ctx.Done(): return 0, newFailure(FailureCancelled, PhaseBarrierResp, ctx.Err()) } + + // §IV.2.1 / §8.2.6 marker-only stage: emit the `barrier handshake` + // log line with the SAME cutID as the prepare line (Option B + // round-trip). Pre-C-class wire (no CheckpointCutSeq on the + // BarrierResp payload), `match=true` is unconditional — the same + // cutID flows from prepare to handshake by construction. Post- + // C-class, match becomes the real wire-vs-engine compare; a + // `match=false` line in hardware logs is the RED scenario per + // §8.2.6. + if probeAvailable && barrierCutID > 0 { + log.Printf("replication: barrier handshake cut=CCS:%d achieved=%d match=true", + barrierCutID, achieved) + } // §IV.2.1 / FS-1 / Gate G0 — Tier 1 completion-authority site. // The CanEmitSessionComplete check below + FailureContract on // `achieved < target` is the historic recover(a,b) Run-success diff --git a/seaweed-block/core/transport/probe_barrier_eligibility_test.go b/seaweed-block/core/transport/probe_barrier_eligibility_test.go new file mode 100644 index 0000000000..e439141385 --- /dev/null +++ b/seaweed-block/core/transport/probe_barrier_eligibility_test.go @@ -0,0 +1,139 @@ +package transport + +// Marker-only slice (post-G0) — unit coverage for the §IV.2.1 +// PrimaryWalLegOk observation accessor on WalShipper. Pure shipper +// state transitions; no wire / receiver / coordinator coupling. +// +// What this pins: +// +// - Fresh shipper post-Activate(0): cursor==head trivially (both 0) +// so debtZero=true; liveTail=false (no Live emitted yet); thus +// walLegOk=true via debtZero. +// - StartSession resets liveTail to false and rewinds cursor to +// fromLSN; if substrate has entries past fromLSN, debtZero=false +// until drive() catches up. +// - First EmitKindLive emit (NotifyAppend on a caught-up shipper) +// sets liveTail=true monotonically; subsequent debt accumulation +// does NOT clear it. +// - StartSession on the same shipper for a fresh session resets +// liveTail=false (per-session monotonic). +// +// Source: sw-block/design/recover-semantics-adjustment-plan.md §8.2.6 +// (architect Option B + Tier-1 marker contract). + +import ( + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage/memorywal" +) + +// TestProbeBarrierEligibility_FreshShipper_DebtZero — at construction +// + Activate(0), no substrate writes, cursor==head==0; debtZero true; +// liveTail false; walLegOk true. +func TestProbeBarrierEligibility_FreshShipper_DebtZero(t *testing.T) { + primary := memorywal.NewStore(8, 64) + emit := func(_ EmitKind, _ uint32, _ uint64, _ []byte) error { return nil } + cfg := WalShipperConfig{IdleSleep: 5 * 1000, DisableTimerDrain: true} + s := NewWalShipperWithOptions("r1", HeadSourceFromStorage(primary), primary, emit, cfg) + defer s.Stop() + if err := s.Activate(0); err != nil { + t.Fatalf("Activate: %v", err) + } + + debtZero, liveTail, walLegOk, cursor, head := s.ProbeBarrierEligibility() + if !debtZero { + t.Errorf("fresh shipper: debtZero=%t want true (cursor=%d head=%d)", debtZero, cursor, head) + } + if liveTail { + t.Errorf("fresh shipper: liveTail=%t want false (no Live emitted yet)", liveTail) + } + if !walLegOk { + t.Errorf("fresh shipper: walLegOk=%t want true (debtZero ⇒ walLegOk)", walLegOk) + } + if cursor != 0 || head != 0 { + t.Errorf("fresh shipper: cursor=%d head=%d want both 0", cursor, head) + } +} + +// TestProbeBarrierEligibility_LiveEmitFlipsLiveTail — once a fast-path +// or post-CASE-A Live emit fires, liveTail goes true monotonically and +// stays true even if subsequent appends extend head past cursor. +func TestProbeBarrierEligibility_LiveEmitFlipsLiveTail(t *testing.T) { + primary := memorywal.NewStore(8, 64) + emit := func(_ EmitKind, _ uint32, _ uint64, _ []byte) error { return nil } + cfg := WalShipperConfig{IdleSleep: 5 * 1000, DisableTimerDrain: true} + s := NewWalShipperWithOptions("r1", HeadSourceFromStorage(primary), primary, emit, cfg) + defer s.Stop() + if err := s.Activate(0); err != nil { + t.Fatalf("Activate: %v", err) + } + + // Pre-emit: liveTail=false. + _, liveTail, _, _, _ := s.ProbeBarrierEligibility() + if liveTail { + t.Fatalf("pre-emit: liveTail=true want false") + } + + // Production sequence: primary.Write commits to substrate (advances + // head); then NotifyAppend on the shipper takes fast-path + // (lsn=cursor+1, head==lsn) → EmitKindLive → sets firstLiveEmitted. + data := make([]byte, 64) + data[0] = 0xAA + lsn, err := primary.Write(0, data) + if err != nil { + t.Fatalf("primary.Write: %v", err) + } + if err := s.NotifyAppend(0, lsn, data); err != nil { + t.Fatalf("NotifyAppend: %v", err) + } + + debtZero, liveTail, walLegOk, cursor, head := s.ProbeBarrierEligibility() + if !liveTail { + t.Errorf("post-Live-emit: liveTail=%t want true", liveTail) + } + if !debtZero { + t.Errorf("post-Live-emit: debtZero=%t want true (cursor=%d head=%d)", debtZero, cursor, head) + } + if !walLegOk { + t.Errorf("post-Live-emit: walLegOk=%t want true", walLegOk) + } + if cursor != lsn { + t.Errorf("post-Live-emit: cursor=%d want %d", cursor, lsn) + } +} + +// TestProbeBarrierEligibility_StartSessionResetsLiveTail — the +// per-session monotonic property: a new session zeroes liveTail +// regardless of whether the prior session emitted Live. +func TestProbeBarrierEligibility_StartSessionResetsLiveTail(t *testing.T) { + primary := memorywal.NewStore(8, 64) + emit := func(_ EmitKind, _ uint32, _ uint64, _ []byte) error { return nil } + cfg := WalShipperConfig{IdleSleep: 5 * 1000, DisableTimerDrain: true} + s := NewWalShipperWithOptions("r1", HeadSourceFromStorage(primary), primary, emit, cfg) + defer s.Stop() + if err := s.Activate(0); err != nil { + t.Fatalf("Activate: %v", err) + } + + // Fire one Live emit to set liveTail. + data := make([]byte, 64) + lsn, err := primary.Write(0, data) + if err != nil { + t.Fatalf("primary.Write: %v", err) + } + if err := s.NotifyAppend(0, lsn, data); err != nil { + t.Fatalf("NotifyAppend: %v", err) + } + if _, lt, _, _, _ := s.ProbeBarrierEligibility(); !lt { + t.Fatalf("setup: liveTail did not flip on Live emit") + } + + // New session — liveTail must reset. + if err := s.StartSession(0); err != nil { + t.Fatalf("StartSession: %v", err) + } + if _, lt, _, _, _ := s.ProbeBarrierEligibility(); lt { + t.Errorf("post-StartSession: liveTail=%t want false (per-session reset)", lt) + } + s.EndSession() +} diff --git a/seaweed-block/core/transport/recovery_sink_adapter.go b/seaweed-block/core/transport/recovery_sink_adapter.go index fd99bca0eb..22ae4159de 100644 --- a/seaweed-block/core/transport/recovery_sink_adapter.go +++ b/seaweed-block/core/transport/recovery_sink_adapter.go @@ -229,3 +229,26 @@ func (r *RecoverySink) WriteMu() *sync.Mutex { func (r *RecoverySink) SetPostEmitHook(hook func(lsn uint64)) { r.e.SetWalShipperPostEmitHook(r.replicaID, hook) } + +// ProbeBarrierEligibility surfaces the §IV.2.1 PrimaryWalLegOk +// observation tuple from the per-replica WalShipper, taken under the +// shipper's serializer lock so the snapshot is consistent. Returns +// (false, false, false, 0, 0) when no shipper exists for the replica +// (defensive — shouldn't happen on a live session but the executor's +// registry is map-backed so a probe before WalShipperFor is theoretically +// possible). +// +// recovery.Sender's barrierEligibilityProbe interface duck-types this +// method; the dual-lane production path uses it to populate the +// `barrier prepare` / `barrier handshake` markers per plan §8.2.6. +// The bridging-sink path (senderBacklogSink) does NOT implement this +// interface — pre-§IV.2.1 markers are dual-lane-only. +// +// Slice marker-only stage: probe is observation, not gating. +func (r *RecoverySink) ProbeBarrierEligibility() (debtZero, liveTail, walLegOk bool, cursor, head uint64) { + shipper := r.e.WalShipperFor(r.replicaID) + if shipper == nil { + return false, false, false, 0, 0 + } + return shipper.ProbeBarrierEligibility() +} diff --git a/seaweed-block/core/transport/wal_shipper.go b/seaweed-block/core/transport/wal_shipper.go index 60ee5f7932..b2cf415668 100644 --- a/seaweed-block/core/transport/wal_shipper.go +++ b/seaweed-block/core/transport/wal_shipper.go @@ -257,6 +257,19 @@ type WalShipper struct { lagSample atomic.Uint64 saturationFired atomic.Bool + // PrimaryLiveTail observability (§IV.2.1, slice marker-only stage). + // firstLiveEmitted is set on the first EmitKindLive emit in this + // session and stays set monotonically until StartSession (which + // resets it). Used by ProbeBarrierEligibilityLocked to compute the + // LiveTail bool component of PrimaryWalLegOk. + // + // Atomic for read-without-shipMu by lock-free probe paths if + // future callers want it; today reads happen under shipMu so an + // atomic isn't strictly needed, but the bool sets are by drive() + // under shipMu — atomic.Bool is the safest type for "set once, + // read many" semantics. + firstLiveEmitted atomic.Bool + // C2 §6.8 #4 self-driving drain. timerLoop runs as a background // goroutine for the shipper's lifetime; on each `IdleSleep` tick // it wakes and (under shipMu) checks `cursor < head`. If true, @@ -439,6 +452,7 @@ func (s *WalShipper) drive(in driveInput) error { return err } s.cursor = in.lsn + s.firstLiveEmitted.Store(true) // §IV.2.1 PrimaryLiveTail seed s.updateLagLocked() return nil } @@ -481,6 +495,7 @@ func (s *WalShipper) drive(in driveInput) error { return err } s.cursor = in.lsn + s.firstLiveEmitted.Store(true) // §IV.2.1 PrimaryLiveTail seed s.updateLagLocked() return nil } @@ -614,6 +629,7 @@ func (s *WalShipper) StartSession(fromLSN uint64) error { s.sessionActive = true s.mode = ModeBacklog s.saturationFired.Store(false) + s.firstLiveEmitted.Store(false) // §IV.2.1 PrimaryLiveTail reset per session return nil } @@ -833,3 +849,35 @@ func (s *WalShipper) SessionActive() bool { defer s.shipMu.Unlock() return s.sessionActive } + +// ProbeBarrierEligibility takes a single consistent snapshot of the +// §IV.2.1 PrimaryWalLegOk inputs under shipMu: +// +// debtZero = (cursor == head observed at this moment) +// liveTail = at least one EmitKindLive frame emitted in this session +// walLegOk = debtZero ∨ liveTail +// cursor = last-emitted LSN +// head = primary's head LSN at the snapshot moment +// +// Slice marker-only stage (§8.2.6 hardware oracle contract): callers +// observe these values and log them in the `barrier prepare` marker +// before frameBarrierReq is written. The values are NOT yet used to +// gate the BarrierReq emission — that gate replacement is the A-class +// wave which un-skips TestRecoverA_DebtZeroPath_BarrierEligible et al. +// +// The accessor name is suffixed with neither "Locked" nor "Unlocked" +// because it manages its own lock — internally takes shipMu, returns, +// releases. Callers must NOT hold shipMu themselves; passing through +// drive() is what serializes against in-flight emits. +// +// Pinned by §IV.2.1 / §8.2.6. +func (s *WalShipper) ProbeBarrierEligibility() (debtZero, liveTail, walLegOk bool, cursor, head uint64) { + s.shipMu.Lock() + defer s.shipMu.Unlock() + cursor = s.cursor + head = s.head.Head() + debtZero = cursor == head + liveTail = s.firstLiveEmitted.Load() + walLegOk = debtZero || liveTail + return +}