recovery: P2c-B-1 — single live path via sink.NotifyAppend (TDD)

Add NotifyAppend(lba, lsn, data) error to WalShipperSink interface.
Sender.PushLiveWrite now routes through s.sink.NotifyAppend instead
of touching liveQueue directly — the sink owns buffering / ordering
discipline.

Bridging path (senderBacklogSink) implements NotifyAppend by
buffering into the sender's liveQueue under queueMu — production
discipline (architect rule 2). streamBacklog is one-shot ScanLBAs;
direct wire emit during the scan would interleave LSNs and break
the receiver's monotonic-LSN check, so the buffer + ordered
drainAndSeal flush stays as the safety net until P2d aligns the
dual-lane wire format.

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 that point the queueMu /
liveQueue / drainAndSeal scaffolding can be deleted (slice B-2).

Tests:
  + TestSender_PushLiveWrite_RoutesViaSinkNotifyAppend — RED→GREEN,
    pins the routing contract (incl. error propagation from sink).
  + TestSenderBacklogSink_NotifyAppend_BuffersForDrainAndSeal — pins
    the bridging-path buffer discipline.

  recordingSink in tests gains NotifyAppend + snapshotNotifyAppend.

Verified:
  - go test ./core/recovery/ — all PASS, including 5 e2e tests
    (PushLiveWriteAtomicSeal exercises mid-session writes and
    barrier convergence end-to-end).
  - go test ./core/transport/ ./core/replication/{,component} — all PASS.

Note: dual-lane frameWALEntry vs MsgShipEntry alignment remains P2d;
backlog relay continues as the bridging sink until then.

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:00:30 -07:00
1 parent 616583fc38
commit bf84ed4ab1
2 files changed
+203 -14

No files matched your search

