From d8b30f59569a69e6701d202eb85540400f4bc269 Mon Sep 17 00:00:00 2001 From: Ping Qiu Date: Wed, 29 Apr 2026 16:23:07 -0700 Subject: [PATCH] G7-redo wiring: cmd flag + replication factory + transport + component fixture (dual-lane reachable from binary) (#13) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * docs: wiring plan for core/recovery → core/transport + cmd Strategy doc for the next PR (g7-redo/wiring): how to land the dual-lane recovery package alongside (NOT replacing) the existing single-lane core/transport path per architect ruling. Sections: - Strategy: --recovery-mode flag (legacy / dual-lane); default legacy until one milestone of dual-lane GREEN observed. - Surface inventory: 6 files in core/transport, 1-2 in cmd, 0 in core/recovery (it stays untouched). - Lifecycle alignment: PeerShipCoordinator is the single source of truth for "is replica P in a rebuild session" when dual-lane active; legacy's BlockExecutor.activeSession is internal to the legacy path. Mode is exclusive. - Wire-format collision (frameSessionStart=0x01 vs MsgShipEntry= 0x01): three options analyzed; recommend separate ports per mode. - Coordinator scope: per-volume, NOT per-replica (so MinPin sees all replicas for a meaningful min). - Priority 2.5 (WAL recycle consumes MinPin): new RecycleFloorSource interface in core/storage; coordinator already implements it exactly; recommend split into g7-redo/recycle-pin-hookup PR after this one. - Test plan: dual-lane integration tests + recycle-pin unit test. Existing legacy tests unchanged. - Rollback: default flip is one-line; legacy removal is a separate later PR. 4 open questions for architect (wire collision option, 2.5 split, default flip timing, legacy removal timing). Out of scope: §3.2 #3 interleave, retry budget (parallel PR), liveShipTargetLSNSentinel removal (waits for legacy removal). Co-Authored-By: Claude Opus 4.7 (1M context) * transport: dual-lane wiring (BlockExecutor + StartRebuild branch) First wiring step per docs/recovery-wiring-plan.md §1-§3. Adds the parallel-flag plumbing for routing StartRebuild through the core/recovery package's PrimaryBridge while leaving the legacy single-lane path completely untouched on the default constructor. Architect ACK on §11 Resolution 1 (separate ports, Option A) drives the design: dual-lane uses a separate listen address from the legacy port; this commit only does the primary-side dial; replica's listen loop is illustrated in dual_lane_test.go and will be hoisted into cmd/blockvolume in a follow-up. What lands: core/transport/executor.go + DualLaneConfig struct (Bridge / DialAddr / ReplicaID). + dualLane *DualLaneConfig field on BlockExecutor. + NewBlockExecutorWithDualLane(primaryStore, replicaAddr, dualLaneAddr, coord, replicaID) constructor. + Bridge captures executor's onStart/onClose via closures so SetOnSession*Callback continues to work post-construction. core/transport/rebuild_sender.go + StartRebuild branches on e.dualLane != nil. + startRebuildDualLane: dial dual-lane port, call bridge.StartRebuildSession, immediately FinishLiveWrites (legacy semantic — no live writes during rebuild). Logs the same "executor: rebuild start" marker QA helpers scrape, with "(dual-lane)" suffix for trace clarity. core/transport/dual_lane_test.go + runDualLaneListener test helper (illustrates what cmd will do in production: net.Listen + accept loop spawning recovery.ReplicaBridge.Serve per conn). + TestDualLane_BlockExecutor_StartRebuild — full path: OnSessionStart fires, OnSessionClose fires with achievedLSN == primaryH, replica's substrate matches primary byte-for-byte, coordinator returns to PhaseIdle. + TestDualLane_LegacyConstructorIsNotDualLane — guard that the existing NewBlockExecutor stays legacy (dualLane == nil). Validation: 2 new tests pass; all existing core/transport tests unchanged; full repo `go test ./...` green. OUT OF SCOPE for this PR (per wiring plan §10): - cmd/blockvolume flag wiring (next commit). - WAL recycle path consuming MinPinAcrossActiveSessions (architect priority 2.5 — separate g7-redo/recycle-pin-hookup PR per §11 Resolution 2). - Removing core/transport/replica.go::liveShipTargetLSNSentinel lane shim (waits for legacy removal milestone). - §3.2 #3 single-queue real-time interleave (architect priority #2). Co-Authored-By: Claude Opus 4.7 (1M context) * wiring: cmd flag + replication factory + listener (dual-lane reachable from binary) Second wiring step per docs/recovery-wiring-plan.md. After this commit, the daemon binary actually exposes the dual-lane recovery path: a flag selects mode, the replication volume injects the right BlockExecutor factory per peer, and a separate listener binds at port+1 for inbound recover-session conns. cmd/blockvolume/main.go + --recovery-mode=legacy|dual-lane flag (default legacy). + Validation: rejects unknown values at parse time. + In dual-lane mode, after constructing replVolume: - new per-volume recovery.PeerShipCoordinator, - SetDualLaneExecutorFactory wires per-peer NewBlockExecutorWithDualLane closures, - separate listener at deriveDualLaneAddr(data-addr) running recovery.ReplicaBridge.AcceptDualLaneLoop in its own goroutine, - graceful close via deferred cancel + ln.Close at daemon shutdown. + deriveDualLaneAddr helper: host:port → host:port+1 (deployment convention, wiring plan §4 Option A). cmd/blockvolume/dual_lane_addr_test.go + Pins the port+1 convention: IPv4, IPv6, port=0 boundary, overflow at 65535, malformed inputs. core/replication/volume.go + dualLaneExecutorFactory type (factory takes replicaID alongside addr — the legacy 2-arg signature does not). + newDualExec field, nil-default = use legacy newExec. + UpdateReplicaSet branches on which factory is set per peer. + SetDualLaneExecutorFactory exported setter for cmd to inject the per-volume coordinator-capturing closure. MUST be called before UpdateReplicaSet (existing peers do not retroactively re-construct). core/recovery/integration_stub.go + Hoist AcceptDualLaneLoop helper from the test file to a public method on ReplicaBridge. Production cmd uses this directly; test wrapper now just calls it. core/transport/dual_lane_test.go + Refactor runDualLaneListener to use the new public helper instead of an inline accept loop. Lifecycle simplified (ctx cancel + ln close → loop returns). Validation: cmd/blockvolume tests + full repo go test ./... PASS. Default --recovery-mode=legacy keeps existing G5-* / G6 behavior identical. Out of scope (still): WAL recycle path consuming MinPin (g7-redo/ recycle-pin-hookup, separate PR per architect §11 Resolution 2), removing legacy lane shim, §3.2 #3 interleave. Co-Authored-By: Claude Opus 4.7 (1M context) * component: dual-lane engine-driven happy path (wiring step 3) Closes the wiring milestone per docs/recovery-wiring-plan.md §7 + architect "P0 = component layer dual-lane full chain" (2026-04-29). Full chain pinned: master fact → adapter.OnAssignment → engine ingest Identity → emits ProbeReplica → executor.Probe → adapter ingests RecoveryFacts → engine.decide() picks rebuild (R --------- Co-authored-by: Claude Opus 4.7 (1M context) --- .../cmd/blockvolume/dual_lane_addr_test.go | 39 ++++ seaweed-block/cmd/blockvolume/main.go | 115 ++++++++++ .../core/recovery/integration_stub.go | 32 +++ .../core/replication/component/cluster.go | 139 +++++++++++- .../component/dual_lane_engine_test.go | 197 ++++++++++++++++++ seaweed-block/core/replication/volume.go | 46 +++- .../core/transport/dual_lane_test.go | 150 +++++++++++++ seaweed-block/core/transport/executor.go | 108 +++++++++- .../core/transport/rebuild_sender.go | 50 +++++ seaweed-block/docs/recovery-wiring-plan.md | 184 ++++++++++++++++ 10 files changed, 1040 insertions(+), 20 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/dual_lane_addr_test.go create mode 100644 seaweed-block/core/replication/component/dual_lane_engine_test.go create mode 100644 seaweed-block/core/transport/dual_lane_test.go create mode 100644 seaweed-block/docs/recovery-wiring-plan.md diff --git a/seaweed-block/cmd/blockvolume/dual_lane_addr_test.go b/seaweed-block/cmd/blockvolume/dual_lane_addr_test.go new file mode 100644 index 0000000000..3a62297312 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/dual_lane_addr_test.go @@ -0,0 +1,39 @@ +package main + +import "testing" + +// TestDeriveDualLaneAddr pins the port+1 deployment convention +// (docs/recovery-wiring-plan.md §4 Option A). Production daemons MUST +// agree on this offset until AssignmentFact carries an explicit +// dual-lane field. +func TestDeriveDualLaneAddr(t *testing.T) { + cases := []struct { + in string + want string + wantErr bool + }{ + {"127.0.0.1:9220", "127.0.0.1:9221", false}, + {"127.0.0.1:0", "127.0.0.1:1", false}, + {"[::1]:9220", "[::1]:9221", false}, + {"192.168.1.10:65534", "192.168.1.10:65535", false}, + {"192.168.1.10:65535", "", true}, // overflow + {"no-port-here", "", true}, + {"127.0.0.1:notanumber", "", true}, + } + for _, tc := range cases { + got, err := deriveDualLaneAddr(tc.in) + if tc.wantErr { + if err == nil { + t.Errorf("deriveDualLaneAddr(%q): want error, got %q", tc.in, got) + } + continue + } + if err != nil { + t.Errorf("deriveDualLaneAddr(%q): unexpected err %v", tc.in, err) + continue + } + if got != tc.want { + t.Errorf("deriveDualLaneAddr(%q): got %q want %q", tc.in, got, tc.want) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 2146ee58fe..d57e97ec58 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -12,6 +12,7 @@ import ( "net" "os" "os/signal" + "strconv" "syscall" "time" @@ -22,7 +23,9 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/memback" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/recovery" "github.com/seaweedfs/seaweed-block/core/replication" + "github.com/seaweedfs/seaweed-block/core/storage" "github.com/seaweedfs/seaweed-block/core/transport" ) @@ -98,6 +101,18 @@ type flags struct { degradedProbeInterval time.Duration degradedProbeCooldownBase time.Duration degradedProbeCooldownCap time.Duration + + // G7-redo: recovery mode selector. "legacy" (default) keeps the + // existing single-lane core/transport rebuild path. "dual-lane" + // routes StartRebuild through core/recovery's PrimaryBridge, + // binding a separate listener at port=data-addr-port+1 per the + // deployment convention (docs/recovery-wiring-plan.md §4 Option A, + // architect ACK 2026-04-29). + // + // Default flip from legacy → dual-lane is a separate operations PR + // after one milestone of dual-lane GREEN observed in CI / hardware + // (architect §11 Resolution 3). + recoveryMode string } func parseFlags(args []string) (flags, error) { @@ -146,10 +161,18 @@ func parseFlags(args []string) (flags, error) { "G5-5C per-peer cooldown ceiling for the consecutive-failure backoff. "+ "Must be >= --degraded-probe-cooldown-base; values below base are normalized up to base. "+ "Ignored when --degraded-probe-interval=0.") + fs.StringVar(&f.recoveryMode, "recovery-mode", "legacy", + "G7-redo: recovery path. \"legacy\" (default) = single-lane "+ + "core/transport rebuild. \"dual-lane\" = core/recovery PrimaryBridge "+ + "with separate listener at data-addr port+1. Default flip is a "+ + "separate ops PR after dual-lane GREEN milestone.") fs.SetOutput(os.Stderr) if err := fs.Parse(args); err != nil { return flags{}, err } + if f.recoveryMode != "legacy" && f.recoveryMode != "dual-lane" { + return flags{}, fmt.Errorf("--recovery-mode=%q invalid; want \"legacy\" or \"dual-lane\"", f.recoveryMode) + } missing := []string{} for name, val := range map[string]string{ "master": f.masterAddr, "server-id": f.serverID, @@ -451,6 +474,32 @@ func run(f flags) int { replVolume = replication.NewReplicationVolume(f.volumeID, store) h.SetReplicationVolume(replVolume) + // G7-redo: when --recovery-mode=dual-lane, inject the dual-lane + // executor factory so per-peer BlockExecutors route StartRebuild + // through core/recovery's PrimaryBridge. Per-volume coordinator + // is shared across all peers so MinPinAcrossActiveSessions + // reflects the true minimum (wiring plan §5). + // + // Dual-lane address derivation: peer.DataAddr's port + 1. + // Convention only — production may eventually carry a separate + // dual-lane field in AssignmentFact. See wiring plan §4 Option A. + if f.recoveryMode == "dual-lane" { + recoveryCoord := recovery.NewPeerShipCoordinator() + replVolume.SetDualLaneExecutorFactory(func(s storage.LogicalStorage, replicaAddr, replicaID string) *transport.BlockExecutor { + peerDualLane, err := deriveDualLaneAddr(replicaAddr) + if err != nil { + // Fall back to legacy ctor; the executor will not + // have a dual-lane path. Logged for diagnostics. + fmt.Fprintf(os.Stderr, + "blockvolume: recovery-mode=dual-lane but peer addr %q has no port+1 form (%v); falling back to legacy executor for this peer\n", + replicaAddr, err) + return transport.NewBlockExecutor(s, replicaAddr) + } + return transport.NewBlockExecutorWithDualLane(s, replicaAddr, peerDualLane, recoveryCoord, recovery.ReplicaID(replicaID)) + }) + fmt.Fprintln(os.Stderr, "blockvolume: G7-redo recovery-mode=dual-lane (PrimaryBridge per-peer; coord per-volume)") + } + // G5-5C: configure + start the degraded-peer probe loop if // the operator opted in via --degraded-probe-interval > 0. // Off by default — preserves G5-4 behavior. Architect-bound @@ -550,6 +599,52 @@ func run(f flags) int { } listener.Serve() replListen = listener + + // G7-redo: when --recovery-mode=dual-lane, also bind a separate + // listener at port=data-addr-port+1 for inbound dual-lane + // recover-session connections. Each accepted conn is handed to + // a fresh recovery.Receiver via ReplicaBridge.AcceptDualLaneLoop. + // Listener lifecycle is goroutine-scoped here; daemon shutdown + // closes the underlying net.Listener via the deferred close + // added below (via the dualLaneListener variable + cleanup). + if f.recoveryMode == "dual-lane" { + dualLaneAddr, err := deriveDualLaneAddr(f.dataAddr) + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: dual-lane listen addr derive:", err) + _ = replListen.Stop + _ = replVolume.Close() + _ = durableProv.Close() + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + dlLn, err := net.Listen("tcp", dualLaneAddr) + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: dual-lane listen:", err) + _ = replListen.Stop + _ = replVolume.Close() + _ = durableProv.Close() + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + replicaBridge := recovery.NewReplicaBridge(store) + dualLaneCtx, dualLaneCancel := context.WithCancel(context.Background()) + go replicaBridge.AcceptDualLaneLoop(dualLaneCtx, dlLn) + defer func() { + dualLaneCancel() + _ = dlLn.Close() + }() + fmt.Fprintf(os.Stderr, "blockvolume: G7-redo dual-lane listener bound at %s\n", dualLaneAddr) + } } // G5-5C addendum (architect ruling 2026-04-28): frontend volume @@ -701,3 +796,23 @@ func run(f flags) int { } return 0 } + +// deriveDualLaneAddr maps "host:port" → "host:port+1". Per +// docs/recovery-wiring-plan.md §4 Option A: dual-lane traffic uses a +// separate port from the legacy data port via this fixed convention. +// Production may eventually carry a separate dual-lane field in +// AssignmentFact; until then, all daemons must agree on this offset. +func deriveDualLaneAddr(addr string) (string, error) { + host, portStr, err := net.SplitHostPort(addr) + if err != nil { + return "", fmt.Errorf("split %q: %w", addr, err) + } + port, err := strconv.Atoi(portStr) + if err != nil { + return "", fmt.Errorf("port %q not numeric: %w", portStr, err) + } + if port+1 > 65535 { + return "", fmt.Errorf("port %d+1 overflows", port) + } + return net.JoinHostPort(host, strconv.Itoa(port+1)), nil +} diff --git a/seaweed-block/core/recovery/integration_stub.go b/seaweed-block/core/recovery/integration_stub.go index 4d4445fef3..781c93d465 100644 --- a/seaweed-block/core/recovery/integration_stub.go +++ b/seaweed-block/core/recovery/integration_stub.go @@ -188,3 +188,35 @@ func (b *ReplicaBridge) Serve(ctx context.Context, conn net.Conn) (uint64, error } return receiver.Run() } + +// AcceptDualLaneLoop runs an accept loop on the given listener, +// dispatching every accepted connection to a fresh ReplicaBridge.Serve +// goroutine. Returns when the listener is closed (caller's signal to +// stop is `ln.Close()`). Production daemon (cmd/blockvolume) uses this +// to bind the dual-lane port; tests can use it directly with a +// temporary `net.Listen("tcp", "127.0.0.1:0")`. +// +// The function is non-blocking-safe: each conn handler runs in its +// own goroutine, so a long-lived recovery session does not block +// further accepts. +// +// Lifecycle: this loop OWNS the goroutines it spawns until the +// listener is closed. After ln.Close, in-flight handlers continue +// (they exit on ctx cancel or their own conn read error). Caller +// owns ctx and listener lifecycles. +func (b *ReplicaBridge) AcceptDualLaneLoop(ctx context.Context, ln net.Listener) { + for { + conn, err := ln.Accept() + if err != nil { + // Listener closed (caller's signal) or fatal accept error; + // either way, stop. Per-conn goroutines spawned earlier + // keep running until they exit on their own. + return + } + go func(c net.Conn) { + subCtx, cancel := context.WithCancel(ctx) + defer cancel() + _, _ = b.Serve(subCtx, c) + }(conn) + } +} diff --git a/seaweed-block/core/replication/component/cluster.go b/seaweed-block/core/replication/component/cluster.go index 5d2d414c2b..95c0346287 100644 --- a/seaweed-block/core/replication/component/cluster.go +++ b/seaweed-block/core/replication/component/cluster.go @@ -17,8 +17,10 @@ import ( "github.com/seaweedfs/seaweed-block/core/adapter" "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/recovery" "github.com/seaweedfs/seaweed-block/core/replication" "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/storage/memorywal" "github.com/seaweedfs/seaweed-block/core/storage/smartwal" "github.com/seaweedfs/seaweed-block/core/transport" ) @@ -61,6 +63,23 @@ func Walstore(t *testing.T, dir, label string, blocks uint32, blockSize int) (st } } +// MemoryWAL is the V2-faithful in-memory WAL substrate factory +// (core/storage/memorywal). Distinct from BlockStore in +// core/storage: MemoryWAL preserves write-time LSN through ScanLBAs +// (RecoveryModeWALReplay) so component tests that need per-LSN +// replay semantics get the right shape without disk overhead. +// +// dir/label arguments are accepted to match SubstrateFactory but +// ignored (the substrate is in-memory). Cleanup is a no-op (Close +// only flips the closed flag; no files to remove). +func MemoryWAL(t *testing.T, _ string, _ string, blocks uint32, blockSize int) (storage.LogicalStorage, func()) { + t.Helper() + s := memorywal.NewStore(blocks, blockSize) + return s, func() { + _ = s.Close() + } +} + // Defaults — tunable per-test via With* methods. const ( DefaultBlocks uint32 = 64 @@ -92,6 +111,13 @@ type Cluster struct { withLiveShip bool // if true, primary spins up StorageBackend + ReplicationVolume engineRecovery bool // T4d hook (currently no-op + warning); see WithEngineDrivenRecovery withApplyGate bool // T4d-2: install replication.ReplicaApplyGate on each replica's listener + dualLane bool // G7-redo: route StartRebuild via core/recovery PrimaryBridge + + // G7-redo: per-volume coordinator + per-replica dual-lane + // listeners populated by Start() when dualLane=true. Tests can + // inspect Coord() to assert pin floor / phase. + coord *recovery.PeerShipCoordinator + dualLaneReplicaAddrs []string // index-aligned with replicas[]; empty when dualLane=false // Built at Start() primary *PrimaryNode @@ -138,6 +164,11 @@ type ReplicaNode struct { Listener *transport.ReplicaListener Addr string + // DualLaneAddr is the recovery-package listener address bound + // alongside Listener when the cluster is built with + // WithDualLaneRecovery; empty otherwise. + DualLaneAddr string + // ApplyGate is non-nil iff cluster was built WithApplyGate (T4d-2). ApplyGate *replication.ReplicaApplyGate @@ -238,6 +269,45 @@ func (c *Cluster) WithEngineDrivenRecovery() *Cluster { return c } +// WithDualLaneRecovery routes StartRebuild through the core/recovery +// PrimaryBridge (mirroring cmd/blockvolume's --recovery-mode=dual-lane). +// Each replica gets a separate dual-lane listener bound to a different +// localhost port; the per-volume coordinator is shared across all +// per-replica executors so MinPinAcrossActiveSessions reflects the +// true minimum. +// +// Compatible with WithEngineDrivenRecovery — engine-driven scenarios +// can stack dual-lane on top so the engine emits StartRebuild and the +// dual-lane bridge handles it transparently. +// +// Per docs/recovery-wiring-plan.md §7: this is the component-layer +// dual-lane integration test surface; closes the gap between "single- +// process unit POC" and "real engine→executor→wire→barrier round-trip". +func (c *Cluster) WithDualLaneRecovery() *Cluster { + c.dualLane = true + return c +} + +// Coord returns the per-volume PeerShipCoordinator when the cluster +// was built WithDualLaneRecovery (nil otherwise). Tests use this to +// assert pin floor advancement, phase transitions, etc. +func (c *Cluster) Coord() *recovery.PeerShipCoordinator { return c.coord } + +// DualLaneReplicaAddr returns the i-th replica's dual-lane listen +// address (bound by Start when WithDualLaneRecovery is set). Empty +// when dual-lane is off. Diagnostic + edge-case tests only — +// production code should never need this. +func (c *Cluster) DualLaneReplicaAddr(i int) string { + c.t.Helper() + if !c.dualLane { + return "" + } + if i < 0 || i >= len(c.dualLaneReplicaAddrs) { + c.t.Fatalf("DualLaneReplicaAddr(%d): out of range (have %d)", i, len(c.dualLaneReplicaAddrs)) + } + return c.dualLaneReplicaAddrs[i] +} + // Adapter returns the per-replica VolumeReplicaAdapter (T4d-4 part B // / round-47). Returns nil if cluster was NOT built with // WithEngineDrivenRecovery. @@ -312,20 +382,56 @@ func (c *Cluster) Start() *Cluster { c.t.Fatalf("%s: NewReplicaListener: %v", label, err) } listener.Serve() - node := &ReplicaNode{ - Idx: i, - Store: store, - Listener: listener, - Addr: listener.Addr(), - ApplyGate: gate, - cleanup: func() { - listener.Stop() + + // G7-redo: when dual-lane is enabled, bind a SECOND listener + // per replica for inbound recover-session conns. Lifecycle is + // goroutine-scoped here; replica cleanup tears it down. + var dualLaneAddr string + var dualLaneStop func() + if c.dualLane { + dlLn, lnErr := net.Listen("tcp", "127.0.0.1:0") + if lnErr != nil { + _ = listener cleanup() - }, + c.t.Fatalf("%s: dual-lane listen: %v", label, lnErr) + } + dualLaneAddr = dlLn.Addr().String() + bridge := recovery.NewReplicaBridge(store) + ctx, cancel := context.WithCancel(context.Background()) + loopDone := make(chan struct{}) + go func() { + defer close(loopDone) + bridge.AcceptDualLaneLoop(ctx, dlLn) + }() + dualLaneStop = func() { + cancel() + _ = dlLn.Close() + <-loopDone + } + } + + nodeCleanup := func() { + if dualLaneStop != nil { + dualLaneStop() + } + listener.Stop() + cleanup() + } + node := &ReplicaNode{ + Idx: i, + Store: store, + Listener: listener, + Addr: listener.Addr(), + DualLaneAddr: dualLaneAddr, + ApplyGate: gate, + cleanup: nodeCleanup, } // Register replica cleanup FIRST so it runs LAST in LIFO. c.t.Cleanup(node.cleanup) c.replicas[i] = node + if c.dualLane { + c.dualLaneReplicaAddrs = append(c.dualLaneReplicaAddrs, dualLaneAddr) + } } // Bring up primary with one BlockExecutor per replica. @@ -338,9 +444,22 @@ func (c *Cluster) Start() *Cluster { pStore = c.primaryWrap(pStoreRaw) } + // G7-redo: when dual-lane is enabled, instantiate the per-volume + // coordinator BEFORE building executors so each executor + // captures the same instance. + if c.dualLane { + c.coord = recovery.NewPeerShipCoordinator() + } executors := make([]*transport.BlockExecutor, c.replicaN) for i, r := range c.replicas { - executors[i] = transport.NewBlockExecutor(pStore, r.Addr) + if c.dualLane { + rid := recovery.ReplicaID(fmt.Sprintf("r-%d", i)) + executors[i] = transport.NewBlockExecutorWithDualLane( + pStore, r.Addr, r.DualLaneAddr, c.coord, rid, + ) + } else { + executors[i] = transport.NewBlockExecutor(pStore, r.Addr) + } } c.primary = &PrimaryNode{ Store: pStore, diff --git a/seaweed-block/core/replication/component/dual_lane_engine_test.go b/seaweed-block/core/replication/component/dual_lane_engine_test.go new file mode 100644 index 0000000000..b7873a72e8 --- /dev/null +++ b/seaweed-block/core/replication/component/dual_lane_engine_test.go @@ -0,0 +1,197 @@ +package component_test + +import ( + "bytes" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/recovery" + "github.com/seaweedfs/seaweed-block/core/replication/component" +) + +// TestDualLane_EngineDrivenRebuild_HappyPath — closes the +// G7-redo wiring milestone: full chain from master fact through +// engine decide → adapter dispatch → BlockExecutor (dual-lane mode) +// → recovery.PrimaryBridge → wire (separate listener at replica's +// DualLaneAddr) → recovery.Receiver → barrier → SessionClosedCompleted +// flowing back to the adapter / engine. +// +// What this pins (per docs/recovery-wiring-plan.md §7): +// +// - WithDualLaneRecovery + WithEngineDrivenRecovery compose: engine +// emits StartRebuild via adapter; adapter dispatches to +// dual-lane-mode BlockExecutor; rebuild succeeds. +// - The cluster's per-volume PeerShipCoordinator is reachable via +// Coord(); after session close it is back to PhaseIdle for this +// replica (no leak). +// - Replica's substrate matches primary byte-for-byte after the +// session — the headline correctness invariant. +// +// What this does NOT cover (still out of scope): +// +// - Hardware integration (separate phase). +// - WAL recycle path consuming MinPin (g7-redo/recycle-pin-hookup). +// - §3.2 #3 single-queue real-time interleave (architect priority #2). +// - Multi-replica fanout under dual-lane (single replica here for +// focus; coordinator already covered for N-replica MinPin in unit +// tests). +func TestDualLane_EngineDrivenRebuild_HappyPath(t *testing.T) { + component.RunSubstrate(t, "memorywal", component.MemoryWAL, func(t *testing.T, c *component.Cluster) { + c.WithReplicas(1). + WithEngineDrivenRecovery(). + WithDualLaneRecovery(). + Start() + + // Seed primary with N writes so probe returns non-trivial R/S/H. + const seedN = 12 + c.PrimaryWriteN(seedN) + c.PrimarySync() + + a := c.Adapter(0) + + // Drive the master assignment — engine ingests Identity, emits + // the auto-probe. + c.DriveAssignment(0, adapter.AssignmentInfo{ + VolumeID: "v1", + ReplicaID: "replica-0", + Epoch: 1, + EndpointVersion: 1, + DataAddr: c.Replica(0).Addr, + CtrlAddr: c.Replica(0).Addr, + }) + + // Drive a probe result that classifies as REBUILD: R < S means + // the replica has been recycled past — engine.decide() picks + // rebuild. R=0 (empty replica), S=1 (primary's WAL retains + // LSN 1+), H=12 (primary head). + c.DriveProbeResult(0, adapter.ProbeResult{ + ReplicaID: "replica-0", + Success: true, + EndpointVersion: 1, + TransportEpoch: 1, + ReplicaFlushedLSN: 0, // R + PrimaryTailLSN: 1, // S + PrimaryHeadLSN: seedN, // H = 12 + }) + + // Wait for engine to dispatch StartRebuild (CommandLog) AND + // for the dual-lane session to complete (Trace records the + // SessionClosedCompleted event flowing back from + // adapter.OnSessionClose into the engine). + deadline := time.Now().Add(5 * 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 { + t.Fatalf("engine did NOT emit StartRebuild; CommandLog=%v", a.CommandLog()) + } + if !sawSessionClosed { + t.Fatalf("dual-lane session did NOT close cleanly; CommandLog=%v Trace=%v", + a.CommandLog(), a.Trace()) + } + + // Coordinator should be back to Idle for replica-0. + if got := c.Coord().Phase(recovery.ReplicaID("r-0")); got != recovery.PhaseIdle { + t.Errorf("coord phase post-session: %s want Idle", got) + } + + // Replica's substrate matches primary byte-for-byte across the + // rebuilt range. PrimaryWriteN writes LBA 0..N-1 with a known + // pattern (cluster's helper). Read each LBA from both sides + // and assert equality. + 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("dual-lane post-rebuild: lba %d primary[0]=%02x replica[0]=%02x not equal", + lba, pd[0], rd[0]) + } + } + }) +} + +// TestDualLane_CoordReleasesPinFloorAfterSession — pins the +// post-session lifecycle invariant: when a rebuild session ends +// (success or failure), the coordinator's pin_floor for that +// replica is dropped (PinFloor returns 0 for an Idle peer per the +// existing coordinator contract). Without this, a long-lived +// daemon could leak pin floors and stall WAL recycle. +// +// Also implicitly pins INV-SESSION-TEARDOWN-IS-EXPLICIT. +func TestDualLane_CoordReleasesPinFloorAfterSession(t *testing.T) { + component.RunSubstrate(t, "memorywal", component.MemoryWAL, func(t *testing.T, c *component.Cluster) { + c.WithReplicas(1). + WithEngineDrivenRecovery(). + WithDualLaneRecovery(). + Start() + + c.PrimaryWriteN(8) + c.PrimarySync() + + 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: 8, + }) + + // Wait for session to complete via Trace (SessionClosedCompleted + // is an EVENT, not a Command; CommandLog won't show it). + a := c.Adapter(0) + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + done := false + for _, te := range a.Trace() { + if te.Step == "event" && te.Detail == "SessionClosedCompleted" { + done = true + } + } + if done { + break + } + time.Sleep(20 * time.Millisecond) + } + + // MinPinAcrossActiveSessions should report no active sessions + // after teardown. Pin floor for the replica reads 0. + if _, anyActive := c.Coord().MinPinAcrossActiveSessions(); anyActive { + t.Errorf("post-session: MinPinAcrossActiveSessions still reports anyActive=true") + } + if got := c.Coord().PinFloor(recovery.ReplicaID("r-0")); got != 0 { + t.Errorf("post-session: PinFloor=%d want 0 (released)", got) + } + }) +} diff --git a/seaweed-block/core/replication/volume.go b/seaweed-block/core/replication/volume.go index c67e9e2b7a..0be5c363ae 100644 --- a/seaweed-block/core/replication/volume.go +++ b/seaweed-block/core/replication/volume.go @@ -37,7 +37,8 @@ type LocalWrite struct { type ReplicationVolume struct { volumeID string store storage.LogicalStorage // borrowed, NEVER closed by us - newExec executorFactory // test seam; default dials real TCP + newExec executorFactory // test seam; default dials real TCP + newDualExec dualLaneExecutorFactory // optional dual-lane override; nil = use newExec coord *DurabilityCoordinator // used by Sync; stateless mu sync.Mutex // serializes UpdateReplicaSet + OnLocalWrite entry AND fan-out AND Sync @@ -75,6 +76,16 @@ type ReplicationVolume struct { // transport.NewBlockExecutor. type executorFactory func(store storage.LogicalStorage, replicaAddr string) *transport.BlockExecutor +// dualLaneExecutorFactory is an optional alternative factory used +// when the daemon is started in --recovery-mode=dual-lane. When non-nil, +// `UpdateReplicaSet` calls it instead of `executorFactory` for each new +// peer, giving the factory both the peer's data address AND its +// replica ID so it can construct a BlockExecutor configured for the +// dual-lane recovery package (per docs/recovery-wiring-plan.md §2). +// +// Default (legacy mode): nil; falls back to executorFactory. +type dualLaneExecutorFactory func(store storage.LogicalStorage, replicaAddr, replicaID string) *transport.BlockExecutor + // NewReplicationVolume constructs a per-volume fan-out coordinator. // The returned volume borrows store — it is a read-only handle from // the volume's perspective and is never closed here (Provider owns @@ -97,6 +108,32 @@ func NewReplicationVolume(volumeID string, store storage.LogicalStorage) *Replic } } +// SetDualLaneExecutorFactory injects the dual-lane BlockExecutor +// constructor so subsequent `UpdateReplicaSet` calls build per-peer +// executors via the recovery package's PrimaryBridge instead of the +// legacy single-lane path. Idempotent; pass nil to revert to legacy. +// +// Caller (cmd/blockvolume) is responsible for: +// - Building a per-volume `recovery.PeerShipCoordinator` ONCE and +// capturing it in the closure (so MinPinAcrossActiveSessions +// reports the true minimum across all peers). +// - Translating peer.replicaAddr (data port) → dual-lane port via +// deployment convention. +// - Starting the local dual-lane listener (see +// `recovery.AcceptDualLaneLoop`). +// +// MUST be called BEFORE the first `UpdateReplicaSet` so the very +// first peer is built with the right factory; later switches DO NOT +// retroactively re-construct existing peers. +// +// Per docs/recovery-wiring-plan.md §3 (lifecycle alignment) — mode is +// exclusive: tests don't mix legacy and dual-lane on the same volume. +func (v *ReplicationVolume) SetDualLaneExecutorFactory(f func(store storage.LogicalStorage, replicaAddr, replicaID string) *transport.BlockExecutor) { + v.mu.Lock() + defer v.mu.Unlock() + v.newDualExec = f +} + // SetDurabilityMode configures the per-volume durability semantic // that Sync uses. Safe to call at any time; effect applies from the // next Sync call forward. Per mini-plan §5, T4b does not support @@ -268,7 +305,12 @@ func (v *ReplicationVolume) UpdateReplicaSet(generation uint64, targets []Replic v.onPeerRemoved(id) } } - executor := v.newExec(v.store, t.DataAddr) + var executor *transport.BlockExecutor + if v.newDualExec != nil { + executor = v.newDualExec(v.store, t.DataAddr, id) + } else { + executor = v.newExec(v.store, t.DataAddr) + } peer, err := NewReplicaPeer(t, executor) if err != nil { return fmt.Errorf("replication: UpdateReplicaSet: add peer %s: %w", id, err) diff --git a/seaweed-block/core/transport/dual_lane_test.go b/seaweed-block/core/transport/dual_lane_test.go new file mode 100644 index 0000000000..84a16e8070 --- /dev/null +++ b/seaweed-block/core/transport/dual_lane_test.go @@ -0,0 +1,150 @@ +package transport + +import ( + "bytes" + "context" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/recovery" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// runDualLaneListener spins up a TCP listener on 127.0.0.1:0 that +// accepts dual-lane recover connections and dispatches each to a +// fresh recovery.Receiver via recovery.ReplicaBridge.Serve. Returns +// the bound address and a stop function. +// +// In production, cmd/blockvolume.main does the equivalent. Inlined +// here so the test can exercise the dual-lane wire path end-to-end +// without a daemon binary. +func runDualLaneListener(t *testing.T, store storage.LogicalStorage) (addr string, stop func()) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + bridge := recovery.NewReplicaBridge(store) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + bridge.AcceptDualLaneLoop(ctx, ln) + }() + return ln.Addr().String(), func() { + cancel() + _ = ln.Close() + <-done + } +} + +// TestDualLane_BlockExecutor_StartRebuild proves that +// NewBlockExecutorWithDualLane delegates StartRebuild through +// recovery.PrimaryBridge correctly: +// +// - Dials the replica's separate dual-lane port (Option A). +// - Coordinator's StartSession fires synchronously before return. +// - OnSessionStart / OnSessionClose callbacks fire with adapter-shaped +// results (so existing engine code consumes them transparently). +// - achievedLSN == primary's H. +// - Replica's substrate matches primary byte-for-byte after barrier. +// +// What this test does NOT cover (out of scope per wiring plan §10): +// +// - §3.2 #3 single-queue real-time interleave. +// - WAL recycle path consuming MinPinAcrossActiveSessions (priority 2.5). +// - cmd flag wiring (production daemon path). +func TestDualLane_BlockExecutor_StartRebuild(t *testing.T) { + const numBlocks = 64 + const blockSize = 4096 + + primary := storage.NewBlockStore(numBlocks, blockSize) + replica := storage.NewBlockStore(numBlocks, blockSize) + + // Seed primary with 30 LBAs of distinguishable bytes. + for lba := uint32(0); lba < 30; lba++ { + data := make([]byte, blockSize) + data[0] = byte(0x80 | lba) + _, _ = primary.Write(lba, data) + } + _, _ = primary.Sync() + + // Replica-side dual-lane listener. + dualLaneAddr, stop := runDualLaneListener(t, replica) + defer stop() + + // Coordinator (per wiring plan §5: per-volume, here per-test). + coord := recovery.NewPeerShipCoordinator() + + // Executor in dual-lane mode. legacy replicaAddr is bogus — this + // test only exercises StartRebuild, which routes via dualLaneAddr. + exec := NewBlockExecutorWithDualLane( + primary, + "127.0.0.1:0", // legacy port, unused in this test + dualLaneAddr, + coord, + recovery.ReplicaID("r1"), + ) + + startCh := make(chan adapter.SessionStartResult, 1) + closeCh := make(chan adapter.SessionCloseResult, 1) + exec.SetOnSessionStart(func(r adapter.SessionStartResult) { startCh <- r }) + exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closeCh <- r }) + + _, _, primaryH := primary.Boundaries() + if err := exec.StartRebuild("r1", 7, 1, 1, primaryH); err != nil { + t.Fatalf("StartRebuild: %v", err) + } + + // OnSessionStart should fire fast (bridge invokes it synchronously + // before the goroutine spawns). + select { + case got := <-startCh: + if got.SessionID != 7 { + t.Errorf("OnSessionStart: SessionID=%d want 7", got.SessionID) + } + case <-time.After(2 * time.Second): + t.Fatal("OnSessionStart did not fire within 2s") + } + + // OnSessionClose: success with achievedLSN == primary H. + select { + case got := <-closeCh: + if !got.Success { + t.Fatalf("OnSessionClose: not Success; FailReason=%q", got.FailReason) + } + if got.AchievedLSN != primaryH { + t.Errorf("OnSessionClose: achievedLSN=%d want %d", got.AchievedLSN, primaryH) + } + case <-time.After(5 * time.Second): + t.Fatal("OnSessionClose did not fire within 5s") + } + + // Replica matches primary on the rebuilt range. + for lba := uint32(0); lba < 30; lba++ { + pd, _ := primary.Read(lba) + rd, _ := replica.Read(lba) + if !bytes.Equal(pd, rd) { + t.Fatalf("lba %d mismatch: primary[0]=%02x replica[0]=%02x", lba, pd[0], rd[0]) + } + } + + // Coordinator returned to Idle (session ended cleanly). + if got := coord.Phase("r1"); got != recovery.PhaseIdle { + t.Errorf("post-session phase=%s want Idle", got) + } +} + +// TestDualLane_LegacyConstructorIsNotDualLane verifies the +// existing NewBlockExecutor path is unchanged: e.dualLane is nil, +// StartRebuild falls through to the legacy single-lane code (no +// behavior change for callers using the legacy constructor). +func TestDualLane_LegacyConstructorIsNotDualLane(t *testing.T) { + primary := storage.NewBlockStore(8, 4096) + exec := NewBlockExecutor(primary, "127.0.0.1:0") + if exec.dualLane != nil { + t.Errorf("legacy NewBlockExecutor: dualLane=%v want nil", exec.dualLane) + } +} diff --git a/seaweed-block/core/transport/executor.go b/seaweed-block/core/transport/executor.go index 18d54a2e74..0e50a967d0 100644 --- a/seaweed-block/core/transport/executor.go +++ b/seaweed-block/core/transport/executor.go @@ -9,22 +9,51 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/recovery" "github.com/seaweedfs/seaweed-block/core/storage" ) // BlockExecutor implements adapter.CommandExecutor using real TCP // transport and a primary-side LogicalStorage. It is the "muscle" // layer — it executes commands but never decides policy. +// +// Recovery mode: nil DualLane => legacy single-lane path (rebuild +// streams MsgRebuildBlock and rejects live ship during rebuild). +// non-nil DualLane => StartRebuild delegates to recovery package's +// PrimaryBridge, dialing the replica's separate dual-lane port (per +// docs/recovery-wiring-plan.md §4 Option A — separate ports). +// Architect ACK on parallel-flag strategy (2026-04-29). type BlockExecutor struct { primaryStore storage.LogicalStorage - replicaAddr string // replica's TCP address + replicaAddr string // replica's legacy port (rebuild + ship + barrier + probe) - mu sync.Mutex - onSessionStart adapter.OnSessionStart - onSessionClose adapter.OnSessionClose - onFenceComplete adapter.OnFenceComplete - sessions map[uint64]*activeSession - stepDelay time.Duration + // dualLane is non-nil when this executor is configured for + // dual-lane recovery. StartRebuild branches on this; ship + + // probe + fence always use the legacy path on replicaAddr. + dualLane *DualLaneConfig + + mu sync.Mutex + onSessionStart adapter.OnSessionStart + onSessionClose adapter.OnSessionClose + onFenceComplete adapter.OnFenceComplete + sessions map[uint64]*activeSession + stepDelay time.Duration +} + +// DualLaneConfig holds the wiring for routing StartRebuild through +// the core/recovery dual-lane mechanism. Constructed at cmd / daemon +// startup when --recovery-mode=dual-lane. +type DualLaneConfig struct { + // Bridge is the primary-side adapter built once per executor + // (bridge captures executor's callback redirections via closures + // in NewBlockExecutorWithDualLane). + Bridge *recovery.PrimaryBridge + // DialAddr is the replica's dual-lane listen address (separate + // port from replicaAddr per the wiring plan §4 Option A). + DialAddr string + // ReplicaID identifies this replica in the coordinator's + // per-peer state. Must match the receiver's session view. + ReplicaID recovery.ReplicaID } type activeSession struct { @@ -37,7 +66,8 @@ var errSessionInvalidated = errors.New("session invalidated") const recoveryConnTimeout = 5 * time.Second -// NewBlockExecutor creates an executor for one primary -> replica pair. +// NewBlockExecutor creates a legacy-mode executor for one primary -> replica +// pair. StartRebuild uses the existing single-lane MsgRebuildBlock path. func NewBlockExecutor(primaryStore storage.LogicalStorage, replicaAddr string) *BlockExecutor { return &BlockExecutor{ primaryStore: primaryStore, @@ -46,6 +76,68 @@ func NewBlockExecutor(primaryStore storage.LogicalStorage, replicaAddr string) * } } +// NewBlockExecutorWithDualLane creates a dual-lane-mode executor. +// StartRebuild routes through the recovery package's PrimaryBridge, +// dialing dualLaneAddr (the replica's separate listen port). All other +// methods (Probe / Fence / StartCatchUp / ship via Ship()) continue to +// use replicaAddr's legacy port. +// +// `coord` must be a per-volume coordinator shared across all replicas +// of the same volume so MinPinAcrossActiveSessions reflects the true +// minimum (per wiring plan §5). +// +// `replicaID` MUST match the SessionStart payload the replica decodes; +// in production it is the engine's per-peer identifier as a string. +// +// The bridge captures executor-state closures so that subsequent +// SetOnSessionStart / SetOnSessionClose calls on this executor +// propagate to bridge callbacks dynamically. +func NewBlockExecutorWithDualLane( + primaryStore storage.LogicalStorage, + replicaAddr string, + dualLaneAddr string, + coord *recovery.PeerShipCoordinator, + replicaID recovery.ReplicaID, +) *BlockExecutor { + e := NewBlockExecutor(primaryStore, replicaAddr) + bridge := recovery.NewPrimaryBridge( + primaryStore, + coord, + func(rid recovery.ReplicaID, sid uint64) { + e.mu.Lock() + cb := e.onSessionStart + e.mu.Unlock() + if cb != nil { + cb(adapter.SessionStartResult{SessionID: sid}) + } + }, + func(rid recovery.ReplicaID, sid uint64, achieved uint64, err error) { + e.mu.Lock() + cb := e.onSessionClose + e.mu.Unlock() + if cb == nil { + return + } + res := adapter.SessionCloseResult{ + SessionID: sid, + AchievedLSN: achieved, + } + if err == nil { + res.Success = true + } else { + res.FailReason = err.Error() + } + cb(res) + }, + ) + e.dualLane = &DualLaneConfig{ + Bridge: bridge, + DialAddr: dualLaneAddr, + ReplicaID: replicaID, + } + return e +} + func (e *BlockExecutor) SetOnSessionClose(fn adapter.OnSessionClose) { e.onSessionClose = fn } diff --git a/seaweed-block/core/transport/rebuild_sender.go b/seaweed-block/core/transport/rebuild_sender.go index f7184618d7..8504ecb7bf 100644 --- a/seaweed-block/core/transport/rebuild_sender.go +++ b/seaweed-block/core/transport/rebuild_sender.go @@ -1,6 +1,7 @@ package transport import ( + "context" "fmt" "log" "net" @@ -17,6 +18,9 @@ import ( // MsgRebuildBlock per LBA, then a terminal MsgRebuildDone whose // BarrierResponse carries the replica's actually achieved frontier. func (e *BlockExecutor) StartRebuild(replicaID string, sessionID, epoch, endpointVersion, targetLSN uint64) error { + if e.dualLane != nil { + return e.startRebuildDualLane(replicaID, sessionID, epoch, endpointVersion, targetLSN) + } lineage := RecoveryLineage{ SessionID: sessionID, Epoch: epoch, @@ -120,3 +124,49 @@ func (e *BlockExecutor) doRebuild(replicaID string, session *activeSession, targ log.Printf("executor: rebuild complete, sent %d blocks (targetLSN=%d)", len(blocks), targetLSN) return resp.AchievedLSN, nil } + +// startRebuildDualLane is the wiring entry into the dual-lane recovery +// package. It dials the replica's separate dual-lane port (per +// 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 + FinishLiveWrites are kicked off). The +// bridge's onClose callback (set in NewBlockExecutorWithDualLane) +// fires the executor's OnSessionClose when the goroutine completes. +// +// 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. +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) + if err != nil { + return fmt.Errorf("dual-lane dial %s: %w", dl.DialAddr, err) + } + // Same observability marker as the legacy path so QA helpers + // scrape it identically across modes (INV-G6-WALRECYCLE-DISPATCHES- + // REBUILD). + log.Printf("executor: rebuild start replica=%s sessionID=%d epoch=%d EV=%d targetLSN=%d (dual-lane)", + replicaID, sessionID, epoch, endpointVersion, targetLSN) + // 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 { + _ = 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 +} diff --git a/seaweed-block/docs/recovery-wiring-plan.md b/seaweed-block/docs/recovery-wiring-plan.md new file mode 100644 index 0000000000..bbbc00e045 --- /dev/null +++ b/seaweed-block/docs/recovery-wiring-plan.md @@ -0,0 +1,184 @@ +# Recovery wiring plan — `core/recovery` into `core/transport` + cmd + +**Status**: design draft, not yet implemented. Targets architect priority **wiring + 2.5** (the natural next milestone after `g7-redo/pin-floor`). +**Branch target**: `g7-redo/wiring`, stacked on `g7-redo/pin-floor`. +**Depends on**: `g7-redo/dual-lane-recovery-poc` + `g7-redo/pin-floor` merged or reviewed first; this PR is meaningless without them. + +This doc fixes the strategy for moving the dual-lane recovery package from a self-contained POC into the production daemon path, alongside (NOT replacing) the existing single-lane `core/transport` path. Architect ruling: "parallel + flag, don't replace existing path until one happy path runs green alongside". + +--- + +## 1. Why parallel-flag, not in-place replacement + +The existing single-lane path (`core/transport/rebuild_sender.go::doRebuild` + `replica.go::handleConn` MsgRebuildBlock/MsgRebuildDone handlers) is what hardware integration tests (G6 §close, prior G5-5* milestones) currently exercise. A direct in-place replacement of `doRebuild` carries the risk of breaking those without giving QA a deterministic A/B comparison. + +Plan: introduce a flag (config + cmd-line + env) that selects between: + +- `--recovery-mode=legacy` (default) — existing single-lane path, no new code on hot path. +- `--recovery-mode=dual-lane` — the new `core/recovery` package drives rebuild sessions. + +Both paths share the same `BlockExecutor` outer surface (`StartRebuild` / `StartRecoverySession` callers do not care which is used). Wire-format compatibility is NOT required between paths — the dual-lane mode opens its own conn / port (TBD; see §4 below), the legacy mode keeps its existing one. + +Until a green hardware run on `--recovery-mode=dual-lane` is observed, the default stays `legacy`. Removal of the legacy path is a separate PR after at least one milestone of dual-lane GREEN observability. + +--- + +## 2. Surface inventory — files that need changes + +### Sender side (primary) + +| File | Change | Notes | +|---|---|---| +| `core/transport/rebuild_sender.go::StartRebuild` | Branch on mode flag. Legacy path unchanged. Dual-lane path delegates to `recovery.PrimaryBridge.StartRebuildSession`. | Outer signature unchanged so all upstream callers (`core/host/volume/peer_command_executor.go`, `core/transport/recovery_session.go::StartRecoverySession`'s `full_extent` branch, etc.) continue working. | +| `core/transport/recovery_session.go::StartRecoverySession` | The `full_extent` branch (line 117 today) calls `StartRebuild`. No change needed if `StartRebuild` itself branches; the dispatch already lives one level up. | Lowest-touch option. | +| `core/transport/executor.go::BlockExecutor` struct | Add optional fields: `dualLaneCoordinator *recovery.PeerShipCoordinator`, `dualLaneBridge *recovery.PrimaryBridge`. Nil ⇒ legacy mode. | Constructor variant `NewBlockExecutorWithDualLane(...)` initializes these. Existing `NewBlockExecutor` stays legacy. | + +### Receiver side (replica) + +| File | Change | Notes | +|---|---|---| +| `core/transport/replica.go::ReplicaListener` | Two listener configurations: legacy listens on existing port for old MsgRebuildBlock dispatch; dual-lane listens on a separate port (or same port + frame-type discriminator). Decision in §4. | Most invasive surface. | +| `core/transport/replica.go::handleConn` | Branch on first frame: if it's `recovery.frameSessionStart` (0x01), hand off to a `recovery.Receiver` for the rest of the conn lifetime. Otherwise use existing dispatch. | Type byte 0x01 in the new wire vs 0x01 (`MsgShipEntry`) in the old wire — collision; see §4. | +| `core/transport/replica.go::liveShipTargetLSNSentinel` + the lane-shim block | Document as deprecated when dual-lane is active (rebuild lineage no longer rejects live ship — that's the whole point of dual-lane). For legacy mode, keep working. | Removal in a later PR after dual-lane is default. | + +### cmd / daemon + +| File | Change | +|---|---| +| `cmd/blockvolume/main.go` (or wherever the executor is constructed) | Add `--recovery-mode` flag. Legacy: build `NewBlockExecutor(...)`. Dual-lane: build coordinator + bridge + `NewBlockExecutorWithDualLane(...)`. | +| `cmd/blockvolume/main.go` | Add `--recovery-pin-floor-recycle` flag (default off) gating priority 2.5 hookup (see §6). | + +### Replication wiring + +| File | Change | +|---|---| +| `core/replication/component/cluster.go` | If integration tests construct executors directly, propagate the mode flag through the test fixture. Otherwise unchanged. | +| `core/host/volume/peer_command_executor.go` | No change — wraps `BlockExecutor`'s `StartRebuild` which itself branches. | + +--- + +## 3. Lifecycle alignment (architect's "不能做第二套相位机") + +**Rule**: there must be exactly one source of truth for "is replica P in a rebuild session right now" — the `recovery.PeerShipCoordinator`. The legacy `BlockExecutor.activeSession` map is internal to the legacy path; the dual-lane path consults `coordinator.Phase()`. Mode is exclusive — at any moment only one tracker is authoritative for a given replica. + +**StartSession ↔ EndSession**: + +- Legacy mode: `BlockExecutor.registerSession` / `finishSession` pair (existing). +- Dual-lane mode: `coord.StartSession` / `coord.EndSession` pair (already implemented in `core/recovery`). The `PrimaryBridge.StartRebuildSession` calls `StartSession` synchronously before returning to its caller; the goroutine spawned underneath handles `EndSession` via `Sender.Run`'s defer. + +**OnSessionStart / OnSessionClose callbacks** (`adapter.CommandExecutor` surface): + +- Legacy: `BlockExecutor.SetOnSessionStart / SetOnSessionClose` already wired. +- Dual-lane: `PrimaryBridge` accepts the same callback shape; `BlockExecutor` constructor in dual-lane mode forwards its `onStart / onClose` down to `PrimaryBridge`. Caller (`HealthyPathExecutor` etc.) cannot tell which path fired the callback — by design. + +--- + +## 4. Wire-format collision + +**Problem**: legacy `MsgShipEntry = 0x01`, dual-lane `frameSessionStart = 0x01`. If both paths share a port, the receiver cannot dispatch on first byte alone. + +**Three resolution options**: + +### Option A — separate port per mode + +`--rebuild-listen=:9221` (legacy) and `--recovery-listen=:9222` (dual-lane). Daemon binds whichever the mode flag selects. **Pro**: zero protocol coupling; **con**: cmd flag surface grows; integration tests need to know which port. + +### Option B — wire-version handshake on connect + +First byte after dial is a wire-version byte (0x00 = legacy, 0x01 = dual-lane). Subsequent bytes follow the corresponding protocol. **Pro**: single port, cleanly versioned; **con**: existing legacy hardware tests don't send a version byte — backward-compat shim required. + +### Option C — re-number dual-lane frames to avoid 0x01 + +Move `frameSessionStart` to e.g. `0x10`, leaving `0x01..0x07` for legacy. **Pro**: same port, no handshake, cheap; **con**: special-cases the frame-type table; collision-free zone shrinks for future frames. + +**Recommend Option A** for this milestone. Cleanest separation, least risk to the legacy hardware path. Reverts to single-port multiplexing later if/when legacy is removed. + +--- + +## 5. Coordinator instance scope + +One `PeerShipCoordinator` per **volume**, NOT per **executor or per replica**. The coordinator's `MinPinAcrossActiveSessions` is meaningful only when it sees ALL replicas of a single volume. Per-replica coordinators would each report their own pin floor with no minimum. + +**Wiring**: cmd constructs a coordinator at volume open; passes it to all per-replica `BlockExecutor` constructors for that volume. The daemon owns the coordinator lifecycle. + +This is also why the WAL recycle hookup (§6 below) lives at the volume level, not the executor level. + +--- + +## 6. Priority 2.5 — WAL recycle path consumes `MinPinAcrossActiveSessions()` + +**Problem**: today `core/storage/walstore.go`'s flusher / recycle path advances `walTail` based on its own retention policy + checkpoint. It does NOT consult any per-peer pin floor. Until the recycle path knows about active sessions' commitments, `pin_floor` advancement is a paper exercise. + +**Hookup point**: `walstore.go::flusher.advanceTail` (or wherever the flusher decides what to recycle). New gate: + +```go +recycleFloor := computeRetentionFloor() // existing logic +if pinSrc != nil { + if pinned, anyActive := pinSrc.MinPinAcrossActiveSessions(); anyActive { + if pinned < recycleFloor { + recycleFloor = pinned // pin holds back recycle + } + } +} +// trim WAL to recycleFloor +``` + +**Interface seam**: `walstore.WALStore` does not know about `core/recovery` (and shouldn't — substrate stays orthogonal to engine). Solution: a small interface in `core/storage`: + +```go +type RecycleFloorSource interface { + MinPinAcrossActiveSessions() (floor uint64, anyActive bool) +} + +func (s *WALStore) SetRecycleFloorSource(src RecycleFloorSource) +``` + +`recovery.PeerShipCoordinator` already implements this signature exactly. cmd wires the coordinator into the volume's WAL store after both are constructed. Default: nil source (legacy behavior). + +**Test**: a new `walstore_recycle_pin_test.go` confirms recycle floor is gated by min pin when source is set; falls back to existing logic when nil. No e2e change required — the unit test is sufficient because the coordinator's contract is already covered. + +**Architect priority 2.5 closes when this hookup lands** AND a brief test confirms the integration works end-to-end (set pin floor on coord, observe recycle path respect it). + +--- + +## 7. Test plan + +Existing tests must continue to pass on `--recovery-mode=legacy` (default). The wiring PR adds: + +| Test | Scope | +|---|---| +| `core/transport/rebuild_sender_dual_lane_test.go` | Dual-lane mode end-to-end with the existing `BlockExecutor` shape: same OnSessionStart/Close callbacks fire, achievedLSN equals primary H. | +| `core/transport/replica_dual_lane_test.go` | Receiver-side dispatch for `frameSessionStart` correctly hands off to a `recovery.Receiver`. | +| `core/storage/walstore_recycle_pin_test.go` | §6 — recycle path consults `MinPinAcrossActiveSessions`. | +| Existing `TestE2E_*` in `core/recovery/` | UNCHANGED — they use `core/recovery` directly, not `core/transport`. Wiring PR doesn't touch them. | + +Hardware acceptance (G7 §2 #2 / #5 / #6): NOT a gate for this PR. Architect ruling: "validate happy-path one round green alongside legacy first, then enable as default in a separate PR". + +--- + +## 8. Rollback / removal plan + +If something is critically wrong with the dual-lane path post-merge: + +- **Default flip back**: change `--recovery-mode` default in cmd from `legacy` to `dual-lane` (or vice versa) is a single-line revert. +- **Code removal**: requires reverting the wiring PR. Because `core/recovery` is independent of `core/transport`, the package itself can stay even if the integration is rolled back. +- **legacy removal**: a future PR removes `core/transport/rebuild_sender.go::doRebuild` + the old wire frames. Should NOT be in this PR. Track as `g7-redo/legacy-removal`. + +--- + +## 9. Open questions for architect — Resolved (architect ACK 2026-04-29) + +1. **Wire collision** (§4): **RESOLVED — Option A (separate ports)**. Daemon binds a second listen address; `--recovery-mode` flag pairs with it. Firewall / Helm registration must follow. Fallback to Option B (version handshake) is permitted only if a platform constraint requires single-port. Option C (re-number frames) is rejected as a long-term solution. +2. **2.5 split**: **RESOLVED — split into `g7-redo/recycle-pin-hookup`**. Wiring PR stays focused on transport + cmd + lifecycle. Recycle hookup lands immediately after wiring merges, NOT held for a long gap (otherwise pin advances in the air while flusher recycles by old policy). +3. **Default mode flip timing**: **RESOLVED — stays `legacy`** until CI + hardware-targeted dual-lane scenarios run GREEN, then a separate single-line PR flips the default. Default flip is a release / ops event, not a wiring implementation detail. +4. **Legacy removal timing**: **RESOLVED — after default flip + at least one release cycle (canary / N weeks)**, NOT just calendar time. Pre-removal checklist: no-flag run green, monitoring / rollback documented. Tracked as `g7-redo/legacy-removal`. + +--- + +## 10. Out of scope (explicit) + +- `§3.2 #3 single-queue real-time interleave` (architect priority #2). Wiring PR ships sequential phases, same as POC. +- `INV-REPL-OVERLAP-HISTORY-NO-REGRESS` bitmap-as-WAL-claim refinement. Separate PR after apply-gate redesign. +- Sparse base + substrate basement-clearing. +- Layer 3 retry budget at engine level (architect priority #3 [retry]). Architect: "可与 wiring 并行 ... 不同目录"; tracked as a separate concurrent PR. +- Removing `core/transport/replica.go::liveShipTargetLSNSentinel` and the lane-shim. Lives until legacy is removed.