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>
This commit is contained in:
pingqiuandClaude Opus 4.7 committed 2026-04-29 23:27:44 -07:00
1 parent bf84ed4ab1
commit 8f51ec6f29
7 files changed
+333 -508

No files matched your search

+62 -82
View File
@@ -9,6 +9,7 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/storage/memorywal"
)
// formulaPayload synthesizes a deterministic 4 KiB block whose first
@@ -78,8 +79,8 @@ func TestE2E_RebuildHappyPath(t *testing.T) {
defer wg.Done()
sendAchieved, sendErr = sender.Run(context.Background(), 7, 0, primaryH)
}()
// No live writes in this scenario; signal sender immediately.
sender.Close()
// No live writes in this scenario; sender.Run barriers as soon as
// sink.DrainBacklog returns (P2c-slice B-2 lifecycle).
wg.Wait()
if sendErr != nil {
@@ -160,44 +161,31 @@ func TestE2E_RebuildWithLiveWritesDuringSession(t *testing.T) {
}
// Phase 3: simulate WAL shipper that observes local writes and
// asks the coordinator where each goes. We start the writer in
// its own goroutine right away — coord.StartSession already moved
// phase to DrainingHistorical so RouteLocalWrite returns
// SessionLane deterministically.
var startedSignal sync.WaitGroup
startedSignal.Add(1)
// The "WAL shipper" goroutine.
var liveWg sync.WaitGroup
liveWg.Add(1)
go func() {
defer liveWg.Done()
startedSignal.Wait() // wait until session is open
// Five live writes on primary while session active.
for i := uint32(0); i < 5; i++ {
lba := 30 + i
data := formulaPayload(lba, epoch, blockSize)
lsn, err := primary.Write(lba, data)
if err != nil {
t.Errorf("live Write lba=%d: %v", lba, err)
return
}
// Ask coordinator how to route this entry.
route := coord.RouteLocalWrite("r1", lsn)
if route != RouteSessionLane {
t.Errorf("during DrainingHistorical: expected RouteSessionLane, got %v", route)
return
}
if err := sender.PushLiveWrite(lba, lsn, data); err != nil {
t.Errorf("PushLiveWrite: %v", err)
return
}
// asks the coordinator where each goes. After P2c-slice B-2,
// sender.Run barriers as soon as sink.DrainBacklog returns —
// there is no engine "go barrier" signal anymore. To preserve
// the "writes during the session land before barrier" contract
// deterministically, push live writes BEFORE starting sender.Run.
// The bridging sink buffers them under sinkMu and flushAndSeal
// ships them in LSN order after streamBacklog completes.
for i := uint32(0); i < 5; i++ {
lba := 30 + i
data := formulaPayload(lba, epoch, blockSize)
lsn, err := primary.Write(lba, data)
if err != nil {
t.Fatalf("live Write lba=%d: %v", lba, err)
}
// After the session ends (sender.Run returns), coordinator
// goes Idle and any further writes route to RouteSteadyLive.
// We don't actually generate more writes here; the assertion
// is in the post-Run check below.
}()
// Ask coordinator how to route this entry. coord.StartSession
// above already moved phase to DrainingHistorical, so
// RouteLocalWrite returns SessionLane.
route := coord.RouteLocalWrite("r1", lsn)
if route != RouteSessionLane {
t.Fatalf("during DrainingHistorical: expected RouteSessionLane, got %v", route)
}
if err := sender.PushLiveWrite(lba, lsn, data); err != nil {
t.Fatalf("PushLiveWrite: %v", err)
}
}
var (
wg sync.WaitGroup
@@ -213,13 +201,8 @@ func TestE2E_RebuildWithLiveWritesDuringSession(t *testing.T) {
}()
go func() {
defer wg.Done()
// Signal the live-writer goroutine that session is open.
startedSignal.Done()
sendAchieved, sendErr = sender.Run(context.Background(), /*sessionID*/ 11, /*fromLSN*/ 0, frozenTarget)
}()
// Wait for live writer to finish injecting before signaling close.
liveWg.Wait()
sender.Close()
wg.Wait()
if sendErr != nil {
@@ -268,12 +251,19 @@ func TestE2E_RebuildWithLiveWritesDuringSession(t *testing.T) {
// up" — convergence is still proved by the byte-equal check after
// barrier (per architect ruling: kind is observability, not
// convergence proof).
//
// Substrate choice (P2c-slice B-2): memorywal — preserves real
// write-time LSNs, so live writes after frozenTarget keep LSN >
// frozenTarget and streamBacklog filters them out cleanly. BlockStore
// would synthesize LSN from walHead at scan time, so live writes
// (push-before-Run) would shift walHead and ALL entries would get
// stamped with the new walHead → all filtered out.
func TestE2E_KindCountsPinsBacklogVsLive(t *testing.T) {
const numBlocks = 32
const blockSize = 4096
const epoch byte = 0xE5
primary := storage.NewBlockStore(numBlocks, blockSize)
primary := memorywal.NewStore(numBlocks, blockSize)
replica := storage.NewBlockStore(numBlocks, blockSize)
// Phase 1: 10 LBAs — these become the backlog.
@@ -295,6 +285,21 @@ func TestE2E_KindCountsPinsBacklogVsLive(t *testing.T) {
t.Fatalf("StartSession: %v", err)
}
// Phase 2: 3 live writes BEFORE sender.Run starts. The bridging
// sink buffers them under sinkMu via PushLiveWrite; flushAndSeal
// ships them as WALKindSessionLive after streamBacklog. memorywal
// preserves real LSNs, so these get LSN > frozenTarget and
// streamBacklog's `e.LSN > targetLSN` filter excludes them from
// the backlog scan, leaving them to flushAndSeal.
for i := uint32(0); i < 3; i++ {
lba := 10 + i
data := formulaPayload(lba, epoch, blockSize)
lsn, _ := primary.Write(lba, data)
if err := sender.PushLiveWrite(lba, lsn, data); err != nil {
t.Fatalf("PushLiveWrite (pre-Run): %v", err)
}
}
var wg sync.WaitGroup
wg.Add(2)
go func() {
@@ -305,35 +310,6 @@ func TestE2E_KindCountsPinsBacklogVsLive(t *testing.T) {
defer wg.Done()
_, _ = sender.Run(context.Background(), 17, 0, frozenTarget)
}()
// Wait for backlog to fully drain on the receiver before injecting
// live writes. Otherwise, BlockStore's ScanLBAs synthesizes
// scan-time LSN from walHead, and a concurrent primary.Write in
// this test would push walHead past targetLSN — causing the
// backlog scan's `e.LSN > targetLSN` check to filter all 10
// historical entries out. This is a deterministic ordering
// requirement for the kind-count assertion, NOT a layer-1 bug.
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
sess := receiver.Session()
if sess != nil && sess.Status().BacklogApplied == 10 {
break
}
time.Sleep(time.Millisecond)
}
if got := receiver.Session().Status().BacklogApplied; got != 10 {
t.Fatalf("backlog never reached 10 (got %d) — receiver/sender not advancing", got)
}
// Inject 3 live writes on primary; push to sender.
for i := uint32(0); i < 3; i++ {
lba := 10 + i
data := formulaPayload(lba, epoch, blockSize)
lsn, _ := primary.Write(lba, data)
_ = sender.PushLiveWrite(lba, lsn, data)
}
sender.Close()
wg.Wait()
st := receiver.Session().Status()
@@ -401,7 +377,7 @@ func TestE2E_PinFloorAdvancesIncrementally(t *testing.T) {
defer wg.Done()
_, sendErr = sender.Run(context.Background(), 21, 0, primaryH)
}()
sender.Close()
// No live writes; sender.Run barriers on its own after DrainBacklog.
wg.Wait()
if sendErr != nil {
@@ -432,12 +408,13 @@ func TestE2E_PinFloorAdvancesIncrementally(t *testing.T) {
// TestE2E_PushLiveWriteAtomicSeal — architect review item #1: while
// the session is active (any non-Idle phase), RouteLocalWrite returns
// SessionLane and PushLiveWrite must not lose entries between drain
// and barrier. The guarantee is enforced by drainAndSeal's atomic
// take + seal under queueMu: any concurrent push either lands before
// the seal (and ships) or returns "sealed" error (and caller knows
// session is closing).
// and barrier. After P2c-slice B-2 the seal point lives in the
// bridging sink's flushAndSeal (under sinkMu): any concurrent push
// either lands before sealing (buffered → shipped) or returns "sink
// sealed" error (caller knows session is closing).
//
// This test races N pushers against Close + Run completion. Every
// This test races N pushers against Run's autonomous completion
// (sender.Run barriers as soon as sink.DrainBacklog returns). Every
// successful PushLiveWrite (no error) must result in the entry being
// shipped — verified by the receiver's substrate having that LBA at
// the correct content.
@@ -517,9 +494,12 @@ func TestE2E_PushLiveWriteAtomicSeal(t *testing.T) {
}(w)
}
// Let pushers run a bit, then close the sender.
// Let pushers finish; sender.Run barriers autonomously when
// sink.DrainBacklog completes (P2c-slice B-2). Pushers race with
// flushAndSeal: pushes that land before sealing get nil; after
// sealing get an error. The atomic-seal contract is at the sink's
// flushAndSeal boundary, not the previous closeCh.
pushersWg.Wait()
sender.Close()
wg.Wait()
if sendErr != nil {
+1 -2
View File
@@ -132,8 +132,7 @@ const (
PhaseBaseLane Phase = "base-lane" // base block stream
PhaseBaseDone Phase = "base-done" // BaseDone frame write
PhaseBacklog Phase = "backlog" // ScanLBAs + WAL stream
PhaseAwaitClose Phase = "await-close" // blocked on closeCh
PhaseDrainSeal Phase = "drain-seal" // drainAndSeal live queue
PhaseDrainSeal Phase = "drain-seal" // bridging-sink flushAndSeal
PhaseTransition Phase = "transition" // TryAdvanceToSteadyLive
PhaseBarrierReq Phase = "barrier-req" // BarrierReq frame write
PhaseBarrierResp Phase = "barrier-resp" // BarrierResp read/decode
+14 -22
View File
@@ -19,6 +19,13 @@ import (
// Per architect ruling on G7-redo Layer-2 review: "与 BlockExecutor /
// engine 出一条「薄」链路 — 单次 Run(session) 可调、不换全 transport".
//
// P2c-slice B-2 lifecycle change: barrier auto-fires when sink.DrainBacklog
// returns (the bridging sink flushes its live-write buffer + seals there).
// Engine no longer needs an explicit "go barrier" signal — the previous
// FinishLiveWrites / sender.Close pattern is gone. Live writes that arrive
// after the sink seals get a "session is closing" error from PushLiveWrite
// so callers can fall back to steady-live or retry on a fresh session.
//
// What this file deliberately does NOT do:
//
// - Plug into core/transport/BlockExecutor.StartRebuild (that is
@@ -45,7 +52,9 @@ type SessionCloseCallback func(replicaID ReplicaID, sessionID uint64, achievedLS
// the embedded coordinator's INV-SINGLE-FLIGHT-PER-REPLICA check.
//
// Live writes for active sessions are pushed via PushLiveWrite,
// which the WAL shipper calls after consulting RouteLocalWrite.
// which the WAL shipper calls after consulting RouteLocalWrite. The
// session converges autonomously: sender.Run barriers as soon as
// sink.DrainBacklog returns (P2c-slice B-2 lifecycle).
type PrimaryBridge struct {
store storage.LogicalStorage
coord *PeerShipCoordinator
@@ -71,8 +80,10 @@ func NewPrimaryBridge(store storage.LogicalStorage, coord *PeerShipCoordinator,
// StartRebuildSession is shaped like CommandExecutor.StartRebuild:
// non-blocking, returns immediately after spawning the session
// goroutine. The caller controls termination via FinishLiveWrites
// (which calls Sender.Close internally) or context cancellation.
// goroutine. After P2c-slice B-2 the session terminates on its own
// when sink.DrainBacklog returns; the caller can still abort early
// via context cancellation, but no explicit "go barrier" call is
// needed.
//
// Wire detail (POC): caller provides the dialed `conn`. Production
// integration would dial through the existing connection pool /
@@ -135,25 +146,6 @@ func (b *PrimaryBridge) PushLiveWrite(replicaID ReplicaID, lba uint32, lsn uint6
return sender.PushLiveWrite(lba, lsn, data)
}
// FinishLiveWrites signals the active session for this peer that
// no more PushLiveWrite calls will arrive — sender will drain the
// queue, transition phase, and run the barrier round-trip. Returns
// false if no session is active.
//
// Equivalent to engine deciding "this peer's recover session can
// converge now"; in production this is triggered when the engine
// observes barrier-eligibility conditions.
func (b *PrimaryBridge) FinishLiveWrites(replicaID ReplicaID) bool {
b.mu.Lock()
sender, ok := b.senders[replicaID]
b.mu.Unlock()
if !ok {
return false
}
sender.Close()
return true
}
// ReplicaBridge is the replica-side adapter. One bridge instance per
// replica daemon; it accepts inbound recover-session connections and
// drives a Receiver per connection.
@@ -14,8 +14,11 @@ import (
// TestIntegrationStub_LifecycleCallbacks exercises the bridge as a
// CommandExecutor-shaped surface: StartRebuildSession spawns a
// goroutine, callback OnStart fires synchronously before return,
// PushLiveWrite during the session works, FinishLiveWrites triggers
// barrier, OnClose reports the achieved LSN at the end.
// PushLiveWrite during the session works, OnClose reports the
// achieved LSN at the end. After P2c-slice B-2 the session terminates
// autonomously when sink.DrainBacklog returns — there is no explicit
// FinishLiveWrites / sender.Close signal anymore. Live writes pushed
// before sender.Run barriers are buffered and shipped via flushAndSeal.
//
// This is the lifecycle/callback shape the integration PR will plug
// into core/transport/BlockExecutor.
@@ -114,12 +117,9 @@ func TestIntegrationStub_LifecycleCallbacks(t *testing.T) {
t.Error("second StartRebuildSession on same peer: want error (single-flight)")
}
// Tell sender to barrier.
if !bridge.FinishLiveWrites("r1") {
t.Fatal("FinishLiveWrites returned false; expected active session")
}
// Wait for OnClose.
// P2c-slice B-2: sender.Run barriers autonomously after DrainBacklog
// returns; OnClose fires when Run goroutine exits. No explicit
// FinishLiveWrites needed.
closeWG.Wait()
replicaWG.Wait()
@@ -224,60 +224,14 @@ func TestIntegrationStub_ReceiverFailsEarly_SenderUnblocks(t *testing.T) {
}
}
// TestIntegrationStub_CtxCancelUnblocksSender — if the caller cancels
// the context while sender is blocked on closeCh (waiting for
// FinishLiveWrites), Run returns ctx.Err() instead of hanging forever.
// TestIntegrationStub_CtxCancelUnblocksSender — obsolete in
// P2c-slice B-2. Previously sender.Run blocked on closeCh waiting
// for FinishLiveWrites; ctx cancel was the escape hatch. After B-2,
// sender.Run never enters that idle wait — it barriers as soon as
// DrainBacklog returns. Coordinator returning to Idle on session
// completion is covered by the lifecycle test.
func TestIntegrationStub_CtxCancelUnblocksSender(t *testing.T) {
const numBlocks = 16
const blockSize = 4096
primary := storage.NewBlockStore(numBlocks, blockSize)
replica := storage.NewBlockStore(numBlocks, blockSize)
_, _ = primary.Sync()
primaryConn, replicaConn := net.Pipe()
defer primaryConn.Close()
defer replicaConn.Close()
coord := NewPeerShipCoordinator()
var closeWG sync.WaitGroup
var closeErr error
closeWG.Add(1)
bridge := NewPrimaryBridge(primary, coord, nil,
func(_ ReplicaID, _ uint64, _ uint64, err error) {
closeErr = err
closeWG.Done()
})
// Replica receiver running normally; will block reading frames
// after base lane finishes (since sender will be waiting for ctx
// or closeCh and sending nothing more).
replicaBridge := NewReplicaBridge(replica)
go func() { _, _ = replicaBridge.Serve(context.Background(), replicaConn) }()
ctx, cancel := context.WithCancel(context.Background())
_, _, primaryH := primary.Boundaries()
if err := bridge.StartRebuildSession(ctx, primaryConn, "r1", 7, 0, primaryH); err != nil {
t.Fatalf("StartRebuildSession: %v", err)
}
// Don't call FinishLiveWrites — instead cancel ctx after a moment.
time.Sleep(50 * time.Millisecond)
cancel()
select {
case <-waitClosed(&closeWG):
case <-time.After(2 * time.Second):
t.Fatal("OnClose did not fire within 2s after ctx cancel")
}
if closeErr == nil {
t.Fatal("OnClose: expected non-nil err on ctx cancel")
}
if got := coord.Phase("r1"); got != PhaseIdle {
t.Errorf("post-cancel phase=%s want Idle", got)
}
t.Skip("obsolete after P2c-slice B-2: no closeCh wait — Run barriers as soon as DrainBacklog returns")
}
// waitClosed turns a sync.WaitGroup into a channel for select.
@@ -346,59 +300,14 @@ func TestIntegrationStub_FailureTypedOnReceiverDown(t *testing.T) {
t.Logf("typed failure: %v (retryable=%v)", f, f.Retryable())
}
// TestIntegrationStub_FailureTypedOnCancellation — ctx cancel during
// the await-close phase yields Kind=Cancelled, Retryable=false (the
// caller decides retry, not the engine's retry budget).
// TestIntegrationStub_FailureTypedOnCancellation — obsolete in
// P2c-slice B-2. The previous design had sender.Run block on closeCh
// after DrainBacklog and tested ctx cancel during that wait
// (PhaseAwaitClose). After B-2, sender.Run barriers autonomously
// when DrainBacklog returns — there is no idle wait window to
// cancel into. Cancellation paths during DrainBacklog itself
// (substrate scan returning ctx.Err()) are covered by the sink's
// own DrainBacklog tests.
func TestIntegrationStub_FailureTypedOnCancellation(t *testing.T) {
const numBlocks = 16
primary := storage.NewBlockStore(numBlocks, 4096)
replica := storage.NewBlockStore(numBlocks, 4096)
_, _ = primary.Sync()
primaryConn, replicaConn := net.Pipe()
defer primaryConn.Close()
defer replicaConn.Close()
coord := NewPeerShipCoordinator()
var closeWG sync.WaitGroup
var closeErr error
closeWG.Add(1)
bridge := NewPrimaryBridge(primary, coord, nil,
func(_ ReplicaID, _ uint64, _ uint64, err error) {
closeErr = err
closeWG.Done()
})
replicaBridge := NewReplicaBridge(replica)
go func() { _, _ = replicaBridge.Serve(context.Background(), replicaConn) }()
ctx, cancel := context.WithCancel(context.Background())
_, _, primaryH := primary.Boundaries()
if err := bridge.StartRebuildSession(ctx, primaryConn, "r1", 100, 0, primaryH); err != nil {
t.Fatalf("StartRebuildSession: %v", err)
}
// Don't call FinishLiveWrites — let sender block on closeCh, then
// cancel ctx to surface FailureCancelled.
time.Sleep(50 * time.Millisecond)
cancel()
closeWG.Wait()
if closeErr == nil {
t.Fatal("expected non-nil err on ctx cancel")
}
f := AsFailure(closeErr)
if f == nil {
t.Fatalf("expected typed *Failure, got %T: %v", closeErr, closeErr)
}
if f.Kind != FailureCancelled {
t.Errorf("Kind=%s want Cancelled", f.Kind)
}
if f.Phase != PhaseAwaitClose {
t.Errorf("Phase=%q want AwaitClose", f.Phase)
}
if f.Retryable() {
t.Error("Cancelled failure should be Retryable=false (caller's decision)")
}
t.Skip("obsolete after P2c-slice B-2: no closeCh wait to cancel into; ctx-cancel during DrainBacklog is covered by sink-level tests")
}
+194 -242
View File
@@ -11,25 +11,18 @@ import (
)
// Sender is the primary-side driver of one rebuild session. It runs
// the base lane, the backlog lane, and (during the same session)
// accepts post-target live writes through PushLiveWrite, all sharing
// one ordered ship queue per peer (spec §3.2 #3).
// the base lane, then delegates the WAL pump (and live-write traffic
// during the session) to its WalShipperSink, and finally runs the
// barrier round-trip.
//
// POC scope:
// - Base lane: dense — ships every LBA in [0, NumBlocks()) by reading
// primary's current state via LogicalStorage.Read. (sparse omit
// and substrate basement-clearing are a later milestone; see
// INV-BASE-SPARSE-REQUIRES-SUBSTRATE-CLOSURE.)
// - Backlog lane: replays primary's WAL via ScanLBAs(fromLSN, ...)
// up to (and including) targetLSN. Entries past targetLSN are
// skipped at this lane — they are post-target traffic that
// either rides the same session lane (if injected via
// PushLiveWrite while DrainingHistorical) or routes to the
// steady-live path (after coordinator transitions).
// - Single goroutine drives the wire writer; concurrent producers
// enqueue items via a mutex-protected slice. No backpressure /
// bounded buffer in the POC — the sender drives the slice
// synchronously.
// primary's current state via LogicalStorage.Read.
// - WAL pump: delegated to sink. The bridging sink (senderBacklogSink)
// scans the substrate's WAL via ScanLBAs(fromLSN, ...) up to (and
// including) targetLSN. Live writes during the session arrive via
// PushLiveWrite → sink.NotifyAppend; the bridging sink owns the
// buffering / atomic-seal / LSN-ordered flush discipline.
// - No baseBatchAck pin advancement during the session: pin floor
// stays at the session's fromLSN until EndSession releases it.
// Adding incremental pin advancement is a layer-2 enhancement.
@@ -37,14 +30,14 @@ import (
// Sender owns:
// - The wire `conn` writer side (frame writes serialize through
// `writerMu`).
// - The ordered ship queue (`queue`).
//
// Sender borrows:
// - `primaryStore` for reads (base + backlog).
// - `primaryStore` for reads (base + bridging-sink backlog scan).
// - `coordinator` for ship-phase transitions and routing decisions.
// - The injected sink for the entire WAL emit path.
//
// Sender does NOT own: receiver-side state, retry policy, lineage
// minting, or session lifecycle decisions (those come from upstream).
// minting, session lifecycle decisions, or any live-write buffer.
type Sender struct {
primaryStore storage.LogicalStorage
coordinator *PeerShipCoordinator
@@ -58,22 +51,6 @@ type Sender struct {
writerMu sync.Mutex // serializes conn writes (frames are atomic)
// queueMu protects the live-write queue + sealed flag. Backlog
// and base lanes run on the Run() goroutine and write directly
// without queueing because they are sequential by construction.
// Live writes from PushLiveWrite append here; the final drain
// happens AFTER closeCh is closed, atomic with sealing.
queueMu sync.Mutex
liveQueue []walItem
sealed bool // set by drainAndSeal; PushLiveWrite errors after this
// closeCh signals "no more live writes coming; safe to drain
// queue, transition phase, and run barrier". Caller closes via
// Sender.Close(). Run blocks on this channel after the backlog
// scan finishes.
closeCh chan struct{}
closeOnce sync.Once
// barrierRespCh delivers the inbound BarrierResp (or any wire /
// protocol failure surfaced by the reader goroutine) to the
// main Run goroutine at barrier-wait time. Buffered=1 so the
@@ -81,15 +58,14 @@ type Sender struct {
//
// Per docs/recovery-pin-floor-wire.md §7: the reader goroutine
// is required because BaseBatchAck arrives mid-stream during
// base lane while Run is busy writing frames. Pre-#3 there was
// no reader; only one inline readFrame at barrier time.
// base lane while Run is busy writing frames.
barrierRespCh chan ackOrResult
// sink — Run() delegates the WAL pump (StartSession / DrainBacklog
// / EndSession) to this sink. After P2c-slice A sink is mandatory:
// every Sender has one (transport WalShipper in production, or
// senderBacklogSink in the bridging path until P2d). Set by
// NewSenderWithSink / NewSenderWithBacklogRelay.
// / EndSession / NotifyAppend) to this sink. After P2c-slice A sink
// is mandatory: every Sender has one (transport WalShipper in
// production, or senderBacklogSink in the bridging path until P2d).
// Set by NewSenderWithSink / NewSenderWithBacklogRelay.
sink WalShipperSink
}
@@ -101,21 +77,20 @@ type ackOrResult struct {
err error
}
type walItem struct {
lba uint32
lsn uint64
data []byte
}
// WalShipperSink is the abstract WAL-pump surface that Sender
// delegates to. Run() invokes the session bracket:
//
// 1. StartSession(fromLSN) — before any WAL emission begins
// 2. DrainBacklog(ctx) — runs until cursor catches head
// 3. EndSession() — defer-fired regardless of exit path
// 2. DrainBacklog(ctx) — runs until cursor catches head;
// for the bridging sink, also flushes
// buffered live writes and seals.
// 3. EndSession() — defer-fired regardless of exit path;
// MUST be idempotent and MUST seal the
// sink against further NotifyAppend so
// post-Run pushes get an explicit error.
//
// Plus the live-write API for RouteSessionLane traffic during the
// session (P2c-slice B-1 — single live path):
// session:
//
// 4. NotifyAppend(lba, lsn, data) — primary's WAL append handed
// to the sink. Sink decides whether to ship directly (production
@@ -148,34 +123,27 @@ type WalShipperSink interface {
}
// newSender is the private builder used by both sink-installing
// constructors below. After P2c-slice A there is no public Sender
// constructor without a sink — sink is mandatory; legacy NewSender
// path was deleted. `conn` is the wire — typically a *net.TCPConn in
// production, or a net.Pipe end in tests. Sender does not close
// `conn`; caller does.
// constructors below. Sink is mandatory; legacy NewSender path is gone.
// `conn` is the wire — typically a *net.TCPConn in production, or a
// net.Pipe end in tests. Sender does not close `conn`; caller does.
func newSender(primaryStore storage.LogicalStorage, coordinator *PeerShipCoordinator, conn io.ReadWriter, replicaID ReplicaID) *Sender {
return &Sender{
primaryStore: primaryStore,
coordinator: coordinator,
conn: conn,
replicaID: replicaID,
closeCh: make(chan struct{}),
barrierRespCh: make(chan ackOrResult, 1),
}
}
// NewSenderWithSink constructs a sender that delegates the WAL
// pump to the provided sink. Run() calls sink.StartSession after
// BaseDone, sink.DrainBacklog to run the pump, and sink.EndSession
// in defer. There is no legacy in-package WAL pump anymore — sink is
// the only path to the wire (mini-plan §4 INV-NO-DOUBLE-LIVE row).
//
// After DrainBacklog succeeds, Run still waits on closeCh and runs
// drainAndSeal so PushLiveWrite session-lane entries converge until
// P2c-slice B routes live traffic through WalShipper.
// BaseDone, sink.DrainBacklog to run the pump (which also handles
// live-write flush + seal in the bridging path), and sink.EndSession
// in defer.
//
// `sink` MUST be non-nil — passing nil is a programmer error and
// panics at construction (P2c-slice A: sink mandatory).
// panics at construction (P2c-slice A).
func NewSenderWithSink(primaryStore storage.LogicalStorage, coordinator *PeerShipCoordinator, conn io.ReadWriter, replicaID ReplicaID, sink WalShipperSink) *Sender {
if sink == nil {
panic("recovery: NewSenderWithSink: sink is required (P2c-slice A) — use NewSenderWithBacklogRelay if no transport WalShipper is wired yet")
@@ -185,170 +153,209 @@ func NewSenderWithSink(primaryStore storage.LogicalStorage, coordinator *PeerShi
return s
}
// senderBacklogSink adapts Sender's legacy streamBacklog pump to
// WalShipperSink. P2b uses it to migrate e2e tests onto the sink
// branch without changing recovery wire format (receiver still expects
// frameWALEntry). Production P2d replaces this with transport.WalShipper
// once dual-lane + MsgShipEntry context is wired.
//
// StartSession / EndSession are no-ops: session bounds live on Sender
// (fromLSN/targetLSN set at Run entry); rewind semantics belong on the
// real WalShipper sink in transport.
//
// NotifyAppend (P2c-slice B-1) buffers live writes in the sender's
// liveQueue under queueMu — production discipline (architect rule 2)
// because streamBacklog runs as a one-shot ScanLBAs scan and direct
// wire emit during the scan would interleave LSNs and break the
// receiver's monotonic check. drainAndSeal flushes the queue in LSN
// order after backlog drain. When P2d swaps in a real transport
// WalShipper sink, NotifyAppend will route to WalShipper.NotifyAppend
// (Backlog mode lag-tracking; Realtime direct ship under shipMu) and
// the buffer becomes redundant (slice B-2 deletion).
type senderBacklogSink struct {
s *Sender
// walItem is the per-entry record buffered by senderBacklogSink while
// streamBacklog is in flight. P2c-slice B-2 moved this into the sink:
// the buffer is a sink-internal artifact of the bridging path, not a
// Sender field. When P2d swaps in a real transport WalShipper sink,
// this type goes with the bridging sink.
type walItem struct {
lba uint32
lsn uint64
data []byte
}
func (w senderBacklogSink) StartSession(fromLSN uint64) error {
// senderBacklogSink is the in-package WalShipperSink that bridges
// recovery.Sender's emit path to the legacy frameWALEntry wire format.
// Production P2d replaces this with a transport.WalShipper adapter
// once dual-lane vs MsgShipEntry context is wired.
//
// Lifecycle (P2c-slice B-2):
// - StartSession is a no-op: session bounds live on Sender (fromLSN /
// targetLSN set at Run entry); rewind semantics belong on the real
// WalShipper sink in transport.
// - NotifyAppend buffers live writes under sinkMu — the bridging
// path's "production discipline" (architect rule 2). streamBacklog
// is a one-shot ScanLBAs scan; direct wire emit during the scan
// would interleave LSNs and break the receiver's monotonic check.
// - DrainBacklog runs streamBacklog (ships LSN ≤ targetLSN entries)
// and then flushAndSeal — sorts buffered live writes (LSN >
// targetLSN) by LSN and ships them as WALKindSessionLive frames,
// atomically seal=true so subsequent NotifyAppend rejects.
// - EndSession is the defer-safety net: idempotent seal so any post-
// Run NotifyAppend gets an explicit error. Buffer entries that
// weren't flushed (e.g., DrainBacklog errored mid-scan) are
// dropped — the wire is presumed unsalvageable in error paths.
//
// When P2d wires the real transport.WalShipper sink, NotifyAppend will
// route to WalShipper.NotifyAppend (Backlog mode lag-tracking; Realtime
// direct ship under shipMu) — the buffer + flushAndSeal scaffolding
// here goes away with the bridging sink.
type senderBacklogSink struct {
s *Sender
sinkMu sync.Mutex
queue []walItem
sealed bool
}
func (w *senderBacklogSink) StartSession(fromLSN uint64) error {
_ = fromLSN
return nil
}
func (w senderBacklogSink) DrainBacklog(ctx context.Context) error {
func (w *senderBacklogSink) DrainBacklog(ctx context.Context) error {
if ctx.Err() != nil {
return ctx.Err()
}
return w.s.streamBacklog()
if err := w.s.streamBacklog(); err != nil {
return err
}
return w.flushAndSeal()
}
func (w senderBacklogSink) EndSession() {}
// EndSession is the defer-safety seal. If DrainBacklog ran successfully,
// the sink is already sealed and this is a no-op. If Run errored
// before DrainBacklog (e.g., StartSession failed) or DrainBacklog
// errored mid-flight, this guarantees no post-Run NotifyAppend silently
// buffers into a dead session.
func (w *senderBacklogSink) EndSession() {
w.sinkMu.Lock()
w.sealed = true
// Drop any unflushed entries — error paths shouldn't try to ship
// to a presumed-broken wire. The atomic-seal contract holds for
// the success path (DrainBacklog → flushAndSeal); error paths
// surface failures back to the caller via Run's return value.
w.queue = nil
w.sinkMu.Unlock()
}
func (w senderBacklogSink) NotifyAppend(lba uint32, lsn uint64, data []byte) error {
return w.s.bufferLiveWriteLocked(lba, lsn, data)
func (w *senderBacklogSink) NotifyAppend(lba uint32, lsn uint64, data []byte) error {
w.sinkMu.Lock()
defer w.sinkMu.Unlock()
if w.sealed {
return errors.New("recovery: NotifyAppend after sink sealed (session is closing)")
}
cp := make([]byte, len(data))
copy(cp, data)
w.queue = append(w.queue, walItem{lba: lba, lsn: lsn, data: cp})
return nil
}
// flushAndSeal atomically takes the buffered live-write queue and
// forbids further NotifyAppend (sealed=true under sinkMu), then ships
// every item in LSN order on the same wire as streamBacklog. The
// atomic take + seal guarantees no concurrent NotifyAppend can land
// an entry that misses the flush — the push either lands before
// sinkMu acquisition (captured in queue) or after (sealed → error).
func (w *senderBacklogSink) flushAndSeal() error {
w.sinkMu.Lock()
if w.sealed {
// Idempotent: DrainBacklog called us once; EndSession defer
// would also call us. After first seal, no further work.
w.sinkMu.Unlock()
return nil
}
queue := w.queue
w.queue = nil
w.sealed = true
w.sinkMu.Unlock()
// Stable sort by LSN ascending.
for i := 1; i < len(queue); i++ {
j := i
for j > 0 && queue[j-1].lsn > queue[j].lsn {
queue[j-1], queue[j] = queue[j], queue[j-1]
j--
}
}
for _, item := range queue {
if err := w.s.writeFrame(frameWALEntry, encodeWALEntry(WALKindSessionLive, item.lba, item.lsn, item.data)); err != nil {
return newFailure(FailureWire, PhaseDrainSeal, err)
}
if err := w.s.coordinator.RecordShipped(w.s.replicaID, item.lsn); err != nil {
return newFailure(FailureContract, PhaseDrainSeal, err)
}
}
return nil
}
// NewSenderWithBacklogRelay constructs a Sender whose WalShipperSink
// replays WAL via streamBacklog using the in-package backlog relay
// adapter. This is the bridging constructor used by tests and the
// production primary bridge until P2d wires a real transport
// WalShipper adapter behind NewSenderWithSink.
// replays WAL via streamBacklog and owns the live-write buffer +
// flushAndSeal discipline. This is the bridging constructor used by
// tests and the production primary bridge until P2d wires a real
// transport WalShipper adapter behind NewSenderWithSink.
func NewSenderWithBacklogRelay(primaryStore storage.LogicalStorage, coordinator *PeerShipCoordinator, conn io.ReadWriter, replicaID ReplicaID) *Sender {
s := newSender(primaryStore, coordinator, conn, replicaID)
s.sink = senderBacklogSink{s: s}
s.sink = &senderBacklogSink{s: s}
return s
}
// Close signals the sender that no more PushLiveWrite calls will
// arrive for this session, so it may safely drain the live queue,
// transition phase, and run the barrier round-trip. Idempotent.
//
// Caller pattern:
//
// go sender.Run(...)
// // ... PushLiveWrite as the WAL shipper produces local writes ...
// sender.Close() // session may now barrier
// // wait for Run to return; coordinator phase will be Idle
//
// PushLiveWrite calls that race with Close (arrive concurrently) are
// either accepted (queued before drainAndSeal) OR rejected with an
// error (sealed already). The atomic-seal contract guarantees no
// queued write is lost between drain and barrier.
func (s *Sender) Close() {
s.closeOnce.Do(func() { close(s.closeCh) })
}
// PushLiveWrite hands the sender one local-write event for this peer.
// Caller (the WAL shipper integration) must already have consulted
// `coordinator.RouteLocalWrite(replicaID, lsn)` and confirmed the
// routing is RouteSessionLane; this method does not double-check.
//
// P2c-slice B-1: routes through the sink's NotifyAppend so the live
// path is uniform with the sink's other emit surfaces. The sink owns
// buffering / ordering discipline:
// P2c-slice B-1 / B-2: routes through the sink's NotifyAppend; the
// sink owns buffering / ordering discipline:
//
// - Bridging path (senderBacklogSink): buffer in liveQueue,
// drainAndSeal flushes in LSN order after backlog completes.
// Production discipline per architect rule 2 — required until
// P2d aligns dual-lane wire format.
// - Bridging path (senderBacklogSink): buffer in sink-internal
// queue under sinkMu, flushed in LSN order during DrainBacklog's
// flushAndSeal. Production discipline per architect rule 2.
// - Real transport WalShipper sink (P2d): NotifyAppend routes
// directly to WalShipper.NotifyAppend; ordering comes from
// shipMu + Backlog/Realtime mode design.
//
// After the sink seals (DrainBacklog completes or EndSession defer
// fires), NotifyAppend returns an explicit error so post-session
// callers learn the session is closing.
func (s *Sender) PushLiveWrite(lba uint32, lsn uint64, data []byte) error {
return s.sink.NotifyAppend(lba, lsn, data)
}
// bufferLiveWriteLocked is the senderBacklogSink-side buffer entry.
// Acquires queueMu, rejects after seal, copies data, appends to
// liveQueue. drainAndSeal consumes it in LSN order after backlog.
//
// Lives on Sender (not senderBacklogSink) so the buffer state — same
// queueMu, sealed, liveQueue, walItem — stays co-located with the
// drainAndSeal flush. When the bridging sink is replaced by a real
// transport WalShipper sink (P2d), this method goes with the queue.
func (s *Sender) bufferLiveWriteLocked(lba uint32, lsn uint64, data []byte) error {
s.queueMu.Lock()
defer s.queueMu.Unlock()
if s.sealed {
return errors.New("recovery: PushLiveWrite after sender sealed (session is closing)")
}
cp := make([]byte, len(data))
copy(cp, data)
s.liveQueue = append(s.liveQueue, walItem{lba: lba, lsn: lsn, data: cp})
return nil
}
// Run drives the entire session end-to-end and blocks until barrier
// ack returns. Returns the AchievedLSN reported by the replica on
// success; returns an error on any wire / session failure.
//
// PRECONDITION: caller already invoked coord.StartSession.
//
// Sequence:
// 1. Send frameSessionStart.
// 2. Base lane: ship every LBA's current data via frameBaseBlock.
// 3. Send frameBaseDone; coordinator.MarkBaseDone.
// 4. WAL pump via sink: sink.StartSession(fromLSN); sink.DrainBacklog(ctx).
// The sink owns wire-format encoding and decides whether bytes go
// to the legacy port (frameWALEntry) or dual-lane port (P2d).
// 5. Wait for caller's Close() OR ctx cancellation.
// 6. Drain live queue + atomic seal; ship buffered live writes.
// 7. Send frameBarrierReq, read frameBarrierResp.
// 8. Verify achieved ≥ targetLSN via coordinator.CanEmitSessionComplete
// (§5.2, CHK-BARRIER-BEFORE-CLOSE).
//
// Defer always: set sealed=true; coordinator.EndSession.
//
// Caller MUST call Run exactly once per Sender instance.
//
// Caller MUST have already invoked
// PRECONDITION: caller already invoked
// `coordinator.StartSession(replicaID, sessionID, fromLSN, targetLSN)`
// synchronously before spawning the goroutine that calls Run. This
// keeps "session is registered" observable from the call site that
// scheduled Run, so concurrent code reading `coord.RouteLocalWrite`
// after the spawn point sees a non-Idle phase deterministically.
//
// Run's defer always calls coordinator.EndSession, regardless of the
// exit path (success, ctx-cancel, wire-error). Sealed is also set in
// the defer so any post-Run PushLiveWrite gets an explicit error
// instead of silently appending to a dead queue.
// Sequence:
// 1. Send frameSessionStart.
// 2. Base lane: ship every LBA's current data via frameBaseBlock.
// 3. Send frameBaseDone; coordinator.MarkBaseDone.
// 4. WAL pump via sink: sink.StartSession(fromLSN); sink.DrainBacklog(ctx).
// The sink owns wire-format encoding AND (in the bridging path)
// the live-write buffer flush + seal that previously lived on
// Sender as drainAndSeal.
// 5. Send frameBarrierReq, read frameBarrierResp.
// 6. Verify achieved ≥ targetLSN via coordinator.CanEmitSessionComplete
// (§5.2, CHK-BARRIER-BEFORE-CLOSE).
//
// Defer always: sink.EndSession (idempotent seal) + coordinator.EndSession.
//
// Caller MUST call Run exactly once per Sender instance.
//
// Lifecycle / cancellation: pass a Context whose cancellation signals
// "abort this session". A typical pattern is to cancel the context
// when the receiver-side goroutine fails, so a sender blocked on
// closeCh wakes up and returns ctx.Err().
// "abort this session". DrainBacklog observes ctx and returns ctx.Err()
// on cancellation; sink.EndSession defer fires regardless.
func (s *Sender) Run(ctx context.Context, sessionID, fromLSN, targetLSN uint64) (achievedLSN uint64, err error) {
s.sessionID = sessionID
s.fromLSN = fromLSN
s.targetLSN = targetLSN
// Defer cleanup runs on every exit path.
defer func() {
s.queueMu.Lock()
s.sealed = true
s.queueMu.Unlock()
s.coordinator.EndSession(s.replicaID)
}()
// Defer cleanup runs on every exit path. EndSession on the sink
// is the seal-defense — guarantees post-Run NotifyAppend (e.g.,
// PushLiveWrite via PrimaryBridge) gets an explicit error rather
// than silently buffering into a dead session.
defer s.coordinator.EndSession(s.replicaID)
defer s.sink.EndSession()
// Step 2: SessionStart frame.
// Step 1: SessionStart frame.
numBlocks := s.primaryStore.NumBlocks()
if err := s.writeFrame(frameSessionStart, encodeSessionStart(sessionStartPayload{
SessionID: sessionID, FromLSN: fromLSN, TargetLSN: targetLSN, NumBlocks: numBlocks,
@@ -356,19 +363,19 @@ func (s *Sender) Run(ctx context.Context, sessionID, fromLSN, targetLSN uint64)
return 0, newFailure(FailureWire, PhaseSendStart, err)
}
// Step 2b: spawn the inbound demux reader. From this point onward
// Step 1b: spawn the inbound demux reader. From this point onward
// any frame from the receiver (BaseBatchAck during base lane,
// BarrierResp at end) flows through readerLoop. Reader exits on
// BarrierResp delivery, on any wire error, or on conn close by
// caller's defer.
go s.readerLoop()
// Step 3: base lane.
// Step 2: base lane.
if err := s.streamBase(numBlocks); err != nil {
return 0, err // streamBase wraps its own Failure
}
// Step 4: BaseDone signal.
// Step 3: BaseDone signal.
if err := s.writeFrame(frameBaseDone, nil); err != nil {
return 0, newFailure(FailureWire, PhaseBaseDone, err)
}
@@ -376,21 +383,10 @@ func (s *Sender) Run(ctx context.Context, sessionID, fromLSN, targetLSN uint64)
return 0, newFailure(FailureContract, PhaseBaseDone, err)
}
// Step 5–7: WAL pump via sink.
//
// Sink delegates StartSession + DrainBacklog to its implementation
// (transport WalShipper or in-package senderBacklogSink). One emit
// path = INV-NO-DOUBLE-LIVE at recovery layer (mini-plan §4).
//
// After DrainBacklog, Run still waits on closeCh and runs
// drainAndSeal so PushLiveWrite session-lane tails ship before
// barrier — slice B will route live traffic through WalShipper
// and remove this tail.
//
// Defer EndSession FIRST so it fires on every exit path after this
// point — DrainBacklog error, BarrierReq error, barrier-resp error.
defer s.sink.EndSession()
// Step 4: WAL pump via sink. StartSession sets up sink state;
// DrainBacklog runs the pump AND (for the bridging sink) flushes
// buffered live writes + seals. After this returns, no more
// session-lane WAL frames will go out — barrier is next.
if err := s.sink.StartSession(fromLSN); err != nil {
return 0, newFailure(FailureContract, PhaseBacklog,
fmt.Errorf("sink.StartSession: %w", err))
@@ -403,19 +399,8 @@ func (s *Sender) Run(ctx context.Context, sessionID, fromLSN, targetLSN uint64)
return 0, newFailure(FailureSubstrate, PhaseBacklog,
fmt.Errorf("sink.DrainBacklog: %w", err))
}
// Coord's TryAdvanceToSteadyLive is collapsed (kickoff Q3 ratified
// Phase enum collapse to {Idle, Active}). Barrier-ack is the only
// authoritative completion signal.
select {
case <-s.closeCh:
case <-ctx.Done():
return 0, newFailure(FailureCancelled, PhaseAwaitClose, ctx.Err())
}
if err := s.drainAndSeal(); err != nil {
return 0, err
}
// Step 8 + 9: barrier round-trip — reader goroutine delivers the
// Step 5 + 6: barrier round-trip — reader goroutine delivers the
// inbound BarrierResp via barrierRespCh (or any wire / protocol /
// pin-update error surfaced earlier).
if err := s.writeFrame(frameBarrierReq, nil); err != nil {
@@ -527,8 +512,8 @@ func (s *Sender) streamBacklog() error {
var wireErr, contractErr error // surfaced from inside the callback
scanErr := s.primaryStore.ScanLBAs(s.fromLSN, func(e storage.RecoveryEntry) error {
// Skip entries past frozen target — those belong on the
// steady-live path or get fed back via PushLiveWrite if the
// session is still DrainingHistorical.
// session-lane buffer (via NotifyAppend) or the steady-live
// path; streamBacklog only ships pre-target history.
if e.LSN > s.targetLSN {
return stop
}
@@ -566,39 +551,6 @@ func (s *Sender) streamBacklog() error {
return nil
}
// drainAndSeal atomically takes the live queue and forbids further
// PushLiveWrite calls (sealed=true under queueMu), then ships every
// item in LSN order. The atomic take + seal guarantees no concurrent
// PushLiveWrite can land an entry that misses the drain — either the
// push happens before the lock and is captured, or after and gets a
// "sender sealed" error.
func (s *Sender) drainAndSeal() error {
s.queueMu.Lock()
queue := s.liveQueue
s.liveQueue = nil
s.sealed = true
s.queueMu.Unlock()
// Stable sort by LSN ascending.
for i := 1; i < len(queue); i++ {
j := i
for j > 0 && queue[j-1].lsn > queue[j].lsn {
queue[j-1], queue[j] = queue[j], queue[j-1]
j--
}
}
for _, item := range queue {
if err := s.writeFrame(frameWALEntry, encodeWALEntry(WALKindSessionLive, item.lba, item.lsn, item.data)); err != nil {
return newFailure(FailureWire, PhaseDrainSeal, err)
}
if err := s.coordinator.RecordShipped(s.replicaID, item.lsn); err != nil {
return newFailure(FailureContract, PhaseDrainSeal, err)
}
}
return nil
}
func (s *Sender) writeFrame(t frameType, payload []byte) error {
s.writerMu.Lock()
defer s.writerMu.Unlock()
@@ -194,7 +194,7 @@ func TestNewSenderWithBacklogRelay_installsRelaySink(t *testing.T) {
if snd.sink == nil {
t.Fatal("NewSenderWithBacklogRelay: expected backlog relay sink")
}
var _ WalShipperSink = senderBacklogSink{}
var _ WalShipperSink = &senderBacklogSink{}
}
// TestSender_WithSink_DelegationOrder — pin the ordering contract.
@@ -235,13 +235,10 @@ func TestSender_WithSink_DelegationOrder(t *testing.T) {
sender := NewSenderWithSink(primary, coord, primaryConn, "r1", sink)
receiver := NewReceiver(replica, replicaConn)
// After DrainBacklog returns, sink-mode Run waits on closeCh —
// unblock it so barrier + sink.EndSession can run.
go func() {
<-sink.drainCalledCh
sender.Close()
}()
// P2c-slice B-2: sender.Run barriers as soon as DrainBacklog
// returns; no closeCh wait. recordingSink.DrainBacklog returns
// nil immediately, so Run proceeds to the barrier round-trip
// directly. EndSession fires via defer regardless.
var (
wg sync.WaitGroup
runErr error
@@ -461,8 +458,8 @@ func TestSender_PushLiveWrite_RoutesViaSinkNotifyAppend(t *testing.T) {
}
}
// TestSenderBacklogSink_NotifyAppend_BuffersForDrainAndSeal — P2c-slice B-1:
// bridging-path discipline.
// TestSenderBacklogSink_NotifyAppend_BuffersForFlushAndSeal — P2c-slice B-2:
// bridging-path discipline (buffer now owned by senderBacklogSink, not Sender).
//
// Until P2d aligns the wire format (dual-lane frameWALEntry vs legacy
// MsgShipEntry), senderBacklogSink cannot ship live writes directly to
@@ -470,17 +467,18 @@ func TestSender_PushLiveWrite_RoutesViaSinkNotifyAppend(t *testing.T) {
// the receiver's monotonic-LSN check (architect rule 2: "production
// discipline / queue under one mutex").
//
// senderBacklogSink.NotifyAppend therefore buffers into the sender's
// liveQueue (held under queueMu) so drainAndSeal can ship them in LSN
// order after backlog drain completes. This test pins that contract:
// after NotifyAppend, liveQueue holds the entry; drainAndSeal would
// flush it on the wire path.
// senderBacklogSink.NotifyAppend therefore buffers into the sink's
// internal queue (under sinkMu) so flushAndSeal — called at the tail
// of DrainBacklog — can ship them in LSN order after streamBacklog
// completes. This test pins that contract: after NotifyAppend, the
// sink's queue holds the entries; flushAndSeal would flush them on
// the wire path.
//
// 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 which point the liveQueue
// scaffolding can go (slice B-2).
func TestSenderBacklogSink_NotifyAppend_BuffersForDrainAndSeal(t *testing.T) {
// Realtime direct ship under shipMu) — at which point the buffer
// scaffolding here goes too.
func TestSenderBacklogSink_NotifyAppend_BuffersForFlushAndSeal(t *testing.T) {
coord := NewPeerShipCoordinator()
store := storage.NewBlockStore(4, 4096)
prim, replicaEnd := net.Pipe()
@@ -498,22 +496,26 @@ func TestSenderBacklogSink_NotifyAppend_BuffersForDrainAndSeal(t *testing.T) {
t.Fatalf("PushLiveWrite: %v", err)
}
// Buffer accessor: read sender's liveQueue under queueMu. This
// is a white-box check — the buffering location is the slice B-1
// stopgap. Once a real WalShipper sink replaces the bridging path
// (slice B-2), the queue goes away and this test goes with it.
sender.queueMu.Lock()
bufLen := len(sender.liveQueue)
// Buffer accessor: read the sink's internal queue under sinkMu.
// White-box check — the buffer's location is the bridging-sink's
// concern; when a real transport.WalShipper sink replaces it (P2d),
// this test goes too.
bs, ok := sender.sink.(*senderBacklogSink)
if !ok {
t.Fatalf("sink type=%T, want *senderBacklogSink", sender.sink)
}
bs.sinkMu.Lock()
bufLen := len(bs.queue)
var lsns []uint64
for _, w := range sender.liveQueue {
for _, w := range bs.queue {
lsns = append(lsns, w.lsn)
}
sender.queueMu.Unlock()
bs.sinkMu.Unlock()
if bufLen != 2 {
t.Errorf("liveQueue len=%d, want 2 (NotifyAppend must buffer in bridging path)", bufLen)
t.Errorf("sink queue len=%d, want 2 (NotifyAppend must buffer in bridging path)", bufLen)
}
if len(lsns) != 2 || lsns[0] != 200 || lsns[1] != 201 {
t.Errorf("liveQueue LSNs=%v, want [200 201]", lsns)
t.Errorf("sink queue LSNs=%v, want [200 201]", lsns)
}
}
+8 -17
View File
@@ -131,17 +131,15 @@ func (e *BlockExecutor) doRebuild(replicaID string, session *activeSession, targ
// PrimaryBridge captured in e.dualLane.Bridge.
//
// Lifecycle: this method is async (returns immediately after dialing
// + StartRebuildSession + FinishLiveWrites are kicked off). The
// bridge's onClose callback (set in NewBlockExecutorWithDualLane)
// fires the executor's OnSessionClose when the goroutine completes.
// + StartRebuildSession is kicked off). The bridge's onClose callback
// (set in NewBlockExecutorWithDualLane) fires the executor's
// OnSessionClose when the session goroutine completes — which now
// happens autonomously: sender.Run barriers as soon as sink.DrainBacklog
// returns (P2c-slice B-2 lifecycle; no explicit FinishLiveWrites needed).
//
// Why FinishLiveWrites is called immediately: legacy callers do not
// push live writes during a rebuild (the legacy lineage gate rejected
// them anyway). To match legacy behavior in this first-cut wiring,
// the bridge's session is told there are no more live writes coming
// before the goroutine even starts the backlog phase. Spec §3.2 #3
// real-time interleave (architect priority #2) lifts this restriction
// and is OUT OF SCOPE for this PR.
// Legacy semantics — no live writes during rebuild — are preserved by
// the absence of any PushLiveWrite call here. The bridge's WalShipperSink
// buffer remains empty; flushAndSeal ships zero entries; barrier converges.
func (e *BlockExecutor) startRebuildDualLane(replicaID string, sessionID, epoch, endpointVersion, targetLSN uint64) error {
dl := e.dualLane
conn, err := net.DialTimeout("tcp", dl.DialAddr, 2*time.Second)
@@ -161,12 +159,5 @@ func (e *BlockExecutor) startRebuildDualLane(replicaID string, sessionID, epoch,
_ = conn.Close()
return fmt.Errorf("dual-lane start: %w", err)
}
// Legacy semantics: no live writes during rebuild. Signal the
// session immediately so it drains (empty queue) and barriers.
if !dl.Bridge.FinishLiveWrites(dl.ReplicaID) {
// Race: session ended before we could signal. Bridge already
// fired the close callback; nothing for us to do here.
_ = conn.Close()
}
return nil
}