+48 -7
View File
@@ -108,19 +108,27 @@ type walItem struct {
}
// WalShipperSink is the abstract WAL-pump surface that Sender
// delegates to in P2 (mini-plan §3 P2). When provided, Run() invokes:
// 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
//
// Plus the live-write API for RouteSessionLane traffic during the
// session (P2c-slice B-1 — single live path):
//
// 4. NotifyAppend(lba, lsn, data) — primary's WAL append handed
// to the sink. Sink decides whether to ship directly (production
// WalShipper Realtime mode) or buffer for ordered drain (bridging
// senderBacklogSink). Sender.PushLiveWrite routes here.
//
// Implementations live OUTSIDE this package (transport.WalShipper
// satisfies it via duck typing — no import cycle since the
// interface lives here). The contract intentionally avoids exposing
// wire format, lineage, or coord state — those are sink-side
// concerns. Sink decides where bytes go (legacy port MsgShipEntry
// vs dual-lane port frameWALEntry); Sender just orchestrates the
// session bracket around the pump.
// session bracket and routes live writes through.
//
// Architect P1 review (2026-04-29) integration rules — must hold at
// the layer that constructs the sink:
@@ -136,6 +144,7 @@ type WalShipperSink interface {
StartSession(fromLSN uint64) error
DrainBacklog(ctx context.Context) error
EndSession()
NotifyAppend(lba uint32, lsn uint64, data []byte) error
}
// newSender is the private builder used by both sink-installing
@@ -185,6 +194,16 @@ func NewSenderWithSink(primaryStore storage.LogicalStorage, coordinator *PeerShi
// 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
}
@@ -203,6 +222,10 @@ func (w senderBacklogSink) DrainBacklog(ctx context.Context) error {
func (w senderBacklogSink) EndSession() {}
func (w senderBacklogSink) NotifyAppend(lba uint32, lsn uint64, data []byte) error {
return w.s.bufferLiveWriteLocked(lba, lsn, data)
}
// 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
@@ -238,12 +261,30 @@ func (s *Sender) Close() {
// `coordinator.RouteLocalWrite(replicaID, lsn)` and confirmed the
// routing is RouteSessionLane; this method does not double-check.
//
// Live writes are buffered until the backlog drain phase finishes,
// then flushed in LSN order before barrier. POC simplification —
// in production the sender would interleave them with backlog by
// LSN order in real time. Spec §3.2 #3 (single ordered queue) is
// preserved at the level of "post-backlog drain, before barrier".
// 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:
//
// - 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.
// - Real transport WalShipper sink (P2d): NotifyAppend routes
// directly to WalShipper.NotifyAppend; ordering comes from
// shipMu + Backlog/Realtime mode design.
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 {
@@ -36,21 +36,30 @@ import (
"github.com/seaweedfs/seaweed-block/core/storage"
)
// notifyAppendCall captures one NotifyAppend invocation for assertions.
type notifyAppendCall struct {
lba uint32
lsn uint64
data []byte
}
// recordingSink is a mock WalShipperSink that captures call order
// + arguments. Tests assert against the recorded log to pin
// delegation ordering.
type recordingSink struct {
mu sync.Mutex
startCalls int
startFromLSNs []uint64
drainCalls int
endCalls int
callOrder []string // sequence of method names
startCalls int
startFromLSNs []uint64
drainCalls int
endCalls int
notifyAppendCalls []notifyAppendCall
callOrder []string // sequence of method names
// Test injection knobs.
startErr error
drainErr error
startErr error
drainErr error
notifyAppendErr error
// drainBlocksUntil is closed by the test to release a blocked
// DrainBacklog call. nil = return immediately.
@@ -117,6 +126,17 @@ func (r *recordingSink) EndSession() {
r.mu.Unlock()
}
func (r *recordingSink) NotifyAppend(lba uint32, lsn uint64, data []byte) error {
r.mu.Lock()
cp := make([]byte, len(data))
copy(cp, data)
r.notifyAppendCalls = append(r.notifyAppendCalls, notifyAppendCall{lba: lba, lsn: lsn, data: cp})
r.callOrder = append(r.callOrder, "NotifyAppend")
err := r.notifyAppendErr
r.mu.Unlock()
return err
}
func (r *recordingSink) snapshot() (startCalls, drainCalls, endCalls int, order []string) {
r.mu.Lock()
defer r.mu.Unlock()
@@ -125,6 +145,14 @@ func (r *recordingSink) snapshot() (startCalls, drainCalls, endCalls int, order
return r.startCalls, r.drainCalls, r.endCalls, o
}
func (r *recordingSink) snapshotNotifyAppend() []notifyAppendCall {
r.mu.Lock()
defer r.mu.Unlock()
out := make([]notifyAppendCall, len(r.notifyAppendCalls))
copy(out, r.notifyAppendCalls)
return out
}
// TestNewSenderWithSink_NilSinkPanics — P2c-slice A: sink is mandatory.
//
// Before P2c, NewSenderWithSink(..., nil) silently promoted to the
@@ -369,3 +397,123 @@ func TestSender_WithSink_NoStreamBacklogReachable(t *testing.T) {
// originates from a non-sink code path.
t.Skip("TODO impl: sink-installed Sender does NOT run streamBacklog (P2a soft assert; P2c compile-time)")
}
// TestSender_PushLiveWrite_RoutesViaSinkNotifyAppend — P2c-slice B-1:
// the single live path. recovery.Sender.PushLiveWrite is the recovery-
// layer entry point for RouteSessionLane writes; after slice B-1 it
// MUST delegate to s.sink.NotifyAppend instead of touching liveQueue
// directly. The sink — production transport WalShipper or bridging
// senderBacklogSink — owns the buffering / ordering discipline.
//
// What this test pins:
// - PushLiveWrite invokes sink.NotifyAppend exactly once per call.
// - lba/lsn/data are forwarded verbatim (caller's bytes; sink
// decides whether to copy).
// - When sink.NotifyAppend returns error, PushLiveWrite returns it
// (caller surfaces the failure to the engine).
//
// What this test does NOT pin (slice B-2 / P2d concerns):
// - Whether liveQueue / drainAndSeal scaffolding is removed.
// - Wire format of session-live frames (frameWALEntry vs MsgShipEntry).
func TestSender_PushLiveWrite_RoutesViaSinkNotifyAppend(t *testing.T) {
coord := NewPeerShipCoordinator()
store := storage.NewBlockStore(4, 4096)
prim, replicaEnd := net.Pipe()
defer prim.Close()
defer replicaEnd.Close()
sink := newRecordingSink()
sender := NewSenderWithSink(store, coord, prim, "r1", sink)
// Three live writes during a hypothetical session window.
calls := []notifyAppendCall{
{lba: 0, lsn: 100, data: []byte{0xAA, 0xBB}},
{lba: 1, lsn: 101, data: []byte{0xCC}},
{lba: 2, lsn: 102, data: []byte{0xDD, 0xEE, 0xFF}},
}
for _, c := range calls {
if err := sender.PushLiveWrite(c.lba, c.lsn, c.data); err != nil {
t.Fatalf("PushLiveWrite(lba=%d lsn=%d): %v", c.lba, c.lsn, err)
}
}
got := sink.snapshotNotifyAppend()
if len(got) != len(calls) {
t.Fatalf("sink.NotifyAppend called %d times; want %d (PushLiveWrite must route via sink)", len(got), len(calls))
}
for i, want := range calls {
if got[i].lba != want.lba || got[i].lsn != want.lsn {
t.Errorf("call %d: got lba=%d lsn=%d, want lba=%d lsn=%d",
i, got[i].lba, got[i].lsn, want.lba, want.lsn)
}
if !bytes.Equal(got[i].data, want.data) {
t.Errorf("call %d: data mismatch: got=%x want=%x", i, got[i].data, want.data)
}
}
// Error propagation: when sink.NotifyAppend errors, PushLiveWrite
// surfaces the error to the caller.
sink.mu.Lock()
sink.notifyAppendErr = errors.New("synthetic NotifyAppend failure")
sink.mu.Unlock()
if err := sender.PushLiveWrite(3, 103, []byte{0x42}); err == nil {
t.Errorf("PushLiveWrite did not surface sink.NotifyAppend error")
}
}
// TestSenderBacklogSink_NotifyAppend_BuffersForDrainAndSeal — P2c-slice B-1:
// bridging-path discipline.
//
// Until P2d aligns the wire format (dual-lane frameWALEntry vs legacy
// MsgShipEntry), senderBacklogSink cannot ship live writes directly to
// the wire — it would interleave with streamBacklog frames and break
// 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.
//
// 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) {
coord := NewPeerShipCoordinator()
store := storage.NewBlockStore(4, 4096)
prim, replicaEnd := net.Pipe()
defer prim.Close()
defer replicaEnd.Close()
sender := NewSenderWithBacklogRelay(store, coord, prim, "r1")
// Push two live writes via the public PushLiveWrite path; this
// goes Sender.PushLiveWrite → sink.NotifyAppend → buffer.
if err := sender.PushLiveWrite(7, 200, []byte{0x11, 0x22}); err != nil {
t.Fatalf("PushLiveWrite: %v", err)
}
if err := sender.PushLiveWrite(8, 201, []byte{0x33}); err != nil {
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)
var lsns []uint64
for _, w := range sender.liveQueue {
lsns = append(lsns, w.lsn)
}
sender.queueMu.Unlock()
if bufLen != 2 {
t.Errorf("liveQueue 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)
}
}