T4a-2: BlockExecutor.Ship — live per-write fan-out send

Adds the steady-state Ship method to BlockExecutor. Sends one WAL
entry to a named replica over the session's attached data conn.
Fire-and-forget: no per-entry ack at this layer; durability closure
is T4b concern.

Port discipline (see v3-phase-15-t4a-2-g1-v2-read.md for full G-1
V2 read; 98 LOC V2 → ~30 LOC V3, 31% ratio flag explicitly
justified by structural decomposition, not invariant loss).

Invariants preserved verbatim from V2 WALShipper.Ship:
  - L1 §2.1 invariant #2 (epoch-== silent drop, wal_shipper.go:217):
    stale-epoch entries return nil without touching the wire. Epoch
    source shifts from epochFn() callback to lineage.Epoch (frame-
    borne authority, H5-LOCK compliant); semantic identical.
  - 3s write deadline (wal_shipper.go:240): byte-identical bound on
    TCP write so a dead replica can't wedge callers on the ~120s
    TCP retransmission timeout.

Ownership shifts (per G-1 §6 QA-approved decisions):
  - §6.1 no lazy dial in Ship — sessions must be pre-registered
    via registerSession + attachConn (same lifecycle used by
    StartCatchUp/StartRebuild). Forward-carry conditions on T4a-3
    (ReplicaPeer.ShipEntry marks Degraded on err) and T4a-6 (L2
    mid-stream-kill recovery test) prove V3's "degrade+catch-up"
    is equivalent to V2's transparent-reconnect property.
  - §6.2 markDegraded moved from executor to caller — Ship returns
    error; ReplicaPeer.Invalidate (T4a-3) does the state mutation.
    BlockExecutor does not own ReplicaState in V3.

Tests (5):
  - TestExecutor_Ship_SingleEntry (happy)
  - TestExecutor_Ship_MultipleEntriesOrdered (LSN/LBA preservation)
  - TestExecutor_Ship_ConnFailure (error return on write fail)
  - TestExecutor_Ship_NoSession (error on unknown sessionID)
  - TestExecutor_Ship_StaleEpoch_SilentDrop (L1 §2.1 inv #2 regression:
    TCP-proxy-counted 0 bytes on wire with stale-epoch Ship, fresh-
    epoch Ship on same session still arrives)

G-2 three-line godoc contract (Called by / Owns / Borrows) inscribed
on Ship per §7.1 Gate G-2. Full core/transport + core/adapter suite
remains green. Gate G-1 approved by QA with forward-carry conditions
recorded on T4a-3 and T4a-6 task entries.
This commit is contained in:
wzcheng99 committed 2026-04-23 11:12:12 -07:00
1 parent 2b54fef3f7
commit 64758502b8
2 files changed
+355

No files matched your search

