diff --git a/seaweed-block/core/recovery/bridge_with_sink_test.go b/seaweed-block/core/recovery/bridge_with_sink_test.go new file mode 100644 index 0000000000..d07c0dafde --- /dev/null +++ b/seaweed-block/core/recovery/bridge_with_sink_test.go @@ -0,0 +1,155 @@ +package recovery + +// PrimaryBridge.StartRebuildSessionWithSink — pre-decision parallel +// wiring (P2d-blocked for production enable). The method exists so +// production callers can plug a real `transport.RecoverySink` adapter +// today without changing the bridge's public surface later. This file +// pins: +// - sink == nil rejected with explicit error +// - injected sink receives StartSession + DrainBacklog + EndSession +// calls during the session lifecycle +// - existing StartRebuildSession (legacy bridging path) unchanged + +import ( + "bytes" + "context" + "net" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// TestPrimaryBridge_StartRebuildSessionWithSink_NilRejected — +// fail-closed: nil sink is a programmer error; method MUST refuse +// rather than silently fall through to the bridging path. Callers +// that want the bridging path call StartRebuildSession explicitly. +func TestPrimaryBridge_StartRebuildSessionWithSink_NilRejected(t *testing.T) { + primary := storage.NewBlockStore(4, 4096) + coord := NewPeerShipCoordinator() + bridge := NewPrimaryBridge(primary, coord, nil, nil) + + prim, replicaEnd := net.Pipe() + defer prim.Close() + defer replicaEnd.Close() + + err := bridge.StartRebuildSessionWithSink( + context.Background(), prim, "r1", 7, 0, 0, nil, + ) + if err == nil { + t.Fatal("StartRebuildSessionWithSink with nil sink: want error, got nil") + } +} + +// TestPrimaryBridge_StartRebuildSessionWithSink_InvokesSinkLifecycle — +// the injected sink receives StartSession / DrainBacklog / EndSession +// in order. Mirrors TestSender_WithSink_DelegationOrder but exercised +// through the bridge's public surface — proves that production callers +// using StartRebuildSessionWithSink get the same lifecycle contract as +// direct NewSenderWithSink users. +// +// Uses a direct Receiver (not ReplicaBridge) + manual replicaConn.Close +// in the receiver goroutine so the sender's readerLoop unblocks when +// receiver exits — recordingSink doesn't pump WAL, so barrier won't +// converge and the receiver returns on its own with a wire/protocol +// error. The CONTRACT being tested is sink lifecycle ordering — that's +// independent of barrier outcome (same convention as +// TestSender_WithSink_DelegationOrder). +func TestPrimaryBridge_StartRebuildSessionWithSink_InvokesSinkLifecycle(t *testing.T) { + const numBlocks = 32 + const blockSize = 4096 + + primary := storage.NewBlockStore(numBlocks, blockSize) + for lba := uint32(0); lba < 5; lba++ { + _, _ = primary.Write(lba, bytes.Repeat([]byte{byte(lba)}, blockSize)) + } + _, _ = primary.Sync() + + replica := storage.NewBlockStore(numBlocks, blockSize) + coord := NewPeerShipCoordinator() + + var closeWG sync.WaitGroup + closeWG.Add(1) + bridge := NewPrimaryBridge(primary, coord, nil, + func(_ ReplicaID, _ uint64, _ uint64, _ error) { + closeWG.Done() + }) + + primaryConn, replicaConn := net.Pipe() + defer primaryConn.Close() + defer replicaConn.Close() + + receiver := NewReceiver(replica, replicaConn) + var recvWG sync.WaitGroup + recvWG.Add(1) + go func() { + defer recvWG.Done() + _, _ = receiver.Run() + _ = replicaConn.Close() + }() + + // Drain DrainBacklog quickly via the recordingSink (it returns + // immediately when drainBlocksUntil is nil). + sink := newRecordingSink() + + _, _, primaryH := primary.Boundaries() + if err := bridge.StartRebuildSessionWithSink( + context.Background(), primaryConn, "r1", 42, 0, primaryH, sink, + ); err != nil { + t.Fatalf("StartRebuildSessionWithSink: %v", err) + } + + closeWG.Wait() + recvWG.Wait() + + startCalls, drainCalls, endCalls, order := sink.snapshot() + if startCalls != 1 { + t.Errorf("StartSession calls=%d want 1", startCalls) + } + if drainCalls != 1 { + t.Errorf("DrainBacklog calls=%d want 1", drainCalls) + } + if endCalls != 1 { + t.Errorf("EndSession calls=%d want 1 (always-cleanup defer)", endCalls) + } + if len(order) < 3 { + t.Fatalf("call log too short: %v", order) + } + want := []string{"StartSession", "DrainBacklog", "EndSession"} + for i, w := range want { + if order[i] != w { + t.Errorf("call[%d]=%q want %q (full order=%v)", i, order[i], w, order) + } + } +} + +// TestPrimaryBridge_StartRebuildSession_StillUsesBridgingSink — +// regression: the legacy entry point continues to construct a +// senderBacklogSink internally. Verifies P2c-B-1's NewSenderWithBacklogRelay +// path is still the default for callers that don't inject a sink. +func TestPrimaryBridge_StartRebuildSession_StillUsesBridgingSink(t *testing.T) { + primary := storage.NewBlockStore(4, 4096) + coord := NewPeerShipCoordinator() + bridge := NewPrimaryBridge(primary, coord, nil, nil) + + prim, replicaEnd := net.Pipe() + defer prim.Close() + defer replicaEnd.Close() + + if err := bridge.StartRebuildSession( + context.Background(), prim, "r1", 7, 0, 0, + ); err != nil { + t.Fatalf("StartRebuildSession: %v", err) + } + + bridge.mu.Lock() + sender := bridge.senders["r1"] + bridge.mu.Unlock() + + if sender == nil { + t.Fatal("expected sender installed by StartRebuildSession") + } + if _, ok := sender.sink.(*senderBacklogSink); !ok { + t.Errorf("StartRebuildSession installed sink type=%T, want *senderBacklogSink (bridging path)", sender.sink) + } +} diff --git a/seaweed-block/core/recovery/integration_stub.go b/seaweed-block/core/recovery/integration_stub.go index c47704a416..acc5944250 100644 --- a/seaweed-block/core/recovery/integration_stub.go +++ b/seaweed-block/core/recovery/integration_stub.go @@ -85,10 +85,45 @@ func NewPrimaryBridge(store storage.LogicalStorage, coord *PeerShipCoordinator, // via context cancellation, but no explicit "go barrier" call is // needed. // +// This method uses the in-package `senderBacklogSink` (bridging path, +// emits frameWALEntry on the dual-lane port). Callers that want to +// route the recovery WAL pump through a real `transport.WalShipper` +// adapter use `StartRebuildSessionWithSink` instead — the wire format +// alignment between the two paths is gated by P2d. +// // Wire detail (POC): caller provides the dialed `conn`. Production // integration would dial through the existing connection pool / // listener registry. func (b *PrimaryBridge) StartRebuildSession(ctx context.Context, conn net.Conn, replicaID ReplicaID, sessionID, fromLSN, targetLSN uint64) error { + return b.startRebuildSessionLocked(ctx, conn, replicaID, sessionID, fromLSN, targetLSN, nil) +} + +// StartRebuildSessionWithSink is the variant that accepts an external +// `WalShipperSink` — typically a `transport.RecoverySink` that wraps +// the per-replica `WalShipper` and enforces architect rules 1+2 +// (emit context set BEFORE StartSession; restored AFTER EndSession). +// +// Pre-decision parallel-safe wiring: this method exists so production +// callers can plug a real adapter today without changing the bridge's +// public surface later. The actual format compatibility between the +// adapter's emits and the receiver's decoder is gated by P2d — until +// that decision lands, callers should typically prefer the bridging +// `StartRebuildSession` to avoid wire-format mismatch in production. +// +// `sink` MUST be non-nil; nil reverts to the bridging path (use +// `StartRebuildSession` for that explicitly). +func (b *PrimaryBridge) StartRebuildSessionWithSink(ctx context.Context, conn net.Conn, replicaID ReplicaID, sessionID, fromLSN, targetLSN uint64, sink WalShipperSink) error { + if sink == nil { + return fmt.Errorf("recovery bridge: StartRebuildSessionWithSink: sink is required (use StartRebuildSession for the bridging path)") + } + return b.startRebuildSessionLocked(ctx, conn, replicaID, sessionID, fromLSN, targetLSN, sink) +} + +// startRebuildSessionLocked is the shared implementation. When `sink` +// is nil, it constructs a bridging `senderBacklogSink` via +// NewSenderWithBacklogRelay (legacy compatible). When non-nil, the +// caller-provided sink is installed via NewSenderWithSink. +func (b *PrimaryBridge) startRebuildSessionLocked(ctx context.Context, conn net.Conn, replicaID ReplicaID, sessionID, fromLSN, targetLSN uint64, sink WalShipperSink) error { // Single-flight check at the bridge level (before coordinator), // so a second call observes our internal sender map first and // reports the racing-bridge-call case distinctly from the @@ -108,7 +143,12 @@ func (b *PrimaryBridge) StartRebuildSession(ctx context.Context, conn net.Conn, return fmt.Errorf("recovery bridge: %w", err) } - sender := NewSenderWithBacklogRelay(b.store, b.coord, conn, replicaID) + var sender *Sender + if sink == nil { + sender = NewSenderWithBacklogRelay(b.store, b.coord, conn, replicaID) + } else { + sender = NewSenderWithSink(b.store, b.coord, conn, replicaID, sink) + } b.senders[replicaID] = sender b.mu.Unlock() diff --git a/seaweed-block/core/transport/executor.go b/seaweed-block/core/transport/executor.go index f976b8f107..1059b568ee 100644 --- a/seaweed-block/core/transport/executor.go +++ b/seaweed-block/core/transport/executor.go @@ -648,6 +648,31 @@ func (e *BlockExecutor) updateWalShipperEmitContext(replicaID string, conn net.C entry.emitCtxMu.Unlock() } +// SnapshotEmitContext returns the per-replica WalShipper's current +// emit conn + lineage under the same mutex production code uses +// (emitCtxMu). Intended for callers that need to capture the steady- +// state context BEFORE constructing a RecoverySink — so EndSession's +// rule-2 restore lands the right values rather than zero / nil. +// +// Returns (nil, zero RecoveryLineage) when no WalShipperEntry exists +// for replicaID (i.e., no Ship has run yet for this replica). That +// is honest — there is no steady context to restore. +// +// Called by: production wiring layer (e.g., transport.startRebuildDualLane) +// right before NewRecoverySink, so the snapshot is consistent with +// what's currently driving Ship(). +func (e *BlockExecutor) SnapshotEmitContext(replicaID string) (net.Conn, RecoveryLineage) { + e.walShipperMu.Lock() + entry, ok := e.walShippers[replicaID] + e.walShipperMu.Unlock() + if !ok { + return nil, RecoveryLineage{} + } + entry.emitCtxMu.Lock() + defer entry.emitCtxMu.Unlock() + return entry.emitConn, entry.emitLineage +} + // Registry lifecycle note (architect P1 review #4): walShippers // entries are never torn down today. For replica churn, lineage // invalidation, or executor reuse across distinct peer diff --git a/seaweed-block/core/transport/snapshot_emit_context_test.go b/seaweed-block/core/transport/snapshot_emit_context_test.go new file mode 100644 index 0000000000..deebb622a8 --- /dev/null +++ b/seaweed-block/core/transport/snapshot_emit_context_test.go @@ -0,0 +1,119 @@ +package transport + +// SnapshotEmitContext — pre-decision integration helper (P2d-parallel). +// +// This accessor lets production wiring code capture the steady-state +// emit context before constructing a RecoverySink, so EndSession's +// rule-2 restore lands the right values rather than zero / nil. + +import ( + "net" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage/memorywal" +) + +// TestSnapshotEmitContext_NoEntry_ReturnsZero — honest signal: when +// no WalShipperEntry exists for replicaID (no Ship has run yet), +// SnapshotEmitContext returns (nil conn, zero lineage). Caller can +// pass these through to NewRecoverySink — there is no steady ship +// to restore on top of. +func TestSnapshotEmitContext_NoEntry_ReturnsZero(t *testing.T) { + primary := memorywal.NewStore(8, 4096) + e := NewBlockExecutor(primary, "127.0.0.1:0") + + conn, lineage := e.SnapshotEmitContext("never-shipped") + if conn != nil { + t.Errorf("SnapshotEmitContext on absent replica: conn=%p want nil", conn) + } + if lineage != (RecoveryLineage{}) { + t.Errorf("SnapshotEmitContext on absent replica: lineage=%+v want zero", lineage) + } +} + +// TestSnapshotEmitContext_AfterUpdate_ReturnsCurrent — basic +// round-trip: updateWalShipperEmitContext writes (conn, lineage); +// SnapshotEmitContext reads them back. Same lock discipline as +// production EmitFunc. +func TestSnapshotEmitContext_AfterUpdate_ReturnsCurrent(t *testing.T) { + primary := memorywal.NewStore(8, 4096) + e := NewBlockExecutor(primary, "127.0.0.1:0") + + const replicaID = "r1" + steadyConn, _ := net.Pipe() + defer steadyConn.Close() + steadyLineage := RecoveryLineage{ + SessionID: 7, Epoch: 2, EndpointVersion: 3, TargetLSN: 100, + } + + // Ensure entry exists, then update. + _ = e.WalShipperFor(replicaID) + e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage) + + gotConn, gotLineage := e.SnapshotEmitContext(replicaID) + if gotConn != steadyConn { + t.Errorf("SnapshotEmitContext conn=%p want %p", gotConn, steadyConn) + } + if gotLineage != steadyLineage { + t.Errorf("SnapshotEmitContext lineage=%+v want %+v", gotLineage, steadyLineage) + } +} + +// TestSnapshotEmitContext_ThenRecoverySink_RestoresCaptured — +// integration: snapshot the steady context, hand it to RecoverySink +// as the steady-restore values, run the session, verify the restore +// matches what was snapshotted. +// +// This is the canonical pre-decision wiring pattern that production +// callers will use once P2d resolves the wire format. +func TestSnapshotEmitContext_ThenRecoverySink_RestoresCaptured(t *testing.T) { + primary := memorywal.NewStore(8, 4096) + e := NewBlockExecutor(primary, "127.0.0.1:0") + + const replicaID = "r1" + steadyConn, _ := net.Pipe() + defer steadyConn.Close() + steadyLineage := RecoveryLineage{ + SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 5, + } + + // Production-shape step: pre-existing steady ship has set context. + _ = e.WalShipperFor(replicaID) + e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage) + + // Caller pattern: snapshot BEFORE constructing RecoverySink, pass + // to the constructor as the steady-restore values. + snappedConn, snappedLineage := e.SnapshotEmitContext(replicaID) + + sessionConn, _ := net.Pipe() + defer sessionConn.Close() + sessionLineage := RecoveryLineage{ + SessionID: 99, Epoch: 5, EndpointVersion: 7, TargetLSN: 9000, + } + + sink := NewRecoverySink(e, replicaID, + sessionConn, sessionLineage, + snappedConn, snappedLineage, + ) + + if err := sink.StartSession(0); err != nil { + t.Fatalf("StartSession: %v", err) + } + + // Mid-session: context is session. + mid, midLin := readEntryEmitContext(t, e, replicaID) + if mid != sessionConn || midLin != sessionLineage { + t.Fatalf("mid-session ctx wrong: conn=%p lineage=%+v", mid, midLin) + } + + sink.EndSession() + + // After EndSession: restored to snapshotted steady values. + got, gotLin := readEntryEmitContext(t, e, replicaID) + if got != steadyConn { + t.Errorf("restored conn=%p want steadyConn=%p", got, steadyConn) + } + if gotLin != steadyLineage { + t.Errorf("restored lineage=%+v want %+v", gotLin, steadyLineage) + } +}