From a1618330cc496c8cd0c00ea80ffa086139c3b8ec Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 00:49:45 -0700 Subject: [PATCH] transport: route replica lane by connection context --- seaweed-block/core/replication/apply_gate.go | 13 ++- .../component/qa_g5_scenarios_test.go | 15 ++-- .../component/t4d3_scenarios_test.go | 62 ++++++++----- .../core/transport/catchup_sender.go | 3 + seaweed-block/core/transport/protocol.go | 4 + seaweed-block/core/transport/protocol_test.go | 3 + seaweed-block/core/transport/replica.go | 68 +++++++------- .../transport/replica_lane_context_test.go | 90 +++++++++++++++++++ 8 files changed, 186 insertions(+), 72 deletions(-) create mode 100644 seaweed-block/core/transport/replica_lane_context_test.go diff --git a/seaweed-block/core/replication/apply_gate.go b/seaweed-block/core/replication/apply_gate.go index 5cb106bd13..368df4e62c 100644 --- a/seaweed-block/core/replication/apply_gate.go +++ b/seaweed-block/core/replication/apply_gate.go @@ -43,14 +43,11 @@ import ( // lane signals were rejected as "changes recovery semantics to // protect an implementation shortcut." // -// Today's caller (transport replica.go MsgShipEntry handler) uses a -// transitional shim based on lineage.TargetLSN to choose which gate -// method to invoke — that shim lives at the CALLER, not in the gate. -// The architectural fence: gate is pure on lane; caller's signal -// source is replaceable. See CARRY-T4D-LANE-CONTEXT-001 (catalogue -// §3.3) for the named carry tracking the future replacement (true -// per-connection lane tag / separate handler routes / distinct -// listener ports). +// The transport caller now derives lane from handler context: legacy +// catch-up connections send MsgRecoveryLaneStart before WAL frames; +// unmarked legacy MsgShipEntry connections are live lane. The +// architectural fence remains: gate is pure on lane and TargetLSN is +// not a lane signal. // // Per-LBA applied LSN source (Option C hybrid, kickoff §2.5 #1): // at session init, query `store.AppliedLSNs()` for substrate- diff --git a/seaweed-block/core/replication/component/qa_g5_scenarios_test.go b/seaweed-block/core/replication/component/qa_g5_scenarios_test.go index 1521e5bc40..421bf2a2f6 100644 --- a/seaweed-block/core/replication/component/qa_g5_scenarios_test.go +++ b/seaweed-block/core/replication/component/qa_g5_scenarios_test.go @@ -29,9 +29,8 @@ package component_test // replicas catch up independently and converge. // // Known framework limitations worked around: -// - sessionID=1 collision under multi-catchup-per-replica (CARRY-T4D- -// LANE-CONTEXT-001 territory) → scenarios use single catch-up per -// replica per test +// - sessionID=1 collision under multi-catchup-per-replica → +// scenarios use single catch-up per replica per test // - Default block geometry 64 blocks → use WithBlockGeometry(256, 4096) // when scenarios touch LBAs > 64 // - AssertNoPerLBARegression / AssertLaneIntegrity / RestartReplica @@ -53,11 +52,10 @@ import ( // // SKIPPED — known framework gap. Both WithLiveShip() and // CatchUpReplica(idx) currently mint sessionID=1 by default; concurrent -// use of both paths (even across different replicas) causes the +// use of both paths (even across different replicas) can cause the // receiver-side replica handler to reject the second session as -// "stale ship session=1". This is the same cross-orchestration -// sessionID coordination gap already inscribed as a T4c §I forward- -// carry (related to CARRY-T4D-LANE-CONTEXT-001 territory). +// "stale ship session=1". This is a cross-orchestration sessionID +// coordination gap, not a TargetLSN lane-discrimination gap. // // When the framework gains per-call session minting (or mock-engine // drives the assignment + minted sessionIDs), this scenario unblocks. @@ -66,7 +64,7 @@ import ( // fence; the composition test waits for framework primitive. func TestG5_QA_LaneDiscipline_LiveAndRecoveryConcurrent_MultiReplica(t *testing.T) { t.Skip("known framework gap: live-ship + concurrent catch-up share sessionID=1; " + - "see T4c §I cross-orchestration carry + CARRY-T4D-LANE-CONTEXT-001 territory. " + + "see T4c §I cross-orchestration sessionID carry. " + "Gate API itself pinned by TestComponent_LanePurity_CallerControlsDispatch.") } @@ -181,4 +179,3 @@ func replicasFirstNLBAsEqual(t *testing.T, c *component.Cluster, replicaIdx int, } return mismatch == 0 } - diff --git a/seaweed-block/core/replication/component/t4d3_scenarios_test.go b/seaweed-block/core/replication/component/t4d3_scenarios_test.go index 25c8b3c93d..bc306baea2 100644 --- a/seaweed-block/core/replication/component/t4d3_scenarios_test.go +++ b/seaweed-block/core/replication/component/t4d3_scenarios_test.go @@ -15,8 +15,9 @@ import ( // - TestT4d3_CatchUp_NonEmptyReplica_ShortGap_BandwidthBounded_Smartwal // - TestT4d3_RetryAfterReplicaAdvanced_OverScansHandledByApplyGate // (round-46 ADDITION 1 — pins §6.2 Option A safety claim) -// - TestT4d3_RecoveryTargetLSN1_KnownGap (CARRY-T4D-LANE-CONTEXT-001 -// close, Option B — documents the H=1 known gap) +// - TestT4d3_RecoveryTargetLSN1_RoutesByConnectionContext +// (CARRY-T4D-LANE-CONTEXT-001 close — recovery TargetLSN=1 no +// longer misroutes as live) // observingScanWrap counts ScanLBAs emissions for bandwidth tests. type observingScanWrap struct { @@ -191,24 +192,41 @@ func TestT4d3_RetryAfterReplicaAdvanced_OverScansHandledByApplyGate(t *testing.T }) } -// TestT4d3_RecoveryTargetLSN1_KnownGap pins -// CARRY-T4D-LANE-CONTEXT-001 known gap (round-46 architect close -// condition Option B). Today the transport replica handler's -// caller-side lane shim uses TargetLSN==1 as the live-lane sentinel. -// A recovery session with TargetLSN=1 (legitimate when H=1; happens -// during initial bootstrap or empty-volume recovery) MISCLASSIFIES -// at the transport handler level — the gate would receive -// ApplyLive instead of ApplyRecovery for this session's frames. -// -// This is the documented gap Option B references. The test SKIPS -// today and stays as a forward-binding marker for the future fix -// (true per-connection lane tag / separate handler routes). -// -// Pre-fix: skipped with TODO. Post-fix (T4e or beyond): un-skip -// when true handler-context lane signaling lands. The gate API -// itself is already lane-pure (ApplyRecovery vs ApplyLive); only -// the caller's signal source needs upgrading per -// CARRY-T4D-LANE-CONTEXT-001. -func TestT4d3_RecoveryTargetLSN1_KnownGap(t *testing.T) { - t.Skip("CARRY-T4D-LANE-CONTEXT-001 known gap (round-46 close condition Option B). Recovery session with TargetLSN=1 misclassifies at transport caller-side lane shim. Gate API is already lane-pure; the gap is in the CALLER's signal source. Un-skip when true handler-context lane signaling lands (T4e or beyond).") +// TestT4d3_RecoveryTargetLSN1_RoutesByConnectionContext pins the +// closure of CARRY-T4D-LANE-CONTEXT-001. Legacy SWRP catch-up now +// sends MsgRecoveryLaneStart before WAL frames, so the replica +// handler routes by connection context instead of sniffing +// lineage.TargetLSN. A recovery session with TargetLSN=1 is valid +// and must still use ApplyRecovery semantics. +func TestT4d3_RecoveryTargetLSN1_RoutesByConnectionContext(t *testing.T) { + component.RunSubstrate(t, "walstore", component.Walstore, func(t *testing.T, c *component.Cluster) { + c.WithReplicas(1).WithApplyGate().Start() + + primaryData := make([]byte, component.DefaultBlockSize) + primaryData[0] = 0x11 + lsn := c.PrimaryWrite(0, primaryData) + if lsn != 1 { + t.Fatalf("test expects first primary LSN=1, got %d", lsn) + } + + // Seed the replica ahead on this LBA. Catch-up will ship the + // primary's LSN=1 entry. If the handler incorrectly routes + // TargetLSN=1 as live, the apply gate returns live-stale and + // the catch-up session fails. Recovery lane must stale-skip. + replicaData := make([]byte, component.DefaultBlockSize) + replicaData[0] = 0x22 + c.ReplicaApply(0, 0, replicaData, 2) + + result := c.CatchUpReplica(0) + if !result.Success { + t.Fatalf("TargetLSN=1 recovery session failed; lane context likely misrouted as live: %+v", result) + } + if !c.ApplyGate(0).SessionRecoveryCoverage(1, 0) { + t.Fatal("recovery TargetLSN=1 did not advance recovery coverage") + } + got, _ := c.Replica(0).Store.Read(0) + if got[0] != 0x22 { + t.Fatalf("stale recovery entry regressed data: got %02x want 22", got[0]) + } + }) } diff --git a/seaweed-block/core/transport/catchup_sender.go b/seaweed-block/core/transport/catchup_sender.go index e5f759a984..02db31bf73 100644 --- a/seaweed-block/core/transport/catchup_sender.go +++ b/seaweed-block/core/transport/catchup_sender.go @@ -105,6 +105,9 @@ func (e *BlockExecutor) doCatchUp(replicaID string, session *activeSession, from if err := conn.SetDeadline(time.Now().Add(recoveryConnTimeout)); err != nil { return 0, fmt.Errorf("catch-up set deadline: %w", err) } + if err := WriteMsg(conn, MsgRecoveryLaneStart, EncodeLineage(session.lineage)); err != nil { + return 0, fmt.Errorf("catch-up recovery lane start: %w", err) + } // Replica's flushed LSN is what catch-up streams from. The // scan starts at fromLSN+1 (entries STRICTLY AFTER the replica's diff --git a/seaweed-block/core/transport/protocol.go b/seaweed-block/core/transport/protocol.go index 277cb1ca85..3292700180 100644 --- a/seaweed-block/core/transport/protocol.go +++ b/seaweed-block/core/transport/protocol.go @@ -42,6 +42,10 @@ const ( MsgRebuildDone byte = 0x05 // primary → replica: rebuild complete MsgBarrierReq byte = 0x06 // primary → replica: sync request MsgBarrierResp byte = 0x07 // replica → primary: sync response + // MsgRecoveryLaneStart marks the current legacy SWRP connection as + // recovery-lane before any MsgShipEntry frames arrive. It replaces + // payload-derived lane guessing from RecoveryLineage.TargetLSN. + MsgRecoveryLaneStart byte = 0x08 ) // RecoveryLineage binds a mutating recovery stream to one accepted recovery diff --git a/seaweed-block/core/transport/protocol_test.go b/seaweed-block/core/transport/protocol_test.go index c628b3f500..1f6823066b 100644 --- a/seaweed-block/core/transport/protocol_test.go +++ b/seaweed-block/core/transport/protocol_test.go @@ -74,6 +74,9 @@ func TestProtocol_EnvelopeRoundTrip(t *testing.T) { {"MsgRebuildDone", MsgRebuildDone, nil}, {"MsgBarrierReq", MsgBarrierReq, nil}, {"MsgBarrierResp", MsgBarrierResp, make([]byte, 8)}, + {"MsgRecoveryLaneStart", MsgRecoveryLaneStart, EncodeLineage( + RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 1}, + )}, } for _, tc := range cases { diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 41b421f496..8a4805c51b 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -8,15 +8,19 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) -// liveShipTargetLSNSentinel is the steady-state live-ship sentinel -// value (== `replication.liveShipTargetLSN`). The replica handler's -// transitional caller-side lane shim consults this sentinel; the -// real fix (true handler-context lane signal) is post-T4d-2. Keeping -// the sentinel here (transport package) avoids a transport→ -// replication import; the value is the same wire-stable constant -// already in production. +// liveShipTargetLSNSentinel is the historical steady-state live-ship +// lineage placeholder (== `replication.liveShipTargetLSN`). It is kept +// for tests and wire compatibility only; replica lane discrimination is +// connection-context based, not TargetLSN based. const liveShipTargetLSNSentinel uint64 = 1 +type mutationLane int + +const ( + mutationLaneLive mutationLane = iota + mutationLaneRecovery +) + // ApplyHook is the T4d-2 plug-in seam for the replica recovery // apply gate. The hook is LANE-EXPLICIT per round-46 architect // ruling: caller (MsgShipEntry handler) decides lane from @@ -72,13 +76,13 @@ func NewReplicaListener(addr string, store storage.LogicalStorage) (*ReplicaList // hook itself is LANE-PURE per round-46 architect ruling — it does // not inspect payload bytes to decide lane. // -// Today the handler's lane decision is a transitional shim based on -// `lineage.TargetLSN == liveShipTargetLSNSentinel` (live) vs -// otherwise (recovery). The shim lives at the CALLER (this handler), -// not in the gate. See `CARRY-T4D-LANE-CONTEXT-001` (catalogue §3.3) -// for the named carry tracking the future replacement (true -// per-connection lane tag / separate handler routes / distinct -// listener ports). +// Lane decision comes from handler context: +// - default legacy SWRP MsgShipEntry connections are live lane +// - StartCatchUp sends MsgRecoveryLaneStart on its connection before +// WAL frames; that marker flips this handler to recovery lane +// +// The hook remains lane-pure: it never inspects TargetLSN to decide +// ApplyRecovery vs ApplyLive. // // Pass nil hook to get the no-gate behavior (== NewReplicaListener). func NewReplicaListenerWithApplyHook(addr string, store storage.LogicalStorage, hook ApplyHook) (*ReplicaListener, error) { @@ -196,6 +200,7 @@ func (r *ReplicaListener) acceptLoop() { func (r *ReplicaListener) handleConn(conn net.Conn) { defer conn.Close() + lane := mutationLaneLive for { msgType, payload, err := ReadMsg(conn) @@ -204,6 +209,19 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { } switch msgType { + case MsgRecoveryLaneStart: + lineage, err := DecodeLineage(payload) + if err != nil { + log.Printf("replica: decode recovery lane start: %v", err) + return + } + if !r.acceptMutationLineage(lineage) { + log.Printf("replica: reject stale recovery lane start session=%d epoch=%d endpointVersion=%d", + lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) + return + } + lane = mutationLaneRecovery + case MsgShipEntry: entry, err := DecodeShipEntry(payload) if err != nil { @@ -220,28 +238,12 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { // gate is lane-pure. Live-lane stale entries return error // here → log + close conn (round-44 // INV-REPL-LIVE-LANE-STALE-FAILS-LOUD). - // - // LANE DISCRIMINATION (transitional shim): - // Today the replica handler has only one signal — the - // payload's TargetLSN. We use the steady-state live-ship - // sentinel (TargetLSN=1) as a transitional caller-side - // rule: TargetLSN=1 → live; otherwise → recovery. This - // shim is CALLER-side; the gate itself never inspects - // TargetLSN. - // - // TODO (T4e or post-G5 refactor): replace this shim with - // true handler-context lane discrimination — e.g., a - // per-connection lane tag set at accept-time via - // session-registration handshake, separate live vs - // recovery handler routes, or distinct listener ports. - // The architectural fence (gate is lane-pure) is in - // place; only the caller's signal source needs upgrading. if r.applyHook != nil { var err error - if entry.Lineage.TargetLSN == liveShipTargetLSNSentinel { - err = r.applyHook.ApplyLive(entry.Lineage, entry.LBA, entry.Data, entry.LSN) - } else { + if lane == mutationLaneRecovery { err = r.applyHook.ApplyRecovery(entry.Lineage, entry.LBA, entry.Data, entry.LSN) + } else { + err = r.applyHook.ApplyLive(entry.Lineage, entry.LBA, entry.Data, entry.LSN) } if err != nil { log.Printf("replica: apply gate: %v", err) diff --git a/seaweed-block/core/transport/replica_lane_context_test.go b/seaweed-block/core/transport/replica_lane_context_test.go new file mode 100644 index 0000000000..4db9e47dda --- /dev/null +++ b/seaweed-block/core/transport/replica_lane_context_test.go @@ -0,0 +1,90 @@ +package transport + +import ( + "net" + "testing" + "time" +) + +type recordingApplyHook struct { + calls chan string +} + +func newRecordingApplyHook() *recordingApplyHook { + return &recordingApplyHook{calls: make(chan string, 8)} +} + +func (h *recordingApplyHook) ApplyRecovery(lineage RecoveryLineage, lba uint32, data []byte, lsn uint64) error { + h.calls <- "recovery" + return nil +} + +func (h *recordingApplyHook) ApplyLive(lineage RecoveryLineage, lba uint32, data []byte, lsn uint64) error { + h.calls <- "live" + return nil +} + +func (h *recordingApplyHook) expect(t *testing.T, want string) { + t.Helper() + select { + case got := <-h.calls: + if got != want { + t.Fatalf("apply lane = %s, want %s", got, want) + } + case <-time.After(2 * time.Second): + t.Fatalf("timed out waiting for %s apply", want) + } +} + +func runReplicaHandlerPipe(t *testing.T, hook ApplyHook) net.Conn { + t.Helper() + client, server := net.Pipe() + r := &ReplicaListener{applyHook: hook} + done := make(chan struct{}) + go func() { + defer close(done) + r.handleConn(server) + }() + t.Cleanup(func() { + _ = client.Close() + <-done + }) + return client +} + +func TestReplicaListener_RecoveryLaneStart_TargetLSN1_RoutesRecovery(t *testing.T) { + hook := newRecordingApplyHook() + conn := runReplicaHandlerPipe(t, hook) + lineage := RecoveryLineage{SessionID: 7, Epoch: 1, EndpointVersion: 1, TargetLSN: 1} + + if err := WriteMsg(conn, MsgRecoveryLaneStart, EncodeLineage(lineage)); err != nil { + t.Fatalf("write recovery lane start: %v", err) + } + if err := WriteMsg(conn, MsgShipEntry, EncodeShipEntry(ShipEntry{ + Lineage: lineage, + LBA: 5, + LSN: 30, + Data: []byte{0xAA}, + })); err != nil { + t.Fatalf("write recovery ship entry: %v", err) + } + + hook.expect(t, "recovery") +} + +func TestReplicaListener_DefaultMsgShipEntry_TargetLSNHigh_RoutesLive(t *testing.T) { + hook := newRecordingApplyHook() + conn := runReplicaHandlerPipe(t, hook) + lineage := RecoveryLineage{SessionID: 9, Epoch: 1, EndpointVersion: 1, TargetLSN: 100} + + if err := WriteMsg(conn, MsgShipEntry, EncodeShipEntry(ShipEntry{ + Lineage: lineage, + LBA: 5, + LSN: 50, + Data: []byte{0xBB}, + })); err != nil { + t.Fatalf("write live ship entry: %v", err) + } + + hook.expect(t, "live") +}