T4a-3: ReplicaPeer (leaf) — per-replica runtime handle

Introduces core/replication/ package and ReplicaPeer — the per-remote-
replica runtime handle that bridges ReplicationVolume fan-out (T4a-4)
to the transport layer (T4a-2). T4a-3 is the Opt-4 leaf: ships first,
then ReplicationVolume consumes it.

Surface (~220 LOC production + 230 LOC tests):
  - ReplicaTarget: authoritative addressing + lineage from master
    assignment (Epoch, EndpointVersion, DataAddr, ControlAddr).
  - ReplicaState: Unknown / Healthy / Degraded. T4a scope only;
    CatchingUp / Rebuilding / NeedsRebuild arrive at T4c with the
    recovery pipeline.
  - NewReplicaPeer: registers a live-ship session in the executor
    using a fresh peer-local SessionID + target.{Epoch,
    EndpointVersion} + constant liveShipTargetLSN = 1. Steady-state
    live-ship session; recovery-bound sessions (with engine-frozen
    TargetLSNs) arrive at T4c.
  - ShipEntry: state-gated fan-out leaf. Healthy → executor.Ship;
    Degraded / closed → reject at peer without dialing. On Ship
    error: mark Degraded + log reason (forward-carry CARRY-1 from
    T4a-2). Caller-supplied lineage is informational for T4a (peer
    owns its session); T4b/T4c may tighten when recovery sessions
    thread through.
  - Invalidate: explicit Healthy → Degraded mutation for authority-
    driven peer-down (no-op on closed peer).
  - Close: idempotent; invalidates the peer's executor session via
    InvalidateSession. Does NOT close the executor — caller owns
    executor lifecycle (BUG-005 discipline).

BlockExecutor gets one new public method:
  - RegisterLiveShipSession(lineage): thin wrapper around internal
    registerSession, needed because ReplicaPeer in core/replication
    needs to register its live-ship session from outside
    core/transport. Tri-line godoc contract attached.

Gate G-2: every public symbol in both files carries a Called by /
Owns / Borrows tri-line contract. PR-rejectable if any symbol lacks
the three-line contract.

Forward-carry CARRY-1 closed: ShipEntry → Invalidate + Degraded on
transport error. Pin test TestReplicaPeer_ShipEntry_ConnFailure_
MarksDegraded asserts (a) first Ship returns dial/write error, (b)
state transitions Healthy → Degraded, (c) subsequent ShipEntry is
rejected at peer without touching the wire. This closes catalogue
§3.2.1 C4 from PARTIAL to DONE.

Tests (6, all green):
  - TestReplicaPeer_ShipEntry_Happy — byte-exact arrival, state
    stays Healthy.
  - TestReplicaPeer_ShipEntry_ConnFailure_MarksDegraded — CARRY-1
    pin.
  - TestReplicaPeer_Invalidate_MovesToDegraded — authority-driven
    path.
  - TestReplicaPeer_Close_Idempotent — double-Close is safe;
    post-Close ShipEntry errors with "closed".
  - TestReplicaPeer_NewReplicaPeer_RejectsNilExecutor.
  - TestReplicaPeer_NewReplicaPeer_RejectsZeroAuthority — fails fast
    at construction rather than at first ship when lineage would be
    rejected by replica's acceptMutationLineage.

Per T4a-3 context note: tests drive against a real
*transport.BlockExecutor + real *transport.ReplicaListener, not
against a ReplicationVolume caller stub (Opt-4 leaf ordering).

Full core/transport + core/replication + core/adapter suites green.
G-3 preserved.
This commit is contained in:
wzcheng99 committed 2026-04-23 14:44:35 -07:00
1 parent dbe0f57b9c
commit debeb55f28
3 files changed
+474 -3

No files matched your search

