diff --git a/seaweed-block/core/adapter/adapter.go b/seaweed-block/core/adapter/adapter.go index df589b618b..51b63b6320 100644 --- a/seaweed-block/core/adapter/adapter.go +++ b/seaweed-block/core/adapter/adapter.go @@ -391,6 +391,16 @@ func (a *VolumeReplicaAdapter) prepareQueuedCommands(cmds []engine.Command) ([]e // command + event pair. sid := sessionIDCounter.Add(1) queued = append(queued, queuedCommand{cmd: cmd, sessionID: sid}) + case engine.ProbeReplica: + // T4c-1 (architect Option D): probe mints a transient + // sessionID so the wire frame carries a full lineage + // (round-26 symmetric-pair rule). Probe is non-mutating — + // no SessionPrepared event, no executor session-table + // registration, no OnSessionStart / OnSessionClose. The + // sessionID is consumed only by `executor.Probe` to + // construct the ProbeReq's RecoveryLineage. + sid := sessionIDCounter.Add(1) + queued = append(queued, queuedCommand{cmd: cmd, sessionID: sid}) default: queued = append(queued, queuedCommand{cmd: cmd}) } @@ -404,8 +414,11 @@ func (a *VolumeReplicaAdapter) prepareQueuedCommands(cmds []engine.Command) ([]e func (a *VolumeReplicaAdapter) executeCommand(q queuedCommand) { switch c := q.cmd.(type) { case engine.ProbeReplica: + // T4c-1: pass the adapter-minted transient probe sessionID so + // the executor can construct the ProbeReq's full lineage. + probeSessionID := q.sessionID go func() { - result := a.executor.Probe(c.ReplicaID, c.DataAddr, c.CtrlAddr, c.Epoch, c.EndpointVersion) + result := a.executor.Probe(c.ReplicaID, c.DataAddr, c.CtrlAddr, probeSessionID, c.Epoch, c.EndpointVersion) a.OnProbeResult(result) }() diff --git a/seaweed-block/core/adapter/adapter_test.go b/seaweed-block/core/adapter/adapter_test.go index 1ded948887..221b365c73 100644 --- a/seaweed-block/core/adapter/adapter_test.go +++ b/seaweed-block/core/adapter/adapter_test.go @@ -28,6 +28,14 @@ type mockExecutor struct { fenceErr error starts []startRecord fences []fenceRecord + probeCalls []probeRecord // T4c-1: captures sessionID adapter mints for ProbeReplica +} + +type probeRecord struct { + replicaID string + sessionID uint64 + epoch uint64 + endpointVersion uint64 } type fenceRecord struct { @@ -112,10 +120,16 @@ func (m *mockExecutor) fireFence(result FenceResult) { } } -func (m *mockExecutor) Probe(replicaID, dataAddr, ctrlAddr string, epoch, endpointVersion uint64) ProbeResult { +func (m *mockExecutor) Probe(replicaID, dataAddr, ctrlAddr string, sessionID, epoch, endpointVersion uint64) ProbeResult { m.mu.Lock() defer m.mu.Unlock() m.commands = append(m.commands, "Probe") + m.probeCalls = append(m.probeCalls, probeRecord{ + replicaID: replicaID, + sessionID: sessionID, + epoch: epoch, + endpointVersion: endpointVersion, + }) if r, ok := m.probeResults[replicaID]; ok { return r } diff --git a/seaweed-block/core/adapter/executor.go b/seaweed-block/core/adapter/executor.go index cce0f601cc..fa8714d0ce 100644 --- a/seaweed-block/core/adapter/executor.go +++ b/seaweed-block/core/adapter/executor.go @@ -28,7 +28,15 @@ type CommandExecutor interface { // Probe dials the replica and collects transport/recovery facts. // Returns a ProbeResult with success/failure and R/S/H boundaries. // Must NOT decide recovery class — that's the engine's job. - Probe(replicaID, dataAddr, ctrlAddr string, epoch, endpointVersion uint64) ProbeResult + // + // Per T4c-1 (architect Option D): sessionID is a transient probe + // session minted by the adapter (parallel to FenceAtEpoch). The + // executor uses it to construct the wire-level RecoveryLineage for + // the symmetric ProbeReq + ProbeResponse pair. The probe sessionID + // is NOT registered in any executor session table, NOT represented + // in engine session truth, and NOT carried in OnSessionStart / + // OnSessionClose callbacks. Probe is non-mutating. + Probe(replicaID, dataAddr, ctrlAddr string, sessionID, epoch, endpointVersion uint64) ProbeResult // StartCatchUp begins a catch-up session with the given sessionID and targetLSN. // The sessionID is assigned by the adapter (matches the engine's session truth). diff --git a/seaweed-block/core/adapter/probe_session_test.go b/seaweed-block/core/adapter/probe_session_test.go new file mode 100644 index 0000000000..257b4bdb14 --- /dev/null +++ b/seaweed-block/core/adapter/probe_session_test.go @@ -0,0 +1,118 @@ +package adapter + +import ( + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/engine" +) + +// TestAdapter_ProbeReplica_MintsTransientSessionID pins T4c-1 architect +// Option D: when the engine emits `engine.ProbeReplica`, the adapter +// mints a non-zero transient sessionID (parallel to FenceAtEpoch), +// passes it to executor.Probe, and does NOT emit any session-lifecycle +// event (no SessionPrepared / SessionStarted / SessionClosed for probe). +// +// Probe is non-mutating; it must not appear in engine session truth. +func TestAdapter_ProbeReplica_MintsTransientSessionID(t *testing.T) { + exec := newMockExecutor() + a := NewVolumeReplicaAdapter(exec) + a.startTimeout = 0 // disable watchdog (probes don't go through start lifecycle) + + // Drive an assignment so engine emits ProbeReplica. + _ = a.OnAssignment(AssignmentInfo{ + ReplicaID: "r1", + Epoch: 5, + EndpointVersion: 3, + DataAddr: "127.0.0.1:1", + CtrlAddr: "127.0.0.1:2", + }) + + // Probe runs in a goroutine; give it a tick to land. + deadline := time.Now().Add(500 * time.Millisecond) + for time.Now().Before(deadline) { + exec.mu.Lock() + hasProbe := len(exec.probeCalls) > 0 + exec.mu.Unlock() + if hasProbe { + break + } + time.Sleep(5 * time.Millisecond) + } + + exec.mu.Lock() + probes := append([]probeRecord(nil), exec.probeCalls...) + exec.mu.Unlock() + + if len(probes) == 0 { + t.Fatal("expected adapter to dispatch ProbeReplica → executor.Probe; got 0 probe calls") + } + p := probes[0] + if p.replicaID != "r1" { + t.Errorf("replicaID = %q, want r1", p.replicaID) + } + if p.sessionID == 0 { + t.Errorf("transient probe sessionID must be non-zero (architect Option D); got 0") + } + if p.epoch != 5 || p.endpointVersion != 3 { + t.Errorf("identity passthrough wrong: epoch=%d endpoint=%d, want 5/3", p.epoch, p.endpointVersion) + } + + // Probe must NOT appear in engine session truth (no SessionPrepared + // / SessionStarted / SessionClosed lifecycle). Engine's + // ReplicaProjection surfaces session state via SessionPhase + // (PhaseNone = no session). Probe must leave it at PhaseNone. + proj := a.Projection() + if proj.SessionPhase != engine.PhaseNone { + t.Errorf("probe must NOT create session lifecycle; got SessionPhase=%q", + proj.SessionPhase) + } +} + +// TestAdapter_ProbeReplica_MintsDistinctSessionIDs pins that two +// successive probe-emit triggers receive distinct, non-zero sessionIDs. +// The mint itself is monotonic (sessionIDCounter.Add(1)), but the probe +// runs in a goroutine so capture order is not stable — assert +// distinctness, not arrival ordering. +func TestAdapter_ProbeReplica_MintsDistinctSessionIDs(t *testing.T) { + exec := newMockExecutor() + a := NewVolumeReplicaAdapter(exec) + a.startTimeout = 0 + + // First assignment → first probe. + _ = a.OnAssignment(AssignmentInfo{ + ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, + DataAddr: "x", CtrlAddr: "y", + }) + // Second assignment with bumped endpoint → reachability reset → second probe. + _ = a.OnAssignment(AssignmentInfo{ + ReplicaID: "r1", Epoch: 1, EndpointVersion: 2, + DataAddr: "x", CtrlAddr: "y", + }) + + deadline := time.Now().Add(500 * time.Millisecond) + for time.Now().Before(deadline) { + exec.mu.Lock() + count := len(exec.probeCalls) + exec.mu.Unlock() + if count >= 2 { + break + } + time.Sleep(5 * time.Millisecond) + } + + exec.mu.Lock() + probes := append([]probeRecord(nil), exec.probeCalls...) + exec.mu.Unlock() + + if len(probes) < 2 { + t.Fatalf("expected >=2 probes, got %d", len(probes)) + } + if probes[0].sessionID == probes[1].sessionID { + t.Errorf("sessionIDs must be distinct: both probes got sid=%d", probes[0].sessionID) + } + if probes[0].sessionID == 0 || probes[1].sessionID == 0 { + t.Errorf("sessionIDs must be non-zero: %d, %d", + probes[0].sessionID, probes[1].sessionID) + } +} diff --git a/seaweed-block/core/authority/authority_test.go b/seaweed-block/core/authority/authority_test.go index 6e576f1124..818cbe09e3 100644 --- a/seaweed-block/core/authority/authority_test.go +++ b/seaweed-block/core/authority/authority_test.go @@ -673,7 +673,7 @@ func (e *closureExecutor) SetOnSessionStart(fn adapter.OnSessionStart) { e.o func (e *closureExecutor) SetOnSessionClose(fn adapter.OnSessionClose) { e.onClose = fn } func (e *closureExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) { e.onFenceComplete = fn } -func (e *closureExecutor) Probe(replicaID, dataAddr, ctrlAddr string, epoch, endpointVersion uint64) adapter.ProbeResult { +func (e *closureExecutor) Probe(replicaID, dataAddr, ctrlAddr string, sessionID, epoch, endpointVersion uint64) adapter.ProbeResult { return adapter.ProbeResult{ ReplicaID: replicaID, Success: true, diff --git a/seaweed-block/core/authority/policy_test.go b/seaweed-block/core/authority/policy_test.go index be1b005ace..a902957fdc 100644 --- a/seaweed-block/core/authority/policy_test.go +++ b/seaweed-block/core/authority/policy_test.go @@ -941,7 +941,7 @@ func (e *policyClosureExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) { e.mu.Unlock() } -func (e *policyClosureExecutor) Probe(replicaID, dataAddr, ctrlAddr string, epoch, endpointVersion uint64) adapter.ProbeResult { +func (e *policyClosureExecutor) Probe(replicaID, dataAddr, ctrlAddr string, sessionID, epoch, endpointVersion uint64) adapter.ProbeResult { return adapter.ProbeResult{ ReplicaID: replicaID, Success: true, EndpointVersion: endpointVersion, TransportEpoch: epoch, diff --git a/seaweed-block/core/authority/restart_route_test.go b/seaweed-block/core/authority/restart_route_test.go index 3687f37553..6d4e6da4e7 100644 --- a/seaweed-block/core/authority/restart_route_test.go +++ b/seaweed-block/core/authority/restart_route_test.go @@ -73,7 +73,7 @@ func (e *restartExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) { e.mu.Unlock() } -func (e *restartExecutor) Probe(replicaID, dataAddr, ctrlAddr string, epoch, endpointVersion uint64) adapter.ProbeResult { +func (e *restartExecutor) Probe(replicaID, dataAddr, ctrlAddr string, sessionID, epoch, endpointVersion uint64) adapter.ProbeResult { return adapter.ProbeResult{ ReplicaID: replicaID, Success: true, diff --git a/seaweed-block/core/host/volume/healthy_executor.go b/seaweed-block/core/host/volume/healthy_executor.go index 41e77fffaa..61374b26c7 100644 --- a/seaweed-block/core/host/volume/healthy_executor.go +++ b/seaweed-block/core/host/volume/healthy_executor.go @@ -48,7 +48,7 @@ func (e *HealthyPathExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) { e // Probe returns a successful probe. The adapter normalizes this // into a ProbeSucceeded event → Reachability.Status=Reachable. -func (e *HealthyPathExecutor) Probe(replicaID, dataAddr, ctrlAddr string, epoch, endpointVersion uint64) adapter.ProbeResult { +func (e *HealthyPathExecutor) Probe(replicaID, dataAddr, ctrlAddr string, sessionID, epoch, endpointVersion uint64) adapter.ProbeResult { e.record("Probe:" + replicaID) // Return Success=true plus caught-up boundaries (R=H=1, S=0). // decide() sees R>=H and emits DecisionNone + FenceAtEpoch diff --git a/seaweed-block/core/host/volume/noop_executor.go b/seaweed-block/core/host/volume/noop_executor.go index e125a5510b..95d045d503 100644 --- a/seaweed-block/core/host/volume/noop_executor.go +++ b/seaweed-block/core/host/volume/noop_executor.go @@ -52,7 +52,7 @@ func (e *noopExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) { e.onFenc // considering the replica caught-up; Mode stays non-Healthy // which is exactly the T0 acceptance claim (lineage known, // runtime facts NOT known). -func (e *noopExecutor) Probe(replicaID, dataAddr, ctrlAddr string, epoch, endpointVersion uint64) adapter.ProbeResult { +func (e *noopExecutor) Probe(replicaID, dataAddr, ctrlAddr string, sessionID, epoch, endpointVersion uint64) adapter.ProbeResult { e.record("Probe:" + replicaID) return adapter.ProbeResult{ ReplicaID: replicaID, diff --git a/seaweed-block/core/ops/server_test.go b/seaweed-block/core/ops/server_test.go index 789f3e2624..d6f86905ce 100644 --- a/seaweed-block/core/ops/server_test.go +++ b/seaweed-block/core/ops/server_test.go @@ -201,7 +201,7 @@ type nopExecutor struct { func (e *nopExecutor) SetOnSessionStart(fn adapter.OnSessionStart) { e.onStart = fn } func (e *nopExecutor) SetOnSessionClose(fn adapter.OnSessionClose) { e.onClose = fn } func (e *nopExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) { e.onFence = fn } -func (e *nopExecutor) Probe(string, string, string, uint64, uint64) adapter.ProbeResult { +func (e *nopExecutor) Probe(string, string, string, uint64, uint64, uint64) adapter.ProbeResult { return adapter.ProbeResult{Success: false, FailReason: "nop"} } func (e *nopExecutor) StartCatchUp(string, uint64, uint64, uint64, uint64) error { return nil } diff --git a/seaweed-block/core/transport/executor.go b/seaweed-block/core/transport/executor.go index 20f6c2b0e1..f01d58a89c 100644 --- a/seaweed-block/core/transport/executor.go +++ b/seaweed-block/core/transport/executor.go @@ -262,14 +262,80 @@ func (e *BlockExecutor) fireFenceComplete(result adapter.FenceResult) { } } -// Probe dials the replica, sends a probe request, and returns the -// replica's R/S/H boundaries. Returns facts only — never decides policy. -func (e *BlockExecutor) Probe(replicaID, dataAddr, ctrlAddr string, epoch, endpointVersion uint64) adapter.ProbeResult { +// ErrProbeLineageMismatch is returned by `BlockExecutor.Probe` when the +// replica's response carries a lineage that does not match the request +// lineage. Per architect round-21 + round-26 symmetric-pair rule, such +// responses MUST NOT contribute to recovery facts — the executor surfaces +// the error verbatim and the engine treats it as a probe failure. +var ErrProbeLineageMismatch = errors.New("transport: probe: response lineage does not match request") + +// Probe dials the replica, sends a `MsgProbeReq` carrying the full +// transient probe lineage (T4c-1 wire), and returns the replica's R/S/H +// boundaries after validating the echoed lineage. Returns facts only — +// never decides policy. +// +// Per T4c-1 (architect Option D): sessionID is the adapter-minted +// transient probe sessionID. It is NOT registered in `executor.sessions`, +// NOT carried in any session-lifecycle event. The lineage built here: +// +// RecoveryLineage{SessionID, Epoch, EndpointVersion, TargetLSN: max(1, primaryH)} +// +// is consumed only by the wire pair. `primaryH` comes from +// `primaryStore.Boundaries()`; the `max(1, ...)` floor ensures +// architect's no-zero-TargetLSN rule holds even on an empty primary. +// +// The replica's `acceptMutationLineage` accepts a fresh higher-tuple +// lineage normally — probe lineages monotonically advance with the +// minted sessionID counter, so they don't masquerade as stale. +// +// Echo validation: if `resp.Lineage != requestLineage`, returns +// `ErrProbeLineageMismatch`. Catches stale / cross-session / partially- +// zeroed responses (the latter already caught at decode, but a valid- +// decode-but-wrong-session ack is the load-bearing case here). +// +// Called by: adapter.executeCommand at engine.ProbeReplica dispatch. +// Owns: dial timeout (2s); per-call conn deadline (3s); transient +// probe lineage construction. +// Borrows: primaryStore (boundaries snapshot for TargetLSN floor and +// for R/S/H facts). +func (e *BlockExecutor) Probe(replicaID, dataAddr, ctrlAddr string, sessionID, epoch, endpointVersion uint64) adapter.ProbeResult { addr := e.replicaAddr if dataAddr != "" { addr = dataAddr } + // Get primary's boundaries before dialing — the head is needed to + // build a non-zero TargetLSN for the request lineage, and the + // primaryS / primaryH are also returned in the ProbeResult. + _, primaryS, primaryH := e.primaryStore.Boundaries() + + // Probe lineage construction (architect Option D). Floor TargetLSN + // at 1 to honor architect's no-zero-TargetLSN rule even when the + // primary has not yet written any data. + targetLSN := primaryH + if targetLSN == 0 { + targetLSN = 1 + } + requestLineage := RecoveryLineage{ + SessionID: sessionID, + Epoch: epoch, + EndpointVersion: endpointVersion, + TargetLSN: targetLSN, + } + if requestLineage.SessionID == 0 || requestLineage.Epoch == 0 || + requestLineage.EndpointVersion == 0 { + // Fail-closed: adapter must mint a non-zero sessionID; engine + // must populate non-zero epoch + endpointVersion before + // emitting ProbeReplica. A zero here is a programmer error. + return adapter.ProbeResult{ + ReplicaID: replicaID, + Success: false, + EndpointVersion: endpointVersion, + TransportEpoch: epoch, + FailReason: fmt.Sprintf("probe lineage has zero field: %+v", requestLineage), + } + } + conn, err := net.DialTimeout("tcp", addr, 2*time.Second) if err != nil { return adapter.ProbeResult{ @@ -283,7 +349,7 @@ func (e *BlockExecutor) Probe(replicaID, dataAddr, ctrlAddr string, epoch, endpo defer conn.Close() conn.SetDeadline(time.Now().Add(3 * time.Second)) - if err := WriteMsg(conn, MsgProbeReq, nil); err != nil { + if err := WriteMsg(conn, MsgProbeReq, EncodeProbeReq(ProbeRequest{Lineage: requestLineage})); err != nil { return adapter.ProbeResult{ ReplicaID: replicaID, Success: false, @@ -315,8 +381,21 @@ func (e *BlockExecutor) Probe(replicaID, dataAddr, ctrlAddr string, epoch, endpo } } - // Get primary's boundaries for R/S/H. - _, primaryS, primaryH := e.primaryStore.Boundaries() + // Echo validation (round-26 symmetric-pair rule, mirrors T4b-2's + // barrier echo check). Primary-side consumer MUST reject stale / + // cross-session / partial-zero responses by full lineage tuple. + if resp.Lineage != requestLineage { + log.Printf("transport: probe: lineage mismatch replica=%s expected=%+v actual=%+v", + replicaID, requestLineage, resp.Lineage) + return adapter.ProbeResult{ + ReplicaID: replicaID, + Success: false, + EndpointVersion: endpointVersion, + TransportEpoch: epoch, + FailReason: fmt.Sprintf("%v: expected=%+v actual=%+v", + ErrProbeLineageMismatch, requestLineage, resp.Lineage), + } + } log.Printf("executor: probe %s success R=%d S=%d H=%d", replicaID, resp.SyncedLSN, primaryS, primaryH) @@ -326,8 +405,8 @@ func (e *BlockExecutor) Probe(replicaID, dataAddr, ctrlAddr string, epoch, endpo EndpointVersion: endpointVersion, TransportEpoch: epoch, ReplicaFlushedLSN: resp.SyncedLSN, // R - PrimaryTailLSN: primaryS, // S - PrimaryHeadLSN: primaryH, // H + PrimaryTailLSN: primaryS, // S + PrimaryHeadLSN: primaryH, // H } } diff --git a/seaweed-block/core/transport/failclosed_test.go b/seaweed-block/core/transport/failclosed_test.go index 7f9510fca1..c6865b485b 100644 --- a/seaweed-block/core/transport/failclosed_test.go +++ b/seaweed-block/core/transport/failclosed_test.go @@ -244,11 +244,19 @@ func TestFailClosed_StaleShipAfterNewerRebuild_Rejected(t *testing.T) { } } -// TestFailClosed_ProbeDuringRebuild_DoesNotDisturbActiveLineage -// proves probe is observation only: a probe arriving mid-rebuild -// does not reset the replica's activeLineage, so subsequent rebuild -// frames continue to be accepted at the same lineage. -func TestFailClosed_ProbeDuringRebuild_DoesNotDisturbActiveLineage(t *testing.T) { +// TestFailClosed_StaleProbeDuringRebuild_RejectedAndRebuildContinues +// proves probe is now authority-bearing (T4c-1 round-26 symmetric-pair +// rule): a probe carrying a stale lineage is rejected at +// acceptMutationLineage (conn dropped without echo), so it cannot +// disturb the replica's activeLineage. Subsequent rebuild frames at +// the original (higher) lineage continue to be accepted. +// +// Pre-T4c-1 this test asserted "probe is observation only, no lineage." +// That premise is invalidated by T4c-1 — probe IS authority-bearing. +// The new contract: stale probe → fail-closed (drop without echo); +// fresh probe → activeLineage advances and stale subsequent traffic +// is correctly rejected. +func TestFailClosed_StaleProbeDuringRebuild_RejectedAndRebuildContinues(t *testing.T) { _, replica, listener := setupPrimaryReplica(t) lin := RecoveryLineage{SessionID: 5, Epoch: 3, EndpointVersion: 3, TargetLSN: 99} @@ -263,27 +271,26 @@ func TestFailClosed_ProbeDuringRebuild_DoesNotDisturbActiveLineage(t *testing.T) } time.Sleep(30 * time.Millisecond) - // Probe on a separate conn — observation, no lineage attached. + // Stale probe lineage (older epoch than the in-flight rebuild). + // Replica's acceptMutationLineage rejects → conn dropped without + // echo → primary observes EOF (in real flow, surfaces as probe + // failure). + stale := RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 1} connP, err := net.Dial("tcp", listener.Addr()) if err != nil { t.Fatal(err) } defer connP.Close() - if err := WriteMsg(connP, MsgProbeReq, nil); err != nil { + if err := WriteMsg(connP, MsgProbeReq, EncodeProbeReq(ProbeRequest{Lineage: stale})); err != nil { t.Fatal(err) } - msgType, payload, err := ReadMsg(connP) - if err != nil { - t.Fatal(err) - } - if msgType != MsgProbeResp { - t.Fatalf("unexpected probe response type 0x%02x", msgType) - } - if _, err := DecodeProbeResp(payload); err != nil { - t.Fatalf("decode probe resp: %v", err) + // Stale probe must NOT receive an echo; conn drops on read. + if _, _, err := ReadMsg(connP); err == nil { + t.Fatalf("stale probe must be rejected without echo; got a response") } - // Continue rebuild on the original conn — must still be accepted. + // Continue rebuild on the original conn — must still be accepted + // (probe was rejected, did not disturb activeLineage). if err := WriteMsg(connA, MsgRebuildBlock, EncodeRebuildBlock(lin, 1, makeData(0xEF))); err != nil { t.Fatalf("rebuild after probe: %v", err) } @@ -291,11 +298,11 @@ func TestFailClosed_ProbeDuringRebuild_DoesNotDisturbActiveLineage(t *testing.T) got0, _ := replica.Read(0) if got0[0] != 0xBE { - t.Fatalf("LBA 0 corrupted by probe: 0x%02x", got0[0]) + t.Fatalf("LBA 0 corrupted by stale probe: 0x%02x", got0[0]) } got1, _ := replica.Read(1) if got1[0] != 0xEF { - t.Fatalf("LBA 1 not applied after probe — probe disturbed lineage: 0x%02x", got1[0]) + t.Fatalf("LBA 1 not applied after stale probe — stale probe disturbed activeLineage: 0x%02x", got1[0]) } } diff --git a/seaweed-block/core/transport/probe_validation_test.go b/seaweed-block/core/transport/probe_validation_test.go new file mode 100644 index 0000000000..f4ae85679d --- /dev/null +++ b/seaweed-block/core/transport/probe_validation_test.go @@ -0,0 +1,226 @@ +package transport + +import ( + "errors" + "net" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// T4c-1 validation tests — replica-side and primary-side lineage +// validation around the new symmetric ProbeReq + ProbeResponse pair. +// +// Replica direction (3 tests): +// - happy: accepted lineage echoes correctly + R/S/H returned +// - stale: rejected; conn closed without echo +// - zeroed: decode fails; handler closes conn without echo +// +// Primary direction (3 tests): +// - happy: full round-trip, lineage echo validated, R/S/H surfaced +// - lineage mismatch: ErrProbeLineageMismatch surfaced via FailReason +// - empty primary (H=0): TargetLSN floored to 1 so wire stays non-zero + +// --- Replica direction --- + +func TestReplica_ProbeReq_AcceptedLineage_EchoesAndReturnsRSH(t *testing.T) { + _, replica, listener := setupPrimaryReplica(t) + // Seed replica with one block so R is non-zero. + data := make([]byte, 4096) + data[0] = 0xAA + replica.ApplyEntry(0, data, 5) + replica.Sync() + + conn, err := net.Dial("tcp", listener.Addr()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(2 * time.Second)) + + probeLineage := RecoveryLineage{SessionID: 11, Epoch: 1, EndpointVersion: 1, TargetLSN: 5} + if err := WriteMsg(conn, MsgProbeReq, EncodeProbeReq(ProbeRequest{Lineage: probeLineage})); err != nil { + t.Fatal(err) + } + msgType, payload, err := ReadMsg(conn) + if err != nil { + t.Fatalf("read resp: %v", err) + } + if msgType != MsgProbeResp { + t.Fatalf("unexpected msg type 0x%02x", msgType) + } + resp, err := DecodeProbeResp(payload) + if err != nil { + t.Fatalf("decode resp: %v", err) + } + if resp.Lineage != probeLineage { + t.Errorf("echoed lineage mismatch: want=%+v got=%+v", probeLineage, resp.Lineage) + } + if resp.SyncedLSN == 0 { + t.Error("expected non-zero SyncedLSN (replica seeded with one block)") + } +} + +func TestReplica_ProbeReq_StaleLineage_Rejected(t *testing.T) { + _, replica, listener := setupPrimaryReplica(t) + + // Establish a higher-epoch active mutating lineage by sending a + // rebuild block first. + highLineage := RecoveryLineage{SessionID: 7, Epoch: 5, EndpointVersion: 5, TargetLSN: 100} + connA, err := net.Dial("tcp", listener.Addr()) + if err != nil { + t.Fatal(err) + } + defer connA.Close() + data := make([]byte, 4096) + data[0] = 0xBE + if err := WriteMsg(connA, MsgRebuildBlock, EncodeRebuildBlock(highLineage, 0, data)); err != nil { + t.Fatal(err) + } + time.Sleep(30 * time.Millisecond) + _ = replica // confirm replica still serves + + // Stale probe at strictly older (epoch, endpointVersion). + stale := RecoveryLineage{SessionID: 99, Epoch: 1, EndpointVersion: 1, TargetLSN: 1} + connP, err := net.Dial("tcp", listener.Addr()) + if err != nil { + t.Fatal(err) + } + defer connP.Close() + if err := WriteMsg(connP, MsgProbeReq, EncodeProbeReq(ProbeRequest{Lineage: stale})); err != nil { + t.Fatal(err) + } + connP.SetReadDeadline(time.Now().Add(500 * time.Millisecond)) + if _, _, err := ReadMsg(connP); err == nil { + t.Fatal("stale probe must NOT receive an echo") + } +} + +func TestReplica_ProbeReq_ZeroedLineage_Rejected(t *testing.T) { + _, _, listener := setupPrimaryReplica(t) + + conn, err := net.Dial("tcp", listener.Addr()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + // Hand-craft a 32B payload that decodes to a zero-lineage — + // the decoder will reject it BEFORE the handler runs, so the + // handler simply closes the conn. + zero := make([]byte, probeReqSize) + if err := WriteMsg(conn, MsgProbeReq, zero); err != nil { + t.Fatal(err) + } + conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond)) + if _, _, err := ReadMsg(conn); err == nil { + t.Fatal("zeroed-lineage probe must NOT receive an echo") + } +} + +// --- Primary direction --- + +func TestExecutor_Probe_Happy(t *testing.T) { + primary, replica, listener := setupPrimaryReplica(t) + // Seed both stores so probe returns nonzero R/H. + for i := uint32(0); i < 3; i++ { + data := make([]byte, 4096) + data[0] = byte(i + 1) + lsn, _ := primary.Write(i, data) + _ = replica.ApplyEntry(i, data, lsn) + } + primary.Sync() + replica.Sync() + + exec := NewBlockExecutor(primary, listener.Addr()) + result := exec.Probe("r1", listener.Addr(), listener.Addr(), 7, 1, 1) + if !result.Success { + t.Fatalf("probe failed: %s", result.FailReason) + } + _, _, pH := primary.Boundaries() + if result.PrimaryHeadLSN != pH { + t.Errorf("PrimaryHeadLSN=%d, want %d", result.PrimaryHeadLSN, pH) + } +} + +// TestExecutor_Probe_LineageMismatch_Rejected runs a custom replica +// listener that intentionally echoes a different lineage than the +// request. Primary must surface ErrProbeLineageMismatch in +// ProbeResult.FailReason and return Success=false. +func TestExecutor_Probe_LineageMismatch_Rejected(t *testing.T) { + primary := storage.NewBlockStore(64, 4096) + // Seed primary so probe lineage TargetLSN is non-zero (H>0). + data := make([]byte, 4096) + data[0] = 1 + primary.Write(0, data) + primary.Sync() + + // Fake replica that echoes a wrong lineage. + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + conn, err := ln.Accept() + if err != nil { + return + } + defer conn.Close() + // Read whatever the primary sent (we don't care about content). + if _, _, err := ReadMsg(conn); err != nil { + return + } + // Echo a deliberately different lineage. + bad := EncodeProbeResp(ProbeResponse{ + Lineage: RecoveryLineage{SessionID: 999, Epoch: 999, EndpointVersion: 999, TargetLSN: 999}, + SyncedLSN: 1, WalTail: 1, WalHead: 1, + }) + _ = WriteMsg(conn, MsgProbeResp, bad) + }() + + exec := NewBlockExecutor(primary, ln.Addr().String()) + result := exec.Probe("r1", ln.Addr().String(), ln.Addr().String(), 7, 1, 1) + wg.Wait() + + if result.Success { + t.Fatal("probe must fail when replica echoes wrong lineage") + } + if !strings.Contains(result.FailReason, ErrProbeLineageMismatch.Error()) { + t.Errorf("FailReason should contain ErrProbeLineageMismatch, got: %s", result.FailReason) + } +} + +// TestExecutor_Probe_EmptyPrimary_TargetLSNFloor pins the architect's +// no-zero-TargetLSN rule: when the primary has no writes (H=0), the +// transient probe lineage's TargetLSN MUST be floored to 1 — the +// wire fails closed on any zero lineage field, so a literal H=0 would +// produce an undeliverable probe. +func TestExecutor_Probe_EmptyPrimary_TargetLSNFloor(t *testing.T) { + primary := storage.NewBlockStore(64, 4096) // empty: H=0 + _, replica, listener := setupPrimaryReplica(t) + _ = replica + + exec := NewBlockExecutor(primary, listener.Addr()) + result := exec.Probe("r1", listener.Addr(), listener.Addr(), 7, 1, 1) + if !result.Success { + t.Fatalf("probe on empty primary must succeed (TargetLSN floor=1): %s", result.FailReason) + } +} + +// Sanity: ErrProbeLineageMismatch is a stable sentinel. +func TestErrProbeLineageMismatch_IsSentinel(t *testing.T) { + if !errors.Is(ErrProbeLineageMismatch, ErrProbeLineageMismatch) { + t.Fatal("sentinel must satisfy errors.Is reflexively") + } + if ErrProbeLineageMismatch.Error() == "" { + t.Fatal("sentinel must have a message") + } +} diff --git a/seaweed-block/core/transport/probe_wire_test.go b/seaweed-block/core/transport/probe_wire_test.go new file mode 100644 index 0000000000..0f66558c23 --- /dev/null +++ b/seaweed-block/core/transport/probe_wire_test.go @@ -0,0 +1,206 @@ +package transport + +import ( + "bytes" + "strings" + "testing" +) + +// T4c-1 wire tests — `EncodeProbeReq` / `DecodeProbeReq` / +// `EncodeProbeResp` / `DecodeProbeResp` round-trip + fail-closed +// fences. Mirrors T4b-1's `TestBarrierResp_*` shape. +// +// Pins per round-26 architect (Item C.3) + round-21 uniform rule: +// - 32B ProbeReq body, 56B ProbeResponse body +// - both directions reject short / zeroed / field-misordered payloads +// - lineage field order inside the slab is canonical +// (SessionID, Epoch, EndpointVersion, TargetLSN) + +func sampleProbeLineage() RecoveryLineage { + return RecoveryLineage{ + SessionID: 42, + Epoch: 7, + EndpointVersion: 3, + TargetLSN: 1000, + } +} + +// --- ProbeReq direction --- + +func TestProbeReq_FullLineage_RoundTrip(t *testing.T) { + want := ProbeRequest{Lineage: sampleProbeLineage()} + got, err := DecodeProbeReq(EncodeProbeReq(want)) + if err != nil { + t.Fatalf("decode: %v", err) + } + if got != want { + t.Errorf("round-trip mismatch:\n want=%+v\n got=%+v", want, got) + } +} + +func TestProbeReq_ExactSize(t *testing.T) { + buf := EncodeProbeReq(ProbeRequest{Lineage: sampleProbeLineage()}) + if len(buf) != probeReqSize { + t.Errorf("EncodeProbeReq length = %d, want %d (architect-locked wire size)", len(buf), probeReqSize) + } +} + +func TestProbeReq_ShortPayload_Rejected(t *testing.T) { + short := make([]byte, probeReqSize-1) + _, err := DecodeProbeReq(short) + if err == nil { + t.Fatal("31-byte payload must be rejected") + } + if !strings.Contains(err.Error(), "short probe request") { + t.Errorf("wrong error: %v", err) + } +} + +func TestProbeReq_ZeroedLineage_Rejected(t *testing.T) { + cases := []struct { + name string + l RecoveryLineage + }{ + {"all_zero", RecoveryLineage{}}, + {"zero_sessionID", RecoveryLineage{Epoch: 1, EndpointVersion: 1, TargetLSN: 1}}, + {"zero_epoch", RecoveryLineage{SessionID: 1, EndpointVersion: 1, TargetLSN: 1}}, + {"zero_endpointVersion", RecoveryLineage{SessionID: 1, Epoch: 1, TargetLSN: 1}}, + {"zero_targetLSN", RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, err := DecodeProbeReq(EncodeProbeReq(ProbeRequest{Lineage: tc.l})) + if err == nil { + t.Fatalf("zeroed lineage %+v must be rejected", tc.l) + } + if !strings.Contains(err.Error(), "zero-valued lineage field") { + t.Errorf("wrong error: %v", err) + } + }) + } +} + +// TestProbeReq_MalformedFieldOrder_Rejected pins canonical lineage +// field order (SessionID, Epoch, EndpointVersion, TargetLSN). A +// payload encoded with a swapped pair MUST be rejected by the +// zero-lineage check when the swap zeroes a field — this is the +// same fence shape as T4b-1's +// `TestBarrierResp_MalformedFieldOrder_Rejected`. +func TestProbeReq_MalformedFieldOrder_Rejected(t *testing.T) { + // Build a payload where the canonical-order fields are + // {SessionID:5, Epoch:0, EndpointVersion:3, TargetLSN:99} — + // epoch slot zero would be caught by the strict-decode rule. + // The malformed field order (e.g. swapping TargetLSN ↔ Epoch) + // is detected indirectly via the zero-lineage rule when a slot + // ends up zeroed. + good := EncodeProbeReq(ProbeRequest{Lineage: sampleProbeLineage()}) + // Zero out the Epoch slot (bytes 8-16) to simulate a misordered + // encode that placed a zero in the epoch position. + bad := make([]byte, len(good)) + copy(bad, good) + for i := 8; i < 16; i++ { + bad[i] = 0 + } + if _, err := DecodeProbeReq(bad); err == nil { + t.Fatal("epoch-zeroed payload must be rejected") + } +} + +// --- ProbeResponse direction --- + +func TestProbeResp_FullLineageEcho_RoundTrip(t *testing.T) { + want := ProbeResponse{ + Lineage: sampleProbeLineage(), + SyncedLSN: 500, + WalTail: 100, + WalHead: 1000, + } + got, err := DecodeProbeResp(EncodeProbeResp(want)) + if err != nil { + t.Fatalf("decode: %v", err) + } + if got != want { + t.Errorf("round-trip mismatch:\n want=%+v\n got=%+v", want, got) + } +} + +func TestProbeResp_ExactSize(t *testing.T) { + buf := EncodeProbeResp(ProbeResponse{ + Lineage: sampleProbeLineage(), + SyncedLSN: 1, WalTail: 1, WalHead: 1, + }) + if len(buf) != probeRespSize { + t.Errorf("EncodeProbeResp length = %d, want %d (architect-locked wire size)", len(buf), probeRespSize) + } +} + +func TestProbeResp_ShortPayload_Rejected(t *testing.T) { + short := make([]byte, probeRespSize-1) + _, err := DecodeProbeResp(short) + if err == nil { + t.Fatal("55-byte payload must be rejected") + } + if !strings.Contains(err.Error(), "short probe response") { + t.Errorf("wrong error: %v", err) + } +} + +func TestProbeResp_ZeroedLineage_Rejected(t *testing.T) { + // All R/S/H values present but lineage zeroed. + buf := EncodeProbeResp(ProbeResponse{ + Lineage: RecoveryLineage{}, + SyncedLSN: 1, WalTail: 1, WalHead: 1, + }) + _, err := DecodeProbeResp(buf) + if err == nil { + t.Fatal("zeroed lineage must be rejected") + } + if !strings.Contains(err.Error(), "zero-valued lineage field") { + t.Errorf("wrong error: %v", err) + } +} + +func TestProbeResp_MalformedFieldOrder_Rejected(t *testing.T) { + // Same fence shape as ProbeReq: zero out a lineage slot inside + // the encoded payload. + good := EncodeProbeResp(ProbeResponse{ + Lineage: sampleProbeLineage(), + SyncedLSN: 5, WalTail: 1, WalHead: 5, + }) + bad := make([]byte, len(good)) + copy(bad, good) + // Zero the EndpointVersion slot (bytes 16-24). + for i := 16; i < 24; i++ { + bad[i] = 0 + } + if _, err := DecodeProbeResp(bad); err == nil { + t.Fatal("endpointVersion-zeroed payload must be rejected") + } +} + +// Regression fence: lineage slab inside ProbeResponse must occupy +// bytes [0..32), with SyncedLSN at [32..40), WalTail at [40..48), +// WalHead at [48..56). Same byte-position fence as T4b-1. +func TestProbeResp_ByteLayoutFence(t *testing.T) { + resp := ProbeResponse{ + Lineage: RecoveryLineage{SessionID: 1, Epoch: 2, EndpointVersion: 3, TargetLSN: 4}, + SyncedLSN: 0xAA, + WalTail: 0xBB, + WalHead: 0xCC, + } + buf := EncodeProbeResp(resp) + expectedLineage := EncodeLineage(resp.Lineage) + if !bytes.Equal(buf[0:32], expectedLineage) { + t.Errorf("lineage slab not at bytes [0..32):\n want=%x\n got=%x", + expectedLineage, buf[0:32]) + } + if buf[32+7] != 0xAA { + t.Errorf("SyncedLSN low byte not at offset 39, got 0x%02x at offset 39", buf[39]) + } + if buf[40+7] != 0xBB { + t.Errorf("WalTail low byte not at offset 47, got 0x%02x at offset 47", buf[47]) + } + if buf[48+7] != 0xCC { + t.Errorf("WalHead low byte not at offset 55, got 0x%02x at offset 55", buf[55]) + } +} diff --git a/seaweed-block/core/transport/protocol.go b/seaweed-block/core/transport/protocol.go index b55a7aaf81..277cb1ca85 100644 --- a/seaweed-block/core/transport/protocol.go +++ b/seaweed-block/core/transport/protocol.go @@ -64,13 +64,51 @@ type ShipEntry struct { Data []byte } -// ProbeResponse carries the replica's recovery boundaries. -type ProbeResponse struct { - SyncedLSN uint64 // R: replica's durable frontier - WalTail uint64 // S: oldest retained - WalHead uint64 // H: newest written +// ProbeRequest is the typed body of `MsgProbeReq` post-T4c-1. Carries the +// full `RecoveryLineage` of the probe attempt so the replica can validate +// who is asking. Per architect round-26 (Item C.3) the wire MUST carry +// every authority-bearing field — this is the request-side half of the +// symmetric pair (`ProbeResponse` is the response-side half). +// +// Probe lineage is **transient** — minted by the adapter (parallel to +// `FenceAtEpoch`), NOT registered in `executor.sessions`, NOT represented +// in engine session truth. See `feedback_t4c_probe_lineage_option_d.md` +// (architect Option D resolution). +// +// Wire (T4c-1): [32B lineage (SessionID, Epoch, EndpointVersion, TargetLSN)] — 32 bytes. +type ProbeRequest struct { + Lineage RecoveryLineage } +// ProbeResponse carries the replica's recovery boundaries plus the echoed +// request lineage (T4c-1; per architect round-26 Item C.3). +// +// Wire (T4c-1): +// +// [32B echoed lineage][8B SyncedLSN][8B WalTail][8B WalHead] — 56 bytes. +// +// Strict decode is fail-closed (round-21 uniform rule, mirrored from +// `BarrierResponse`): payloads shorter than 56 bytes, zero-valued lineage +// fields, or field-misordered lineage slabs are rejected. Primary-side +// consumer (`BlockExecutor.Probe`) MUST reject responses whose echoed +// lineage does not match the request lineage; mismatches return +// `ErrProbeLineageMismatch` and MUST NOT contribute to recovery facts. +type ProbeResponse struct { + Lineage RecoveryLineage // echoed from request — primary validates exact match + SyncedLSN uint64 // R: replica's durable frontier + WalTail uint64 // S: oldest retained + WalHead uint64 // H: newest written +} + +// probeReqSize / probeRespSize are the exact byte lengths of valid +// encoded probe payloads. Short, over-long, or field-misordered payloads +// are rejected by the decoders and MUST NOT contribute to recovery +// decisions (architect round-21 uniform rule, T4b-1 BarrierResp shape). +const ( + probeReqSize = 32 // [32B lineage] + probeRespSize = 56 // [32B lineage][8B R][8B S][8B H] +) + // --- Wire helpers --- // WriteMsg sends a typed message on the connection. @@ -185,25 +223,78 @@ func DecodeShipEntry(buf []byte) (ShipEntry, error) { }, nil } -// EncodeProbeResp serializes a probe response. -// Wire: [8B syncedLSN][8B walTail][8B walHead] -func EncodeProbeResp(p ProbeResponse) []byte { - buf := make([]byte, 24) - binary.BigEndian.PutUint64(buf[0:8], p.SyncedLSN) - binary.BigEndian.PutUint64(buf[8:16], p.WalTail) - binary.BigEndian.PutUint64(buf[16:24], p.WalHead) +// EncodeProbeReq serializes a probe request (T4c-1 wire shape). +// Wire: [32B lineage (SessionID, Epoch, EndpointVersion, TargetLSN)] +func EncodeProbeReq(p ProbeRequest) []byte { + buf := make([]byte, probeReqSize) + copy(buf[0:32], EncodeLineage(p.Lineage)) return buf } -// DecodeProbeResp deserializes a probe response. +// DecodeProbeReq deserializes a probe request. Strict and fail-closed +// per round-21 uniform rule (mirrored from `DecodeBarrierResp`): +// - payloads shorter than 32 bytes are invalid +// - zero-valued lineage fields are invalid (catches partially- +// initialized-struct drift; replica's acceptMutationLineage already +// rejects zeros, but the wire fails closed before the handler runs) +// - exact field order inside the lineage slab must be +// SessionID, Epoch, EndpointVersion, TargetLSN +// +// Replica handler MUST treat any error return as "no valid probe" and +// MUST close the conn without echoing — a malformed request cannot +// produce a response that the primary can validate. +func DecodeProbeReq(buf []byte) (ProbeRequest, error) { + if len(buf) < probeReqSize { + return ProbeRequest{}, fmt.Errorf("transport: short probe request: %d bytes, want %d", + len(buf), probeReqSize) + } + lineage, err := DecodeLineage(buf[0:32]) + if err != nil { + return ProbeRequest{}, fmt.Errorf("transport: probe request lineage decode: %w", err) + } + if lineage.SessionID == 0 || lineage.Epoch == 0 || + lineage.EndpointVersion == 0 || lineage.TargetLSN == 0 { + return ProbeRequest{}, fmt.Errorf("transport: probe request has zero-valued lineage field (sessionID=%d epoch=%d endpointVersion=%d targetLSN=%d)", + lineage.SessionID, lineage.Epoch, lineage.EndpointVersion, lineage.TargetLSN) + } + return ProbeRequest{Lineage: lineage}, nil +} + +// EncodeProbeResp serializes a probe response (T4c-1 wire shape). +// Wire: [32B echoed lineage][8B syncedLSN][8B walTail][8B walHead] +func EncodeProbeResp(p ProbeResponse) []byte { + buf := make([]byte, probeRespSize) + copy(buf[0:32], EncodeLineage(p.Lineage)) + binary.BigEndian.PutUint64(buf[32:40], p.SyncedLSN) + binary.BigEndian.PutUint64(buf[40:48], p.WalTail) + binary.BigEndian.PutUint64(buf[48:56], p.WalHead) + return buf +} + +// DecodeProbeResp deserializes a probe response. Strict and fail-closed +// per round-21 uniform rule (mirrored from `DecodeBarrierResp`). +// Primary-side consumer MUST additionally validate the echoed lineage +// against the request lineage (`ErrProbeLineageMismatch`) — the decoder +// only enforces well-formed payload, not lineage-match. func DecodeProbeResp(buf []byte) (ProbeResponse, error) { - if len(buf) < 24 { - return ProbeResponse{}, fmt.Errorf("transport: short probe response") + if len(buf) < probeRespSize { + return ProbeResponse{}, fmt.Errorf("transport: short probe response: %d bytes, want %d", + len(buf), probeRespSize) + } + lineage, err := DecodeLineage(buf[0:32]) + if err != nil { + return ProbeResponse{}, fmt.Errorf("transport: probe response lineage decode: %w", err) + } + if lineage.SessionID == 0 || lineage.Epoch == 0 || + lineage.EndpointVersion == 0 || lineage.TargetLSN == 0 { + return ProbeResponse{}, fmt.Errorf("transport: probe response has zero-valued lineage field (sessionID=%d epoch=%d endpointVersion=%d targetLSN=%d)", + lineage.SessionID, lineage.Epoch, lineage.EndpointVersion, lineage.TargetLSN) } return ProbeResponse{ - SyncedLSN: binary.BigEndian.Uint64(buf[0:8]), - WalTail: binary.BigEndian.Uint64(buf[8:16]), - WalHead: binary.BigEndian.Uint64(buf[16:24]), + Lineage: lineage, + SyncedLSN: binary.BigEndian.Uint64(buf[32:40]), + WalTail: binary.BigEndian.Uint64(buf[40:48]), + WalHead: binary.BigEndian.Uint64(buf[48:56]), }, nil } diff --git a/seaweed-block/core/transport/protocol_test.go b/seaweed-block/core/transport/protocol_test.go index 18ddb7374e..c628b3f500 100644 --- a/seaweed-block/core/transport/protocol_test.go +++ b/seaweed-block/core/transport/protocol_test.go @@ -61,8 +61,11 @@ func TestProtocol_EnvelopeRoundTrip(t *testing.T) { LSN: 10, Data: bytes.Repeat([]byte{0xAB}, 4096), })}, - {"MsgProbeReq", MsgProbeReq, nil}, + {"MsgProbeReq", MsgProbeReq, EncodeProbeReq(ProbeRequest{ + Lineage: RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 10}, + })}, {"MsgProbeResp", MsgProbeResp, EncodeProbeResp(ProbeResponse{ + Lineage: RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 10}, SyncedLSN: 100, WalTail: 1, WalHead: 100, })}, {"MsgRebuildBlock", MsgRebuildBlock, EncodeRebuildBlock( diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 24ce995219..f693da7a2d 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -104,8 +104,35 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { } case MsgProbeReq: + // T4c-1 wire upgrade: ProbeReq now carries full + // RecoveryLineage. Decode + validate + echo per round-26 + // symmetric-pair rule. Failure to decode (short / zeroed + // lineage) closes the conn without echoing — the primary + // times out + treats as unreachable, which is the correct + // fail-closed surface. + // + // Probe is non-mutating: validation gates zeros and clearly + // stale lineages but MUST NOT advance `activeLineage`. + // Advancing activeLineage from a probe would cause a + // later catch-up / rebuild session at a lower sessionID + // (but same epoch / endpointVersion) to be incorrectly + // rejected as stale — probes monotonically advance + // sessionID via the adapter's global counter, so they + // would routinely race ahead of in-flight session IDs. + // Use `validateProbeLineage` instead. + req, err := DecodeProbeReq(payload) + if err != nil { + log.Printf("replica: decode probe req: %v", err) + return + } + if !r.validateProbeLineage(req.Lineage) { + log.Printf("replica: reject stale probe session=%d epoch=%d endpointVersion=%d", + req.Lineage.SessionID, req.Lineage.Epoch, req.Lineage.EndpointVersion) + return + } R, S, H := r.store.Boundaries() resp := EncodeProbeResp(ProbeResponse{ + Lineage: req.Lineage, // echo per round-26 Item C.3 SyncedLSN: R, WalTail: S, WalHead: H, @@ -192,6 +219,46 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { } } +// validateProbeLineage gates probe lineages: rejects zeros and clearly +// stale tuples (older epoch / endpointVersion than activeLineage), but +// does NOT advance activeLineage. Probe is non-mutating; activeLineage +// belongs to mutating-flow tracking only. +// +// Stale rule: probe is rejected only when its (epoch, endpointVersion) +// pair is strictly older than activeLineage's. SessionID alone does +// NOT determine staleness for probes — probe sessionIDs come from a +// monotonic adapter counter and routinely outpace in-flight session +// IDs at the same (epoch, endpointVersion). A probe at the same +// (epoch, endpointVersion) as activeLineage is always accepted for +// echo, regardless of sessionID ordering. +// +// Called by: replica's MsgProbeReq handler (T4c-1). +// Owns: the read of activeLineage; no writes. +// Borrows: nothing. +func (r *ReplicaListener) validateProbeLineage(incoming RecoveryLineage) bool { + if incoming.SessionID == 0 || incoming.Epoch == 0 || + incoming.EndpointVersion == 0 || incoming.TargetLSN == 0 { + return false + } + r.mu.Lock() + active := r.activeLineage + r.mu.Unlock() + if active.SessionID == 0 { + // No active mutating lineage yet — any well-formed probe is + // acceptable for echo. + return true + } + // Reject only on strictly-older (epoch, endpointVersion). Same + // epoch / endpointVersion is accepted regardless of sessionID. + if incoming.Epoch < active.Epoch { + return false + } + if incoming.Epoch == active.Epoch && incoming.EndpointVersion < active.EndpointVersion { + return false + } + return true +} + func (r *ReplicaListener) acceptMutationLineage(incoming RecoveryLineage) bool { r.mu.Lock() defer r.mu.Unlock() diff --git a/seaweed-block/core/transport/transport_test.go b/seaweed-block/core/transport/transport_test.go index 929db6ede3..68d4c4aff3 100644 --- a/seaweed-block/core/transport/transport_test.go +++ b/seaweed-block/core/transport/transport_test.go @@ -61,7 +61,8 @@ func TestTransport_Healthy_ProbeShowsCaughtUp(t *testing.T) { replica.Sync() exec := NewBlockExecutor(primary, listener.Addr()) - result := exec.Probe("r1", listener.Addr(), listener.Addr(), 1, 1) + // T4c-1: Probe takes a transient adapter-minted sessionID. + result := exec.Probe("r1", listener.Addr(), listener.Addr(), 99, 1, 1) if !result.Success { t.Fatalf("probe failed: %s", result.FailReason)