From 3ccf2ec729911ad70d41e749c2f03f5d99c808b4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 1 May 2026 22:03:12 -0700 Subject: [PATCH] transport: gate live WAL through active recovery session --- .../core/recovery/integration_stub.go | 11 ++ seaweed-block/core/replication/peer.go | 16 +- seaweed-block/core/replication/peer_test.go | 121 +++++++++++++++ seaweed-block/core/transport/executor.go | 24 ++- seaweed-block/core/transport/ship_sender.go | 12 ++ .../core/transport/ship_sender_test.go | 140 ++++++++++++++++++ 6 files changed, 320 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/recovery/integration_stub.go b/seaweed-block/core/recovery/integration_stub.go index db3167d746..7e431a471e 100644 --- a/seaweed-block/core/recovery/integration_stub.go +++ b/seaweed-block/core/recovery/integration_stub.go @@ -173,6 +173,17 @@ func (b *PrimaryBridge) startRebuildSessionLocked(ctx context.Context, conn net. return nil } +// HasActiveSession reports whether a dual-lane recovery session is +// currently in flight for the given replica. Transport uses this as the +// active-session gate before the legacy steady Ship path can touch the +// resident WalShipper's emit context. +func (b *PrimaryBridge) HasActiveSession(replicaID ReplicaID) bool { + b.mu.Lock() + defer b.mu.Unlock() + _, ok := b.senders[replicaID] + return ok +} + // PushLiveWrite forwards a primary-side WAL append to the active // session for this peer (if any). Caller is the WAL shipper // integration; they MUST have already consulted diff --git a/seaweed-block/core/replication/peer.go b/seaweed-block/core/replication/peer.go index c7d7f8d5f4..24b6ef29e9 100644 --- a/seaweed-block/core/replication/peer.go +++ b/seaweed-block/core/replication/peer.go @@ -468,13 +468,23 @@ func (p *ReplicaPeer) ShipEntry(ctx context.Context, lineage transport.RecoveryL p.target.ReplicaID, lba, lsn) return fmt.Errorf("replication: ShipEntry: peer %s closed", p.target.ReplicaID) } + peerLineage := p.lineage + targetID := p.target.ReplicaID + executor := p.executor if p.state == ReplicaDegraded { p.mu.Unlock() + if handled, err := executor.TryPushLiveWrite(targetID, lba, lsn, data); handled { + if err != nil { + return err + } + log.Printf("replication: ship session-lane peer=%s lba=%d lsn=%d (peer degraded, active recovery session)", + targetID, lba, lsn) + return nil + } log.Printf("replication: ship gate-degraded peer=%s lba=%d lsn=%d (peer degraded)", - p.target.ReplicaID, lba, lsn) - return fmt.Errorf("replication: ShipEntry: peer %s degraded", p.target.ReplicaID) + targetID, lba, lsn) + return fmt.Errorf("replication: ShipEntry: peer %s degraded", targetID) } - peerLineage := p.lineage p.mu.Unlock() if err := p.executor.Ship(p.target.ReplicaID, peerLineage, lba, lsn, data); err != nil { diff --git a/seaweed-block/core/replication/peer_test.go b/seaweed-block/core/replication/peer_test.go index dce6200094..274901af8e 100644 --- a/seaweed-block/core/replication/peer_test.go +++ b/seaweed-block/core/replication/peer_test.go @@ -6,11 +6,14 @@ package replication import ( "bytes" "context" + "io" "net" "strings" + "sync" "testing" "time" + "github.com/seaweedfs/seaweed-block/core/recovery" "github.com/seaweedfs/seaweed-block/core/storage" "github.com/seaweedfs/seaweed-block/core/transport" ) @@ -145,6 +148,124 @@ func TestReplicaPeer_ShipEntry_ConnFailure_MarksDegraded(t *testing.T) { } } +type peerRecordingSessionSink struct { + started chan struct{} + release chan struct{} + ended chan struct{} + + mu sync.Mutex + entries int +} + +func newPeerRecordingSessionSink() *peerRecordingSessionSink { + return &peerRecordingSessionSink{ + started: make(chan struct{}), + release: make(chan struct{}), + ended: make(chan struct{}), + } +} + +func (s *peerRecordingSessionSink) StartSession(fromLSN uint64) error { + _ = fromLSN + close(s.started) + return nil +} + +func (s *peerRecordingSessionSink) DrainBacklog(ctx context.Context) error { + select { + case <-s.release: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (s *peerRecordingSessionSink) EndSession() { + select { + case <-s.ended: + default: + close(s.ended) + } +} + +func (s *peerRecordingSessionSink) NotifyAppend(lba uint32, lsn uint64, data []byte) error { + _, _, _ = lba, lsn, data + s.mu.Lock() + s.entries++ + s.mu.Unlock() + return nil +} + +func (s *peerRecordingSessionSink) Entries() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.entries +} + +// TestReplicaPeer_ShipEntry_DegradedWithActiveSession_RoutesSessionLane +// pins the production call path for the global single-emitter rule. +// Hardware #5 showed that executor-level gates are too low: degraded +// peers used to reject before BlockExecutor.Ship was reached. Active +// recovery sessions must get first refusal even when the peer's coarse +// state is Degraded. +func TestReplicaPeer_ShipEntry_DegradedWithActiveSession_RoutesSessionLane(t *testing.T) { + primary := storage.NewBlockStore(8, 4096) + coord := recovery.NewPeerShipCoordinator() + replicaID := "r-peer-session" + exec := transport.NewBlockExecutorWithDualLane(primary, "127.0.0.1:1", "127.0.0.1:2", coord, recovery.ReplicaID(replicaID)) + target := ReplicaTarget{ + ReplicaID: replicaID, + DataAddr: "127.0.0.1:1", + ControlAddr: "127.0.0.1:1", + Epoch: 3, + EndpointVersion: 1, + } + peer, err := NewReplicaPeer(target, exec) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = peer.Close() }) + peer.SetState(ReplicaDegraded) + + sessionClient, sessionServer := net.Pipe() + t.Cleanup(func() { + _ = sessionClient.Close() + _ = sessionServer.Close() + }) + go func() { + _, _ = io.Copy(io.Discard, sessionServer) + }() + + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + sink := newPeerRecordingSessionSink() + bridge, _, ok := exec.DualLanePrimaryBridge() + if !ok { + t.Fatal("missing dual-lane bridge") + } + if err := bridge.StartRebuildSessionWithSink(ctx, sessionClient, recovery.ReplicaID(replicaID), 77, 10, 10, sink); err != nil { + t.Fatalf("start active session: %v", err) + } + select { + case <-sink.started: + case <-time.After(2 * time.Second): + t.Fatal("session sink did not start") + } + + data := make([]byte, 4096) + if err := peer.ShipEntry(context.Background(), transport.RecoveryLineage{}, 4, 11, data); err != nil { + t.Fatalf("ShipEntry on degraded peer with active session: %v", err) + } + if got := sink.Entries(); got != 1 { + t.Fatalf("ShipEntry routed %d entries to active session; want 1", got) + } + + cancel() + _ = sessionClient.Close() + _ = sessionServer.Close() + close(sink.release) +} + // TestReplicaPeer_Invalidate_MovesToDegraded — direct call to // Invalidate (outside ShipEntry path) also moves Healthy → Degraded. // Exercises the authority-driven path (ReplicationVolume would call diff --git a/seaweed-block/core/transport/executor.go b/seaweed-block/core/transport/executor.go index 319bde2ea6..0619d41efe 100644 --- a/seaweed-block/core/transport/executor.go +++ b/seaweed-block/core/transport/executor.go @@ -386,6 +386,7 @@ func (e *BlockExecutor) doFence(replicaID string, lineage RecoveryLineage) { // (T4b-1 wire) // - this method rejects valid-decode-but-wrong-session acks via // ErrBarrierLineageMismatch (T4b-2 ack-consumer validation) +// // A future optimization MUST NOT weaken this to epoch-only; the // full-lineage rule is load-bearing for H5 LOCK. // @@ -608,7 +609,7 @@ func (e *BlockExecutor) Probe(replicaID, dataAddr, ctrlAddr string, sessionID, e Success: false, EndpointVersion: endpointVersion, TransportEpoch: epoch, - FailReason: fmt.Sprintf("%v: expected=%+v actual=%+v", + FailReason: fmt.Sprintf("%v: expected=%+v actual=%+v", ErrProbeLineageMismatch, requestLineage, resp.Lineage), } } @@ -871,6 +872,27 @@ func (e *BlockExecutor) DualLanePrimaryBridge() (*recovery.PrimaryBridge, recove return e.dualLane.Bridge, e.dualLane.ReplicaID, true } +// TryPushLiveWrite routes a live WAL entry through an active dual-lane +// recovery session if one exists for replicaID. Returns (handled=true) +// whenever the entry was claimed by that session path, even if the +// session sink returned an error. Legacy-mode executors, or dual-lane +// executors with no active session for replicaID, return handled=false. +// +// This is the peer-layer counterpart to Ship's internal active-session +// gate: callers that would otherwise reject on coarse peer state can +// still respect the single-emitter rule and offer writes to the active +// recovery session before falling back to steady shipping. +func (e *BlockExecutor) TryPushLiveWrite(replicaID string, lba uint32, lsn uint64, data []byte) (handled bool, err error) { + if e.dualLane == nil { + return false, nil + } + rid := recovery.ReplicaID(replicaID) + if !e.dualLane.Bridge.HasActiveSession(rid) { + return false, nil + } + return true, e.dualLane.Bridge.PushLiveWrite(rid, lba, lsn, data) +} + // Registry lifecycle note (architect P1 review #4): walShippers // entries are never torn down today. For replica churn, lineage // invalidation, or executor reuse across distinct peer diff --git a/seaweed-block/core/transport/ship_sender.go b/seaweed-block/core/transport/ship_sender.go index 57ae8e08a5..1a4f96f310 100644 --- a/seaweed-block/core/transport/ship_sender.go +++ b/seaweed-block/core/transport/ship_sender.go @@ -5,6 +5,8 @@ import ( "log" "net" "time" + + "github.com/seaweedfs/seaweed-block/core/recovery" ) // shipWriteDeadline bounds Ship's TCP write so a dead replica can't @@ -56,6 +58,16 @@ const shipDialTimeout = 3 * time.Second // epoch return nil without writing anything to the wire. // - 3s write deadline (wal_shipper.go:240): byte-identical bound. func (e *BlockExecutor) Ship(replicaID string, lineage RecoveryLineage, lba uint32, lsn uint64, data []byte) error { + // Global single-emitter gate: an active recovery session owns the + // peer's live WAL egress. Ship must not fall through to the legacy + // steady MsgShip path because that path mutates the resident + // WalShipper's emit context. During recovery, every live write must + // enter through the active session sink so the one monotonic cursor + // speaks through one wire profile. + if e.dualLane != nil && e.dualLane.Bridge.HasActiveSession(recovery.ReplicaID(replicaID)) { + return e.dualLane.Bridge.PushLiveWrite(recovery.ReplicaID(replicaID), lba, lsn, data) + } + e.mu.Lock() session, ok := e.sessions[lineage.SessionID] if !ok || session == nil { diff --git a/seaweed-block/core/transport/ship_sender_test.go b/seaweed-block/core/transport/ship_sender_test.go index fb83132e96..0fddec1dcf 100644 --- a/seaweed-block/core/transport/ship_sender_test.go +++ b/seaweed-block/core/transport/ship_sender_test.go @@ -2,14 +2,18 @@ package transport import ( "bytes" + "context" "errors" + "io" "net" "os" "strings" + "sync" "sync/atomic" "testing" "time" + "github.com/seaweedfs/seaweed-block/core/recovery" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -463,3 +467,139 @@ func isTimeoutErr(err error) bool { } return false } + +type recordingSessionSink struct { + started chan struct{} + release chan struct{} + ended chan struct{} + startErr error + + mu sync.Mutex + entries []struct { + lba uint32 + lsn uint64 + data []byte + } +} + +func newRecordingSessionSink() *recordingSessionSink { + return &recordingSessionSink{ + started: make(chan struct{}), + release: make(chan struct{}), + ended: make(chan struct{}), + } +} + +func (s *recordingSessionSink) StartSession(fromLSN uint64) error { + _ = fromLSN + close(s.started) + return s.startErr +} + +func (s *recordingSessionSink) DrainBacklog(ctx context.Context) error { + select { + case <-s.release: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (s *recordingSessionSink) EndSession() { + select { + case <-s.ended: + default: + close(s.ended) + } +} + +func (s *recordingSessionSink) NotifyAppend(lba uint32, lsn uint64, data []byte) error { + cp := append([]byte(nil), data...) + s.mu.Lock() + s.entries = append(s.entries, struct { + lba uint32 + lsn uint64 + data []byte + }{lba: lba, lsn: lsn, data: cp}) + s.mu.Unlock() + return nil +} + +func (s *recordingSessionSink) Entries() int { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.entries) +} + +// TestExecutor_Ship_ActiveDualLaneSession_RoutesThroughSingleSessionEmitter +// pins the global single-emitter rule at the executor boundary. +// +// While a dual-lane recovery session is active for a replica, Ship must +// not fall through to the legacy steady MsgShip path. The only legal live +// WAL egress is PrimaryBridge.PushLiveWrite -> active session sink. If this +// regresses, Ship overwrites the resident WalShipper's emit context and the +// same monotonic cursor can speak through two wire profiles. +func TestExecutor_Ship_ActiveDualLaneSession_RoutesThroughSingleSessionEmitter(t *testing.T) { + primary := storage.NewBlockStore(8, 4096) + coord := recovery.NewPeerShipCoordinator() + replicaID := "r1" + exec := NewBlockExecutorWithDualLane(primary, "127.0.0.1:1", "127.0.0.1:2", coord, recovery.ReplicaID(replicaID)) + + steadyClient, steadyServer := net.Pipe() + t.Cleanup(func() { + _ = steadyClient.Close() + _ = steadyServer.Close() + }) + steadyLineage := RecoveryLineage{SessionID: 91, Epoch: 7, EndpointVersion: 3, TargetLSN: 100} + _ = exec.WalShipperFor(replicaID) + exec.updateWalShipperEmitContext(replicaID, steadyClient, steadyLineage, EmitProfileSteadyMsgShip) + + sessionClient, sessionServer := net.Pipe() + t.Cleanup(func() { + _ = sessionClient.Close() + _ = sessionServer.Close() + }) + go func() { + _, _ = io.Copy(io.Discard, sessionServer) + }() + + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + sink := newRecordingSessionSink() + if err := exec.dualLane.Bridge.StartRebuildSessionWithSink( + ctx, sessionClient, recovery.ReplicaID(replicaID), 77, 10, 10, sink, + ); err != nil { + t.Fatalf("StartRebuildSessionWithSink: %v", err) + } + select { + case <-sink.started: + case <-time.After(2 * time.Second): + t.Fatal("session sink did not start") + } + + shipLineage := RecoveryLineage{SessionID: 92, Epoch: 7, EndpointVersion: 3, TargetLSN: 200} + data := make([]byte, 4096) + data[0] = 0x5a + if err := exec.Ship(replicaID, shipLineage, 4, 11, data); err != nil { + t.Fatalf("Ship during active dual-lane session: %v", err) + } + if got := sink.Entries(); got != 1 { + t.Fatalf("active session Ship routed %d entries to session sink; want 1", got) + } + + gotConn, gotLineage, gotProfile := exec.SnapshotEmitContext(replicaID) + if gotConn != steadyClient { + t.Fatalf("Ship during active session overwrote emit conn: got %p want steady %p", gotConn, steadyClient) + } + if gotLineage != steadyLineage { + t.Fatalf("Ship during active session overwrote emit lineage: got %+v want %+v", gotLineage, steadyLineage) + } + if gotProfile != EmitProfileSteadyMsgShip { + t.Fatalf("Ship during active session changed emit profile: got %s want %s", gotProfile, EmitProfileSteadyMsgShip) + } + + cancel() + _ = sessionClient.Close() + _ = sessionServer.Close() + close(sink.release) +}