fix(recovery,transport): dual-lane rebuild WAL-recycle + completion marker

Hardware-validated fix for the silent rebuild stall on 40da4c8. Three
coordinated changes that close the gap between unit-test-green and
hardware-completing dual-lane rebuild:

1. **`startRebuildDualLane` — sentinel translation**
   Caller passed `fromLSN=0` to the bridge, taken literally by
   `WalShipper.StartSession(0)`. On a primary that's been running,
   the WAL retention floor is at `checkpointLSN` (entries through
   the checkpoint are durable in the extent and the WAL ring has
   recycled past 0); `ScanLBAs(0)` immediately returns
   `ErrWALRecycled`, the wal goroutine errors, sender exits before
   barrier emission, hardware silently stalls.

   Fix: pass `sessionFromLSN = targetLSN` (the snapshot pin). Base
   lane covers the snapshot through the checkpoint, WAL drain has
   nothing to ship at the pin (cursor==head), live writes during
   the session flow via NotifyAppend on the steady-state path.

2. **`WalShipper.DrainBacklog` — cursor-caught-up shortcut**
   At the dual-lane bootstrap with `cursor == fromLSN == targetLSN
   == primary head`, the loop entered ScanLBAs and hit the recycle
   gate. Add an early shortcut: if `cursor >= head` at iter start,
   skip ScanLBAs and try the R1 transition directly.

3. **`RebuildSession.SeedWalApplied` + receiver wiring**
   For a base-only rebuild (WAL drain ships nothing), `walApplied`
   stayed at 0; `TryComplete`'s `walApplied >= targetLSN` conjunct
   could never hold. Seed it with `fromLSN` at SessionStart so the
   predicate satisfies after `MarkBaseComplete` + `WitnessBarrier`.

4. **`executor.go` dual-lane onClose — completion marker**
   QA harness `wait_until_rebuild_complete` greps for
   `executor: rebuild complete, sent N blocks (targetLSN=N)` —
   emitted only by the legacy `doRebuild` path. Mirror it on the
   dual-lane bridge's onClose callback so the harness recognizes
   completion identically across modes.

Hardware result (G7 #2 — empty replica join, 1000 LBAs):
  rebuild dispatched in 1s, completed in 1s after dispatch
  (total 2s), 1000 LBAs byte-equal verified post-rebuild.
  Markers fired: `barrier prepare ... WalLegOk=true` +
  `barrier handshake ... match=true` + peer state
  `catching_up → healthy`.

Known seam (out of scope, T4-during-live-writes):
  When live writes arrive during the session, the receiver's T4
  monotonic checker expects `lsn == appliedWalLSN+1` where
  `appliedWalLSN` is seeded to `fromLSN`. Live writes get LSNs
  starting at `fromLSN`, breaking T4. Resolving this requires
  splitting the wire-fromLSN (T4 expectation) from the
  shipper-anchor (DrainBacklog cursor) — separate work. The
  hardware harness's scenario #5 (concurrent writes during
  rebuild) hits an unrelated probe-loop dispatch issue first
  and never gets to exercise this seam.

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 18:02:49 -07:00
1 parent cb60bd396d
commit 8f10be2869
5 files changed
+93 -6

No files matched your search

