P14 S1: proactive R>=H fence with ack-gated healthy publication

Adds an explicit FenceAtEpoch command + FenceCompleted/FenceFailed
event pair on the caught-up recovery branch. A replica with R >= H
under a newer identity epoch is no longer declared healthy until the
replica's lineage gate has been bumped to match Identity.Epoch via a
FenceCompleted — closing the window where stale old-epoch traffic
could still land on the replica while the projection already reads
healthy.

Contract surface:
  * Caught-up path emits ONLY FenceAtEpoch — no catch-up / no rebuild.
    Fence is a command+event pair, not a session lifecycle.
  * PublishHealthy held until FenceCompleted advances FencedEpoch.
    Publication and DeriveProjection both gate on this so the
    operator-visible mode reflects the ack-gated contract, not
    just the command stream.
  * FenceFailed is fail-closed: FencedEpoch is NOT advanced; retry
    is probe-driven (next successful probe re-runs decide() and
    re-emits FenceAtEpoch).
  * Session completion (catch-up / rebuild) implicitly fences,
    because mutating traffic at the current epoch already bumped
    the replica's gate.
  * Stale FenceCompleted (epoch < Identity.Epoch, or same epoch
    with older endpointVersion) is rejected without mutating state.
  * FencedEpoch is engine-internal; NOT exposed in ReplicaProjection.

Adapter-side fence dispatch:
  * fenceInFlight keyed by fence LINEAGE
    (replicaID, epoch, endpointVersion), NOT by replicaID alone.
    This prevents a newer-epoch fence from being starved by an
    older in-flight fence — both occupy distinct slots, the old
    one is dropped by the engine as stale when its callback lands,
    and the newer one drives publication to healthy without
    waiting for an unrelated later probe.

Proof tests:
  * engine: TestFence_CaughtUpPath_UsesNoDataRecovery
  * engine: TestFence_HealthyOnlyAfterFenceComplete
  * engine: TestFence_FailureLeavesFencedEpochUnchanged
  * engine: TestFence_StaleOldEpochRejectedAfterFenceOnCaughtUp
  * adapter: TestFullRoute_CaughtUp_NotHealthyUntilFenceComplete
  * adapter: TestFence_NewerEpochNotStarvedByOlderInFlightFence

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
wzcheng99andClaude Opus 4.7 committed 2026-04-17 16:29:23 -07:00
1 parent 2f07922234
commit dec084485b
15 files changed
+1157 -40

No files matched your search

