T4b-2: BlockExecutor.Barrier + doFence ack-validation upgrade

Architect round-22 bundle: new BlockExecutor.Barrier public method +
upgrade of existing executor.doFence to respect round-21 uniform
rule (INV-REPL-LINEAGE-BORNE-ON-BARRIER-ACK). Two coupled changes,
same file, same executor-level ownership, one commit — shipping
Barrier with validation while leaving doFence silent-accept would
violate the uniform rule at the first ack-consuming surface.

Changes:

  core/transport/barrier.go
    New BarrierAck type: {Lineage, AchievedLSN, Success, Reason} —
    validated per-peer barrier outcome surfaced to
    DurabilityCoordinator (T4b-3).
    New ErrBarrierLineageMismatch sentinel: returned by Barrier
    when the response lineage does not match the request. Callers
    treat it as a failed barrier for quorum arithmetic.

  core/transport/executor.go (doFence upgrade)
    After recvBarrierResp succeeds, validate that resp.Lineage
    matches the lineage we sent. Mismatch → FenceResult with
    Success=false + FailReason containing expected=<lineage>
    actual=<lineage> tuple. Short/zeroed/malformed decode failures
    already surface as recvBarrierResp errors (T4b-1 decode layer);
    they now cleanly propagate to OnFenceComplete instead of
    silent-accept ("_ = resp" removed).

  core/transport/executor.go (new Barrier method)
    func (e *BlockExecutor) Barrier(replicaID, lineage, targetLSN)
        (BarrierAck, error)
    Implementation mirrors Ship (architect round-11 Option B
    composite):
      1. Session lookup by lineage.SessionID
      2. Epoch-== fence (silent drop on stale epoch via error return)
      3. Lazy-dial if session.conn == nil, with "first-winner keeps"
         race resolution under e.mu
      4. sendBarrierReq + recvBarrierResp (existing helpers; both
         set conn deadlines, so timeout is bounded by
         recoveryConnTimeout=5s)
      5. Full-lineage validation — resp.Lineage != lineage returns
         ErrBarrierLineageMismatch with diagnostic log format
         matching architect round-21 text (peer ID + expected +
         actual tuple)

Tests (5 required per mini-plan §2 T4b-2):

  - TestExecutor_Barrier_Happy — real ReplicaListener round-trip;
    lineage echo byte-exact; Success=true
  - TestExecutor_Barrier_TimeoutFires — replica accepts but never
    responds; Barrier's recv deadline fires in ~5s (elapsed
    between 4s and 15s, must wedge for most of the deadline to
    count as deadline-driven rather than fast-error)
  - TestExecutor_Barrier_LineageMismatch_Rejected — custom replica
    sends a valid-decode BarrierResponse with different lineage;
    Barrier returns ErrBarrierLineageMismatch
  - TestExecutor_Fence_LineageMismatch_MarksFailure — the round-22
    pin; custom replica sends wrong-lineage ack; doFence propagates
    Success=false through OnFenceComplete with FailReason carrying
    expected= + actual= tuples. This catches "first existing ack
    consumer silently accepts" regression class.
  - TestExecutor_Fence_ShortOrZeroedLineage_MarksFailure — two
    sub-cases (8-byte short payload, 40-byte all-zero lineage);
    both propagate through OnFenceComplete as Success=false (the
    T4b-1 decode-layer error is faithfully relayed to the callback).

Preserve:
  - sendBarrierReq / recvBarrierResp helper signatures unchanged
  - Existing catch-up (catchup_sender.go:102-108) and rebuild
    (rebuild_sender.go:103) paths continue to decode successfully
    with the extended wire; they ignore the lineage field for T4b
    scope — their lineage-validation lands at T4c (catch-up) and
    T5 (rebuild) respectively
  - adapter.OnFenceComplete callback shape unchanged (FenceResult
    gains fuller FailReason content but fields untouched)

Verification: full 21-package repo suite green. G-2 tri-line godoc
on Barrier + BarrierAck + ErrBarrierLineageMismatch. G-3 cumulative.
Timeout test elapsed = 5.00s exactly, confirming deadline is the
unblocking mechanism.

