From f1fb148989f368b3e46b1df4050b8060f7f8a7ed Mon Sep 17 00:00:00 2001 From: wzcheng99 Date: Thu, 23 Apr 2026 11:39:54 -0700 Subject: [PATCH] T4a-2 fix: restore lazy dial in Ship (architect-revised Option B) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to 6475850. Architect review of the initial T4a-2 commit surfaced that sw had (a) described V2 semantics incorrectly as "transparent single-call retry" — V2 does lazy-dial → single write → degrade-on-fail-return-nil, no retry loop — and (b) proposed lifting ensureDataConn into ReplicaPeer.ShipEntry, which would have smeared transport-conn-lifecycle across core/transport + core/replication in violation of the "core/transport = sole net.Dial + frame-I/O owner" principle. Architect-revised decision (v3-phase-15-t4a-2-g1-v2-read.md §6-REV): Change 1 — Do not auto-register sessions inside Ship. Ship's epoch fence depends on accepted-lineage. If Ship invented sessions from incoming lineage the fence would collapse into self-validation. Session registration stays bound to explicit lifecycle entry points; Ship only lazy-dials when session.conn == nil on an already- registered session. Change 2 — Return error on dial/write failure. V2 return nil worked because WALShipper owned markDegraded. V3 BlockExecutor does not own peer state. Literal return nil would silently swallow a real fault. Ship returns error; ReplicaPeer.ShipEntry (T4a-3) translates error → peer-state Degraded + Invalidate. Ship now: - looks up session by lineage.SessionID (no auto-register) - epoch-== silent drop preserved - if session.conn == nil → net.DialTimeout(replicaAddr, 3s) + attach-under-mu with race handling: * session invalidated during dial → close + error * concurrent dial raced ahead → use theirs, close ours * we win → install our conn - 3s write deadline preserved - dial/write error → return error (peer layer degrades) Tests (7, all green): - TestExecutor_Ship_SingleEntry (happy) - TestExecutor_Ship_MultipleEntriesOrdered (order preserved) - TestExecutor_Ship_ConnFailure (write error after attached conn) - TestExecutor_Ship_NoSession (no auto-register — Ship errors on unknown sessionID; preserves accepted-lineage model) - TestExecutor_Ship_LazyDial_OnRegisteredSessionWithoutConn (NEW: registered session no conn → lazy-dial + attach + send; second Ship reuses attached conn) - TestExecutor_Ship_LazyDial_DialFailure_ReturnsError (NEW: unreachable replicaAddr → error; session stays registered) - TestExecutor_Ship_StaleEpoch_SilentDrop (L1 §2.1 inv #2 regression; TCP-proxy-counted 0 bytes on wire) §8C.3 trigger #1 logged in mini-plan change-log (already at line 389-390): preserve-baseline read too narrowly at method level, missed V2 lazy-dial stability seam. §0-B Stability-Locality rule adopted as default G-1 heuristic for future non-literal ports (see memory/feedback_g1_pre_code_review.md). Full core/transport + core/adapter suite remains green. --- seaweed-block/core/transport/ship_sender.go | 84 +++++++++--- .../core/transport/ship_sender_test.go | 127 +++++++++++++++++- 2 files changed, 193 insertions(+), 18 deletions(-) diff --git a/seaweed-block/core/transport/ship_sender.go b/seaweed-block/core/transport/ship_sender.go index cbe94ccb4c..d0668c2743 100644 --- a/seaweed-block/core/transport/ship_sender.go +++ b/seaweed-block/core/transport/ship_sender.go @@ -12,24 +12,45 @@ import ( // Matches V2 WALShipper.Ship (wal_shipper.go:240) verbatim. const shipWriteDeadline = 3 * time.Second +// shipDialTimeout bounds the lazy-dial window inside Ship when an +// already-registered session has no attached conn yet. Matches V2 +// WALShipper.ensureDataConn (wal_shipper.go:636) verbatim. +const shipDialTimeout = 3 * time.Second + // Ship sends one WAL entry live to the named replica over the session's // attached data connection. Fire-and-forget: no per-entry ack at this // layer — durability closure is T4b concern (Barrier / sync_all). // -// The session for lineage.SessionID must already be registered and have -// an attached conn (via StartCatchUp / StartRebuild / future steady-state -// attach). Ship does NOT lazy-dial — by design, per v3-phase-15-t4a-2- -// g1-v2-read.md §6.1: V3 lifts dial responsibility to the peer layer -// (ReplicaPeer.ShipEntry), preserving V2's transparent-reconnect property -// via "degrade + catch-up" at the caller, not inside Ship. +// Session contract: the session for lineage.SessionID MUST already be +// registered (e.g., from a prior Probe / StartCatchUp / StartRebuild / +// future steady-state attach). Ship does NOT auto-register from the +// incoming lineage — doing so would weaken the accepted-lineage model +// that the epoch fence depends on. If the session exists but has no +// attached conn yet, Ship lazy-dials e.replicaAddr and attaches. This +// preserves the V2 transport-muscle lazy-dial seam (wal_shipper.go:632 +// ensureDataConn) at the V3 V2-faithful location (§0-B Stability- +// Locality rule). +// +// On dial or write failure, Ship returns error. The peer layer +// (ReplicaPeer.ShipEntry, T4a-3) translates the error to peer-state +// Degraded + Invalidate(reason). This is the architect-revised seam: +// V3 BlockExecutor does not own ReplicaState, so V2's silent +// return-nil-after-markDegraded cannot be literal-ported without a +// concrete executor→peer failure callback — error return is the +// correct V3-layering substitute (see v3-phase-15-t4a-2-g1-v2-read.md +// §6 architect review). // // Called by: ReplicaPeer.ShipEntry (T4a-3) on behalf of // ReplicationVolume.OnLocalWrite fan-out. -// Owns: per-write deadline on the session's conn; nothing persistent. +// Owns: per-write deadline on the session's conn; lazy dial + attach +// of the session's data conn when missing. // Borrows: session (by SessionID lookup); data slice — caller retains, // Ship does not mutate and does not retain past return. // // Invariants preserved from V2 WALShipper.Ship: +// - Lazy dial on missing conn (wal_shipper.go:632-643): same trigger, +// same 3s DialTimeout; attach-under-mu races resolved by "first +// winner keeps" semantics. // - Epoch-== silent drop (L1 §2.1 invariant #2, wal_shipper.go:217-221): // entries whose lineage.Epoch does not match the session's accepted // epoch return nil without writing anything to the wire. @@ -56,9 +77,35 @@ func (e *BlockExecutor) Ship(replicaID string, lineage RecoveryLineage, lba uint conn := session.conn e.mu.Unlock() + // Lazy dial if the registered session has no conn attached yet. + // Done outside e.mu so a slow dial doesn't wedge other sessions. if conn == nil { - return fmt.Errorf("transport: ship: session %d for replica=%s has no attached conn", - lineage.SessionID, replicaID) + dialed, err := net.DialTimeout("tcp", e.replicaAddr, shipDialTimeout) + if err != nil { + return fmt.Errorf("transport: ship: dial replica=%s sessionID=%d: %w", + replicaID, lineage.SessionID, err) + } + // Re-acquire lock to attach. Handle three races: + // 1. Session invalidated between release+reacquire → drop our conn. + // 2. Another Ship already dialed and attached → use theirs, drop ours. + // 3. We win → install our conn. + e.mu.Lock() + current, stillActive := e.sessions[lineage.SessionID] + switch { + case !stillActive || current != session: + e.mu.Unlock() + _ = dialed.Close() + return fmt.Errorf("transport: ship: session %d invalidated during dial", + lineage.SessionID) + case session.conn != nil: + conn = session.conn + e.mu.Unlock() + _ = dialed.Close() + default: + session.conn = dialed + conn = dialed + e.mu.Unlock() + } } payload := EncodeShipEntry(ShipEntry{ @@ -79,13 +126,10 @@ func (e *BlockExecutor) Ship(replicaID string, lineage RecoveryLineage, lba uint } // attachShipSession registers a session + attaches the given conn for -// Ship dispatch. Exposed only to tests and to ReplicaPeer (T4a-3) via -// the executor's session lifecycle. Kept unexported; higher layers call -// StartCatchUp/StartRebuild or (future) a dedicated steady-state attach -// method to establish sessions. -// -// This helper lets tests drive Ship without going through StartCatchUp -// (which runs a streaming catch-up that's not what we want to test). +// Ship dispatch. Test-only helper — production code registers sessions +// via the normal lifecycle (StartCatchUp / StartRebuild / future +// steady-state attach) and relies on Ship's lazy dial for the +// conn-attach step. func (e *BlockExecutor) attachShipSession(lineage RecoveryLineage, conn net.Conn) error { sess, err := e.registerSession(lineage) if err != nil { @@ -96,3 +140,11 @@ func (e *BlockExecutor) attachShipSession(lineage RecoveryLineage, conn net.Conn } return nil } + +// registerShipSessionForTest is a test-only helper that registers a +// session WITHOUT attaching any conn. Lets tests exercise Ship's +// lazy-dial path against a registered session whose conn is nil. +func (e *BlockExecutor) registerShipSessionForTest(lineage RecoveryLineage) error { + _, err := e.registerSession(lineage) + return err +} diff --git a/seaweed-block/core/transport/ship_sender_test.go b/seaweed-block/core/transport/ship_sender_test.go index 4e34eb3cb5..48ece9300e 100644 --- a/seaweed-block/core/transport/ship_sender_test.go +++ b/seaweed-block/core/transport/ship_sender_test.go @@ -132,8 +132,10 @@ func TestExecutor_Ship_ConnFailure(t *testing.T) { } // TestExecutor_Ship_NoSession — Ship against an unknown sessionID returns -// error without panicking. Exercises the pre-registration contract -// documented in ship_sender.go godoc. +// error without panicking. Exercises the pre-registration contract: +// Ship does NOT auto-register from incoming lineage (architect-revised +// G-1, Change 1) because the accepted-lineage model is what grounds +// the epoch fence. func TestExecutor_Ship_NoSession(t *testing.T) { primary := storage.NewBlockStore(64, 4096) exec := NewBlockExecutor(primary, "127.0.0.1:0") @@ -148,6 +150,127 @@ func TestExecutor_Ship_NoSession(t *testing.T) { } } +// TestExecutor_Ship_LazyDial_OnRegisteredSessionWithoutConn — architect- +// revised Option B regression: when the session is registered but has +// no attached conn, Ship lazy-dials replicaAddr, attaches, and sends. +// Preserves V2 ensureDataConn semantic (wal_shipper.go:632) at the +// V2-faithful V3 location. +func TestExecutor_Ship_LazyDial_OnRegisteredSessionWithoutConn(t *testing.T) { + _, replica, listener := setupPrimaryReplica(t) + primary := storage.NewBlockStore(64, 4096) + exec := NewBlockExecutor(primary, listener.Addr()) + + lineage := shipTestLineage() + if err := exec.registerShipSessionForTest(lineage); err != nil { + t.Fatalf("registerShipSessionForTest: %v", err) + } + // Close whatever conn Ship lazy-dials so the replica listener's + // handleConn goroutine can exit — listener.Stop() waits on it. + t.Cleanup(func() { + exec.mu.Lock() + if s := exec.sessions[lineage.SessionID]; s != nil && s.conn != nil { + _ = s.conn.Close() + } + exec.mu.Unlock() + }) + + // Verify no conn attached before first Ship. + exec.mu.Lock() + if exec.sessions[lineage.SessionID].conn != nil { + exec.mu.Unlock() + t.Fatal("precondition violated: conn already attached") + } + exec.mu.Unlock() + + data := make([]byte, 4096) + data[0], data[1] = 0xBA, 0xBE + if err := exec.Ship("r1", lineage, 2, 1, data); err != nil { + t.Fatalf("Ship lazy-dial: %v", err) + } + + // Post-Ship: conn must be attached to the session. + exec.mu.Lock() + attached := exec.sessions[lineage.SessionID].conn != nil + exec.mu.Unlock() + if !attached { + t.Fatal("lazy-dial did not attach conn to session") + } + + // Data must arrive on replica. + deadline := time.Now().Add(2 * time.Second) + var got []byte + for time.Now().Before(deadline) { + got, _ = replica.Read(2) + if got != nil && got[0] == 0xBA { + break + } + time.Sleep(10 * time.Millisecond) + } + if got == nil || got[0] != 0xBA || got[1] != 0xBE { + t.Fatalf("replica LBA 2 did not receive lazy-dialed ship: got [%02x %02x]", + got[0], got[1]) + } + + // Second Ship must reuse the already-attached conn (no re-dial). + exec.mu.Lock() + connAfterFirst := exec.sessions[lineage.SessionID].conn + exec.mu.Unlock() + + data2 := make([]byte, 4096) + data2[0] = 0xEF + if err := exec.Ship("r1", lineage, 3, 2, data2); err != nil { + t.Fatalf("Ship 2: %v", err) + } + exec.mu.Lock() + connAfterSecond := exec.sessions[lineage.SessionID].conn + exec.mu.Unlock() + if connAfterFirst != connAfterSecond { + t.Fatal("second Ship re-dialed instead of reusing attached conn") + } +} + +// TestExecutor_Ship_LazyDial_DialFailure_ReturnsError — architect-revised +// Change 2: dial failure returns error (not V2's silent return-nil), +// because V3 BlockExecutor does not own peer state. Peer layer +// (ReplicaPeer.ShipEntry, T4a-3) will translate the error to Degraded +// + Invalidate. +func TestExecutor_Ship_LazyDial_DialFailure_ReturnsError(t *testing.T) { + // Reserve a port then release it → guaranteed unreachable. + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + deadAddr := ln.Addr().String() + _ = ln.Close() + + primary := storage.NewBlockStore(64, 4096) + exec := NewBlockExecutor(primary, deadAddr) + + lineage := shipTestLineage() + if err := exec.registerShipSessionForTest(lineage); err != nil { + t.Fatal(err) + } + + data := make([]byte, 4096) + err = exec.Ship("r1", lineage, 0, 1, data) + if err == nil { + t.Fatal("expected dial-failure error, got nil") + } + if !strings.Contains(err.Error(), "dial") { + t.Fatalf("expected 'dial' error, got: %v", err) + } + + // Session must remain registered but without a conn so a future + // dial can succeed once replicaAddr becomes reachable again. + exec.mu.Lock() + sess, ok := exec.sessions[lineage.SessionID] + stillNoConn := ok && sess != nil && sess.conn == nil + exec.mu.Unlock() + if !stillNoConn { + t.Fatal("dial failure should leave session registered with no conn") + } +} + // TestExecutor_Ship_StaleEpoch_SilentDrop is the explicit regression test // for L1 §2.1 invariant #2 (epoch-== silent drop). QA added this as a // Gate G-1 closing condition.