diff --git a/seaweed-block/core/recovery/wire.go b/seaweed-block/core/recovery/wire.go index 82fe05c1dd..8512c2cf65 100644 --- a/seaweed-block/core/recovery/wire.go +++ b/seaweed-block/core/recovery/wire.go @@ -177,6 +177,23 @@ func decodeWALEntry(p []byte) (kind WALEntryKind, lba uint32, lsn uint64, data [ return kind, binary.BigEndian.Uint32(p[1:]), binary.BigEndian.Uint64(p[5:]), p[13:], nil } +// WriteWALEntryFrame writes one WAL-lane frame on the dual-lane wire +// — public surface for transport-side EmitFunc that targets the +// recovery dual-lane port (P2d profile = DualLaneWALFrame). +// +// Wraps the package-internal frame format (writeFrame + encodeWALEntry) +// so the transport layer can emit recovery-compatible WAL frames +// without duplicating the encoding logic. +// +// `kind` MUST be WALKindBacklog (DrainBacklog scan emit) or +// WALKindSessionLive (NotifyAppend Realtime emit during session). +// The receiver-side rebuild_session uses kind only for observability +// counts (BacklogApplied / SessionLiveApplied); apply behavior is +// identical for both. +func WriteWALEntryFrame(w io.Writer, kind WALEntryKind, lba uint32, lsn uint64, data []byte) error { + return writeFrame(w, frameWALEntry, encodeWALEntry(kind, lba, lsn, data)) +} + // baseBatchAck: [8 SessionID][8 AcknowledgedLSN][4 BaseLBAUpper] // // SessionID identifies which session this ack belongs to (must match diff --git a/seaweed-block/core/replication/component/cluster.go b/seaweed-block/core/replication/component/cluster.go index e5e422ef89..013fbc956b 100644 --- a/seaweed-block/core/replication/component/cluster.go +++ b/seaweed-block/core/replication/component/cluster.go @@ -504,6 +504,17 @@ func (c *Cluster) Start() *Cluster { // Primary returns the primary node handle. func (c *Cluster) Primary() *PrimaryNode { return c.primary } +// BlockExecutor returns the primary-side transport executor for replica +// idx (same index as Replica / Adapter). Used by integration tests that +// exercise dual-lane surfaces (e.g. PushLiveWrite on PrimaryBridge). +func (c *Cluster) BlockExecutor(replicaIdx int) *transport.BlockExecutor { + c.t.Helper() + if replicaIdx < 0 || replicaIdx >= len(c.primary.executors) { + c.t.Fatalf("BlockExecutor(%d): out of range (have %d)", replicaIdx, len(c.primary.executors)) + } + return c.primary.executors[replicaIdx] +} + // Replica returns the i-th replica handle. func (c *Cluster) Replica(i int) *ReplicaNode { c.t.Helper() diff --git a/seaweed-block/core/replication/component/dual_lane_engine_test.go b/seaweed-block/core/replication/component/dual_lane_engine_test.go index b7873a72e8..a2e702d30f 100644 --- a/seaweed-block/core/replication/component/dual_lane_engine_test.go +++ b/seaweed-block/core/replication/component/dual_lane_engine_test.go @@ -195,3 +195,120 @@ func TestDualLane_CoordReleasesPinFloorAfterSession(t *testing.T) { } }) } + +// TestDualLane_EngineDrivenRebuild_WithPushLiveDuringSession is the +// component-lane extension of TestDualLane_EngineDrivenRebuild_HappyPath: +// after the engine emits StartRebuild, tests inject one extra WAL entry +// via primary substrate Write + PrimaryBridge.PushLiveWrite (session +// lane), matching core/recovery/integration_stub_test.go semantics. +// +// This pins the coordinator/bridge path for "live tail during rebuild" +// without yet wiring ReplicationVolume steady-ship to PushLiveWrite +// (that remains product work). WalShipper remains separate from the dual- +// lane rebuild sender until P2d unifies EncodeShipEntry vs frameWALEntry. +func TestDualLane_EngineDrivenRebuild_WithPushLiveDuringSession(t *testing.T) { + component.RunSubstrate(t, "memorywal", component.MemoryWAL, func(t *testing.T, c *component.Cluster) { + c.WithReplicas(1). + WithEngineDrivenRecovery(). + WithDualLaneRecovery(). + Start() + + const seedN = 12 + c.PrimaryWriteN(seedN) + c.PrimarySync() + + a := c.Adapter(0) + + c.DriveAssignment(0, adapter.AssignmentInfo{ + VolumeID: "v1", + ReplicaID: "replica-0", + Epoch: 1, + EndpointVersion: 1, + DataAddr: c.Replica(0).Addr, + CtrlAddr: c.Replica(0).Addr, + }) + + c.DriveProbeResult(0, adapter.ProbeResult{ + ReplicaID: "replica-0", + Success: true, + EndpointVersion: 1, + TransportEpoch: 1, + ReplicaFlushedLSN: 0, + PrimaryTailLSN: 1, + PrimaryHeadLSN: seedN, + }) + + br, coordRID, ok := c.BlockExecutor(0).DualLanePrimaryBridge() + if !ok || br == nil { + t.Fatal("BlockExecutor missing dual-lane PrimaryBridge") + } + + // PeerShipCoordinator keys match NewBlockExecutorWithDualLane replica id ("r-0"). + if c.Coord().Phase(coordRID) == recovery.PhaseIdle { + t.Fatal("coord still Idle after rebuild dispatch — PushLiveWrite would fail") + } + + liveLBA := uint32(55) + liveData := make([]byte, component.DefaultBlockSize) + liveData[0] = 0xEE + liveData[component.DefaultBlockSize-1] = 0xDD + liveLSN := c.PrimaryWrite(liveLBA, liveData) + + if rt := c.Coord().RouteLocalWrite(coordRID, liveLSN); rt != recovery.RouteSessionLane { + t.Fatalf("RouteLocalWrite during session: got %v want RouteSessionLane", rt) + } + if err := br.PushLiveWrite(coordRID, liveLBA, liveLSN, liveData); err != nil { + t.Fatalf("PushLiveWrite: %v", err) + } + + deadline := time.Now().Add(8 * time.Second) + var sawStartRebuild bool + var sawSessionClosed bool + for time.Now().Before(deadline) { + for _, cmd := range a.CommandLog() { + if cmd == "StartRebuild" { + sawStartRebuild = true + } + } + for _, te := range a.Trace() { + if te.Step == "event" && te.Detail == "SessionClosedCompleted" { + sawSessionClosed = true + } + } + if sawStartRebuild && sawSessionClosed { + break + } + time.Sleep(20 * time.Millisecond) + } + if !sawStartRebuild || !sawSessionClosed { + t.Fatalf("expected StartRebuild + SessionClosedCompleted got cmd=%v trace=%v", + a.CommandLog(), a.Trace()) + } + + for lba := uint32(0); lba < seedN; lba++ { + pd, err := c.Primary().Store.Read(lba) + if err != nil { + t.Fatalf("primary Read lba=%d: %v", lba, err) + } + rd, err := c.Replica(0).Store.Read(lba) + if err != nil { + t.Fatalf("replica Read lba=%d: %v", lba, err) + } + if !bytes.Equal(pd, rd) { + t.Fatalf("mismatch seeded lba %d", lba) + } + } + pl, err := c.Primary().Store.Read(liveLBA) + if err != nil { + t.Fatalf("primary Read live lba=%d: %v", liveLBA, err) + } + rl, err := c.Replica(0).Store.Read(liveLBA) + if err != nil { + t.Fatalf("replica Read live lba=%d: %v", liveLBA, err) + } + if !bytes.Equal(pl, rl) { + t.Fatalf("live PushLiveWrite LBA mismatch primary[0]=%02x replica[0]=%02x", + pl[0], rl[0]) + } + }) +} diff --git a/seaweed-block/core/transport/dual_lane_p2d_profile_test.go b/seaweed-block/core/transport/dual_lane_p2d_profile_test.go new file mode 100644 index 0000000000..08124629b4 --- /dev/null +++ b/seaweed-block/core/transport/dual_lane_p2d_profile_test.go @@ -0,0 +1,213 @@ +package transport + +// P2d unit-level dispatch tests: assert the per-replica WalShipper's +// EmitFunc selects the correct encoder based on the entry's emit +// profile (architect 2026-04-30 ratification). +// +// Architectural contract: +// - EmitProfileSteadyMsgShip → SWRP envelope around EncodeShipEntry +// - EmitProfileDualLaneWALFrame → recovery frameWALEntry + +// encodeWALEntry; EmitKind controls WALKind tag +// +// E2E coverage of the production hot path (startRebuildDualLane → +// RecoverySink → WalShipper) is provided by: +// - TestDualLane_BlockExecutor_StartRebuild (byte-equal post-rebuild) +// - TestDualLane_LiveWritesDuringSession_AtomicSeal (40 concurrent +// pushes, all byte-equal on replica) +// - TestDualLane_EngineDrivenRebuild_HappyPath (component) +// — these IMPLICITLY pin profile dispatch (wrong profile → receiver +// can't decode → byte-equality fails). +// +// The tests below explicitly pin the dispatch by capturing wire bytes +// produced by the EmitFunc and comparing against the canonical +// encoder output for each profile. + +import ( + "bytes" + "context" + "net" + "testing" + + "github.com/seaweedfs/seaweed-block/core/recovery" + "github.com/seaweedfs/seaweed-block/core/storage/memorywal" +) + +// readUntilEOF reads from conn in a loop until error/EOF. Used to +// drain net.Pipe writes that may arrive in multiple chunks (header +// then payload from WriteMsg). +func readUntilEOF(conn net.Conn) []byte { + var buf bytes.Buffer + chunk := make([]byte, 1024) + for { + n, err := conn.Read(chunk) + if n > 0 { + buf.Write(chunk[:n]) + } + if err != nil { + return buf.Bytes() + } + } +} + +// TestP2d_EmitDispatch_SteadyMsgShipProfile — when entry.emitProfile +// is SteadyMsgShip, EmitFunc produces SWRP-wrapped MsgShipEntry on +// the wire. Verified by checking the first 6 bytes are the SWRP +// preamble (magic + version + msgType=MsgShipEntry). +func TestP2d_EmitDispatch_SteadyMsgShipProfile(t *testing.T) { + primary := memorywal.NewStore(8, 4096) + e := NewBlockExecutor(primary, "127.0.0.1:0") + const replicaID = "r1" + + writerConn, readerConn := net.Pipe() + defer writerConn.Close() + defer readerConn.Close() + + steadyLineage := RecoveryLineage{ + SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 100, + } + shipper := e.WalShipperFor(replicaID) + e.updateWalShipperEmitContext(replicaID, writerConn, steadyLineage, EmitProfileSteadyMsgShip) + + resCh := make(chan []byte, 1) + go func() { + resCh <- readUntilEOF(readerConn) + }() + + if err := shipper.NotifyAppend(7, 50, []byte{0xDE, 0xAD, 0xBE, 0xEF}); err != nil { + t.Fatalf("NotifyAppend: %v", err) + } + _ = writerConn.Close() + + got := <-resCh + if len(got) < 6 { + t.Fatalf("not enough bytes: got=%d", len(got)) + } + + // SWRP preamble: bytes 0..3 = "SWRP" magic; byte 4 = version; + // byte 5 = msgType. + wantMagic := []byte{0x53, 0x57, 0x52, 0x50} // "SWRP" + if !bytes.Equal(got[0:4], wantMagic) { + t.Errorf("SteadyMsgShip: first 4 bytes=%x want SWRP magic %x", got[0:4], wantMagic) + } + if got[5] != MsgShipEntry { + t.Errorf("SteadyMsgShip: msgType byte=%x want MsgShipEntry=%x", got[5], MsgShipEntry) + } +} + +// TestP2d_EmitDispatch_DualLaneWALFrameProfile_LiveKind — +// when entry.emitProfile is DualLaneWALFrame and the emit comes from +// NotifyAppend (EmitKindLive), the wire frame is recovery's +// frameWALEntry with WALKindSessionLive in the payload. +// +// Recovery frame format: [1 type][4 len][payload]; payload first +// byte is the WAL kind tag. +func TestP2d_EmitDispatch_DualLaneWALFrameProfile_LiveKind(t *testing.T) { + primary := memorywal.NewStore(8, 4096) + e := NewBlockExecutor(primary, "127.0.0.1:0") + const replicaID = "r1" + + writerConn, readerConn := net.Pipe() + defer writerConn.Close() + defer readerConn.Close() + + sessionLineage := RecoveryLineage{ + SessionID: 42, Epoch: 1, EndpointVersion: 1, TargetLSN: 1000, + } + shipper := e.WalShipperFor(replicaID) + e.updateWalShipperEmitContext(replicaID, writerConn, sessionLineage, EmitProfileDualLaneWALFrame) + + resCh := make(chan []byte, 1) + go func() { + resCh <- readUntilEOF(readerConn) + }() + + if err := shipper.NotifyAppend(11, 200, []byte{0xCA, 0xFE}); err != nil { + t.Fatalf("NotifyAppend: %v", err) + } + _ = writerConn.Close() + + got := <-resCh + if len(got) < 6 { + t.Fatalf("not enough bytes: got=%d", len(got)) + } + + // NOT SWRP magic — recovery frames don't have SWRP preamble. + swrpMagic := []byte{0x53, 0x57, 0x52, 0x50} + if bytes.Equal(got[0:4], swrpMagic) { + t.Errorf("DualLaneWALFrame Live: starts with SWRP magic — wire format wrong (legacy MsgShipEntry instead of recovery frame)") + } + + // Recovery frame: [1 type][4 len][1 kind][...]. Byte 5 = WAL kind. + if got[5] != byte(recovery.WALKindSessionLive) { + t.Errorf("DualLaneWALFrame Live: kind byte=%d want WALKindSessionLive=%d", + got[5], recovery.WALKindSessionLive) + } +} + +// TestP2d_EmitDispatch_DualLaneWALFrameProfile_BacklogKind — +// when EmitKind is Backlog (passed by WalShipper.DrainBacklog scan), +// the WALKind tag is WALKindBacklog. We can't easily trigger +// DrainBacklog directly without a full session, so we exercise the +// dispatch via a synthetic emit using the package-internal EmitFunc +// from the shipper. +// +// Workaround: install a session that drains an empty substrate to +// transition into Backlog → Realtime. Then directly invoke the +// shipper's emit path via NotifyAppend with profile already set. +// NotifyAppend always passes EmitKindLive, so to test Backlog kind +// we need the DrainBacklog path. Use a substrate seeded with one +// entry; the scan emits it with EmitKindBacklog. +func TestP2d_EmitDispatch_DualLaneWALFrameProfile_BacklogKind(t *testing.T) { + const blockSize = 64 + primary := memorywal.NewStore(8, blockSize) + // Seed one substrate entry so DrainBacklog has something to scan. + seedData := bytes.Repeat([]byte{0xAB}, blockSize) + if _, err := primary.Write(3, seedData); err != nil { + t.Fatalf("seed Write: %v", err) + } + if _, err := primary.Sync(); err != nil { + t.Fatalf("Sync: %v", err) + } + + e := NewBlockExecutor(primary, "127.0.0.1:0") + const replicaID = "r1" + + writerConn, readerConn := net.Pipe() + defer writerConn.Close() + defer readerConn.Close() + + sessionLineage := RecoveryLineage{ + SessionID: 99, Epoch: 1, EndpointVersion: 1, TargetLSN: 500, + } + shipper := e.WalShipperFor(replicaID) + e.updateWalShipperEmitContext(replicaID, writerConn, sessionLineage, EmitProfileDualLaneWALFrame) + + if err := shipper.StartSession(0); err != nil { + t.Fatalf("StartSession: %v", err) + } + + resCh := make(chan []byte, 1) + go func() { + resCh <- readUntilEOF(readerConn) + }() + + // DrainBacklog runs the scan; the seeded entry emits with + // EmitKindBacklog → WALKindBacklog tag on the wire. + go func() { + _ = shipper.DrainBacklog(context.Background()) + _ = writerConn.Close() + }() + + got := <-resCh + + // Find a frameWALEntry with WALKindBacklog. The first byte of + // payload after the 5-byte frame header is the kind. + if len(got) < 6 { + t.Fatalf("not enough bytes captured: got=%d", len(got)) + } + // Frame format: [1 type][4 len][payload]; payload first byte = kind. + kindByte := got[5] + if kindByte != byte(recovery.WALKindBacklog) { + t.Errorf("Backlog kind byte=%d want WALKindBacklog=%d", kindByte, recovery.WALKindBacklog) + } +} diff --git a/seaweed-block/core/transport/executor.go b/seaweed-block/core/transport/executor.go index 1059b568ee..f317841668 100644 --- a/seaweed-block/core/transport/executor.go +++ b/seaweed-block/core/transport/executor.go @@ -48,29 +48,64 @@ type BlockExecutor struct { walShippers map[string]*walShipperEntry } +// EmitProfile selects the wire encoder + frame format used by the +// per-replica WalShipper's EmitFunc. P2d (architect 2026-04-30): +// dual-lane connections use frameWALEntry; legacy steady connections +// use MsgShipEntry. The profile is part of the emit context (alongside +// conn + lineage) and switches when recovery sessions bracket the +// shipper into the dual-lane port. +type EmitProfile int + +const ( + // EmitProfileSteadyMsgShip — legacy port WAL ship: SWRP envelope + // (`WriteMsg(MsgShipEntry, EncodeShipEntry(...))`). Used outside + // recovery sessions and by Ship() in steady state. + EmitProfileSteadyMsgShip EmitProfile = iota + // EmitProfileDualLaneWALFrame — recovery dual-lane port: 5-byte + // recovery frame header + encodeWALEntry payload (via + // recovery.WriteWALEntryFrame). Used inside recovery sessions on + // the dual-lane connection. Kind tag derives from the EmitKind + // passed by WalShipper: Backlog or SessionLive. + EmitProfileDualLaneWALFrame +) + +func (p EmitProfile) String() string { + switch p { + case EmitProfileSteadyMsgShip: + return "SteadyMsgShip" + case EmitProfileDualLaneWALFrame: + return "DualLaneWALFrame" + default: + return fmt.Sprintf("EmitProfile(%d)", int(p)) + } +} + // walShipperEntry pairs a per-replica WalShipper with its mutable -// wire-emit context (conn + lineage). Ship() / recovery-session -// initialization updates the context under emitCtxMu before delegating -// to the shipper; the EmitFunc reads it under the same mutex. +// wire-emit context (conn + lineage + profile). Ship() / recovery- +// session initialization updates the context under emitCtxMu before +// delegating to the shipper; the EmitFunc reads it under the same +// mutex. // // Architect P1 review (2026-04-29 #1): encoding MUST happen INSIDE // the EmitFunc, not by the caller before NotifyAppend. WalShipper -// hands `(lba, lsn, raw block bytes)` to EmitFunc; EmitFunc owns -// `EncodeShipEntry` so both steady-state Ship() AND backlog scan -// (recovery.Sender via DrainBacklog, P2) feed the SAME EmitFunc -// shape — one encoding seam, one wire frame type. +// hands `(kind, lba, lsn, raw block bytes)` to EmitFunc; EmitFunc +// owns the encoding so steady Ship() AND recovery-session emits +// feed the SAME EmitFunc, with the profile selecting which wire +// frame format to emit. // -// emitLineage is the lineage used for `EncodeShipEntry`. For -// steady-state ship, Ship() updates it from the active session per -// call. For recovery-session backlog (P2), the session-installer -// updates it from the session's lineage at StartSession time and -// restores steady lineage at EndSession. +// emitLineage is the lineage embedded in MsgShipEntry payloads +// (steady profile only — frameWALEntry has no lineage field). +// For steady-state ship, Ship() updates it from the active session +// per call. For recovery-session emits, the session-installer +// (RecoverySink) updates context at StartSession and restores +// steady context at EndSession. type walShipperEntry struct { shipper *WalShipper emitCtxMu sync.Mutex emitConn net.Conn emitLineage RecoveryLineage + emitProfile EmitProfile } // DualLaneConfig holds the wiring for routing StartRebuild through @@ -584,29 +619,58 @@ func (e *BlockExecutor) WalShipperFor(replicaID string) *WalShipper { } entry := &walShipperEntry{} - emit := func(lba uint32, lsn uint64, data []byte) error { + emit := func(kind EmitKind, lba uint32, lsn uint64, data []byte) error { entry.emitCtxMu.Lock() conn := entry.emitConn lineage := entry.emitLineage + profile := entry.emitProfile entry.emitCtxMu.Unlock() if conn == nil { - return fmt.Errorf("transport: WalShipper for replica %s has no conn", replicaID) + // No emit context yet (Ship hasn't run; recovery session + // hasn't installed session context). Drop silently — same + // semantics as ModeIdle. Caller's NotifyAppend returns nil; + // entry remains in primary substrate and will be picked up + // by the next emit context's drain (recovery DrainBacklog + // scan or steady catch-up). This avoids racing against + // session-bracket installation when callers inject live + // writes via PushLiveWrite during the WalShipperFor → + // sink.StartSession window. + return nil } + + // P2d profile dispatch (architect 2026-04-30): + // SteadyMsgShip → legacy MsgShipEntry on legacy port. + // DualLaneWALFrame → recovery frameWALEntry on dual-lane port. // Encoding lives HERE (architect P1 review #1): WalShipper - // hands raw `(lba, lsn, data)` tuples; EmitFunc owns - // `EncodeShipEntry` so steady Ship() + backlog ScanLBAs - // both produce the same MsgShipEntry frame shape on the - // wire. Without this, P2's DrainBacklog would ship raw - // substrate bytes that the replica's MsgShipEntry handler - // can't decode. - payload := EncodeShipEntry(ShipEntry{ - Lineage: lineage, - LBA: lba, - LSN: lsn, - Data: data, - }) + // hands raw tuples; EmitFunc owns the encoder choice so steady + // Ship and recovery-session emits both feed one delivery seam. _ = conn.SetWriteDeadline(time.Now().Add(shipWriteDeadline)) - err := WriteMsg(conn, MsgShipEntry, payload) + var err error + switch profile { + case EmitProfileSteadyMsgShip: + payload := EncodeShipEntry(ShipEntry{ + Lineage: lineage, + LBA: lba, + LSN: lsn, + Data: data, + }) + err = WriteMsg(conn, MsgShipEntry, payload) + case EmitProfileDualLaneWALFrame: + // Map EmitKind → recovery WALEntryKind. Backlog scan emits + // → WALKindBacklog; Realtime / NotifyAppend emits during + // session → WALKindSessionLive (the kind tag drives the + // receiver's BacklogApplied vs SessionLiveApplied counters + // — observability only; apply behavior identical). + var walKind recovery.WALEntryKind + if kind == EmitKindBacklog { + walKind = recovery.WALKindBacklog + } else { + walKind = recovery.WALKindSessionLive + } + err = recovery.WriteWALEntryFrame(conn, walKind, lba, lsn, data) + default: + err = fmt.Errorf("transport: WalShipper for replica %s has unknown emit profile %s", replicaID, profile) + } _ = conn.SetWriteDeadline(time.Time{}) return err } @@ -620,22 +684,26 @@ func (e *BlockExecutor) WalShipperFor(replicaID string) *WalShipper { return s } -// updateWalShipperEmitContext sets the wire conn + lineage that the -// per-replica WalShipper's EmitFunc will use on its next emit. -// Ship() calls this before delegating NotifyAppend; the EmitFunc -// reads emitConn + emitLineage at emit time and `EncodeShipEntry` -// the (raw block bytes, lineage) → MsgShipEntry payload. +// updateWalShipperEmitContext sets the wire conn + lineage + profile +// that the per-replica WalShipper's EmitFunc will use on its next +// emit. Ship() calls this before delegating NotifyAppend; recovery +// session start (RecoverySink) calls it to install the dual-lane +// session context. // // Ordering invariant (architect P1 review #3): every code path -// that ends in an emit (steady Ship, future recovery-session -// backlog DrainBacklog, future Activate) MUST refresh this -// context BEFORE the call that may emit. Otherwise EmitFunc emits -// with stale lineage / nil conn. P2 wiring of recovery.Sender -// must call this from the session-installer before StartSession. +// that ends in an emit (steady Ship, recovery-session DrainBacklog, +// recovery-session NotifyAppend) MUST refresh this context BEFORE +// the call that may emit. Otherwise EmitFunc emits with stale +// lineage / nil conn / wrong profile. +// +// P2d (architect 2026-04-30): `profile` is part of the context — +// SteadyMsgShip for legacy port, DualLaneWALFrame for dual-lane port. +// The profile selects the encoder; legacy callers pass +// EmitProfileSteadyMsgShip to preserve existing wire shape. // // No-op if the WalShipper hasn't been created yet (caller will // create via WalShipperFor and re-call). -func (e *BlockExecutor) updateWalShipperEmitContext(replicaID string, conn net.Conn, lineage RecoveryLineage) { +func (e *BlockExecutor) updateWalShipperEmitContext(replicaID string, conn net.Conn, lineage RecoveryLineage, profile EmitProfile) { e.walShipperMu.Lock() entry, ok := e.walShippers[replicaID] e.walShipperMu.Unlock() @@ -645,32 +713,52 @@ func (e *BlockExecutor) updateWalShipperEmitContext(replicaID string, conn net.C entry.emitCtxMu.Lock() entry.emitConn = conn entry.emitLineage = lineage + entry.emitProfile = profile 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. +// emit conn + lineage + profile 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. +// Returns (nil, zero RecoveryLineage, EmitProfileSteadyMsgShip) when +// no WalShipperEntry exists for replicaID (i.e., no Ship has run yet +// for this replica). That is honest: the steady restore is "no +// context yet, default to steady profile" — matching what a fresh +// Ship() call would set. // // 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) { +func (e *BlockExecutor) SnapshotEmitContext(replicaID string) (net.Conn, RecoveryLineage, EmitProfile) { e.walShipperMu.Lock() entry, ok := e.walShippers[replicaID] e.walShipperMu.Unlock() if !ok { - return nil, RecoveryLineage{} + return nil, RecoveryLineage{}, EmitProfileSteadyMsgShip } entry.emitCtxMu.Lock() defer entry.emitCtxMu.Unlock() - return entry.emitConn, entry.emitLineage + return entry.emitConn, entry.emitLineage, entry.emitProfile +} + +// DualLanePrimaryBridge returns the recovery PrimaryBridge plus the +// coordinator replica key when this executor was built with +// NewBlockExecutorWithDualLane. Legacy executors return (_, _, false). +// +// Integration tests (e.g. core/replication/component) use this to drive +// PushLiveWrite during an engine-dispatched rebuild. Production should +// ideally route session-lane writes via a single control plane; this +// accessor exists so tests can close the bridge/coordinator seam without +// duplicating cluster executor construction. +func (e *BlockExecutor) DualLanePrimaryBridge() (*recovery.PrimaryBridge, recovery.ReplicaID, bool) { + if e.dualLane == nil { + return nil, "", false + } + return e.dualLane.Bridge, e.dualLane.ReplicaID, true } // Registry lifecycle note (architect P1 review #4): walShippers diff --git a/seaweed-block/core/transport/rebuild_sender.go b/seaweed-block/core/transport/rebuild_sender.go index 65cd9c6360..5e467a720e 100644 --- a/seaweed-block/core/transport/rebuild_sender.go +++ b/seaweed-block/core/transport/rebuild_sender.go @@ -130,16 +130,20 @@ func (e *BlockExecutor) doRebuild(replicaID string, session *activeSession, targ // docs/recovery-wiring-plan.md §4 Option A) and delegates to the // PrimaryBridge captured in e.dualLane.Bridge. // -// Lifecycle: this method is async (returns immediately after dialing -// + 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). +// P2d (architect 2026-04-30): the WAL pump routes through the +// resident per-replica WalShipper via a transport.RecoverySink adapter. +// Steady (legacy port) emit context is snapshotted before constructing +// the sink so EndSession's rule-2 restore lands the right values. +// During session, the WalShipper's emit profile is DualLaneWALFrame +// (writes frameWALEntry on the dual-lane conn); after EndSession the +// shipper's emit context is restored to the steady snapshot. // -// 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. +// Lifecycle: this method is async (returns immediately after dialing +// + StartRebuildSessionWithSink is kicked off). The bridge's onClose +// callback (set in NewBlockExecutorWithDualLane) fires the executor's +// OnSessionClose when the session goroutine completes — happens +// autonomously: sender.Run barriers as soon as sink.DrainBacklog +// returns (P2c-slice B-2 lifecycle). 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) @@ -151,11 +155,34 @@ func (e *BlockExecutor) startRebuildDualLane(replicaID string, sessionID, epoch, // REBUILD). log.Printf("executor: rebuild start replica=%s sessionID=%d epoch=%d EV=%d targetLSN=%d (dual-lane)", replicaID, sessionID, epoch, endpointVersion, targetLSN) + + // P2d wiring: build the RecoverySink that brackets the resident + // WalShipper around this session. + // + // Snapshot the steady emit context (legacy port + MsgShipEntry) + // before installing session context, so EndSession's rule-2 + // restore lands the correct values. SnapshotEmitContext returns + // (nil, zero, SteadyMsgShip) when no Ship has run yet — that's + // the honest "no steady context to restore" signal. + steadyConn, steadyLineage, steadyProfile := e.SnapshotEmitContext(replicaID) + sessionLineage := RecoveryLineage{ + SessionID: sessionID, + Epoch: epoch, + EndpointVersion: endpointVersion, + TargetLSN: targetLSN, + } + sink := NewRecoverySinkWithProfiles(e, replicaID, + conn, sessionLineage, EmitProfileDualLaneWALFrame, + 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. - if err := dl.Bridge.StartRebuildSession(context.Background(), conn, dl.ReplicaID, sessionID, 0, targetLSN); err != nil { + if err := dl.Bridge.StartRebuildSessionWithSink( + context.Background(), conn, dl.ReplicaID, sessionID, 0, targetLSN, sink, + ); err != nil { _ = conn.Close() return fmt.Errorf("dual-lane start: %w", err) } diff --git a/seaweed-block/core/transport/recovery_sink_adapter.go b/seaweed-block/core/transport/recovery_sink_adapter.go index 26be2d6d95..3919a02f4d 100644 --- a/seaweed-block/core/transport/recovery_sink_adapter.go +++ b/seaweed-block/core/transport/recovery_sink_adapter.go @@ -2,7 +2,9 @@ package transport import ( "context" + "errors" "net" + "sync" ) // RecoverySink is the transport-side adapter that satisfies @@ -39,16 +41,38 @@ type RecoverySink struct { replicaID string // Session-context: applied BEFORE StartSession (rule 1). + // P2d (architect 2026-04-30): sessionProfile is fixed at + // EmitProfileDualLaneWALFrame in production — recovery sessions + // always emit on the dual-lane port using frameWALEntry. sessionConn net.Conn sessionLineage RecoveryLineage + sessionProfile EmitProfile // Pre-session / steady context: restored AFTER EndSession - // (rule 2). nil conn / zero lineage is honest — it just - // means "no steady emit context active before this session". + // (rule 2). nil conn / zero lineage / SteadyMsgShip profile is + // honest — "no steady emit context active before this session". steadyConn net.Conn steadyLineage RecoveryLineage + steadyProfile EmitProfile + + // sealMu protects sealed and serializes NotifyAppend's check- + // then-delegate against EndSession. After EndSession sets + // sealed=true, NotifyAppend returns ErrSinkSealed instead of + // delegating to WalShipper — matches senderBacklogSink's + // post-flushAndSeal contract so callers (PrimaryBridge.PushLiveWrite) + // get a clean "session is closing" signal during the brief + // window between sink-end and bridge-map-removal. + sealMu sync.Mutex + sealed bool } +// ErrSinkSealed is returned by RecoverySink.NotifyAppend after the +// session's EndSession has fired. Callers (PushLiveWrite) treat this +// as "session is closing — fall back to steady-live or retry on a +// fresh session". Mirrors the senderBacklogSink "sink sealed" error +// so both sink implementations look the same to the caller. +var ErrSinkSealed = errors.New("recovery: NotifyAppend after sink sealed (session is closing)") + // NewRecoverySink constructs a RecoverySink bound to the // executor's per-replica WalShipper. Caller provides: // @@ -82,6 +106,26 @@ func NewRecoverySink( sessionLineage RecoveryLineage, steadyConn net.Conn, steadyLineage RecoveryLineage, +) *RecoverySink { + return NewRecoverySinkWithProfiles(e, replicaID, + sessionConn, sessionLineage, EmitProfileDualLaneWALFrame, + steadyConn, steadyLineage, EmitProfileSteadyMsgShip, + ) +} + +// NewRecoverySinkWithProfiles is NewRecoverySink with explicit profile +// arguments — for tests that want to exercise non-production +// profile combinations or for future variants where the steady +// profile differs from the legacy default. +func NewRecoverySinkWithProfiles( + e *BlockExecutor, + replicaID string, + sessionConn net.Conn, + sessionLineage RecoveryLineage, + sessionProfile EmitProfile, + steadyConn net.Conn, + steadyLineage RecoveryLineage, + steadyProfile EmitProfile, ) *RecoverySink { _ = e.WalShipperFor(replicaID) // ensure entry exists return &RecoverySink{ @@ -89,8 +133,10 @@ func NewRecoverySink( replicaID: replicaID, sessionConn: sessionConn, sessionLineage: sessionLineage, + sessionProfile: sessionProfile, steadyConn: steadyConn, steadyLineage: steadyLineage, + steadyProfile: steadyProfile, } } @@ -100,7 +146,7 @@ func NewRecoverySink( // emit context has already been updated — caller's defer of // EndSession will restore it. func (r *RecoverySink) StartSession(fromLSN uint64) error { - r.e.updateWalShipperEmitContext(r.replicaID, r.sessionConn, r.sessionLineage) + r.e.updateWalShipperEmitContext(r.replicaID, r.sessionConn, r.sessionLineage, r.sessionProfile) return r.e.WalShipperFor(r.replicaID).StartSession(fromLSN) } @@ -117,16 +163,37 @@ func (r *RecoverySink) DrainBacklog(ctx context.Context) error { // emit triggered by the EndSession path completes under session // context before the restore lands. func (r *RecoverySink) EndSession() { + // Set sealed FIRST so any in-flight NotifyAppend that races + // past the sealMu check sees the sealed=true gate before the + // WalShipper transitions and emit context is restored. This is + // the analogue of senderBacklogSink.flushAndSeal's atomic seal + // boundary. + r.sealMu.Lock() + r.sealed = true + r.sealMu.Unlock() + r.e.WalShipperFor(r.replicaID).EndSession() - r.e.updateWalShipperEmitContext(r.replicaID, r.steadyConn, r.steadyLineage) + r.e.updateWalShipperEmitContext(r.replicaID, r.steadyConn, r.steadyLineage, r.steadyProfile) } -// NotifyAppend delegates to WalShipper.NotifyAppend. In Backlog -// mode (during the session) the call updates the lag sample; -// the actual emit happens via the drain loop. In Realtime mode -// (after EndSession) it ships directly under whatever emit -// context is current — session context until restore, steady -// context after. +// NotifyAppend delegates to WalShipper.NotifyAppend during the +// session. In Backlog mode the call updates the lag sample; the +// drain loop picks up the entry from substrate. In Realtime mode +// it ships directly under the session emit context (dual-lane port +// + frameWALEntry). +// +// After EndSession seals the sink, NotifyAppend returns ErrSinkSealed +// — matches senderBacklogSink's post-flushAndSeal contract so +// callers (PushLiveWrite) get a clean "session is closing" signal. +// Without this, a NotifyAppend racing in after EndSession would hit +// the WalShipper with a steady (nil) emit context and produce a +// confusing "no conn" error. func (r *RecoverySink) NotifyAppend(lba uint32, lsn uint64, data []byte) error { + r.sealMu.Lock() + sealed := r.sealed + r.sealMu.Unlock() + if sealed { + return ErrSinkSealed + } return r.e.WalShipperFor(r.replicaID).NotifyAppend(lba, lsn, data) } diff --git a/seaweed-block/core/transport/recovery_sink_adapter_test.go b/seaweed-block/core/transport/recovery_sink_adapter_test.go index d248f357d4..8a6930c3cd 100644 --- a/seaweed-block/core/transport/recovery_sink_adapter_test.go +++ b/seaweed-block/core/transport/recovery_sink_adapter_test.go @@ -23,6 +23,7 @@ package transport import ( "bytes" "context" + "errors" "net" "sync" "testing" @@ -31,12 +32,14 @@ import ( ) // recordedEmit captures one emit observation from the test's -// recording EmitFunc. Intentionally records (conn, lineage, lba, -// lsn) but NOT data — the test pins lifecycle ordering, not wire -// format. +// recording EmitFunc. Intentionally records (conn, lineage, profile, +// kind, lba, lsn) but NOT data — the test pins lifecycle ordering, +// not wire format. type recordedEmit struct { conn net.Conn lineage RecoveryLineage + profile EmitProfile + kind EmitKind lba uint32 lsn uint64 } @@ -72,14 +75,16 @@ func installRecordingShipper(t *testing.T, e *BlockExecutor, replicaID string) ( var recMu sync.Mutex recorded := []recordedEmit{} - rec := func(lba uint32, lsn uint64, data []byte) error { + rec := func(kind EmitKind, lba uint32, lsn uint64, data []byte) error { entry.emitCtxMu.Lock() conn := entry.emitConn lineage := entry.emitLineage + profile := entry.emitProfile entry.emitCtxMu.Unlock() recMu.Lock() recorded = append(recorded, recordedEmit{ - conn: conn, lineage: lineage, lba: lba, lsn: lsn, + conn: conn, lineage: lineage, profile: profile, + kind: kind, lba: lba, lsn: lsn, }) recMu.Unlock() return nil @@ -138,7 +143,7 @@ func TestRecoverySink_StartSession_InstallsSessionContext(t *testing.T) { // Pre-state: install steady context. This mimics Ship() having // been the previous user of the shipper. _ = e.WalShipperFor(replicaID) - e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage) + e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage, EmitProfileSteadyMsgShip) pre, preLin := readEntryEmitContext(t, e, replicaID) if pre != steadyConn || preLin != steadyLineage { @@ -205,7 +210,7 @@ func TestRecoverySink_DrainBacklogEmits_UseSessionContext(t *testing.T) { sessionLineage := RecoveryLineage{ SessionID: 99, Epoch: 2, EndpointVersion: 3, TargetLSN: 1000, } - e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage) + e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage, EmitProfileSteadyMsgShip) sink := NewRecoverySink(e, replicaID, sessionConn, sessionLineage, @@ -263,7 +268,7 @@ func TestRecoverySink_EndSession_RestoresSteadyContext(t *testing.T) { } _ = e.WalShipperFor(replicaID) - e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage) + e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage, EmitProfileSteadyMsgShip) sink := NewRecoverySink(e, replicaID, sessionConn, sessionLineage, @@ -321,7 +326,7 @@ func TestRecoverySink_NotifyAppendAfterEndSession_UsesSteadyContext(t *testing.T SessionID: 42, Epoch: 1, EndpointVersion: 1, TargetLSN: 200, } - e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage) + e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage, EmitProfileSteadyMsgShip) sink := NewRecoverySink(e, replicaID, sessionConn, sessionLineage, @@ -336,10 +341,16 @@ func TestRecoverySink_NotifyAppendAfterEndSession_UsesSteadyContext(t *testing.T } sink.EndSession() - // Post-EndSession Realtime-mode NotifyAppend MUST emit under - // steady context (rule 2 surface check from the emit side). - if err := sink.NotifyAppend(7, 100, []byte{0xCC}); err != nil { - t.Fatalf("NotifyAppend post-EndSession: %v", err) + // Post-EndSession: sink itself is sealed (rejects NotifyAppend + // with ErrSinkSealed — verified separately in + // TestRecoverySink_NotifyAppendAfterEndSession_Sealed). The + // rule-2 architectural assertion is "emit context restored to + // steady" which is independent of sink seal — verify by calling + // the underlying WalShipper directly so the recording EmitFunc + // captures the post-EndSession context state. + shipper := e.WalShipperFor(replicaID) + if err := shipper.NotifyAppend(7, 100, []byte{0xCC}); err != nil { + t.Fatalf("WalShipper.NotifyAppend post-EndSession: %v", err) } recMu.Lock() @@ -396,7 +407,7 @@ func TestRecoverySink_FullLifecycle(t *testing.T) { SessionID: 99, Epoch: 5, EndpointVersion: 7, TargetLSN: 5000, } - e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage) + e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage, EmitProfileSteadyMsgShip) sink := NewRecoverySink(e, replicaID, sessionConn, sessionLineage, @@ -420,9 +431,12 @@ func TestRecoverySink_FullLifecycle(t *testing.T) { sink.EndSession() - // Post-session Realtime emit. - if err := sink.NotifyAppend(15, 9999, []byte{0xFF}); err != nil { - t.Fatalf("NotifyAppend post-EndSession: %v", err) + // Post-session Realtime emit. Sink is sealed; bypass it and + // call the underlying WalShipper directly to verify the post- + // EndSession emit context is the restored steady context. + shipper := e.WalShipperFor(replicaID) + if err := shipper.NotifyAppend(15, 9999, []byte{0xFF}); err != nil { + t.Fatalf("WalShipper.NotifyAppend post-EndSession: %v", err) } recMu.Lock() @@ -453,6 +467,53 @@ func TestRecoverySink_FullLifecycle(t *testing.T) { sessionEmitCount, totalEmits-sessionEmitCount) } +// TestRecoverySink_NotifyAppendAfterEndSession_Sealed — post- +// EndSession the sink itself rejects NotifyAppend with ErrSinkSealed. +// Mirrors senderBacklogSink's post-flushAndSeal contract so callers +// (PrimaryBridge.PushLiveWrite) get a clean "session is closing" +// signal — without this gate, races between EndSession and bridge- +// map-removal would produce confusing "no conn" errors from the +// underlying WalShipper. +func TestRecoverySink_NotifyAppendAfterEndSession_Sealed(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() + sessionConn, _ := net.Pipe() + defer sessionConn.Close() + + steadyLineage := RecoveryLineage{ + SessionID: 7, Epoch: 1, EndpointVersion: 1, TargetLSN: 1, + } + sessionLineage := RecoveryLineage{ + SessionID: 42, Epoch: 1, EndpointVersion: 1, TargetLSN: 200, + } + + _ = e.WalShipperFor(replicaID) + e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage, EmitProfileSteadyMsgShip) + + sink := NewRecoverySink(e, replicaID, + sessionConn, sessionLineage, + steadyConn, steadyLineage, + ) + + if err := sink.StartSession(0); err != nil { + t.Fatalf("StartSession: %v", err) + } + sink.EndSession() + + // Post-EndSession NotifyAppend MUST return ErrSinkSealed. + err := sink.NotifyAppend(0, 1, []byte{0x42}) + if err == nil { + t.Fatal("post-EndSession NotifyAppend: want error, got nil") + } + if !errors.Is(err, ErrSinkSealed) { + t.Errorf("post-EndSession NotifyAppend err=%v want ErrSinkSealed", err) + } +} + // TestRecoverySink_SatisfiesWalShipperSink — compile-time check // that *RecoverySink implements the recovery.WalShipperSink // interface by duck typing. The interface lives in `recovery` diff --git a/seaweed-block/core/transport/ship_sender.go b/seaweed-block/core/transport/ship_sender.go index e662c280ef..57ae8e08a5 100644 --- a/seaweed-block/core/transport/ship_sender.go +++ b/seaweed-block/core/transport/ship_sender.go @@ -129,7 +129,7 @@ func (e *BlockExecutor) Ship(replicaID string, lineage RecoveryLineage, lba uint // // Per v3-recovery-wal-shipper-mini-plan.md §3 P1. s := e.WalShipperFor(replicaID) - e.updateWalShipperEmitContext(replicaID, conn, lineage) + e.updateWalShipperEmitContext(replicaID, conn, lineage, EmitProfileSteadyMsgShip) if err := s.NotifyAppend(lba, lsn, data); err != nil { return fmt.Errorf("transport: ship: write failed replica=%s lsn=%d: %w", replicaID, lsn, err) diff --git a/seaweed-block/core/transport/snapshot_emit_context_test.go b/seaweed-block/core/transport/snapshot_emit_context_test.go index deebb622a8..829b8a33ff 100644 --- a/seaweed-block/core/transport/snapshot_emit_context_test.go +++ b/seaweed-block/core/transport/snapshot_emit_context_test.go @@ -22,13 +22,16 @@ 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") + conn, lineage, profile := 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) } + if profile != EmitProfileSteadyMsgShip { + t.Errorf("SnapshotEmitContext on absent replica: profile=%s want SteadyMsgShip", profile) + } } // TestSnapshotEmitContext_AfterUpdate_ReturnsCurrent — basic @@ -48,15 +51,18 @@ func TestSnapshotEmitContext_AfterUpdate_ReturnsCurrent(t *testing.T) { // Ensure entry exists, then update. _ = e.WalShipperFor(replicaID) - e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage) + e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage, EmitProfileSteadyMsgShip) - gotConn, gotLineage := e.SnapshotEmitContext(replicaID) + gotConn, gotLineage, gotProfile := 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) } + if gotProfile != EmitProfileSteadyMsgShip { + t.Errorf("SnapshotEmitContext profile=%s want SteadyMsgShip", gotProfile) + } } // TestSnapshotEmitContext_ThenRecoverySink_RestoresCaptured — @@ -79,11 +85,11 @@ func TestSnapshotEmitContext_ThenRecoverySink_RestoresCaptured(t *testing.T) { // Production-shape step: pre-existing steady ship has set context. _ = e.WalShipperFor(replicaID) - e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage) + e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage, EmitProfileSteadyMsgShip) // Caller pattern: snapshot BEFORE constructing RecoverySink, pass // to the constructor as the steady-restore values. - snappedConn, snappedLineage := e.SnapshotEmitContext(replicaID) + snappedConn, snappedLineage, _ := e.SnapshotEmitContext(replicaID) sessionConn, _ := net.Pipe() defer sessionConn.Close() diff --git a/seaweed-block/core/transport/wal_shipper.go b/seaweed-block/core/transport/wal_shipper.go index d51d29fd65..7999fb8138 100644 --- a/seaweed-block/core/transport/wal_shipper.go +++ b/seaweed-block/core/transport/wal_shipper.go @@ -38,6 +38,27 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) +// EmitKind tags one emit with its source lane semantic. Passed by +// WalShipper to EmitFunc; the EmitFunc uses it only when the wire +// profile cares (e.g., dual-lane recovery WAL frame's WALKind tag); +// the legacy MsgShipEntry profile ignores it. +// +// EmitKindLive: NotifyAppend in Realtime mode (live writes from the +// primary's local apply path). +// EmitKindBacklog: DrainBacklog scan loop emits (substrate ScanLBAs +// catch-up during recovery session backlog phase). +// +// P2d (architect 2026-04-30): kind plus the entry's emit profile +// determines the wire frame: SteadyMsgShip + any kind → MsgShipEntry; +// DualLaneWALFrame + Live → frameWALEntry(WALKindSessionLive); +// DualLaneWALFrame + Backlog → frameWALEntry(WALKindBacklog). +type EmitKind int + +const ( + EmitKindLive EmitKind = iota + EmitKindBacklog +) + // EmitFunc is the wire-side delivery surface. WalShipper hands every // emit through this function. In production: BlockExecutor.Ship's // WriteMsg. In test: a mock that records LSN sequence + asserts @@ -49,7 +70,7 @@ import ( // belongs to the executor / engine layer (e.g., mark peer Degraded, // schedule retry, fail-close session). Mode stays unchanged on emit // error; cursor is NOT advanced for the failed emit. -type EmitFunc func(lba uint32, lsn uint64, data []byte) error +type EmitFunc func(kind EmitKind, lba uint32, lsn uint64, data []byte) error // HeadSource provides primary's current head LSN. WalShipper queries // this in R1's double-check and on each timer tick. The substrate's @@ -278,7 +299,7 @@ func (s *WalShipper) NotifyAppend(lba uint32, lsn uint64, data []byte) error { // Idempotent: write already accounted for (e.g. retry). return nil } - if err := s.emit(lba, lsn, data); err != nil { + if err := s.emit(EmitKindLive, lba, lsn, data); err != nil { return err } s.cursor = lsn @@ -340,7 +361,7 @@ func (s *WalShipper) DrainBacklog(ctx context.Context) error { if s.mode != ModeBacklog || e.LSN <= s.cursor { return nil // mode flipped or already-emitted; skip } - if err := s.emit(e.LBA, e.LSN, e.Data); err != nil { + if err := s.emit(EmitKindBacklog, e.LBA, e.LSN, e.Data); err != nil { hardErr = fmt.Errorf("walshipper: backlog emit lsn=%d: %w", e.LSN, err) return err } diff --git a/seaweed-block/core/transport/wal_shipper_test.go b/seaweed-block/core/transport/wal_shipper_test.go index ddfb4343e3..c137f2af7e 100644 --- a/seaweed-block/core/transport/wal_shipper_test.go +++ b/seaweed-block/core/transport/wal_shipper_test.go @@ -56,7 +56,7 @@ func newRecordingEmit() *recordingEmit { } func (r *recordingEmit) Func() EmitFunc { - return func(lba uint32, lsn uint64, data []byte) error { + return func(_ EmitKind, lba uint32, lsn uint64, data []byte) error { // INV-NO-DOUBLE-LIVE probe: track concurrent emits. shipMu // should serialize so this never exceeds 1. cur := r.inFlight.Add(1) @@ -757,9 +757,9 @@ func TestWalShipper_BacklogStaysBacklog_UnderLoad(t *testing.T) { // Block emit briefly per call to simulate slow wire — emit can't // keep up with writes. emit := newRecordingEmit() - slowEmit := EmitFunc(func(lba uint32, lsn uint64, data []byte) error { + slowEmit := EmitFunc(func(kind EmitKind, lba uint32, lsn uint64, data []byte) error { time.Sleep(50 * time.Microsecond) // slow wire simulator - return emit.Func()(lba, lsn, data) + return emit.Func()(kind, lba, lsn, data) }) s := NewWalShipper("r1", HeadSourceFromStorage(primary), primary, slowEmit) diff --git a/seaweed-block/core/transport/walshipper_resident_test.go b/seaweed-block/core/transport/walshipper_resident_test.go index fa9fe90b3b..4b51b5a8aa 100644 --- a/seaweed-block/core/transport/walshipper_resident_test.go +++ b/seaweed-block/core/transport/walshipper_resident_test.go @@ -161,7 +161,7 @@ func TestWalShipper_Resident_SteadyShipBetweenSessions(t *testing.T) { steadyLineage := RecoveryLineage{ SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 1, } - e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage) + e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage, EmitProfileSteadyMsgShip) // Phase 1: steady NotifyAppend (Realtime). if err := shipper.NotifyAppend(0, 1, []byte{0x01}); err != nil { @@ -258,7 +258,7 @@ func TestWalShipper_Resident_NotifyAppendDuringSession_BacklogMode(t *testing.T) sessionLineage := RecoveryLineage{ SessionID: 100, Epoch: 1, EndpointVersion: 1, TargetLSN: 1000, } - e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage) + e.updateWalShipperEmitContext(replicaID, steadyConn, steadyLineage, EmitProfileSteadyMsgShip) sink := NewRecoverySink(e, replicaID, sessionConn, sessionLineage,