+224
View File
@@ -0,0 +1,224 @@
// Package replication implements per-volume replication coordination:
// fan-out of live writes from primary to replicas (ReplicationVolume),
// per-replica runtime state (ReplicaPeer), and the seam to the master
// authority callback (wired at T4a-5).
//
// T4a scope: best_effort single-replica live ship. Durability closure
// (sync_all, sync_quorum, barriers) lands at T4b. Recovery pipeline
// (probe, catch-up, rebuild, promotion) lands at T4c.
package replication
import (
"context"
"fmt"
"log"
"sync"
"sync/atomic"
"github.com/seaweedfs/seaweed-block/core/transport"
)
// ReplicaTarget carries the authoritative per-replica addressing and
// lineage information from a master assignment event. Produced by the
// Host authority-callback wire (T4a-5) and consumed by
// ReplicationVolume.UpdateReplicaSet (T4a-4).
type ReplicaTarget struct {
ReplicaID string
DataAddr string
ControlAddr string
Epoch uint64
EndpointVersion uint64
}
// ReplicaState is the coarse peer health state. T4a scope supports
// only Healthy ↔ Degraded. Richer states (CatchingUp, Rebuilding,
// NeedsRebuild) arrive at T4c when the recovery pipeline lands.
type ReplicaState int
const (
ReplicaUnknown ReplicaState = iota
ReplicaHealthy
ReplicaDegraded
)
func (s ReplicaState) String() string {
switch s {
case ReplicaHealthy:
return "healthy"
case ReplicaDegraded:
return "degraded"
default:
return "unknown"
}
}
// liveShipTargetLSN is the placeholder TargetLSN stamped into every
// live steady-state lineage. It is > 0 (required by the replica's
// acceptMutationLineage gate) and stable across all ShipEntry calls
// within a peer's lifetime so the replica's "same-authority ⇒ same
// TargetLSN" fence holds. Distinct from recovery TargetLSNs, which
// come from engine-frozen recovery contracts at T4c.
const liveShipTargetLSN uint64 = 1
// peerSessionIDCounter mints unique SessionIDs for live steady-state
// sessions. Recovery-bound sessions carry engine-minted SessionIDs;
// those arrive with the T4c recovery command chain.
var peerSessionIDCounter atomic.Uint64
// ReplicaPeer is the per-remote-replica runtime handle. Owns its
// coarse health state, the peer-scoped live-ship RecoveryLineage, and
// the lifecycle of its registered session in the executor. Bridges
// ReplicationVolume fan-out (T4a-4) to the transport layer (T4a-2).
type ReplicaPeer struct {
target ReplicaTarget
executor *transport.BlockExecutor
sessionID uint64
lineage transport.RecoveryLineage
mu sync.Mutex
state ReplicaState
closed bool
}
// NewReplicaPeer constructs a per-replica runtime handle and registers
// a live-ship session against the given executor. The session's
// lineage is derived from target.{Epoch, EndpointVersion}, a freshly
// minted peer-local SessionID, and a constant liveShipTargetLSN.
// Recovery-minted sessions (with engine-frozen TargetLSNs) arrive at
// T4c when the recovery command chain ports over.
//
// Called by: ReplicationVolume.UpdateReplicaSet (T4a-4) when adding
// a new peer to the authoritative replica set.
// Owns: ReplicaState; the peer's registered session in the executor
// (released by Close via InvalidateSession); the peer-scoped
// RecoveryLineage.
// Borrows: *transport.BlockExecutor — caller retains ownership and
// is responsible for executor lifecycle. Peer does not close the
// executor (BUG-005-class discipline).
func NewReplicaPeer(target ReplicaTarget, executor *transport.BlockExecutor) (*ReplicaPeer, error) {
if executor == nil {
return nil, fmt.Errorf("replication: NewReplicaPeer: executor is nil")
}
if target.Epoch == 0 || target.EndpointVersion == 0 {
return nil, fmt.Errorf(
"replication: NewReplicaPeer: target needs nonzero epoch (got %d) and endpointVersion (got %d)",
target.Epoch, target.EndpointVersion)
}
sessionID := peerSessionIDCounter.Add(1)
lineage := transport.RecoveryLineage{
SessionID: sessionID,
Epoch: target.Epoch,
EndpointVersion: target.EndpointVersion,
TargetLSN: liveShipTargetLSN,
}
if err := executor.RegisterLiveShipSession(lineage); err != nil {
return nil, fmt.Errorf("replication: NewReplicaPeer: register session: %w", err)
}
return &ReplicaPeer{
target: target,
executor: executor,
sessionID: sessionID,
lineage: lineage,
state: ReplicaHealthy,
}, nil
}
// Target returns the peer's ReplicaTarget. Read-only accessor for
// callers that need to inspect the authoritative lineage or address.
func (p *ReplicaPeer) Target() ReplicaTarget { return p.target }
// State returns the peer's current coarse health state. Thread-safe.
func (p *ReplicaPeer) State() ReplicaState {
p.mu.Lock()
defer p.mu.Unlock()
return p.state
}
// ShipEntry ships one live WAL entry to this peer via its BlockExecutor.
// Returns error on transport failure; on error the peer is marked
// Degraded via Invalidate (forward-carry CARRY-1 from T4a-2). A
// Degraded peer rejects subsequent ShipEntry calls until the recovery
// pipeline (T4c) drives it back to Healthy.
//
// The lineage param shape matches the sketch in v3-phase-15-t4-sketch
// so ReplicationVolume (T4a-4) can thread authoritative lineage info
// through. For T4a, the peer ships under its own registered lineage
// (peer owns its live-ship session); caller-supplied lineage is
// informational only. T4b/T4c may tighten this as recovery-bound
// sessions arrive.
//
// Called by: ReplicationVolume.OnLocalWrite (T4a-4) fan-out loop.
// Owns: peer-state mutation on ship error (via Invalidate).
// Borrows: data slice — caller retains, ShipEntry does not mutate
// and does not retain past return.
func (p *ReplicaPeer) ShipEntry(ctx context.Context, lineage transport.RecoveryLineage, lba uint32, lsn uint64, data []byte) error {
_ = lineage // T4a: peer-owned lineage; caller param is informational.
if err := ctx.Err(); err != nil {
return err
}
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return fmt.Errorf("replication: ShipEntry: peer %s closed", p.target.ReplicaID)
}
if p.state == ReplicaDegraded {
p.mu.Unlock()
return fmt.Errorf("replication: ShipEntry: peer %s degraded", p.target.ReplicaID)
}
peerLineage := p.lineage
p.mu.Unlock()
if err := p.executor.Ship(p.target.ReplicaID, peerLineage, lba, lsn, data); err != nil {
p.Invalidate(fmt.Sprintf("ship error: %v", err))
return err
}
return nil
}
// Invalidate marks the peer Degraded and logs the reason. No state
// transitions beyond Healthy ↔ Degraded in T4a; CatchingUp /
// Rebuilding / NeedsRebuild arrive at T4c. Calling Invalidate on an
// already-Degraded peer is a no-op (beyond the log line — still
// useful because the reason string may be new).
//
// Called by: ShipEntry on transport error; ReplicationVolume on
// explicit peer-down from authority updates.
// Owns: peer-state mutation under internal lock.
// Borrows: reason string — caller retains.
func (p *ReplicaPeer) Invalidate(reason string) {
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return
}
prev := p.state
p.state = ReplicaDegraded
p.mu.Unlock()
log.Printf("replication: peer %s invalidated (prev=%s, reason=%s)",
p.target.ReplicaID, prev, reason)
}
// Close tears down the peer's registered session in the executor and
// prevents further ShipEntry calls. Idempotent — second and later
// calls are no-ops and return nil. Does NOT close the executor
// (caller owns executor lifecycle, BUG-005 discipline).
//
// Called by: ReplicationVolume.UpdateReplicaSet when removing this
// peer from the authoritative replica set.
// Owns: invalidation of the peer's session in the executor; setting
// the closed flag.
// Borrows: nothing.
func (p *ReplicaPeer) Close() error {
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return nil
}
p.closed = true
sessionID := p.sessionID
replicaID := p.target.ReplicaID
p.state = ReplicaUnknown
p.mu.Unlock()
p.executor.InvalidateSession(replicaID, sessionID, "replica peer closed")
return nil
}
+230
View File
@@ -0,0 +1,230 @@
package replication
import (
"bytes"
"context"
"net"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/transport"
)
// setupPeerWithRealReplica stands up an in-process real replica
// (ReplicaListener + BlockStore) and a fresh executor aimed at it,
// then constructs a peer pointed at the listener. Returns the peer,
// the replica's store (for assertions), and the listener addr.
//
// This is the "real *transport.BlockExecutor + real *transport.
// ReplicaListener" setup required by T4a-3 context note: ReplicaPeer
// is a leaf; its tests drive against the real transport layer, not
// against a ReplicationVolume caller stub.
func setupPeerWithRealReplica(t *testing.T) (*ReplicaPeer, *storage.BlockStore, *transport.ReplicaListener) {
t.Helper()
replicaStore := storage.NewBlockStore(64, 4096)
listener, err := transport.NewReplicaListener("127.0.0.1:0", replicaStore)
if err != nil {
t.Fatalf("NewReplicaListener: %v", err)
}
listener.Serve()
t.Cleanup(func() { listener.Stop() })
primaryStore := storage.NewBlockStore(64, 4096)
exec := transport.NewBlockExecutor(primaryStore, listener.Addr())
target := ReplicaTarget{
ReplicaID: "r-peer-test",
DataAddr: listener.Addr(),
ControlAddr: listener.Addr(),
Epoch: 5,
EndpointVersion: 2,
}
peer, err := NewReplicaPeer(target, exec)
if err != nil {
t.Fatalf("NewReplicaPeer: %v", err)
}
t.Cleanup(func() { _ = peer.Close() })
return peer, replicaStore, listener
}
// TestReplicaPeer_ShipEntry_Happy — one entry through a fully-wired
// peer arrives at the replica byte-exact; peer stays Healthy.
func TestReplicaPeer_ShipEntry_Happy(t *testing.T) {
peer, replica, _ := setupPeerWithRealReplica(t)
data := make([]byte, 4096)
data[0], data[1] = 0xAB, 0xCD
if err := peer.ShipEntry(context.Background(), transport.RecoveryLineage{}, 5, 1, data); err != nil {
t.Fatalf("ShipEntry: %v", err)
}
if peer.State() != ReplicaHealthy {
t.Fatalf("expected ReplicaHealthy after successful ship, got %s", peer.State())
}
deadline := time.Now().Add(2 * time.Second)
var got []byte
for time.Now().Before(deadline) {
got, _ = replica.Read(5)
if got != nil && got[0] == 0xAB {
break
}
time.Sleep(10 * time.Millisecond)
}
if !bytes.Equal(got, data) {
t.Fatalf("replica LBA 5 data mismatch: got [%02x %02x]", got[0], got[1])
}
}
// TestReplicaPeer_ShipEntry_ConnFailure_MarksDegraded — the forward-
// carry CARRY-1 pin test from T4a-2. On ship error, peer must mark
// Degraded + (implicitly) Invalidate. Subsequent ShipEntry on the
// same peer returns error without touching the wire (T4a state gate).
//
// This closes catalogue §3.2.1 C4 (no-hard-stop / error-return
// handoff) from PARTIAL to DONE.
func TestReplicaPeer_ShipEntry_ConnFailure_MarksDegraded(t *testing.T) {
// Reserve a port then release it → guaranteed unreachable. Ship
// will lazy-dial and fail.
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 := transport.NewBlockExecutor(primary, deadAddr)
target := ReplicaTarget{
ReplicaID: "r-dead",
DataAddr: deadAddr,
ControlAddr: deadAddr,
Epoch: 3,
EndpointVersion: 1,
}
peer, err := NewReplicaPeer(target, exec)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = peer.Close() })
if peer.State() != ReplicaHealthy {
t.Fatalf("expected ReplicaHealthy at construction, got %s", peer.State())
}
data := make([]byte, 4096)
err = peer.ShipEntry(context.Background(), transport.RecoveryLineage{}, 0, 1, data)
if err == nil {
t.Fatal("expected ShipEntry error against unreachable replica, got nil")
}
if !strings.Contains(err.Error(), "dial") && !strings.Contains(err.Error(), "write") {
t.Fatalf("expected dial/write error, got: %v", err)
}
// Peer must have transitioned Healthy → Degraded.
if peer.State() != ReplicaDegraded {
t.Fatalf("expected ReplicaDegraded after ship failure, got %s", peer.State())
}
// Subsequent ShipEntry is rejected at the peer without touching
// the wire (peer-state gate). This is the "no-hard-stop" shape:
// failure degrades the peer, and upstream callers see a cheap
// error instead of a real dial attempt every time.
err = peer.ShipEntry(context.Background(), transport.RecoveryLineage{}, 1, 2, data)
if err == nil {
t.Fatal("Degraded peer should reject subsequent ShipEntry, got nil")
}
if !strings.Contains(err.Error(), "degraded") {
t.Fatalf("expected 'degraded' error, got: %v", err)
}
}
// TestReplicaPeer_Invalidate_MovesToDegraded — direct call to
// Invalidate (outside ShipEntry path) also moves Healthy → Degraded.
// Exercises the authority-driven path (ReplicationVolume would call
// this on explicit peer-down from master updates).
func TestReplicaPeer_Invalidate_MovesToDegraded(t *testing.T) {
peer, _, _ := setupPeerWithRealReplica(t)
if peer.State() != ReplicaHealthy {
t.Fatalf("precondition: expected Healthy, got %s", peer.State())
}
peer.Invalidate("authority said so")
if peer.State() != ReplicaDegraded {
t.Fatalf("expected Degraded after Invalidate, got %s", peer.State())
}
// Second Invalidate is a no-op state-wise (already Degraded).
peer.Invalidate("still said so")
if peer.State() != ReplicaDegraded {
t.Fatalf("state should remain Degraded, got %s", peer.State())
}
}
// TestReplicaPeer_Close_Idempotent — Close twice does not panic and
// the second call returns nil. Post-Close, ShipEntry and Invalidate
// are no-ops (reject / ignore).
func TestReplicaPeer_Close_Idempotent(t *testing.T) {
peer, _, _ := setupPeerWithRealReplica(t)
if err := peer.Close(); err != nil {
t.Fatalf("first Close: %v", err)
}
if err := peer.Close(); err != nil {
t.Fatalf("second Close: %v", err)
}
// ShipEntry on closed peer returns error.
data := make([]byte, 4096)
err := peer.ShipEntry(context.Background(), transport.RecoveryLineage{}, 0, 1, data)
if err == nil {
t.Fatal("ShipEntry on closed peer should error")
}
if !strings.Contains(err.Error(), "closed") {
t.Fatalf("expected 'closed' error, got: %v", err)
}
// Invalidate on closed peer is a silent no-op.
peer.Invalidate("post-close")
// No state assertion — closed is closed. No panic == pass.
}
// TestReplicaPeer_NewReplicaPeer_RejectsNilExecutor — defensive check;
// a nil executor cannot participate in the session lifecycle.
func TestReplicaPeer_NewReplicaPeer_RejectsNilExecutor(t *testing.T) {
target := ReplicaTarget{
ReplicaID: "r-x",
Epoch: 1,
EndpointVersion: 1,
}
_, err := NewReplicaPeer(target, nil)
if err == nil {
t.Fatal("expected error on nil executor")
}
}
// TestReplicaPeer_NewReplicaPeer_RejectsZeroAuthority — Epoch=0 or
// EndpointVersion=0 would produce a lineage the replica listener
// rejects (acceptMutationLineage requires nonzero). Catch it at
// construction, not at first ship.
func TestReplicaPeer_NewReplicaPeer_RejectsZeroAuthority(t *testing.T) {
primary := storage.NewBlockStore(64, 4096)
exec := transport.NewBlockExecutor(primary, "127.0.0.1:0")
cases := []struct {
name string
target ReplicaTarget
}{
{"ZeroEpoch", ReplicaTarget{ReplicaID: "r", Epoch: 0, EndpointVersion: 1}},
{"ZeroEndpointVersion", ReplicaTarget{ReplicaID: "r", Epoch: 1, EndpointVersion: 0}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, err := NewReplicaPeer(tc.target, exec)
if err == nil {
t.Fatal("expected error on zero authority field")
}
})
}
}
+20 -3
View File
@@ -125,11 +125,28 @@ func (e *BlockExecutor) Ship(replicaID string, lineage RecoveryLineage, lba uint
return nil
}
// RegisterLiveShipSession registers a session for steady-state live
// shipping. The session is registered without a conn — Ship will
// lazy-dial replicaAddr on first call. This is the V3 "steady-state
// attach" lifecycle entry point; recovery commands use StartCatchUp
// / StartRebuild instead.
//
// Called by: ReplicaPeer constructor (core/replication, T4a-3).
// Owns: the new activeSession entry in the executor's sessions map.
// Borrows: lineage — caller retains. Caller is responsible for a
// matching InvalidateSession on peer teardown.
func (e *BlockExecutor) RegisterLiveShipSession(lineage RecoveryLineage) error {
if _, err := e.registerSession(lineage); err != nil {
return err
}
return nil
}
// attachShipSession registers a session + attaches the given conn for
// 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.
// via the normal lifecycle (RegisterLiveShipSession / StartCatchUp /
// StartRebuild) 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 {