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 599f60e /
a08dea1 / faafa46.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 4.7 committed 2026-05-01 15:23:45 -07:00
1 parent faafa468c5
commit 32b16004fa
6 files changed
+374

No files matched your search

@@ -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:<barrierAttempt>` 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:<n>` 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).
@@ -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)
}
}
+74
View File
@@ -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:<n>`).
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
@@ -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()
}
@@ -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()
}
@@ -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
}