@@ -0,0 +1,98 @@
package transport
import (
"fmt"
"log"
"net"
"time"
)
// shipWriteDeadline bounds Ship's TCP write so a dead replica can't
// wedge the caller on the ~120s TCP retransmission timeout.
// Matches V2 WALShipper.Ship (wal_shipper.go:240) verbatim.
const shipWriteDeadline = 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.
//
// Called by: ReplicaPeer.ShipEntry (T4a-3) on behalf of
// ReplicationVolume.OnLocalWrite fan-out.
// Owns: per-write deadline on the session's conn; nothing persistent.
// 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:
// - 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.
// - 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 {
e.mu.Lock()
session, ok := e.sessions[lineage.SessionID]
if !ok || session == nil {
e.mu.Unlock()
return fmt.Errorf("transport: ship: no session for replica=%s sessionID=%d",
replicaID, lineage.SessionID)
}
// Epoch-== fence. V2 wal_shipper.go:217-221 silent drop.
// Source of epoch differs from V2 (V2: epochFn() callback; V3:
// session.lineage.Epoch from registered session), but semantic is
// identical — stale-epoch entries never reach the wire.
if lineage.Epoch != session.lineage.Epoch {
sessionEpoch := session.lineage.Epoch
e.mu.Unlock()
log.Printf("transport: ship: dropping LSN=%d replica=%s stale epoch %d (session epoch %d)",
lsn, replicaID, lineage.Epoch, sessionEpoch)
return nil
}
conn := session.conn
e.mu.Unlock()
if conn == nil {
return fmt.Errorf("transport: ship: session %d for replica=%s has no attached conn",
lineage.SessionID, replicaID)
}
payload := EncodeShipEntry(ShipEntry{
Lineage: lineage,
LBA: lba,
LSN: lsn,
Data: data,
})
_ = conn.SetWriteDeadline(time.Now().Add(shipWriteDeadline))
err := WriteMsg(conn, MsgShipEntry, payload)
_ = conn.SetWriteDeadline(time.Time{})
if err != nil {
return fmt.Errorf("transport: ship: write failed replica=%s lsn=%d: %w",
replicaID, lsn, err)
}
return nil
}
// 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).
func (e *BlockExecutor) attachShipSession(lineage RecoveryLineage, conn net.Conn) error {
sess, err := e.registerSession(lineage)
if err != nil {
return err
}
if err := e.attachConn(sess, conn); err != nil {
return err
}
return nil
}
@@ -0,0 +1,257 @@
package transport
import (
"bytes"
"net"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// shipTestLineage is the canonical lineage used by Ship tests.
func shipTestLineage() RecoveryLineage {
return RecoveryLineage{
SessionID: 42,
Epoch: 7,
EndpointVersion: 3,
TargetLSN: 1000,
}
}
// dialAttachedShipSession stands up a primary executor + replica listener,
// registers a session, dials the replica, and attaches the conn to the
// session. Returns the live (exec, replicaStore) ready for Ship calls.
func dialAttachedShipSession(t *testing.T, lineage RecoveryLineage) (*BlockExecutor, *storage.BlockStore) {
t.Helper()
_, replica, listener := setupPrimaryReplica(t)
primary := storage.NewBlockStore(64, 4096)
exec := NewBlockExecutor(primary, listener.Addr())
conn, err := net.Dial("tcp", listener.Addr())
if err != nil {
t.Fatalf("dial replica: %v", err)
}
t.Cleanup(func() { _ = conn.Close() })
if err := exec.attachShipSession(lineage, conn); err != nil {
t.Fatalf("attachShipSession: %v", err)
}
return exec, replica
}
// TestExecutor_Ship_SingleEntry — happy path: one entry, one replica,
// verify byte-exact arrival.
func TestExecutor_Ship_SingleEntry(t *testing.T) {
lineage := shipTestLineage()
exec, replica := dialAttachedShipSession(t, lineage)
data := make([]byte, 4096)
data[0], data[1] = 0xAB, 0xCD
lsn := uint64(1)
if err := exec.Ship("r1", lineage, 3, lsn, data); err != nil {
t.Fatalf("Ship: %v", err)
}
// Replica apply is async — wait for the LBA to land.
deadline := time.Now().Add(2 * time.Second)
var got []byte
for time.Now().Before(deadline) {
got, _ = replica.Read(3)
if got != nil && got[0] == 0xAB && got[1] == 0xCD {
break
}
time.Sleep(10 * time.Millisecond)
}
if !bytes.Equal(got, data) {
t.Fatalf("replica LBA 3 data mismatch: got [%02x %02x ...], want [ab cd ...]",
got[0], got[1])
}
}
// TestExecutor_Ship_MultipleEntriesOrdered — ship 10 entries sequentially;
// replica apply order must preserve LBA/LSN ordering byte-exact.
func TestExecutor_Ship_MultipleEntriesOrdered(t *testing.T) {
lineage := shipTestLineage()
exec, replica := dialAttachedShipSession(t, lineage)
const n = 10
for i := uint32(0); i < n; i++ {
data := make([]byte, 4096)
data[0] = byte(i + 1)
data[1] = byte(0xA0 + i)
if err := exec.Ship("r1", lineage, i, uint64(i+1), data); err != nil {
t.Fatalf("Ship %d: %v", i, err)
}
}
// Wait for all LBAs to land.
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
last, _ := replica.Read(n - 1)
if last != nil && last[0] == byte(n) {
break
}
time.Sleep(10 * time.Millisecond)
}
for i := uint32(0); i < n; i++ {
got, _ := replica.Read(i)
if got == nil || got[0] != byte(i+1) || got[1] != byte(0xA0+i) {
t.Fatalf("LBA %d mismatch: got [%02x %02x], want [%02x %02x]",
i, got[0], got[1], byte(i+1), byte(0xA0+i))
}
}
}
// TestExecutor_Ship_ConnFailure — kill conn before Ship; Ship returns
// error. This is the error-return behavior the forward-carry condition
// relies on (T4a-3 ReplicaPeer translates error → Invalidate).
func TestExecutor_Ship_ConnFailure(t *testing.T) {
lineage := shipTestLineage()
exec, _ := dialAttachedShipSession(t, lineage)
// Yank the conn out from under the session to force a write error.
exec.mu.Lock()
sess := exec.sessions[lineage.SessionID]
conn := sess.conn
exec.mu.Unlock()
_ = conn.Close()
data := make([]byte, 4096)
err := exec.Ship("r1", lineage, 0, 1, data)
if err == nil {
t.Fatal("expected Ship error after conn close, got nil")
}
if !strings.Contains(err.Error(), "write failed") {
t.Fatalf("expected 'write failed' error, got: %v", err)
}
}
// TestExecutor_Ship_NoSession — Ship against an unknown sessionID returns
// error without panicking. Exercises the pre-registration contract
// documented in ship_sender.go godoc.
func TestExecutor_Ship_NoSession(t *testing.T) {
primary := storage.NewBlockStore(64, 4096)
exec := NewBlockExecutor(primary, "127.0.0.1:0")
data := make([]byte, 4096)
err := exec.Ship("r1", shipTestLineage(), 0, 1, data)
if err == nil {
t.Fatal("expected error with no registered session, got nil")
}
if !strings.Contains(err.Error(), "no session") {
t.Fatalf("expected 'no session' error, got: %v", err)
}
}
// 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.
//
// Primary session is registered at epoch E. A Ship arrives with
// lineage.Epoch = E-1 (stale). Ship must:
// 1. Return nil (not error — caller keeps shipping subsequent entries)
// 2. Not write any bytes to the wire (nothing reaches replica)
func TestExecutor_Ship_StaleEpoch_SilentDrop(t *testing.T) {
lineage := shipTestLineage() // Epoch = 7
_, replica, listener := setupPrimaryReplica(t)
primary := storage.NewBlockStore(64, 4096)
exec := NewBlockExecutor(primary, listener.Addr())
// Intercept the replica side with a counting wrapper so we can assert
// "nothing crossed the wire." Use a TCP proxy that forwards bytes to
// the real replica listener and increments a counter on any byte seen.
proxyLn, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = proxyLn.Close() })
var bytesForwarded atomic.Int64
go func() {
for {
client, err := proxyLn.Accept()
if err != nil {
return
}
upstream, err := net.Dial("tcp", listener.Addr())
if err != nil {
_ = client.Close()
continue
}
go func(c, u net.Conn) {
defer c.Close()
defer u.Close()
buf := make([]byte, 4096)
for {
n, err := c.Read(buf)
if n > 0 {
bytesForwarded.Add(int64(n))
_, wErr := u.Write(buf[:n])
if wErr != nil {
return
}
}
if err != nil {
return
}
}
}(client, upstream)
}
}()
conn, err := net.Dial("tcp", proxyLn.Addr().String())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
if err := exec.attachShipSession(lineage, conn); err != nil {
t.Fatal(err)
}
// Ship with stale epoch (E-1).
stale := lineage
stale.Epoch = lineage.Epoch - 1
data := make([]byte, 4096)
data[0], data[1] = 0x11, 0x22
if err := exec.Ship("r1", stale, 5, 1, data); err != nil {
t.Fatalf("stale-epoch Ship should return nil, got: %v", err)
}
// Let any stray bytes settle.
time.Sleep(100 * time.Millisecond)
if got := bytesForwarded.Load(); got != 0 {
t.Fatalf("stale-epoch Ship must not cross the wire, %d bytes forwarded", got)
}
// Replica must not have applied LBA 5.
rd, _ := replica.Read(5)
if rd != nil && (rd[0] != 0 || rd[1] != 0) {
t.Fatalf("replica LBA 5 should be untouched by stale-epoch Ship, got [%02x %02x]",
rd[0], rd[1])
}
// Sanity: a matching-epoch Ship on the same session still works.
fresh := make([]byte, 4096)
fresh[0], fresh[1] = 0xAA, 0xBB
if err := exec.Ship("r1", lineage, 6, 2, fresh); err != nil {
t.Fatalf("fresh-epoch Ship: %v", err)
}
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
rd, _ = replica.Read(6)
if rd != nil && rd[0] == 0xAA {
break
}
time.Sleep(10 * time.Millisecond)
}
if rd == nil || rd[0] != 0xAA || rd[1] != 0xBB {
t.Fatalf("fresh-epoch Ship should arrive: got [%02x %02x]", rd[0], rd[1])
}
}