@@ -186,6 +186,28 @@ func (s *RebuildSession) MarkBaseComplete() {
s.store.AdvanceFrontier(s.targetLSN)
}
// SeedWalApplied seeds walApplied at session start with the receiver's
// fromLSN watermark. Called by the receiver after constructing the
// session in frameSessionStart, BEFORE any ApplyWALEntry.
//
// Rationale: for a "rebuild" session where the base lane covers the
// entire snapshot through targetLSN, no WAL frames will arrive (nothing
// to drain past the pin on the primary side). Without seeding, walApplied
// stays at 0 and TryComplete's `walApplied >= targetLSN` conjunct never
// holds — base-only rebuilds would never close. Seeding with fromLSN
// represents "the receiver starts the session already at or past
// fromLSN by virtue of base-lane coverage"; ApplyWALEntry monotonically
// advances it from there if WAL frames do arrive.
//
// Idempotent: only advances; lower seeds are silently ignored.
func (s *RebuildSession) SeedWalApplied(lsn uint64) {
s.mu.Lock()
defer s.mu.Unlock()
if lsn > s.walApplied {
s.walApplied = lsn
}
}
// WitnessBarrier latches the barrier-arrival witness. Called by the
// receiver immediately on frameBarrierReq arrival, BEFORE TryComplete.
//
+6
View File
@@ -143,6 +143,12 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) {
}
r.sessionID = s.SessionID
r.session = NewRebuildSession(r.store, s.TargetLSN)
// Base-only rebuild gate: seed walApplied with fromLSN so
// TryComplete's `walApplied >= targetLSN` conjunct can hold
// when no WAL frames arrive (base lane covers the snapshot
// through targetLSN; primary's WAL drain ships nothing
// past the pin). See RebuildSession.SeedWalApplied doc.
r.session.SeedWalApplied(s.FromLSN)
r.recvFromLSN = s.FromLSN
r.appliedWalLSN = s.FromLSN
log.Printf("g7-debug: Receiver.Run frameSessionStart sessionID=%d fromLSN=%d targetLSN=%d numBlocks=%d", s.SessionID, s.FromLSN, s.TargetLSN, s.NumBlocks)
+10
View File
@@ -211,6 +211,16 @@ func NewBlockExecutorWithDualLane(
}
},
func(rid recovery.ReplicaID, sid uint64, achieved uint64, err error) {
// Hardware-harness completion marker (matches the legacy
// doRebuild Printf form so QA's wait_until_rebuild_complete
// helper regex catches the dual-lane path identically). The
// "blocks sent" count is the dense streamBase coverage (==
// volume's NumBlocks); future sparse base lane would emit
// the actual count.
if err == nil {
log.Printf("executor: rebuild complete, sent %d blocks (targetLSN=%d)",
e.primaryStore.NumBlocks(), achieved)
}
e.mu.Lock()
cb := e.onSessionClose
e.mu.Unlock()
+26 -6
View File
@@ -203,13 +203,33 @@ func (e *BlockExecutor) startRebuildDualLane(replicaID string, sessionID, epoch,
steadyConn, steadyLineage, steadyProfile,
)
// fromLSN=0 for full rebuild matches the legacy doRebuild semantic
// (base lane covers everything; no catch-up tail). When a future
// caller wants partial rebuild from a specific LSN, the
// StartRebuild signature would need fromLSN added — out of scope.
log.Printf("g7-debug: startRebuildDualLane calling Bridge.StartRebuildSessionWithSink replica=%s sessionID=%d targetLSN=%d", replicaID, sessionID, targetLSN)
// Rebuild-sentinel translation: caller passes targetLSN as the
// frozen frontier the replica must reach. The session's "fromLSN"
// is the snapshot pin — the LSN through which the base lane's
// extent snapshot is durable. WAL drain ships entries past the pin
// up to targetLSN.
//
// For a full rebuild (replica empty / too far behind retention to
// catch up via WAL alone), pin = targetLSN: base covers the snapshot
// through the checkpoint, WAL drain has nothing to ship at session
// start (cursor==head; see WalShipper.DrainBacklog cursor-caught-up
// shortcut), and any new writes during the session flow via
// NotifyAppend on the live path.
//
// Without this translation, passing fromLSN=0 to WalShipper.StartSession
// makes DrainBacklog's ScanLBAs(0) hit the recycle gate
// (`fromLSN <= floor=checkpointLSN`) and fail-fast — wal goroutine
// errors before barrier emission, hardware silently stalls.
// Hardware-validated 2026-05-02 (g7-debug trail captured the
// recycle error pre-fix).
//
// Future: when callers want catch-up-from-replicaLSN semantics,
// extend the StartRebuild signature with a `pin uint64` param;
// today targetLSN-as-pin is the only mode.
sessionFromLSN := targetLSN
log.Printf("g7-debug: startRebuildDualLane calling Bridge.StartRebuildSessionWithSink replica=%s sessionID=%d sessionFromLSN=%d targetLSN=%d", replicaID, sessionID, sessionFromLSN, targetLSN)
if err := dl.Bridge.StartRebuildSessionWithSink(
context.Background(), conn, argRID, sessionID, 0, targetLSN, sink,
context.Background(), conn, argRID, sessionID, sessionFromLSN, targetLSN, sink,
); err != nil {
log.Printf("g7-debug: startRebuildDualLane Bridge.StartRebuildSessionWithSink err replica=%s err=%v", replicaID, err)
_ = conn.Close()
@@ -719,6 +719,35 @@ func (s *WalShipper) DrainBacklog(ctx context.Context) error {
s.shipMu.Unlock()
log.Printf("g7-debug: WalShipper.DrainBacklog iter replica=%s cursor=%d head=%d totalEmitted=%d", s.replicaID, cursor, head, totalEmitted)
// Cursor-already-caught-up shortcut: if cursor >= head at iter
// start, there's nothing to scan from substrate. Skip ScanLBAs
// (which would hit the recycle gate when cursor == checkpointLSN
// at the boundary) and try R1 transition directly.
//
// Hits in the dual-lane rebuild bootstrap (cursor == fromLSN ==
// targetLSN == primary head, no entries to drain) — pre-fix this
// path errored out via ErrWALRecycled and stalled hardware.
if cursor >= head {
s.shipMu.Lock()
head = s.head.Head() // re-read under lock
if s.cursor >= head {
if s.assertCaughtUpAndEnableTailShipLocked(head) {
s.shipMu.Unlock()
return nil
}
}
s.shipMu.Unlock()
// Head moved during the check; loop and re-scan.
if s.cfg.IdleSleep > 0 {
select {
case <-ctx.Done():
return fmt.Errorf("walshipper: DrainBacklog cancelled: %w", ctx.Err())
case <-time.After(s.cfg.IdleSleep):
}
}
continue
}
// Pull-and-ship one scan cycle. ScanLBAs iterates entries
// with LSN > cursor; emit each under shipMu (so concurrent
// NotifyAppend serializes naturally and INV-NO-DOUBLE-LIVE