Second task in T4b batch. Next: T4b-3 DurabilityCoordinator (muscle
path; G-1 pre-code V2 diff-footprint required before coding).
This commit is contained in:
pingqiu committed 2026-04-23 18:25:47 -07:00
1 parent 77cf6e2836
commit 4b16a2e759
3 files changed
+481 -1

No files matched your search

+24
View File
@@ -2,11 +2,35 @@ package transport
import (
"encoding/binary"
"errors"
"fmt"
"net"
"time"
)
// BarrierAck is the validated per-peer barrier outcome surfaced to
// callers of BlockExecutor.Barrier. It captures the echoed lineage
// (which the caller has already validated against the session's
// expected lineage before receiving this struct) and the replica's
// achieved frontier.
//
// Reason is populated by higher-layer aggregation (DurabilityCoordinator)
// and is empty on successful Barrier returns.
type BarrierAck struct {
Lineage RecoveryLineage
AchievedLSN uint64
Success bool
Reason string
}
// ErrBarrierLineageMismatch is returned by BlockExecutor.Barrier when
// the replica's response carries a lineage that does not match the
// lineage the caller sent. Per architect round-21 uniform rule, such
// acks MUST NOT be counted toward durability — the caller surfaces
// the error verbatim; DurabilityCoordinator treats it as a failed
// barrier for quorum arithmetic.
var ErrBarrierLineageMismatch = errors.New("transport: barrier: response lineage does not match request")
// BarrierResponse is the typed reply to MsgBarrierReq and to the
// terminal MsgRebuildDone. AchievedLSN is the replica's actual
// synced frontier after applying every pending write — NOT the
@@ -0,0 +1,342 @@
package transport
import (
"errors"
"net"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// --- Test 1: Barrier happy round-trip ---
// TestExecutor_Barrier_Happy — end-to-end round-trip against a real
// ReplicaListener. Primary registers a session, calls Barrier; the
// listener echoes the full lineage per T4b-1; Barrier returns a
// BarrierAck with Lineage + AchievedLSN validated.
func TestExecutor_Barrier_Happy(t *testing.T) {
_, _, listener := setupPrimaryReplica(t)
primary := storage.NewBlockStore(64, 4096)
exec := NewBlockExecutor(primary, listener.Addr())
lineage := shipTestLineage()
if err := exec.registerShipSessionForTest(lineage); err != nil {
t.Fatalf("register session: %v", err)
}
// Close the session's lazy-dialed conn at end so the listener's
// handleConn can exit cleanly (same pattern as Ship tests).
t.Cleanup(func() {
exec.mu.Lock()
if s := exec.sessions[lineage.SessionID]; s != nil && s.conn != nil {
_ = s.conn.Close()
}
exec.mu.Unlock()
})
ack, err := exec.Barrier("r1", lineage, 500)
if err != nil {
t.Fatalf("Barrier: %v", err)
}
if !ack.Success {
t.Fatalf("ack.Success=false")
}
if ack.Lineage != lineage {
t.Fatalf("lineage echo mismatch: got %+v want %+v", ack.Lineage, lineage)
}
// Replica's initial frontier is 0 (fresh store); AchievedLSN is
// whatever store.Sync() returns. We don't pin an exact value
// here because the harness store has no writes — we just require
// the Success path was taken and the lineage round-tripped.
}
// --- Test 2: Barrier timeout ---
// TestExecutor_Barrier_TimeoutFires — replica accepts the conn but
// never reads / responds; Barrier's recv deadline must fire within
// ~recoveryConnTimeout (5s) so a silent replica cannot wedge the
// caller on the TCP retransmission timeout (V2 pattern; mirrors
// T4a-2 TestExecutor_Ship_WriteDeadline_Fires).
func TestExecutor_Barrier_TimeoutFires(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ln.Close() })
// Accept one conn, drain the request, never respond.
accepted := make(chan net.Conn, 1)
go func() {
c, aerr := ln.Accept()
if aerr != nil {
return
}
accepted <- c
// Drain the barrier request so sendBarrierReq doesn't block;
// then sit idle — the recv side of Barrier must time out.
buf := make([]byte, 128)
_, _ = c.Read(buf)
}()
t.Cleanup(func() {
select {
case c := <-accepted:
_ = c.Close()
default:
}
})
primary := storage.NewBlockStore(64, 4096)
exec := NewBlockExecutor(primary, ln.Addr().String())
lineage := shipTestLineage()
if err := exec.registerShipSessionForTest(lineage); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
exec.mu.Lock()
if s := exec.sessions[lineage.SessionID]; s != nil && s.conn != nil {
_ = s.conn.Close()
}
exec.mu.Unlock()
})
start := time.Now()
_, err = exec.Barrier("r1", lineage, 99)
elapsed := time.Since(start)
if err == nil {
t.Fatalf("Barrier returned nil after %v; expected timeout", elapsed)
}
// Budget: recoveryConnTimeout is 5s; allow up to 10s for OS
// scheduling slop. If we hit 15s the deadline didn't fire.
if elapsed > 15*time.Second {
t.Fatalf("Barrier took %v; expected ~5s (recoveryConnTimeout). Deadline likely not firing — invariant regression.",
elapsed)
}
// And: must have wedged for most of the deadline. A fast-return
// error isn't a deadline-driven timeout.
if elapsed < 4*time.Second {
t.Fatalf("Barrier returned in %v — too fast to be deadline-driven", elapsed)
}
if !isTimeoutErr(err) && !strings.Contains(err.Error(), "barrier") {
t.Fatalf("error does not look like a barrier timeout: %v", err)
}
}
// --- Test 3: Barrier lineage mismatch rejection ---
// TestExecutor_Barrier_LineageMismatch_Rejected — replica sends a
// valid-decode BarrierResponse whose lineage differs from the
// primary's request. Barrier MUST return ErrBarrierLineageMismatch
// (architect round-21 uniform rule; full lineage is the authority
// identity of the ack). Log format must include peer ID + expected
// + actual tuple.
func TestExecutor_Barrier_LineageMismatch_Rejected(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ln.Close() })
// Custom replica: decode the barrier request, then respond with
// a DIFFERENT (but valid-decode-able) lineage.
wrongLineage := RecoveryLineage{
SessionID: 999,
Epoch: 999,
EndpointVersion: 999,
TargetLSN: 999,
}
done := make(chan struct{})
go func() {
defer close(done)
c, err := ln.Accept()
if err != nil {
return
}
defer c.Close()
// Read request (barrier req with self lineage).
if _, _, err := ReadMsg(c); err != nil {
return
}
// Echo WRONG lineage.
payload := EncodeBarrierResp(BarrierResponse{
Lineage: wrongLineage,
AchievedLSN: 42,
})
_ = WriteMsg(c, MsgBarrierResp, payload)
}()
primary := storage.NewBlockStore(64, 4096)
exec := NewBlockExecutor(primary, ln.Addr().String())
lineage := shipTestLineage()
if err := exec.registerShipSessionForTest(lineage); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
exec.mu.Lock()
if s := exec.sessions[lineage.SessionID]; s != nil && s.conn != nil {
_ = s.conn.Close()
}
exec.mu.Unlock()
})
_, err = exec.Barrier("r1", lineage, 100)
if !errors.Is(err, ErrBarrierLineageMismatch) {
t.Fatalf("expected ErrBarrierLineageMismatch, got: %v", err)
}
select {
case <-done:
case <-time.After(3 * time.Second):
t.Fatal("custom replica goroutine didn't finish")
}
}
// --- Test 4: Fence lineage mismatch marks failure ---
// TestExecutor_Fence_LineageMismatch_MarksFailure — the architect
// round-22 correction pin. executor.doFence previously discarded
// the BarrierResponse ("_ = resp // AchievedLSN is not used by
// fence"). After T4b-2, it MUST validate the echoed lineage and
// fire OnFenceComplete with Success=false on mismatch.
//
// This is the "first existing consumer of the extended wire respects
// the uniform rule" fence (round-22).
func TestExecutor_Fence_LineageMismatch_MarksFailure(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ln.Close() })
// Custom replica that echoes wrong lineage for any barrier request.
wrongLineage := RecoveryLineage{
SessionID: 100,
Epoch: 100,
EndpointVersion: 100,
TargetLSN: 100,
}
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
go func(conn net.Conn) {
defer conn.Close()
if _, _, err := ReadMsg(conn); err != nil {
return
}
payload := EncodeBarrierResp(BarrierResponse{
Lineage: wrongLineage,
AchievedLSN: 42,
})
_ = WriteMsg(conn, MsgBarrierResp, payload)
}(c)
}
}()
primary := storage.NewBlockStore(64, 4096)
exec := NewBlockExecutor(primary, ln.Addr().String())
resultCh := make(chan adapter.FenceResult, 1)
exec.SetOnFenceComplete(func(r adapter.FenceResult) { resultCh <- r })
if err := exec.Fence("r1", 7, 5, 3); err != nil {
t.Fatalf("Fence: %v", err)
}
select {
case r := <-resultCh:
if r.Success {
t.Fatal("Fence should have failed on lineage mismatch")
}
if !strings.Contains(r.FailReason, "lineage mismatch") {
t.Fatalf("FailReason missing 'lineage mismatch': %q", r.FailReason)
}
// Diagnostic must include expected + actual tuples for
// operators to diagnose asymmetric authority bugs.
if !strings.Contains(r.FailReason, "expected=") || !strings.Contains(r.FailReason, "actual=") {
t.Fatalf("FailReason missing expected=/actual= tuple: %q", r.FailReason)
}
case <-time.After(5 * time.Second):
t.Fatal("OnFenceComplete never fired")
}
}
// --- Test 5: Fence short/zeroed payload marks failure ---
// TestExecutor_Fence_ShortOrZeroedLineage_MarksFailure — doFence
// propagates the T4b-1 decode-layer failure (short / zero-valued /
// malformed payload) via the OnFenceComplete callback with
// Success=false. No silent-accept, per round-22.
//
// Tests two shapes:
// (a) short payload (< 40B)
// (b) zeroed lineage in a full-size payload
// Both must reach the callback as Success=false.
func TestExecutor_Fence_ShortOrZeroedLineage_MarksFailure(t *testing.T) {
cases := []struct {
name string
payload []byte
}{
{
name: "short_payload",
payload: make([]byte, 8), // old 8-byte format — < 40B
},
{
name: "zeroed_lineage", // full 40B but lineage all zero
payload: make([]byte, 40),
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ln.Close() })
payloadCopy := tc.payload
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
go func(conn net.Conn) {
defer conn.Close()
if _, _, err := ReadMsg(conn); err != nil {
return
}
_ = WriteMsg(conn, MsgBarrierResp, payloadCopy)
}(c)
}
}()
primary := storage.NewBlockStore(64, 4096)
exec := NewBlockExecutor(primary, ln.Addr().String())
resultCh := make(chan adapter.FenceResult, 1)
exec.SetOnFenceComplete(func(r adapter.FenceResult) { resultCh <- r })
if err := exec.Fence("r1", 7, 5, 3); err != nil {
t.Fatalf("Fence: %v", err)
}
select {
case r := <-resultCh:
if r.Success {
t.Fatalf("Fence should have failed on %s", tc.name)
}
if !strings.Contains(r.FailReason, "fence barrier resp") {
t.Fatalf("FailReason should describe resp-side failure, got: %q", r.FailReason)
}
case <-time.After(5 * time.Second):
t.Fatalf("%s: OnFenceComplete never fired", tc.name)
}
})
}
}
+115 -1
View File
@@ -122,18 +122,132 @@ func (e *BlockExecutor) doFence(replicaID string, lineage RecoveryLineage) {
}
resp, err := recvBarrierResp(conn, recoveryConnTimeout)
if err != nil {
// Short / zero-valued / field-order-malformed payloads are
// rejected at the T4b-1 decode layer as errors, so they
// surface here and fail the fence — NOT a silent accept.
// Covers the uniform-rule failure class at the first
// existing consumer of the extended BarrierResponse wire
// (architect round 22).
result.Success = false
result.FailReason = fmt.Sprintf("fence barrier resp: %v", err)
e.fireFenceComplete(result)
return
}
_ = resp // AchievedLSN is not used by fence — we only needed the replica's ack
// T4b-2 round-22 lineage validation: the replica's echoed lineage
// MUST match the lineage we sent. This is the "valid-decode but
// wrong-session" case — decode was fine, but the ack is for a
// different authority tuple than the one we're awaiting.
// AchievedLSN is still not semantically meaningful for fence;
// the validation is purely about confirming the replica acked
// OUR request, not some concurrent / stale one.
if resp.Lineage != lineage {
result.Success = false
result.FailReason = fmt.Sprintf("fence barrier resp lineage mismatch: expected=%+v actual=%+v",
lineage, resp.Lineage)
log.Printf("executor: fence lineage mismatch replica=%s expected=%+v actual=%+v",
replicaID, lineage, resp.Lineage)
e.fireFenceComplete(result)
return
}
result.Success = true
log.Printf("executor: fence complete replica=%s epoch=%d", replicaID, lineage.Epoch)
e.fireFenceComplete(result)
}
// Barrier issues a per-peer barrier round-trip carrying the session
// lineage. Blocks until the response arrives or the deadline fires.
// Returns the validated BarrierAck on success, or error on transport
// failure / ack rejection.
//
// Architect round-21 uniform rule applies end-to-end:
// - decode rejects short / zeroed / field-order-malformed acks
// (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.
//
// Called by: DurabilityCoordinator.SyncLocalAndReplicas (T4b-3)
// per-peer fan-out.
// Owns: per-call conn deadline (recoveryConnTimeout); lineage binding;
// ack validation against the session's registered lineage.
// Borrows: session by replicaID + lineage.SessionID; BarrierAck
// payload fields are value-copied into the returned struct.
func (e *BlockExecutor) Barrier(replicaID string, lineage RecoveryLineage, targetLSN uint64) (BarrierAck, error) {
// Session lookup + epoch-== fence (same pattern as Ship).
e.mu.Lock()
session, ok := e.sessions[lineage.SessionID]
if !ok || session == nil {
e.mu.Unlock()
return BarrierAck{}, fmt.Errorf("transport: barrier: no session for replica=%s sessionID=%d",
replicaID, lineage.SessionID)
}
if lineage.Epoch != session.lineage.Epoch {
sessionEpoch := session.lineage.Epoch
e.mu.Unlock()
log.Printf("transport: barrier: dropping targetLSN=%d replica=%s stale epoch %d (session epoch %d)",
targetLSN, replicaID, lineage.Epoch, sessionEpoch)
return BarrierAck{}, fmt.Errorf("transport: barrier: stale epoch %d (session %d)",
lineage.Epoch, sessionEpoch)
}
conn := session.conn
e.mu.Unlock()
// Lazy-dial if no conn (same pattern as Ship, architect round-11
// Option B). Attach-under-mu with "first winner keeps" races.
if conn == nil {
dialed, err := net.DialTimeout("tcp", e.replicaAddr, shipDialTimeout)
if err != nil {
return BarrierAck{}, fmt.Errorf("transport: barrier: dial replica=%s sessionID=%d: %w",
replicaID, lineage.SessionID, err)
}
e.mu.Lock()
current, stillActive := e.sessions[lineage.SessionID]
switch {
case !stillActive || current != session:
e.mu.Unlock()
_ = dialed.Close()
return BarrierAck{}, fmt.Errorf("transport: barrier: 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()
}
}
// Send request + receive response with deadlines on both sides
// (sendBarrierReq / recvBarrierResp already set conn deadline).
if err := sendBarrierReq(conn, lineage, recoveryConnTimeout); err != nil {
return BarrierAck{}, fmt.Errorf("transport: barrier: send replica=%s: %w", replicaID, err)
}
resp, err := recvBarrierResp(conn, recoveryConnTimeout)
if err != nil {
return BarrierAck{}, fmt.Errorf("transport: barrier: recv replica=%s: %w", replicaID, err)
}
// Full-lineage validation (architect round-21 uniform rule).
// Stale or cross-session acks fail here. Diagnostic log format
// matches architect's round-21 text: peer ID + full expected /
// actual lineage tuple.
if resp.Lineage != lineage {
log.Printf("transport: barrier: lineage mismatch replica=%s expected=%+v actual=%+v",
replicaID, lineage, resp.Lineage)
return BarrierAck{}, ErrBarrierLineageMismatch
}
return BarrierAck{
Lineage: resp.Lineage,
AchievedLSN: resp.AchievedLSN,
Success: true,
}, nil
}
func (e *BlockExecutor) fireFenceComplete(result adapter.FenceResult) {
e.mu.Lock()
cb := e.onFenceComplete