+147
View File
@@ -33,6 +33,36 @@ type VolumeReplicaAdapter struct {
startTimeout time.Duration
startWatchdogs map[uint64]*time.Timer
watchdogLog []WatchdogEvent
// fenceInFlight: at most one fence attempt outstanding per
// fence LINEAGE — keyed by (replicaID, epoch, endpointVersion).
// Value is the sessionID of the in-flight fence; used to match
// the returning FenceResult to the live attempt and drop
// callbacks for superseded attempts.
//
// IMPORTANT: keying by lineage (not by replicaID alone) prevents
// a newer-epoch fence from being starved by an older in-flight
// fence. If identity advances mid-fence, decide() emits a new
// FenceAtEpoch at the new lineage — which occupies its own slot
// and is dispatched in parallel with the older one. The older
// callback is dropped by the engine as stale
// (applyFenceCompleted checks e.Epoch >= Identity.Epoch); the
// newer one advances FencedEpoch normally.
//
// Same-lineage duplicates (engine re-emits FenceAtEpoch at the
// same (epoch, endpointVersion) on a later probe while the
// first attempt is still pending) are dropped by the slot check.
fenceInFlight map[fenceKey]uint64
}
// fenceKey is the lineage key for fence dedupe. Two fence attempts
// are "the same attempt" iff their (replicaID, epoch, endpointVersion)
// tuples are equal. Newer-epoch fences therefore never dedupe against
// older-epoch fences and cannot be starved by them.
type fenceKey struct {
replicaID string
epoch uint64
endpointVersion uint64
}
var sessionIDCounter atomic.Uint64
@@ -52,6 +82,7 @@ func NewVolumeReplicaAdapter(exec CommandExecutor) *VolumeReplicaAdapter {
executor: exec,
startTimeout: defaultSessionStartTimeout,
startWatchdogs: make(map[uint64]*time.Timer),
fenceInFlight: make(map[fenceKey]uint64),
}
exec.SetOnSessionStart(func(result SessionStartResult) {
a.OnSessionStart(result)
@@ -60,6 +91,10 @@ func NewVolumeReplicaAdapter(exec CommandExecutor) *VolumeReplicaAdapter {
exec.SetOnSessionClose(func(result SessionCloseResult) {
a.OnSessionClose(result)
})
// Wire the fence callback: executor → adapter.OnFenceComplete → engine.
exec.SetOnFenceComplete(func(result FenceResult) {
a.OnFenceComplete(result)
})
return a
}
@@ -91,6 +126,85 @@ func (a *VolumeReplicaAdapter) OnSessionStart(result SessionStartResult) ApplyLo
return a.applyBatchAndExecute([]engine.Event{NormalizeSessionStart(result)}, "SessionStart")
}
// OnFenceComplete processes a fence outcome from the transport.
// Releases the in-flight slot (keyed by lineage) and normalizes to
// FenceCompleted (success) or FenceFailed (failure) into the engine.
// Callbacks whose (replicaID, epoch, endpointVersion) are not tracked,
// or whose sessionID does not match the tracked attempt for that
// lineage (e.g. a late straggler after the slot was reassigned by an
// explicit clear), are dropped silently.
func (a *VolumeReplicaAdapter) OnFenceComplete(result FenceResult) ApplyLog {
key := fenceKey{
replicaID: result.ReplicaID,
epoch: result.Epoch,
endpointVersion: result.EndpointVersion,
}
a.mu.Lock()
trackedSessionID, ok := a.fenceInFlight[key]
if ok && trackedSessionID == result.SessionID {
delete(a.fenceInFlight, key)
}
a.mu.Unlock()
if !ok || trackedSessionID != result.SessionID {
// Superseded / late callback: drop silently. The engine
// already moved on (or never expected this attempt).
return ApplyLog{EventKind: "fence_callback_dropped"}
}
var ev engine.Event
if result.Success {
ev = engine.FenceCompleted{
ReplicaID: result.ReplicaID,
Epoch: result.Epoch,
EndpointVersion: result.EndpointVersion,
}
} else {
ev = engine.FenceFailed{
ReplicaID: result.ReplicaID,
Epoch: result.Epoch,
EndpointVersion: result.EndpointVersion,
Reason: result.FailReason,
}
}
return a.applyBatchAndExecute([]engine.Event{ev}, "FenceComplete")
}
// acquireFenceSlot atomically claims the fence slot for the full
// fence lineage (replicaID, epoch, endpointVersion). Returns false
// if a fence at the SAME lineage is already running — the duplicate
// FenceAtEpoch command from the engine (e.g. re-emitted on a later
// probe while the first attempt is still pending) is dropped.
//
// Critically, a fence at a DIFFERENT lineage (newer epoch or newer
// endpoint) acquires its own slot and is dispatched — it is NOT
// starved by an older in-flight fence. This is the bounded-closure
// fix for the "newer-epoch fence dropped behind older in-flight"
// linger bug.
func (a *VolumeReplicaAdapter) acquireFenceSlot(replicaID string, epoch, endpointVersion, sessionID uint64) bool {
a.mu.Lock()
defer a.mu.Unlock()
key := fenceKey{
replicaID: replicaID,
epoch: epoch,
endpointVersion: endpointVersion,
}
if _, inFlight := a.fenceInFlight[key]; inFlight {
return false
}
a.fenceInFlight[key] = sessionID
return true
}
func (a *VolumeReplicaAdapter) releaseFenceSlot(replicaID string, epoch, endpointVersion uint64) {
a.mu.Lock()
defer a.mu.Unlock()
key := fenceKey{
replicaID: replicaID,
epoch: epoch,
endpointVersion: endpointVersion,
}
delete(a.fenceInFlight, key)
}
// Projection returns the current operator-facing projection.
func (a *VolumeReplicaAdapter) Projection() engine.ReplicaProjection {
a.mu.Lock()
@@ -196,6 +310,14 @@ func (a *VolumeReplicaAdapter) prepareQueuedCommands(cmds []engine.Command) ([]e
NormalizeSessionPrepared(c.ReplicaID, sid, engine.SessionRebuild, c.TargetLSN),
)
queued = append(queued, queuedCommand{cmd: cmd, sessionID: sid})
case engine.FenceAtEpoch:
// Fence mints its own sessionID so the lineage wire frame
// carries a unique tuple. No SessionPrepared event —
// fence does NOT go through the session lifecycle
// (no Starting/Running/Completed phases), it's a
// command + event pair.
sid := sessionIDCounter.Add(1)
queued = append(queued, queuedCommand{cmd: cmd, sessionID: sid})
default:
queued = append(queued, queuedCommand{cmd: cmd})
}
@@ -244,6 +366,31 @@ func (a *VolumeReplicaAdapter) executeCommand(q queuedCommand) {
case engine.PublishDegraded:
a.executor.PublishDegraded(c.ReplicaID, c.Reason)
case engine.FenceAtEpoch:
// Dedupe keyed by full fence lineage (replicaID, epoch,
// endpointVersion). Same-lineage duplicates (engine
// re-emits on a later probe) are dropped. Different-
// lineage attempts (e.g. newer epoch after identity
// advance) claim their own slot — the older in-flight
// fence does NOT starve them.
if !a.acquireFenceSlot(c.ReplicaID, c.Epoch, c.EndpointVersion, q.sessionID) {
return
}
err := a.executor.Fence(c.ReplicaID, q.sessionID, c.Epoch, c.EndpointVersion)
if err != nil {
// Synchronous dispatch failure — normalize to
// FenceFailed and release this lineage's slot.
a.releaseFenceSlot(c.ReplicaID, c.Epoch, c.EndpointVersion)
a.OnFenceComplete(FenceResult{
ReplicaID: c.ReplicaID,
SessionID: q.sessionID,
Epoch: c.Epoch,
EndpointVersion: c.EndpointVersion,
Success: false,
FailReason: fmt.Sprintf("fence_dispatch_failed: %v", err),
})
}
}
}
+292 -14
View File
@@ -13,17 +13,28 @@ import (
// mockExecutor records commands and wires the session close callback.
type mockExecutor struct {
mu sync.Mutex
probeResults map[string]ProbeResult
commands []string
nextSession atomic.Uint64
onSessionStart OnSessionStart
onSessionClose OnSessionClose // wired by adapter
autoStart bool
autoClose bool
catchUpErr error
rebuildErr error
starts []startRecord
mu sync.Mutex
probeResults map[string]ProbeResult
commands []string
nextSession atomic.Uint64
onSessionStart OnSessionStart
onSessionClose OnSessionClose // wired by adapter
onFenceComplete OnFenceComplete
autoStart bool
autoClose bool
autoFence bool // fire OnFenceComplete(Success=true) on Fence()
catchUpErr error
rebuildErr error
fenceErr error
starts []startRecord
fences []fenceRecord
}
type fenceRecord struct {
replicaID string
sessionID uint64
epoch uint64
endpointVersion uint64
}
type startRecord struct {
@@ -36,6 +47,7 @@ func newMockExecutor() *mockExecutor {
probeResults: make(map[string]ProbeResult),
autoStart: true,
autoClose: true,
autoFence: true,
}
m.nextSession.Store(100)
return m
@@ -53,6 +65,53 @@ func (m *mockExecutor) SetOnSessionClose(fn OnSessionClose) {
m.onSessionClose = fn
}
func (m *mockExecutor) SetOnFenceComplete(fn OnFenceComplete) {
m.mu.Lock()
defer m.mu.Unlock()
m.onFenceComplete = fn
}
func (m *mockExecutor) Fence(replicaID string, sessionID, epoch, endpointVersion uint64) error {
m.mu.Lock()
m.commands = append(m.commands, "Fence")
m.fences = append(m.fences, fenceRecord{
replicaID: replicaID, sessionID: sessionID,
epoch: epoch, endpointVersion: endpointVersion,
})
cb := m.onFenceComplete
auto := m.autoFence
errVal := m.fenceErr
m.mu.Unlock()
if errVal != nil {
return errVal
}
if auto && cb != nil {
// Sync callback: deterministic mock — no goroutine. Real
// transport is async; the unit-test mock fires inline so
// tests can read projection without arbitrary sleeps.
cb(FenceResult{
ReplicaID: replicaID,
SessionID: sessionID,
Epoch: epoch,
EndpointVersion: endpointVersion,
Success: true,
})
}
return nil
}
// fireFence triggers the registered fence callback manually — used
// by tests that need to control fence outcome timing.
func (m *mockExecutor) fireFence(result FenceResult) {
m.mu.Lock()
cb := m.onFenceComplete
m.mu.Unlock()
if cb != nil {
cb(result)
}
}
func (m *mockExecutor) Probe(replicaID, dataAddr, ctrlAddr string, epoch, endpointVersion uint64) ProbeResult {
m.mu.Lock()
defer m.mu.Unlock()
@@ -521,7 +580,22 @@ func TestTerminal_OnlySessionCloseProducesHealthy(t *testing.T) {
// --- Already caught up: no session needed ---
func TestFullRoute_AlreadyCaughtUp(t *testing.T) {
// P14 S1: caught-up under a new identity epoch is NOT
// immediately healthy. The engine emits FenceAtEpoch and
// holds publication at not-healthy until FenceCompleted
// advances the replica's lineage gate. With autoFence=true on
// the mock, the fence fires inline synchronously, so the
// sequence is: probe → fence command → fence completes →
// publication flips to healthy.
exec := newMockExecutor()
// Register success for the background probe triggered by
// OnAssignment so it doesn't race the manual OnProbeResult
// below with a ProbeFailed that would clobber reachability.
exec.probeResults["r1"] = ProbeResult{
ReplicaID: "r1", Success: true,
EndpointVersion: 1, TransportEpoch: 1,
ReplicaFlushedLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100,
}
a := NewVolumeReplicaAdapter(exec)
a.OnAssignment(AssignmentInfo{
@@ -529,16 +603,220 @@ func TestFullRoute_AlreadyCaughtUp(t *testing.T) {
Epoch: 1, EndpointVersion: 1,
DataAddr: "a", CtrlAddr: "b",
})
// Let the background probe finish.
time.Sleep(30 * time.Millisecond)
a.OnProbeResult(ProbeResult{
// autoFence completed synchronously during dispatch; projection
// must now be healthy.
p := a.Projection()
if p.Mode != engine.ModeHealthy {
t.Fatalf("caught up + auto-fence: expected healthy, got %s", p.Mode)
}
}
// TestFullRoute_CaughtUp_NotHealthyUntilFenceComplete proves the
// ack-gated contract at the operator-visible surface: if the fence
// is still in flight (fence callback has not fired), Mode must NOT
// be ModeHealthy. This is the test the architect called out — P14
// S1's contract is operator-visible, not just command-list-level.
func TestFullRoute_CaughtUp_NotHealthyUntilFenceComplete(t *testing.T) {
exec := newMockExecutor()
exec.autoFence = false // hold the fence callback
// Pre-register a caught-up probe result so the background probe
// triggered by OnAssignment drives the full route on its own.
// Avoids racing a failing background probe against a manual
// ProbeSucceeded.
exec.probeResults["r1"] = ProbeResult{
ReplicaID: "r1", Success: true,
EndpointVersion: 1, TransportEpoch: 1,
ReplicaFlushedLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100,
}
a := NewVolumeReplicaAdapter(exec)
a.OnAssignment(AssignmentInfo{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 1, EndpointVersion: 1,
DataAddr: "a", CtrlAddr: "b",
})
// Wait for the background probe → fence dispatch chain to settle.
// autoFence=false guarantees the fence stays in flight.
deadline := time.Now().Add(500 * time.Millisecond)
for time.Now().Before(deadline) {
exec.mu.Lock()
n := len(exec.fences)
exec.mu.Unlock()
if n == 1 {
break
}
time.Sleep(10 * time.Millisecond)
}
// Fence was dispatched but not completed — projection must
// NOT be healthy. Must also not be degraded (nothing's wrong).
p := a.Projection()
if p.Mode == engine.ModeHealthy {
t.Fatalf("fence not yet complete: Mode must not be healthy, got %s", p.Mode)
}
if p.Mode == engine.ModeDegraded {
t.Fatalf("fence pending is transitional, not degraded, got %s", p.Mode)
}
// Expected: ModeRecovering (transitional, waiting on fence).
if p.Mode != engine.ModeRecovering {
t.Fatalf("fence pending should show recovering, got %s", p.Mode)
}
// Find the in-flight fence and fire a success callback.
exec.mu.Lock()
if len(exec.fences) != 1 {
exec.mu.Unlock()
t.Fatalf("expected 1 fence in flight, got %d", len(exec.fences))
}
fr := exec.fences[0]
exec.mu.Unlock()
exec.fireFence(FenceResult{
ReplicaID: fr.replicaID,
SessionID: fr.sessionID,
Epoch: fr.epoch,
EndpointVersion: fr.endpointVersion,
Success: true,
})
p := a.Projection()
// Now projection must be healthy.
p = a.Projection()
if p.Mode != engine.ModeHealthy {
t.Fatalf("already caught up: expected healthy, got %s", p.Mode)
t.Fatalf("after fence complete: expected healthy, got %s", p.Mode)
}
}
// TestFence_NewerEpochNotStarvedByOlderInFlightFence — regression
// test for the adapter's fence dedupe key. If the dedupe is keyed
// only by replicaID, a newer-epoch fence emitted after an identity
// advance is dropped while the older fence is still in flight. The
// old callback then arrives, gets normalized to a FenceCompleted
// event at the old epoch, which the engine rejects as stale — and
// nothing re-drives decide() for the new epoch. Result: the replica
// lingers non-healthy until some unrelated later probe happens.
//
// The fix keys dedupe by full fence lineage (replicaID, epoch,
// endpointVersion). This test proves: after identity advances with
// an older fence still in flight, the newer-epoch fence is
// dispatched to the executor (NOT starved), and publishing healthy
// depends only on the newer fence completing.
func TestFence_NewerEpochNotStarvedByOlderInFlightFence(t *testing.T) {
exec := newMockExecutor()
exec.autoFence = false // hold all fence callbacks
// Caught-up probe at epoch=1.
exec.probeResults["r1"] = ProbeResult{
ReplicaID: "r1", Success: true,
EndpointVersion: 1, TransportEpoch: 1,
ReplicaFlushedLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100,
}
a := NewVolumeReplicaAdapter(exec)
a.OnAssignment(AssignmentInfo{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 1, EndpointVersion: 1,
DataAddr: "a", CtrlAddr: "b",
})
// Wait for the first fence to be dispatched but not completed.
deadline := time.Now().Add(500 * time.Millisecond)
for time.Now().Before(deadline) {
exec.mu.Lock()
n := len(exec.fences)
exec.mu.Unlock()
if n == 1 {
break
}
time.Sleep(10 * time.Millisecond)
}
exec.mu.Lock()
if len(exec.fences) != 1 {
exec.mu.Unlock()
t.Fatalf("expected 1 in-flight fence at epoch 1, got %d", len(exec.fences))
}
oldFence := exec.fences[0]
exec.mu.Unlock()
if oldFence.epoch != 1 || oldFence.endpointVersion != 1 {
t.Fatalf("old fence at wrong lineage: epoch=%d ev=%d",
oldFence.epoch, oldFence.endpointVersion)
}
// Identity advances to epoch=2 before the old fence completes.
// Update the pre-registered probe result so the background probe
// triggered by the new assignment returns epoch=2 boundaries.
exec.mu.Lock()
exec.probeResults["r1"] = ProbeResult{
ReplicaID: "r1", Success: true,
EndpointVersion: 2, TransportEpoch: 2,
ReplicaFlushedLSN: 200, PrimaryTailLSN: 20, PrimaryHeadLSN: 200,
}
exec.mu.Unlock()
a.OnAssignment(AssignmentInfo{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 2, EndpointVersion: 2,
DataAddr: "a2", CtrlAddr: "b2",
})
// Wait for the newer-epoch fence to be dispatched.
deadline = time.Now().Add(500 * time.Millisecond)
for time.Now().Before(deadline) {
exec.mu.Lock()
n := len(exec.fences)
exec.mu.Unlock()
if n >= 2 {
break
}
time.Sleep(10 * time.Millisecond)
}
exec.mu.Lock()
n := len(exec.fences)
var newFence fenceRecord
if n >= 2 {
newFence = exec.fences[1]
}
exec.mu.Unlock()
if n < 2 {
t.Fatalf("newer-epoch fence was starved by older in-flight fence — still only %d fence(s) dispatched",
n)
}
if newFence.epoch != 2 || newFence.endpointVersion != 2 {
t.Fatalf("new fence at wrong lineage: epoch=%d ev=%d",
newFence.epoch, newFence.endpointVersion)
}
// Projection must not be healthy yet — the newer fence is still
// in flight and the old one would be stale even if it arrived.
if got := a.Projection().Mode; got == engine.ModeHealthy {
t.Fatalf("mode flipped Healthy before newer-epoch fence completed, got %s", got)
}
// Fire the NEW fence success callback. This must drive the
// replica to healthy under the new lineage.
exec.fireFence(FenceResult{
ReplicaID: newFence.replicaID,
SessionID: newFence.sessionID,
Epoch: newFence.epoch,
EndpointVersion: newFence.endpointVersion,
Success: true,
})
if got := a.Projection().Mode; got != engine.ModeHealthy {
t.Fatalf("after newer-epoch fence complete: expected healthy, got %s", got)
}
if got := a.Projection().Epoch; got != 2 {
t.Fatalf("projection epoch=%d, want 2", got)
}
// Late straggler: the OLD fence callback finally arrives. It
// must be dropped without disturbing the already-healthy state.
exec.fireFence(FenceResult{
ReplicaID: oldFence.replicaID,
SessionID: oldFence.sessionID,
Epoch: oldFence.epoch,
EndpointVersion: oldFence.endpointVersion,
Success: true,
})
if got := a.Projection().Mode; got != engine.ModeHealthy {
t.Fatalf("late old-epoch callback perturbed healthy state, mode=%s", got)
}
}
+31
View File
@@ -46,6 +46,21 @@ type CommandExecutor interface {
// PublishDegraded reports this replica as degraded.
PublishDegraded(replicaID string, reason string)
// Fence runs a one-barrier exchange at the given lineage
// (epoch, endpointVersion, sessionID). No catch-up, no
// rebuild — a single MsgBarrierReq that the replica accepts
// (advancing its activeLineage) or rejects. Runs
// asynchronously; outcome MUST be reported via the registered
// OnFenceComplete callback exactly once.
Fence(replicaID string, sessionID, epoch, endpointVersion uint64) error
// SetOnFenceComplete registers the callback for fence outcomes.
// Success=true means the replica acked at this epoch;
// Success=false with FailReason means the fence did not
// complete. Retry is probe-driven — the callback MUST NOT
// retry internally.
SetOnFenceComplete(fn OnFenceComplete)
}
// OnSessionClose is the callback signature for session completion/failure.
@@ -57,3 +72,19 @@ type OnSessionClose func(SessionCloseResult)
// The adapter registers this with the executor so SessionStarted is
// tied to actual execution start instead of command issuance alone.
type OnSessionStart func(SessionStartResult)
// OnFenceComplete is the callback signature for FenceAtEpoch outcomes.
// Fires exactly once per Fence call. Success=true advances
// Reachability.FencedEpoch; Success=false leaves it unchanged and
// relies on the next probe to re-trigger.
type OnFenceComplete func(FenceResult)
// FenceResult is the fence outcome reported back to the adapter.
type FenceResult struct {
ReplicaID string
SessionID uint64
Epoch uint64
EndpointVersion uint64
Success bool
FailReason string
}
+6 -2
View File
@@ -54,7 +54,7 @@ cases:
must_not_emit_commands: [StartCatchUp]
- name: "caught_up_healthy"
description: "R >= H → no recovery, PublishHealthy emitted"
description: "R >= H → FenceAtEpoch first; PublishHealthy only after FenceCompleted"
events:
- kind: AssignmentObserved
volume_id: vol1
@@ -72,10 +72,14 @@ cases:
r: 100
s: 10
h: 100
- kind: FenceCompleted
replica_id: r1
epoch: 1
endpoint_version: 1
expect:
mode: healthy
recovery_decision: none
must_emit_commands: [PublishHealthy]
must_emit_commands: [FenceAtEpoch, PublishHealthy]
must_not_emit_commands: [StartCatchUp, StartRebuild]
- name: "stale_epoch_rejected"
+95 -5
View File
@@ -91,6 +91,16 @@ func Apply(st *ReplicaState, ev Event) ApplyResult {
break
}
applySessionInvalidated(st, e, &result, trace)
case FenceCompleted:
if !checkReplicaID(st, e.ReplicaID, &result, trace) {
break
}
applyFenceCompleted(st, e, &result, trace)
case FenceFailed:
if !checkReplicaID(st, e.ReplicaID, &result, trace) {
break
}
applyFenceFailed(st, e, &result, trace)
default:
trace("unknown_event", "ignored")
}
@@ -319,9 +329,26 @@ func decide(st *ReplicaState, r *ApplyResult, trace func(string, string)) {
st.Recovery.DecisionReason = "caught_up"
trace("decision", "none (R >= H)")
// If no active session and caught up, publish healthy.
// Ack-gated caught-up handoff: the replica's lineage gate
// needs the new epoch established before we can publish
// healthy, otherwise stale old-epoch traffic could still
// land. If Identity.Epoch > Reachability.FencedEpoch, emit
// FenceAtEpoch and HOLD PublishHealthy. PublishHealthy is
// only emitted once FenceCompleted has bumped FencedEpoch
// to match Identity.Epoch. On FenceFailed the engine leaves
// FencedEpoch unchanged; the next probe re-runs decide()
// and may re-emit the fence.
if st.Session.Phase == PhaseNone || st.Session.Phase == PhaseCompleted {
r.Commands = append(r.Commands, PublishHealthy{ReplicaID: st.Identity.ReplicaID})
if st.Identity.Epoch > st.Reachability.FencedEpoch {
r.Commands = append(r.Commands, FenceAtEpoch{
ReplicaID: st.Identity.ReplicaID,
Epoch: st.Identity.Epoch,
EndpointVersion: st.Identity.EndpointVersion,
})
trace("command", "FenceAtEpoch")
} else {
r.Commands = append(r.Commands, PublishHealthy{ReplicaID: st.Identity.ReplicaID})
}
}
case R >= S && R < H:
@@ -419,6 +446,12 @@ func applySessionCompleted(st *ReplicaState, e SessionClosedCompleted, r *ApplyR
st.Session.Phase = PhaseCompleted
st.Session.AchievedLSN = e.AchievedLSN
st.Recovery.R = e.AchievedLSN // advance replica boundary
// A successful catch-up/rebuild session sent mutating traffic
// at the current identity epoch, so the replica's lineage gate
// is now at this epoch. Treat completion as an implicit fence.
if st.Identity.Epoch > st.Reachability.FencedEpoch {
st.Reachability.FencedEpoch = st.Identity.Epoch
}
trace("session_completed", "")
// Re-evaluate: may be caught up now.
@@ -453,6 +486,52 @@ func applySessionInvalidated(st *ReplicaState, e SessionInvalidated, r *ApplyRes
trace("session_invalidated", e.Reason)
}
// --- Fence events (P14 S1) ---
func applyFenceCompleted(st *ReplicaState, e FenceCompleted, r *ApplyResult, trace func(string, string)) {
// Lineage check: the fence result must belong to the current
// identity. A fence at an older epoch than Identity.Epoch is
// stale (identity advanced mid-fence); drop without mutating.
// A fence for an endpoint the engine no longer recognizes is
// also stale.
if e.Epoch < st.Identity.Epoch {
trace("stale_fence_completed", fmt.Sprintf("event epoch=%d older than current=%d",
e.Epoch, st.Identity.Epoch))
return
}
if e.Epoch == st.Identity.Epoch && e.EndpointVersion < st.Identity.EndpointVersion {
trace("stale_fence_completed", fmt.Sprintf("same epoch=%d but older endpointVersion=%d < current=%d",
e.Epoch, e.EndpointVersion, st.Identity.EndpointVersion))
return
}
if e.Epoch > st.Reachability.FencedEpoch {
st.Reachability.FencedEpoch = e.Epoch
trace("fenced", fmt.Sprintf("epoch=%d", e.Epoch))
} else {
trace("fence_completed_idempotent", fmt.Sprintf("epoch=%d already fenced", e.Epoch))
}
// Re-run decide: a caught-up replica that was waiting behind
// the fence can now publish healthy.
if st.Recovery.R != 0 || st.Recovery.S != 0 || st.Recovery.H != 0 {
decide(st, r, trace)
}
}
func applyFenceFailed(st *ReplicaState, e FenceFailed, r *ApplyResult, trace func(string, string)) {
// Fence failure is fail-closed: FencedEpoch is NOT advanced.
// The next probe will re-run decide() and re-emit FenceAtEpoch
// if the engine still believes the replica is caught up under
// the new epoch. We do NOT re-emit here; retry is probe-driven.
if e.Epoch < st.Identity.Epoch {
trace("stale_fence_failed", fmt.Sprintf("event epoch=%d older than current=%d",
e.Epoch, st.Identity.Epoch))
return
}
trace("fence_failed", fmt.Sprintf("epoch=%d reason=%s", e.Epoch, e.Reason))
}
func phaseMismatchDetail(eventID, currentID uint64) string {
if currentID == 0 {
return fmt.Sprintf("event session=%d but no active session", eventID)
@@ -475,9 +554,20 @@ func derivePublication(st *ReplicaState, trace func(string, string)) {
switch {
case st.Recovery.Decision == DecisionNone && st.Reachability.Status == ProbeReachable:
st.Publication.Healthy = true
st.Publication.Degraded = false
st.Publication.NeedsAttention = false
// Caught-up branch. Ack-gated on fence completion (P14 S1):
// the operator-visible Healthy must not flip true until the
// replica's lineage gate has observed Identity.Epoch via
// FenceCompleted. Otherwise stale old-epoch traffic could
// still land while the projection already reads healthy.
if st.Identity.Epoch > st.Reachability.FencedEpoch {
st.Publication.Healthy = false
st.Publication.Degraded = false
st.Publication.NeedsAttention = true
} else {
st.Publication.Healthy = true
st.Publication.Degraded = false
st.Publication.NeedsAttention = false
}
case st.Session.Phase == PhaseRunning || st.Session.Phase == PhaseStarting:
st.Publication.Healthy = false
st.Publication.Degraded = false
+201 -1
View File
@@ -75,7 +75,26 @@ func TestV3_Decision_CaughtUp_NoRecovery(t *testing.T) {
if r.Projection.RecoveryDecision != DecisionNone {
t.Fatalf("R>=H should be none, got %s", r.Projection.RecoveryDecision)
}
assertHasCommand(t, r, "PublishHealthy")
// P14 S1: caught-up path now emits FenceAtEpoch first to
// advance the replica's lineage gate. PublishHealthy MUST NOT
// be in the command list yet, and projection Mode MUST NOT be
// healthy — the operator-visible contract is ack-gated.
assertHasCommand(t, r, "FenceAtEpoch")
for _, cmd := range r.Commands {
if CommandKind(cmd) == "PublishHealthy" {
t.Fatal("PublishHealthy emitted before FenceCompleted — contract is ack-gated")
}
}
if r.Projection.Mode == ModeHealthy {
t.Fatalf("projection flipped healthy before fence complete: %s", r.Projection.Mode)
}
// Complete the fence → engine re-runs decide → emits PublishHealthy.
r2 := Apply(st, FenceCompleted{ReplicaID: "r1", Epoch: st.Identity.Epoch, EndpointVersion: st.Identity.EndpointVersion})
assertHasCommand(t, r2, "PublishHealthy")
if r2.Projection.Mode != ModeHealthy {
t.Fatalf("after FenceCompleted: expected healthy, got %s", r2.Projection.Mode)
}
}
func TestV3_Decision_CatchUp_GapWithinWAL(t *testing.T) {
@@ -659,6 +678,187 @@ func TestV3_Property_RandomStaleSessionEventsCannotMutateLiveSession(t *testing.
}
}
// ============================================================
// P14 S1 — Dedicated Fence Proof Tests
//
// These tests pin the operator-visible contract of the ack-gated
// fence on the caught-up path. They must remain together so the
// contract is auditable as a single unit.
//
// Contract surface (what these prove):
// 1. Caught-up path emits ONLY FenceAtEpoch — no StartCatchUp,
// no StartRebuild. Fence is not a data-recovery session.
// 2. PublishHealthy MUST NOT appear in any command stream before
// FenceCompleted has been applied.
// 3. FenceFailed is fail-closed: FencedEpoch does not advance.
// The next probe re-runs decide() and re-emits FenceAtEpoch.
// 4. A FenceCompleted for an old epoch (under a newer identity)
// is rejected — identity-advancement invalidates in-flight
// fence results.
// ============================================================
// TestFence_CaughtUpPath_UsesNoDataRecovery — a caught-up replica
// under a newer identity epoch must not trigger a catch-up or
// rebuild session. The only command the engine issues on the
// caught-up branch is FenceAtEpoch. This is the structural proof
// that fence is a command+event pair, NOT a session lifecycle.
func TestFence_CaughtUpPath_UsesNoDataRecovery(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st)
r := Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 100, S: 10, H: 100})
assertHasCommand(t, r, "FenceAtEpoch")
assertNoCommand(t, r, "StartCatchUp")
assertNoCommand(t, r, "StartRebuild")
// Also not a session — session phase is untouched.
if st.Session.Phase != PhaseNone {
t.Fatalf("fence is not a session: session phase=%s, want none",
st.Session.Phase)
}
if st.Session.SessionID != 0 {
t.Fatalf("fence must not allocate a session in engine state, got sid=%d",
st.Session.SessionID)
}
}
// TestFence_HealthyOnlyAfterFenceComplete — operator-visible
// contract: PublishHealthy is held until FenceCompleted bumps the
// replica's FencedEpoch. Observed from the projection Mode and the
// command stream.
func TestFence_HealthyOnlyAfterFenceComplete(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st)
r1 := Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 100, S: 10, H: 100})
// Before FenceCompleted: no PublishHealthy, Mode not Healthy.
assertNoCommand(t, r1, "PublishHealthy")
if r1.Projection.Mode == ModeHealthy {
t.Fatalf("pre-fence projection flipped Healthy: %s", r1.Projection.Mode)
}
if st.Reachability.FencedEpoch >= st.Identity.Epoch {
t.Fatalf("pre-fence FencedEpoch=%d must be < Identity.Epoch=%d",
st.Reachability.FencedEpoch, st.Identity.Epoch)
}
// FenceCompleted at the current lineage — engine re-runs decide
// and must now emit PublishHealthy.
r2 := Apply(st, FenceCompleted{
ReplicaID: "r1",
Epoch: st.Identity.Epoch,
EndpointVersion: st.Identity.EndpointVersion,
})
assertHasCommand(t, r2, "PublishHealthy")
if r2.Projection.Mode != ModeHealthy {
t.Fatalf("post-fence projection not Healthy: %s", r2.Projection.Mode)
}
if st.Reachability.FencedEpoch != st.Identity.Epoch {
t.Fatalf("FencedEpoch=%d must match Identity.Epoch=%d after fence",
st.Reachability.FencedEpoch, st.Identity.Epoch)
}
}
// TestFence_FailureLeavesFencedEpochUnchanged — fail-closed
// contract: FenceFailed does NOT advance FencedEpoch, and does NOT
// re-emit FenceAtEpoch on its own. Retry is probe-driven: the next
// successful probe re-runs decide() and re-emits FenceAtEpoch.
func TestFence_FailureLeavesFencedEpochUnchanged(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st)
// Caught-up fact set — the engine should emit FenceAtEpoch.
r1 := Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 100, S: 10, H: 100})
assertHasCommand(t, r1, "FenceAtEpoch")
preFencedEpoch := st.Reachability.FencedEpoch
if preFencedEpoch >= st.Identity.Epoch {
t.Fatalf("pre-fence FencedEpoch=%d must be < Identity.Epoch=%d",
preFencedEpoch, st.Identity.Epoch)
}
// FenceFailed at the current lineage — MUST NOT advance
// FencedEpoch and MUST NOT re-emit FenceAtEpoch here.
r2 := Apply(st, FenceFailed{
ReplicaID: "r1",
Epoch: st.Identity.Epoch,
EndpointVersion: st.Identity.EndpointVersion,
Reason: "simulated_barrier_timeout",
})
if st.Reachability.FencedEpoch != preFencedEpoch {
t.Fatalf("FenceFailed advanced FencedEpoch: pre=%d post=%d",
preFencedEpoch, st.Reachability.FencedEpoch)
}
assertNoCommand(t, r2, "FenceAtEpoch")
assertNoCommand(t, r2, "PublishHealthy")
if r2.Projection.Mode == ModeHealthy {
t.Fatalf("post-FenceFailed projection must not be Healthy, got %s",
r2.Projection.Mode)
}
// Probe-driven retry: another successful probe re-runs decide()
// and emits FenceAtEpoch again.
r3 := Apply(st, ProbeSucceeded{
ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1,
})
assertHasCommand(t, r3, "FenceAtEpoch")
assertNoCommand(t, r3, "PublishHealthy")
}
// TestFence_StaleOldEpochRejectedAfterFenceOnCaughtUp — identity
// advance invalidates in-flight fences: a FenceCompleted carrying
// an older epoch than the current identity must not advance the
// gate and must not produce healthy publication.
func TestFence_StaleOldEpochRejectedAfterFenceOnCaughtUp(t *testing.T) {
st := &ReplicaState{}
// Epoch 1 identity, caught-up, fence emitted but in-flight.
assignAndProbe(st)
r1 := Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 100, S: 10, H: 100})
assertHasCommand(t, r1, "FenceAtEpoch")
// Identity advances to epoch 2 before the fence completes.
// Engine must clear reachability/session and request a probe.
Apply(st, AssignmentObserved{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 2, EndpointVersion: 2,
DataAddr: "a", CtrlAddr: "b",
})
if st.Identity.Epoch != 2 {
t.Fatalf("identity did not advance, got epoch=%d", st.Identity.Epoch)
}
// Stale FenceCompleted arrives for epoch 1 (the superseded
// attempt). It must be rejected: FencedEpoch must not jump to
// stale epoch, and the replica must not become Healthy.
rStale := Apply(st, FenceCompleted{
ReplicaID: "r1",
Epoch: 1,
EndpointVersion: 1,
})
if st.Reachability.FencedEpoch >= st.Identity.Epoch {
t.Fatalf("stale FenceCompleted advanced FencedEpoch: got %d, identity=%d",
st.Reachability.FencedEpoch, st.Identity.Epoch)
}
assertTraceContains(t, rStale, "stale_fence_completed")
assertNoCommand(t, rStale, "PublishHealthy")
if rStale.Projection.Mode == ModeHealthy {
t.Fatalf("stale fence must not produce Healthy, got %s", rStale.Projection.Mode)
}
// A fresh fence at the new epoch must advance the gate normally.
Apply(st, ProbeSucceeded{ReplicaID: "r1", EndpointVersion: 2, TransportEpoch: 2})
Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 2, TransportEpoch: 2, R: 100, S: 10, H: 100})
rFresh := Apply(st, FenceCompleted{
ReplicaID: "r1",
Epoch: 2,
EndpointVersion: 2,
})
if st.Reachability.FencedEpoch != 2 {
t.Fatalf("fresh fence did not advance FencedEpoch to 2, got %d",
st.Reachability.FencedEpoch)
}
assertHasCommand(t, rFresh, "PublishHealthy")
if rFresh.Projection.Mode != ModeHealthy {
t.Fatalf("post-fresh-fence projection not Healthy: %s", rFresh.Projection.Mode)
}
}
// === Helpers ===
func assertHasCommand(t *testing.T, r ApplyResult, kind string) {
+17
View File
@@ -48,6 +48,23 @@ type InvalidateSession struct {
func (InvalidateSession) commandKind() string { return "InvalidateSession" }
// FenceAtEpoch: request the runtime to establish the given epoch on
// the replica's lineage gate. Used only on the caught-up handoff
// branch (R >= H), where no recovery traffic would otherwise carry
// the new epoch to the replica.
//
// Ack-gated: PublishHealthy must NOT follow FenceAtEpoch unless a
// FenceCompleted event confirms the replica accepted the barrier
// at this epoch. On failure, the engine leaves Reachability.
// FencedEpoch unchanged; the next probe re-triggers decide().
type FenceAtEpoch struct {
ReplicaID string
Epoch uint64
EndpointVersion uint64
}
func (FenceAtEpoch) commandKind() string { return "FenceAtEpoch" }
// PublishHealthy: declare this replica healthy for external consumption.
type PublishHealthy struct {
ReplicaID string
+27
View File
@@ -131,6 +131,33 @@ type SessionInvalidated struct {
func (SessionInvalidated) eventKind() string { return "SessionInvalidated" }
// --- Fence events (authority: transport) ---
// FenceCompleted: a FenceAtEpoch command completed successfully —
// the replica's lineage gate has now observed this epoch via a
// barrier ack. Advances Reachability.FencedEpoch.
type FenceCompleted struct {
ReplicaID string
Epoch uint64
EndpointVersion uint64
}
func (FenceCompleted) eventKind() string { return "FenceCompleted" }
// FenceFailed: a FenceAtEpoch command did not complete (timeout,
// dial failure, replica unreachable mid-barrier). Reachability.
// FencedEpoch is NOT advanced; the next probe will re-trigger
// decide(), which will re-emit FenceAtEpoch if the engine still
// thinks the replica is caught up under the newer epoch.
type FenceFailed struct {
ReplicaID string
Epoch uint64
EndpointVersion uint64
Reason string
}
func (FenceFailed) eventKind() string { return "FenceFailed" }
// EventKind returns the string name of an event for tracing.
func EventKind(e Event) string {
if e == nil {
+8
View File
@@ -47,6 +47,14 @@ func DeriveProjection(st *ReplicaState) ReplicaProjection {
p.Mode = ModeRecovering
case st.Publication.Healthy:
p.Mode = ModeHealthy
case st.Recovery.Decision == DecisionNone &&
st.Reachability.Status == ProbeReachable &&
st.Identity.Epoch > st.Reachability.FencedEpoch:
// P14 S1: caught-up but fence not yet acked. Transitional
// — not healthy yet, but nothing is wrong. Show as
// recovering rather than degraded so operators read the
// transition correctly.
p.Mode = ModeRecovering
default:
p.Mode = ModeDegraded
}
+10
View File
@@ -58,6 +58,16 @@ type ReachabilityTruth struct {
LastContactKind ContactKind
ObservedEndpointVersion uint64
TransportEpoch uint64
// FencedEpoch is the highest epoch for which a FenceAtEpoch
// barrier has completed successfully on the replica's lineage
// gate. Bumped by applyFenceCompleted; reset on identity change.
// Used by decide() to gate PublishHealthy on the R>=H branch:
// caught-up handoff is only considered safe once the replica's
// lineage gate has observed the new epoch via mutating traffic
// (the fence barrier). Engine-internal; not exposed in
// ReplicaProjection.
FencedEpoch uint64
}
// RecoveryDecision represents the recovery classification.
+8 -5
View File
@@ -194,15 +194,18 @@ func TestState_UpdateReflectsInSnapshot(t *testing.T) {
type nopExecutor struct {
onStart adapter.OnSessionStart
onClose adapter.OnSessionClose
onFence adapter.OnFenceComplete
}
func (e *nopExecutor) SetOnSessionStart(fn adapter.OnSessionStart) { e.onStart = fn }
func (e *nopExecutor) SetOnSessionClose(fn adapter.OnSessionClose) { e.onClose = fn }
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 {
return adapter.ProbeResult{Success: false, FailReason: "nop"}
}
func (e *nopExecutor) StartCatchUp(string, uint64, uint64, uint64, uint64) error { return nil }
func (e *nopExecutor) StartRebuild(string, uint64, uint64, uint64, uint64) error { return nil }
func (e *nopExecutor) InvalidateSession(string, uint64, string) {}
func (e *nopExecutor) PublishHealthy(string) {}
func (e *nopExecutor) PublishDegraded(string, string) {}
func (e *nopExecutor) Fence(string, uint64, uint64, uint64) error { return nil }
func (e *nopExecutor) InvalidateSession(string, uint64, string) {}
func (e *nopExecutor) PublishHealthy(string) {}
func (e *nopExecutor) PublishDegraded(string, string) {}
+15
View File
@@ -100,6 +100,21 @@ func ToEngineEvent(ei EventInput) (engine.Event, error) {
Reason: ei.Reason,
}, nil
case "FenceCompleted":
return engine.FenceCompleted{
ReplicaID: ei.ReplicaID,
Epoch: ei.Epoch,
EndpointVersion: ei.EndpointVersion,
}, nil
case "FenceFailed":
return engine.FenceFailed{
ReplicaID: ei.ReplicaID,
Epoch: ei.Epoch,
EndpointVersion: ei.EndpointVersion,
Reason: ei.Reason,
}, nil
default:
return nil, fmt.Errorf("schema: unknown event kind %q", ei.Kind)
}
+82 -10
View File
@@ -13,17 +13,18 @@ import (
)
// BlockExecutor implements adapter.CommandExecutor using real TCP
// transport and in-memory storage. It is the "muscle" layer — it
// executes commands but never decides policy.
// transport and a primary-side LogicalStorage. It is the "muscle"
// layer — it executes commands but never decides policy.
type BlockExecutor struct {
primaryStore *storage.BlockStore
primaryStore storage.LogicalStorage
replicaAddr string // replica's TCP address
mu sync.Mutex
onSessionStart adapter.OnSessionStart
onSessionClose adapter.OnSessionClose
sessions map[uint64]*activeSession
stepDelay time.Duration
mu sync.Mutex
onSessionStart adapter.OnSessionStart
onSessionClose adapter.OnSessionClose
onFenceComplete adapter.OnFenceComplete
sessions map[uint64]*activeSession
stepDelay time.Duration
}
type activeSession struct {
@@ -36,8 +37,8 @@ var errSessionInvalidated = errors.New("session invalidated")
const recoveryConnTimeout = 5 * time.Second
// NewBlockExecutor creates an executor for one primary → replica pair.
func NewBlockExecutor(primaryStore *storage.BlockStore, replicaAddr string) *BlockExecutor {
// NewBlockExecutor creates an executor for one primary -> replica pair.
func NewBlockExecutor(primaryStore storage.LogicalStorage, replicaAddr string) *BlockExecutor {
return &BlockExecutor{
primaryStore: primaryStore,
replicaAddr: replicaAddr,
@@ -59,6 +60,77 @@ func (e *BlockExecutor) SetStepDelay(d time.Duration) {
e.mu.Unlock()
}
func (e *BlockExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) {
e.onFenceComplete = fn
}
// Fence sends one MsgBarrierReq at the given lineage to the
// replica and awaits MsgBarrierResp. Does NOT ship any blocks and
// does NOT go through the session registry — fence is a single
// barrier exchange, not a recovery session.
//
// On success or failure, fires the registered OnFenceComplete
// callback exactly once. Retry is the adapter/engine's
// responsibility (probe-driven); this method never retries.
func (e *BlockExecutor) Fence(replicaID string, sessionID, epoch, endpointVersion uint64) error {
lineage := RecoveryLineage{
SessionID: sessionID,
Epoch: epoch,
EndpointVersion: endpointVersion,
// TargetLSN is not used by acceptMutationLineage for order
// comparison; set to 0 to signal "fence, no recovery target."
TargetLSN: 0,
}
go e.doFence(replicaID, lineage)
return nil
}
func (e *BlockExecutor) doFence(replicaID string, lineage RecoveryLineage) {
result := adapter.FenceResult{
ReplicaID: replicaID,
SessionID: lineage.SessionID,
Epoch: lineage.Epoch,
EndpointVersion: lineage.EndpointVersion,
}
conn, err := net.DialTimeout("tcp", e.replicaAddr, 2*time.Second)
if err != nil {
result.Success = false
result.FailReason = fmt.Sprintf("fence dial: %v", err)
e.fireFenceComplete(result)
return
}
defer conn.Close()
if err := sendBarrierReq(conn, lineage, recoveryConnTimeout); err != nil {
result.Success = false
result.FailReason = fmt.Sprintf("fence barrier send: %v", err)
e.fireFenceComplete(result)
return
}
resp, err := recvBarrierResp(conn, recoveryConnTimeout)
if err != nil {
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
result.Success = true
log.Printf("executor: fence complete replica=%s epoch=%d", replicaID, lineage.Epoch)
e.fireFenceComplete(result)
}
func (e *BlockExecutor) fireFenceComplete(result adapter.FenceResult) {
e.mu.Lock()
cb := e.onFenceComplete
e.mu.Unlock()
if cb != nil {
cb(result)
}
}
// 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 {
@@ -0,0 +1,214 @@
package transport
import (
"bytes"
"os"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func newPersistentTestDir(t *testing.T) string {
t.Helper()
dir, err := os.MkdirTemp("", "seaweed-block-transport-persist-*")
if err != nil {
t.Fatalf("MkdirTemp: %v", err)
}
t.Cleanup(func() {
var lastErr error
for i := 0; i < 20; i++ {
lastErr = os.RemoveAll(dir)
if lastErr == nil || os.IsNotExist(lastErr) {
return
}
time.Sleep(25 * time.Millisecond)
}
t.Logf("best-effort RemoveAll(%s): %v", dir, lastErr)
})
return dir
}
func createWALStoreForTest(t *testing.T, dir, name string) *storage.WALStore {
t.Helper()
path := filepath.Join(dir, name)
s, err := storage.CreateWALStore(path, 64, 4096)
if err != nil {
t.Fatalf("CreateWALStore(%s): %v", name, err)
}
return s
}
func writePersistentBlocks(t *testing.T, store storage.LogicalStorage, count uint32) uint64 {
t.Helper()
for i := uint32(0); i < count; i++ {
data := make([]byte, 4096)
data[0] = byte(i + 1)
data[1] = byte(i + 0xA0)
if _, err := store.Write(i, data); err != nil {
t.Fatalf("Write LBA %d: %v", i, err)
}
}
lsn, err := store.Sync()
if err != nil {
t.Fatalf("Sync: %v", err)
}
return lsn
}
func assertLogicalStorageMatch(t *testing.T, label string, primary, replica storage.LogicalStorage, count uint32) {
t.Helper()
for i := uint32(0); i < count; i++ {
pd, err := primary.Read(i)
if err != nil {
t.Fatalf("%s: primary read LBA %d: %v", label, i, err)
}
rd, err := replica.Read(i)
if err != nil {
t.Fatalf("%s: replica read LBA %d: %v", label, i, err)
}
if !bytes.Equal(pd, rd) {
t.Fatalf("%s: LBA %d mismatch (primary[0]=%d replica[0]=%d)", label, i, pd[0], rd[0])
}
}
}
func TestTransport_CatchUp_WALStore_PersistsAcrossReplicaReopen(t *testing.T) {
dir := newPersistentTestDir(t)
primary := createWALStoreForTest(t, dir, "primary-catchup.dat")
replica := createWALStoreForTest(t, dir, "replica-catchup.dat")
listener, err := NewReplicaListener("127.0.0.1:0", replica)
if err != nil {
t.Fatal(err)
}
listener.Serve()
pH := writePersistentBlocks(t, primary, 10)
exec := NewBlockExecutor(primary, listener.Addr())
startCh := make(chan adapter.SessionStartResult, 1)
closeCh := make(chan adapter.SessionCloseResult, 1)
exec.SetOnSessionStart(func(r adapter.SessionStartResult) { startCh <- r })
exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closeCh <- r })
if err := exec.StartCatchUp("r1", 41, 1, 1, pH); err != nil {
t.Fatal(err)
}
select {
case <-startCh:
case <-time.After(5 * time.Second):
t.Fatal("timeout waiting for catch-up start")
}
select {
case result := <-closeCh:
if !result.Success {
t.Fatalf("catch-up failed: %s", result.FailReason)
}
if result.AchievedLSN != pH {
t.Fatalf("achievedLSN=%d want %d", result.AchievedLSN, pH)
}
case <-time.After(5 * time.Second):
t.Fatal("timeout waiting for catch-up close")
}
listener.Stop()
if err := replica.Close(); err != nil {
t.Fatalf("replica Close: %v", err)
}
reopened, err := storage.OpenWALStore(filepath.Join(dir, "replica-catchup.dat"))
if err != nil {
t.Fatalf("OpenWALStore replica reopen: %v", err)
}
defer reopened.Close()
recovered, err := reopened.Recover()
if err != nil {
t.Fatalf("Recover replica reopen: %v", err)
}
if recovered != pH {
t.Fatalf("recovered frontier=%d want %d", recovered, pH)
}
assertLogicalStorageMatch(t, "catch-up WALStore reopen", primary, reopened, 10)
if err := reopened.Close(); err != nil {
t.Fatalf("reopened Close: %v", err)
}
if err := primary.Close(); err != nil {
t.Fatalf("primary Close: %v", err)
}
}
func TestTransport_Rebuild_WALStore_PersistsAcrossReplicaReopen(t *testing.T) {
dir := newPersistentTestDir(t)
primary := createWALStoreForTest(t, dir, "primary-rebuild.dat")
replica := createWALStoreForTest(t, dir, "replica-rebuild.dat")
listener, err := NewReplicaListener("127.0.0.1:0", replica)
if err != nil {
t.Fatal(err)
}
listener.Serve()
pH := writePersistentBlocks(t, primary, 10)
exec := NewBlockExecutor(primary, listener.Addr())
startCh := make(chan adapter.SessionStartResult, 1)
closeCh := make(chan adapter.SessionCloseResult, 1)
exec.SetOnSessionStart(func(r adapter.SessionStartResult) { startCh <- r })
exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closeCh <- r })
if err := exec.StartRebuild("r1", 42, 1, 1, pH); err != nil {
t.Fatal(err)
}
select {
case <-startCh:
case <-time.After(5 * time.Second):
t.Fatal("timeout waiting for rebuild start")
}
select {
case result := <-closeCh:
if !result.Success {
t.Fatalf("rebuild failed: %s", result.FailReason)
}
if result.AchievedLSN != pH {
t.Fatalf("achievedLSN=%d want %d", result.AchievedLSN, pH)
}
case <-time.After(5 * time.Second):
t.Fatal("timeout waiting for rebuild close")
}
listener.Stop()
if err := replica.Close(); err != nil {
t.Fatalf("replica Close: %v", err)
}
reopened, err := storage.OpenWALStore(filepath.Join(dir, "replica-rebuild.dat"))
if err != nil {
t.Fatalf("OpenWALStore replica reopen: %v", err)
}
defer reopened.Close()
recovered, err := reopened.Recover()
if err != nil {
t.Fatalf("Recover replica reopen: %v", err)
}
if recovered != pH {
t.Fatalf("recovered frontier=%d want %d", recovered, pH)
}
assertLogicalStorageMatch(t, "rebuild WALStore reopen", primary, reopened, 10)
if err := reopened.Close(); err != nil {
t.Fatalf("reopened Close: %v", err)
}
if err := primary.Close(); err != nil {
t.Fatalf("primary Close: %v", err)
}
}
+4 -3
View File
@@ -10,9 +10,10 @@ import (
)
// ReplicaListener accepts connections from the primary and handles
// WAL shipping, probe requests, and rebuild streams.
// WAL shipping, probe requests, and rebuild streams against a
// replica-side LogicalStorage.
type ReplicaListener struct {
store *storage.BlockStore
store storage.LogicalStorage
listener net.Listener
stopCh chan struct{}
wg sync.WaitGroup
@@ -22,7 +23,7 @@ type ReplicaListener struct {
}
// NewReplicaListener creates a listener on the given address.
func NewReplicaListener(addr string, store *storage.BlockStore) (*ReplicaListener, error) {
func NewReplicaListener(addr string, store storage.LogicalStorage) (*ReplicaListener, error) {
ln, err := net.Listen("tcp", addr)
if err != nil {
return nil, err